import { g as getDefaultExportFromCjs, c as commonjsGlobal, r as reactExports, R as React, a as reactDomExports, b as ReactRenderer, i as index_default, d as ReactNodeViewRenderer, m as mergeAttributes, N as NodeViewWrapper, e as Node3, B as BubbleMenu, f as index_default$1, T as TableRow, h as index_default$2, k as index_default$3, l as Table$1, n as TableHeader, o as TableCell, p as index_default$4, q as index_default$5, u as useEditor, E as EditorContent, j as jsxRuntimeExports, s as requireReact, t as requireReactDom } from "./assets/vendor-tiptap-DRFaxGEb.js";
import require$$0$1 from "util";
import stream, { Readable } from "stream";
import require$$1 from "path";
import require$$3, { createServer } from "http";
import require$$4 from "https";
import require$$5 from "url";
import require$$6 from "fs";
import require$$1$1 from "crypto";
import http2 from "http2";
import require$$4$1 from "assert";
import require$$1$2 from "tty";
import require$$0$2 from "os";
import zlib from "zlib";
import { EventEmitter } from "events";
import { t as tippy } from "./assets/vendor-tooltip-CIQaDNlG.js";
import minproc from "node:process";
import minpath from "node:path";
import { fileURLToPath } from "node:url";
import { P as Pusher, E as E$2 } from "./assets/vendor-realtime-DYEIbD6w.js";
import { u as useReducedMotion, m as motion, A as AnimatePresence } from "./assets/vendor-motion-CotXNotG.js";
import * as s from "process";
import require$$2 from "async_hooks";
import "buffer";
import "child_process";
import "net";
import "tls";
function bind(fn, thisArg) {
  return function wrap2() {
    return fn.apply(thisArg, arguments);
  };
}
const { toString: toString$2 } = Object.prototype;
const { getPrototypeOf } = Object;
const { iterator, toStringTag } = Symbol;
const kindOf = /* @__PURE__ */ ((cache) => (thing) => {
  const str = toString$2.call(thing);
  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null));
const kindOfTest = (type2) => {
  type2 = type2.toLowerCase();
  return (thing) => kindOf(thing) === type2;
};
const typeOfTest = (type2) => (thing) => typeof thing === type2;
const { isArray } = Array;
const isUndefined = typeOfTest("undefined");
function isBuffer(val) {
  return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
const isArrayBuffer = kindOfTest("ArrayBuffer");
function isArrayBufferView(val) {
  let result;
  if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) {
    result = ArrayBuffer.isView(val);
  } else {
    result = val && val.buffer && isArrayBuffer(val.buffer);
  }
  return result;
}
const isString = typeOfTest("string");
const isFunction$1 = typeOfTest("function");
const isNumber = typeOfTest("number");
const isObject = (thing) => thing !== null && typeof thing === "object";
const isBoolean = (thing) => thing === true || thing === false;
const isPlainObject$1 = (val) => {
  if (kindOf(val) !== "object") {
    return false;
  }
  const prototype2 = getPrototypeOf(val);
  return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(toStringTag in val) && !(iterator in val);
};
const isEmptyObject = (val) => {
  if (!isObject(val) || isBuffer(val)) {
    return false;
  }
  try {
    return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
  } catch (e) {
    return false;
  }
};
const isDate = kindOfTest("Date");
const isFile = kindOfTest("File");
const isReactNativeBlob = (value) => {
  return !!(value && typeof value.uri !== "undefined");
};
const isReactNative = (formData) => formData && typeof formData.getParts !== "undefined";
const isBlob = kindOfTest("Blob");
const isFileList = kindOfTest("FileList");
const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
function getGlobal() {
  if (typeof globalThis !== "undefined") return globalThis;
  if (typeof self !== "undefined") return self;
  if (typeof window !== "undefined") return window;
  if (typeof global !== "undefined") return global;
  return {};
}
const G$2 = getGlobal();
const FormDataCtor = typeof G$2.FormData !== "undefined" ? G$2.FormData : void 0;
const isFormData = (thing) => {
  let kind;
  return thing && (FormDataCtor && thing instanceof FormDataCtor || isFunction$1(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance
  kind === "object" && isFunction$1(thing.toString) && thing.toString() === "[object FormData]"));
};
const isURLSearchParams = kindOfTest("URLSearchParams");
const [isReadableStream, isRequest, isResponse, isHeaders] = [
  "ReadableStream",
  "Request",
  "Response",
  "Headers"
].map(kindOfTest);
const trim = (str) => {
  return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
};
function forEach(obj, fn, { allOwnKeys = false } = {}) {
  if (obj === null || typeof obj === "undefined") {
    return;
  }
  let i;
  let l3;
  if (typeof obj !== "object") {
    obj = [obj];
  }
  if (isArray(obj)) {
    for (i = 0, l3 = obj.length; i < l3; i++) {
      fn.call(null, obj[i], i, obj);
    }
  } else {
    if (isBuffer(obj)) {
      return;
    }
    const keys2 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
    const len = keys2.length;
    let key;
    for (i = 0; i < len; i++) {
      key = keys2[i];
      fn.call(null, obj[key], key, obj);
    }
  }
}
function findKey(obj, key) {
  if (isBuffer(obj)) {
    return null;
  }
  key = key.toLowerCase();
  const keys2 = Object.keys(obj);
  let i = keys2.length;
  let _key;
  while (i-- > 0) {
    _key = keys2[i];
    if (key === _key.toLowerCase()) {
      return _key;
    }
  }
  return null;
}
const _global = (() => {
  if (typeof globalThis !== "undefined") return globalThis;
  return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global;
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
function merge$1() {
  const { caseless, skipUndefined } = isContextDefined(this) && this || {};
  const result = {};
  const assignValue = (val, key) => {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      return;
    }
    const targetKey = caseless && findKey(result, key) || key;
    if (isPlainObject$1(result[targetKey]) && isPlainObject$1(val)) {
      result[targetKey] = merge$1(result[targetKey], val);
    } else if (isPlainObject$1(val)) {
      result[targetKey] = merge$1({}, val);
    } else if (isArray(val)) {
      result[targetKey] = val.slice();
    } else if (!skipUndefined || !isUndefined(val)) {
      result[targetKey] = val;
    }
  };
  for (let i = 0, l3 = arguments.length; i < l3; i++) {
    arguments[i] && forEach(arguments[i], assignValue);
  }
  return result;
}
const extend$2 = (a, b2, thisArg, { allOwnKeys } = {}) => {
  forEach(
    b2,
    (val, key) => {
      if (thisArg && isFunction$1(val)) {
        Object.defineProperty(a, key, {
          value: bind(val, thisArg),
          writable: true,
          enumerable: true,
          configurable: true
        });
      } else {
        Object.defineProperty(a, key, {
          value: val,
          writable: true,
          enumerable: true,
          configurable: true
        });
      }
    },
    { allOwnKeys }
  );
  return a;
};
const stripBOM = (content2) => {
  if (content2.charCodeAt(0) === 65279) {
    content2 = content2.slice(1);
  }
  return content2;
};
const inherits = (constructor, superConstructor, props, descriptors) => {
  constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  Object.defineProperty(constructor.prototype, "constructor", {
    value: constructor,
    writable: true,
    enumerable: false,
    configurable: true
  });
  Object.defineProperty(constructor, "super", {
    value: superConstructor.prototype
  });
  props && Object.assign(constructor.prototype, props);
};
const toFlatObject = (sourceObj, destObj, filter2, propFilter) => {
  let props;
  let i;
  let prop;
  const merged = {};
  destObj = destObj || {};
  if (sourceObj == null) return destObj;
  do {
    props = Object.getOwnPropertyNames(sourceObj);
    i = props.length;
    while (i-- > 0) {
      prop = props[i];
      if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
        destObj[prop] = sourceObj[prop];
        merged[prop] = true;
      }
    }
    sourceObj = filter2 !== false && getPrototypeOf(sourceObj);
  } while (sourceObj && (!filter2 || filter2(sourceObj, destObj)) && sourceObj !== Object.prototype);
  return destObj;
};
const endsWith = (str, searchString, position2) => {
  str = String(str);
  if (position2 === void 0 || position2 > str.length) {
    position2 = str.length;
  }
  position2 -= searchString.length;
  const lastIndex = str.indexOf(searchString, position2);
  return lastIndex !== -1 && lastIndex === position2;
};
const toArray = (thing) => {
  if (!thing) return null;
  if (isArray(thing)) return thing;
  let i = thing.length;
  if (!isNumber(i)) return null;
  const arr = new Array(i);
  while (i-- > 0) {
    arr[i] = thing[i];
  }
  return arr;
};
const isTypedArray = /* @__PURE__ */ ((TypedArray) => {
  return (thing) => {
    return TypedArray && thing instanceof TypedArray;
  };
})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));
const forEachEntry = (obj, fn) => {
  const generator = obj && obj[iterator];
  const _iterator = generator.call(obj);
  let result;
  while ((result = _iterator.next()) && !result.done) {
    const pair = result.value;
    fn.call(obj, pair[0], pair[1]);
  }
};
const matchAll = (regExp, str) => {
  let matches;
  const arr = [];
  while ((matches = regExp.exec(str)) !== null) {
    arr.push(matches);
  }
  return arr;
};
const isHTMLForm = kindOfTest("HTMLFormElement");
const toCamelCase = (str) => {
  return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m2, p1, p2) {
    return p1.toUpperCase() + p2;
  });
};
const hasOwnProperty$1 = (({ hasOwnProperty: hasOwnProperty2 }) => (obj, prop) => hasOwnProperty2.call(obj, prop))(Object.prototype);
const isRegExp = kindOfTest("RegExp");
const reduceDescriptors = (obj, reducer2) => {
  const descriptors = Object.getOwnPropertyDescriptors(obj);
  const reducedDescriptors = {};
  forEach(descriptors, (descriptor, name2) => {
    let ret;
    if ((ret = reducer2(descriptor, name2, obj)) !== false) {
      reducedDescriptors[name2] = ret || descriptor;
    }
  });
  Object.defineProperties(obj, reducedDescriptors);
};
const freezeMethods = (obj) => {
  reduceDescriptors(obj, (descriptor, name2) => {
    if (isFunction$1(obj) && ["arguments", "caller", "callee"].indexOf(name2) !== -1) {
      return false;
    }
    const value = obj[name2];
    if (!isFunction$1(value)) return;
    descriptor.enumerable = false;
    if ("writable" in descriptor) {
      descriptor.writable = false;
      return;
    }
    if (!descriptor.set) {
      descriptor.set = () => {
        throw Error("Can not rewrite read-only method '" + name2 + "'");
      };
    }
  });
};
const toObjectSet = (arrayOrString, delimiter) => {
  const obj = {};
  const define = (arr) => {
    arr.forEach((value) => {
      obj[value] = true;
    });
  };
  isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
  return obj;
};
const noop = () => {
};
const toFiniteNumber = (value, defaultValue) => {
  return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
function isSpecCompliantForm(thing) {
  return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === "FormData" && thing[iterator]);
}
const toJSONObject = (obj) => {
  const stack = new Array(10);
  const visit2 = (source, i) => {
    if (isObject(source)) {
      if (stack.indexOf(source) >= 0) {
        return;
      }
      if (isBuffer(source)) {
        return source;
      }
      if (!("toJSON" in source)) {
        stack[i] = source;
        const target = isArray(source) ? [] : {};
        forEach(source, (value, key) => {
          const reducedValue = visit2(value, i + 1);
          !isUndefined(reducedValue) && (target[key] = reducedValue);
        });
        stack[i] = void 0;
        return target;
      }
    }
    return source;
  };
  return visit2(obj, 0);
};
const isAsyncFn = kindOfTest("AsyncFunction");
const isThenable = (thing) => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
  if (setImmediateSupported) {
    return setImmediate;
  }
  return postMessageSupported ? ((token, callbacks) => {
    _global.addEventListener(
      "message",
      ({ source, data }) => {
        if (source === _global && data === token) {
          callbacks.length && callbacks.shift()();
        }
      },
      false
    );
    return (cb) => {
      callbacks.push(cb);
      _global.postMessage(token, "*");
    };
  })(`axios@${Math.random()}`, []) : (cb) => setTimeout(cb);
})(typeof setImmediate === "function", isFunction$1(_global.postMessage));
const asap = typeof queueMicrotask !== "undefined" ? queueMicrotask.bind(_global) : typeof process !== "undefined" && process.nextTick || _setImmediate;
const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
const utils$2 = {
  isArray,
  isArrayBuffer,
  isBuffer,
  isFormData,
  isArrayBufferView,
  isString,
  isNumber,
  isBoolean,
  isObject,
  isPlainObject: isPlainObject$1,
  isEmptyObject,
  isReadableStream,
  isRequest,
  isResponse,
  isHeaders,
  isUndefined,
  isDate,
  isFile,
  isReactNativeBlob,
  isReactNative,
  isBlob,
  isRegExp,
  isFunction: isFunction$1,
  isStream,
  isURLSearchParams,
  isTypedArray,
  isFileList,
  forEach,
  merge: merge$1,
  extend: extend$2,
  trim,
  stripBOM,
  inherits,
  toFlatObject,
  kindOf,
  kindOfTest,
  endsWith,
  toArray,
  forEachEntry,
  matchAll,
  isHTMLForm,
  hasOwnProperty: hasOwnProperty$1,
  hasOwnProp: hasOwnProperty$1,
  // an alias to avoid ESLint no-prototype-builtins detection
  reduceDescriptors,
  freezeMethods,
  toObjectSet,
  toCamelCase,
  noop,
  toFiniteNumber,
  findKey,
  global: _global,
  isContextDefined,
  isSpecCompliantForm,
  toJSONObject,
  isAsyncFn,
  isThenable,
  setImmediate: _setImmediate,
  asap,
  isIterable
};
let AxiosError$1 = class AxiosError extends Error {
  static from(error, code2, config, request, response, customProps) {
    const axiosError = new AxiosError(error.message, code2 || error.code, config, request, response);
    axiosError.cause = error;
    axiosError.name = error.name;
    if (error.status != null && axiosError.status == null) {
      axiosError.status = error.status;
    }
    customProps && Object.assign(axiosError, customProps);
    return axiosError;
  }
  /**
   * Create an Error with the specified message, config, error code, request and response.
   *
   * @param {string} message The error message.
   * @param {string} [code] The error code (for example, 'ECONNABORTED').
   * @param {Object} [config] The config.
   * @param {Object} [request] The request.
   * @param {Object} [response] The response.
   *
   * @returns {Error} The created error.
   */
  constructor(message, code2, config, request, response) {
    super(message);
    Object.defineProperty(this, "message", {
      value: message,
      enumerable: true,
      writable: true,
      configurable: true
    });
    this.name = "AxiosError";
    this.isAxiosError = true;
    code2 && (this.code = code2);
    config && (this.config = config);
    request && (this.request = request);
    if (response) {
      this.response = response;
      this.status = response.status;
    }
  }
  toJSON() {
    return {
      // Standard
      message: this.message,
      name: this.name,
      // Microsoft
      description: this.description,
      number: this.number,
      // Mozilla
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      // Axios
      config: utils$2.toJSONObject(this.config),
      code: this.code,
      status: this.status
    };
  }
};
AxiosError$1.ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
AxiosError$1.ERR_BAD_OPTION = "ERR_BAD_OPTION";
AxiosError$1.ECONNABORTED = "ECONNABORTED";
AxiosError$1.ETIMEDOUT = "ETIMEDOUT";
AxiosError$1.ERR_NETWORK = "ERR_NETWORK";
AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
AxiosError$1.ERR_DEPRECATED = "ERR_DEPRECATED";
AxiosError$1.ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
AxiosError$1.ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
AxiosError$1.ERR_CANCELED = "ERR_CANCELED";
AxiosError$1.ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
AxiosError$1.ERR_INVALID_URL = "ERR_INVALID_URL";
var delayed_stream;
var hasRequiredDelayed_stream;
function requireDelayed_stream() {
  if (hasRequiredDelayed_stream) return delayed_stream;
  hasRequiredDelayed_stream = 1;
  var Stream = stream.Stream;
  var util = require$$0$1;
  delayed_stream = DelayedStream;
  function DelayedStream() {
    this.source = null;
    this.dataSize = 0;
    this.maxDataSize = 1024 * 1024;
    this.pauseStream = true;
    this._maxDataSizeExceeded = false;
    this._released = false;
    this._bufferedEvents = [];
  }
  util.inherits(DelayedStream, Stream);
  DelayedStream.create = function(source, options) {
    var delayedStream = new this();
    options = options || {};
    for (var option in options) {
      delayedStream[option] = options[option];
    }
    delayedStream.source = source;
    var realEmit = source.emit;
    source.emit = function() {
      delayedStream._handleEmit(arguments);
      return realEmit.apply(source, arguments);
    };
    source.on("error", function() {
    });
    if (delayedStream.pauseStream) {
      source.pause();
    }
    return delayedStream;
  };
  Object.defineProperty(DelayedStream.prototype, "readable", {
    configurable: true,
    enumerable: true,
    get: function() {
      return this.source.readable;
    }
  });
  DelayedStream.prototype.setEncoding = function() {
    return this.source.setEncoding.apply(this.source, arguments);
  };
  DelayedStream.prototype.resume = function() {
    if (!this._released) {
      this.release();
    }
    this.source.resume();
  };
  DelayedStream.prototype.pause = function() {
    this.source.pause();
  };
  DelayedStream.prototype.release = function() {
    this._released = true;
    this._bufferedEvents.forEach((function(args) {
      this.emit.apply(this, args);
    }).bind(this));
    this._bufferedEvents = [];
  };
  DelayedStream.prototype.pipe = function() {
    var r = Stream.prototype.pipe.apply(this, arguments);
    this.resume();
    return r;
  };
  DelayedStream.prototype._handleEmit = function(args) {
    if (this._released) {
      this.emit.apply(this, args);
      return;
    }
    if (args[0] === "data") {
      this.dataSize += args[1].length;
      this._checkIfMaxDataSizeExceeded();
    }
    this._bufferedEvents.push(args);
  };
  DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
    if (this._maxDataSizeExceeded) {
      return;
    }
    if (this.dataSize <= this.maxDataSize) {
      return;
    }
    this._maxDataSizeExceeded = true;
    var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
    this.emit("error", new Error(message));
  };
  return delayed_stream;
}
var combined_stream;
var hasRequiredCombined_stream;
function requireCombined_stream() {
  if (hasRequiredCombined_stream) return combined_stream;
  hasRequiredCombined_stream = 1;
  var util = require$$0$1;
  var Stream = stream.Stream;
  var DelayedStream = requireDelayed_stream();
  combined_stream = CombinedStream;
  function CombinedStream() {
    this.writable = false;
    this.readable = true;
    this.dataSize = 0;
    this.maxDataSize = 2 * 1024 * 1024;
    this.pauseStreams = true;
    this._released = false;
    this._streams = [];
    this._currentStream = null;
    this._insideLoop = false;
    this._pendingNext = false;
  }
  util.inherits(CombinedStream, Stream);
  CombinedStream.create = function(options) {
    var combinedStream = new this();
    options = options || {};
    for (var option in options) {
      combinedStream[option] = options[option];
    }
    return combinedStream;
  };
  CombinedStream.isStreamLike = function(stream2) {
    return typeof stream2 !== "function" && typeof stream2 !== "string" && typeof stream2 !== "boolean" && typeof stream2 !== "number" && !Buffer.isBuffer(stream2);
  };
  CombinedStream.prototype.append = function(stream2) {
    var isStreamLike = CombinedStream.isStreamLike(stream2);
    if (isStreamLike) {
      if (!(stream2 instanceof DelayedStream)) {
        var newStream = DelayedStream.create(stream2, {
          maxDataSize: Infinity,
          pauseStream: this.pauseStreams
        });
        stream2.on("data", this._checkDataSize.bind(this));
        stream2 = newStream;
      }
      this._handleErrors(stream2);
      if (this.pauseStreams) {
        stream2.pause();
      }
    }
    this._streams.push(stream2);
    return this;
  };
  CombinedStream.prototype.pipe = function(dest, options) {
    Stream.prototype.pipe.call(this, dest, options);
    this.resume();
    return dest;
  };
  CombinedStream.prototype._getNext = function() {
    this._currentStream = null;
    if (this._insideLoop) {
      this._pendingNext = true;
      return;
    }
    this._insideLoop = true;
    try {
      do {
        this._pendingNext = false;
        this._realGetNext();
      } while (this._pendingNext);
    } finally {
      this._insideLoop = false;
    }
  };
  CombinedStream.prototype._realGetNext = function() {
    var stream2 = this._streams.shift();
    if (typeof stream2 == "undefined") {
      this.end();
      return;
    }
    if (typeof stream2 !== "function") {
      this._pipeNext(stream2);
      return;
    }
    var getStream = stream2;
    getStream((function(stream3) {
      var isStreamLike = CombinedStream.isStreamLike(stream3);
      if (isStreamLike) {
        stream3.on("data", this._checkDataSize.bind(this));
        this._handleErrors(stream3);
      }
      this._pipeNext(stream3);
    }).bind(this));
  };
  CombinedStream.prototype._pipeNext = function(stream2) {
    this._currentStream = stream2;
    var isStreamLike = CombinedStream.isStreamLike(stream2);
    if (isStreamLike) {
      stream2.on("end", this._getNext.bind(this));
      stream2.pipe(this, { end: false });
      return;
    }
    var value = stream2;
    this.write(value);
    this._getNext();
  };
  CombinedStream.prototype._handleErrors = function(stream2) {
    var self2 = this;
    stream2.on("error", function(err) {
      self2._emitError(err);
    });
  };
  CombinedStream.prototype.write = function(data) {
    this.emit("data", data);
  };
  CombinedStream.prototype.pause = function() {
    if (!this.pauseStreams) {
      return;
    }
    if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") this._currentStream.pause();
    this.emit("pause");
  };
  CombinedStream.prototype.resume = function() {
    if (!this._released) {
      this._released = true;
      this.writable = true;
      this._getNext();
    }
    if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") this._currentStream.resume();
    this.emit("resume");
  };
  CombinedStream.prototype.end = function() {
    this._reset();
    this.emit("end");
  };
  CombinedStream.prototype.destroy = function() {
    this._reset();
    this.emit("close");
  };
  CombinedStream.prototype._reset = function() {
    this.writable = false;
    this._streams = [];
    this._currentStream = null;
  };
  CombinedStream.prototype._checkDataSize = function() {
    this._updateDataSize();
    if (this.dataSize <= this.maxDataSize) {
      return;
    }
    var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded.";
    this._emitError(new Error(message));
  };
  CombinedStream.prototype._updateDataSize = function() {
    this.dataSize = 0;
    var self2 = this;
    this._streams.forEach(function(stream2) {
      if (!stream2.dataSize) {
        return;
      }
      self2.dataSize += stream2.dataSize;
    });
    if (this._currentStream && this._currentStream.dataSize) {
      this.dataSize += this._currentStream.dataSize;
    }
  };
  CombinedStream.prototype._emitError = function(err) {
    this._reset();
    this.emit("error", err);
  };
  return combined_stream;
}
var mimeTypes = {};
const require$$0 = {
  "application/1d-interleaved-parityfec": { "source": "iana" },
  "application/3gpdash-qoe-report+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/3gpp-ims+xml": { "source": "iana", "compressible": true },
  "application/3gpphal+json": { "source": "iana", "compressible": true },
  "application/3gpphalforms+json": { "source": "iana", "compressible": true },
  "application/a2l": { "source": "iana" },
  "application/ace+cbor": { "source": "iana" },
  "application/activemessage": { "source": "iana" },
  "application/activity+json": { "source": "iana", "compressible": true },
  "application/alto-costmap+json": { "source": "iana", "compressible": true },
  "application/alto-costmapfilter+json": { "source": "iana", "compressible": true },
  "application/alto-directory+json": { "source": "iana", "compressible": true },
  "application/alto-endpointcost+json": { "source": "iana", "compressible": true },
  "application/alto-endpointcostparams+json": { "source": "iana", "compressible": true },
  "application/alto-endpointprop+json": { "source": "iana", "compressible": true },
  "application/alto-endpointpropparams+json": { "source": "iana", "compressible": true },
  "application/alto-error+json": { "source": "iana", "compressible": true },
  "application/alto-networkmap+json": { "source": "iana", "compressible": true },
  "application/alto-networkmapfilter+json": { "source": "iana", "compressible": true },
  "application/alto-updatestreamcontrol+json": { "source": "iana", "compressible": true },
  "application/alto-updatestreamparams+json": { "source": "iana", "compressible": true },
  "application/aml": { "source": "iana" },
  "application/andrew-inset": { "source": "iana", "extensions": ["ez"] },
  "application/applefile": { "source": "iana" },
  "application/applixware": { "source": "apache", "extensions": ["aw"] },
  "application/at+jwt": { "source": "iana" },
  "application/atf": { "source": "iana" },
  "application/atfx": { "source": "iana" },
  "application/atom+xml": { "source": "iana", "compressible": true, "extensions": ["atom"] },
  "application/atomcat+xml": { "source": "iana", "compressible": true, "extensions": ["atomcat"] },
  "application/atomdeleted+xml": { "source": "iana", "compressible": true, "extensions": ["atomdeleted"] },
  "application/atomicmail": { "source": "iana" },
  "application/atomsvc+xml": { "source": "iana", "compressible": true, "extensions": ["atomsvc"] },
  "application/atsc-dwd+xml": { "source": "iana", "compressible": true, "extensions": ["dwd"] },
  "application/atsc-dynamic-event-message": { "source": "iana" },
  "application/atsc-held+xml": { "source": "iana", "compressible": true, "extensions": ["held"] },
  "application/atsc-rdt+json": { "source": "iana", "compressible": true },
  "application/atsc-rsat+xml": { "source": "iana", "compressible": true, "extensions": ["rsat"] },
  "application/atxml": { "source": "iana" },
  "application/auth-policy+xml": { "source": "iana", "compressible": true },
  "application/bacnet-xdd+zip": { "source": "iana", "compressible": false },
  "application/batch-smtp": { "source": "iana" },
  "application/bdoc": { "compressible": false, "extensions": ["bdoc"] },
  "application/beep+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/calendar+json": { "source": "iana", "compressible": true },
  "application/calendar+xml": { "source": "iana", "compressible": true, "extensions": ["xcs"] },
  "application/call-completion": { "source": "iana" },
  "application/cals-1840": { "source": "iana" },
  "application/captive+json": { "source": "iana", "compressible": true },
  "application/cbor": { "source": "iana" },
  "application/cbor-seq": { "source": "iana" },
  "application/cccex": { "source": "iana" },
  "application/ccmp+xml": { "source": "iana", "compressible": true },
  "application/ccxml+xml": { "source": "iana", "compressible": true, "extensions": ["ccxml"] },
  "application/cdfx+xml": { "source": "iana", "compressible": true, "extensions": ["cdfx"] },
  "application/cdmi-capability": { "source": "iana", "extensions": ["cdmia"] },
  "application/cdmi-container": { "source": "iana", "extensions": ["cdmic"] },
  "application/cdmi-domain": { "source": "iana", "extensions": ["cdmid"] },
  "application/cdmi-object": { "source": "iana", "extensions": ["cdmio"] },
  "application/cdmi-queue": { "source": "iana", "extensions": ["cdmiq"] },
  "application/cdni": { "source": "iana" },
  "application/cea": { "source": "iana" },
  "application/cea-2018+xml": { "source": "iana", "compressible": true },
  "application/cellml+xml": { "source": "iana", "compressible": true },
  "application/cfw": { "source": "iana" },
  "application/city+json": { "source": "iana", "compressible": true },
  "application/clr": { "source": "iana" },
  "application/clue+xml": { "source": "iana", "compressible": true },
  "application/clue_info+xml": { "source": "iana", "compressible": true },
  "application/cms": { "source": "iana" },
  "application/cnrp+xml": { "source": "iana", "compressible": true },
  "application/coap-group+json": { "source": "iana", "compressible": true },
  "application/coap-payload": { "source": "iana" },
  "application/commonground": { "source": "iana" },
  "application/conference-info+xml": { "source": "iana", "compressible": true },
  "application/cose": { "source": "iana" },
  "application/cose-key": { "source": "iana" },
  "application/cose-key-set": { "source": "iana" },
  "application/cpl+xml": { "source": "iana", "compressible": true, "extensions": ["cpl"] },
  "application/csrattrs": { "source": "iana" },
  "application/csta+xml": { "source": "iana", "compressible": true },
  "application/cstadata+xml": { "source": "iana", "compressible": true },
  "application/csvm+json": { "source": "iana", "compressible": true },
  "application/cu-seeme": { "source": "apache", "extensions": ["cu"] },
  "application/cwt": { "source": "iana" },
  "application/cybercash": { "source": "iana" },
  "application/dart": { "compressible": true },
  "application/dash+xml": { "source": "iana", "compressible": true, "extensions": ["mpd"] },
  "application/dash-patch+xml": { "source": "iana", "compressible": true, "extensions": ["mpp"] },
  "application/dashdelta": { "source": "iana" },
  "application/davmount+xml": { "source": "iana", "compressible": true, "extensions": ["davmount"] },
  "application/dca-rft": { "source": "iana" },
  "application/dcd": { "source": "iana" },
  "application/dec-dx": { "source": "iana" },
  "application/dialog-info+xml": { "source": "iana", "compressible": true },
  "application/dicom": { "source": "iana" },
  "application/dicom+json": { "source": "iana", "compressible": true },
  "application/dicom+xml": { "source": "iana", "compressible": true },
  "application/dii": { "source": "iana" },
  "application/dit": { "source": "iana" },
  "application/dns": { "source": "iana" },
  "application/dns+json": { "source": "iana", "compressible": true },
  "application/dns-message": { "source": "iana" },
  "application/docbook+xml": { "source": "apache", "compressible": true, "extensions": ["dbk"] },
  "application/dots+cbor": { "source": "iana" },
  "application/dskpp+xml": { "source": "iana", "compressible": true },
  "application/dssc+der": { "source": "iana", "extensions": ["dssc"] },
  "application/dssc+xml": { "source": "iana", "compressible": true, "extensions": ["xdssc"] },
  "application/dvcs": { "source": "iana" },
  "application/ecmascript": { "source": "iana", "compressible": true, "extensions": ["es", "ecma"] },
  "application/edi-consent": { "source": "iana" },
  "application/edi-x12": { "source": "iana", "compressible": false },
  "application/edifact": { "source": "iana", "compressible": false },
  "application/efi": { "source": "iana" },
  "application/elm+json": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/elm+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.cap+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/emergencycalldata.comment+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.control+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.deviceinfo+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.ecall.msd": { "source": "iana" },
  "application/emergencycalldata.providerinfo+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.serviceinfo+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.subscriberinfo+xml": { "source": "iana", "compressible": true },
  "application/emergencycalldata.veds+xml": { "source": "iana", "compressible": true },
  "application/emma+xml": { "source": "iana", "compressible": true, "extensions": ["emma"] },
  "application/emotionml+xml": { "source": "iana", "compressible": true, "extensions": ["emotionml"] },
  "application/encaprtp": { "source": "iana" },
  "application/epp+xml": { "source": "iana", "compressible": true },
  "application/epub+zip": { "source": "iana", "compressible": false, "extensions": ["epub"] },
  "application/eshop": { "source": "iana" },
  "application/exi": { "source": "iana", "extensions": ["exi"] },
  "application/expect-ct-report+json": { "source": "iana", "compressible": true },
  "application/express": { "source": "iana", "extensions": ["exp"] },
  "application/fastinfoset": { "source": "iana" },
  "application/fastsoap": { "source": "iana" },
  "application/fdt+xml": { "source": "iana", "compressible": true, "extensions": ["fdt"] },
  "application/fhir+json": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/fhir+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/fido.trusted-apps+json": { "compressible": true },
  "application/fits": { "source": "iana" },
  "application/flexfec": { "source": "iana" },
  "application/font-sfnt": { "source": "iana" },
  "application/font-tdpfr": { "source": "iana", "extensions": ["pfr"] },
  "application/font-woff": { "source": "iana", "compressible": false },
  "application/framework-attributes+xml": { "source": "iana", "compressible": true },
  "application/geo+json": { "source": "iana", "compressible": true, "extensions": ["geojson"] },
  "application/geo+json-seq": { "source": "iana" },
  "application/geopackage+sqlite3": { "source": "iana" },
  "application/geoxacml+xml": { "source": "iana", "compressible": true },
  "application/gltf-buffer": { "source": "iana" },
  "application/gml+xml": { "source": "iana", "compressible": true, "extensions": ["gml"] },
  "application/gpx+xml": { "source": "apache", "compressible": true, "extensions": ["gpx"] },
  "application/gxf": { "source": "apache", "extensions": ["gxf"] },
  "application/gzip": { "source": "iana", "compressible": false, "extensions": ["gz"] },
  "application/h224": { "source": "iana" },
  "application/held+xml": { "source": "iana", "compressible": true },
  "application/hjson": { "extensions": ["hjson"] },
  "application/http": { "source": "iana" },
  "application/hyperstudio": { "source": "iana", "extensions": ["stk"] },
  "application/ibe-key-request+xml": { "source": "iana", "compressible": true },
  "application/ibe-pkg-reply+xml": { "source": "iana", "compressible": true },
  "application/ibe-pp-data": { "source": "iana" },
  "application/iges": { "source": "iana" },
  "application/im-iscomposing+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/index": { "source": "iana" },
  "application/index.cmd": { "source": "iana" },
  "application/index.obj": { "source": "iana" },
  "application/index.response": { "source": "iana" },
  "application/index.vnd": { "source": "iana" },
  "application/inkml+xml": { "source": "iana", "compressible": true, "extensions": ["ink", "inkml"] },
  "application/iotp": { "source": "iana" },
  "application/ipfix": { "source": "iana", "extensions": ["ipfix"] },
  "application/ipp": { "source": "iana" },
  "application/isup": { "source": "iana" },
  "application/its+xml": { "source": "iana", "compressible": true, "extensions": ["its"] },
  "application/java-archive": { "source": "apache", "compressible": false, "extensions": ["jar", "war", "ear"] },
  "application/java-serialized-object": { "source": "apache", "compressible": false, "extensions": ["ser"] },
  "application/java-vm": { "source": "apache", "compressible": false, "extensions": ["class"] },
  "application/javascript": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["js", "mjs"] },
  "application/jf2feed+json": { "source": "iana", "compressible": true },
  "application/jose": { "source": "iana" },
  "application/jose+json": { "source": "iana", "compressible": true },
  "application/jrd+json": { "source": "iana", "compressible": true },
  "application/jscalendar+json": { "source": "iana", "compressible": true },
  "application/json": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["json", "map"] },
  "application/json-patch+json": { "source": "iana", "compressible": true },
  "application/json-seq": { "source": "iana" },
  "application/json5": { "extensions": ["json5"] },
  "application/jsonml+json": { "source": "apache", "compressible": true, "extensions": ["jsonml"] },
  "application/jwk+json": { "source": "iana", "compressible": true },
  "application/jwk-set+json": { "source": "iana", "compressible": true },
  "application/jwt": { "source": "iana" },
  "application/kpml-request+xml": { "source": "iana", "compressible": true },
  "application/kpml-response+xml": { "source": "iana", "compressible": true },
  "application/ld+json": { "source": "iana", "compressible": true, "extensions": ["jsonld"] },
  "application/lgr+xml": { "source": "iana", "compressible": true, "extensions": ["lgr"] },
  "application/link-format": { "source": "iana" },
  "application/load-control+xml": { "source": "iana", "compressible": true },
  "application/lost+xml": { "source": "iana", "compressible": true, "extensions": ["lostxml"] },
  "application/lostsync+xml": { "source": "iana", "compressible": true },
  "application/lpf+zip": { "source": "iana", "compressible": false },
  "application/lxf": { "source": "iana" },
  "application/mac-binhex40": { "source": "iana", "extensions": ["hqx"] },
  "application/mac-compactpro": { "source": "apache", "extensions": ["cpt"] },
  "application/macwriteii": { "source": "iana" },
  "application/mads+xml": { "source": "iana", "compressible": true, "extensions": ["mads"] },
  "application/manifest+json": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["webmanifest"] },
  "application/marc": { "source": "iana", "extensions": ["mrc"] },
  "application/marcxml+xml": { "source": "iana", "compressible": true, "extensions": ["mrcx"] },
  "application/mathematica": { "source": "iana", "extensions": ["ma", "nb", "mb"] },
  "application/mathml+xml": { "source": "iana", "compressible": true, "extensions": ["mathml"] },
  "application/mathml-content+xml": { "source": "iana", "compressible": true },
  "application/mathml-presentation+xml": { "source": "iana", "compressible": true },
  "application/mbms-associated-procedure-description+xml": { "source": "iana", "compressible": true },
  "application/mbms-deregister+xml": { "source": "iana", "compressible": true },
  "application/mbms-envelope+xml": { "source": "iana", "compressible": true },
  "application/mbms-msk+xml": { "source": "iana", "compressible": true },
  "application/mbms-msk-response+xml": { "source": "iana", "compressible": true },
  "application/mbms-protection-description+xml": { "source": "iana", "compressible": true },
  "application/mbms-reception-report+xml": { "source": "iana", "compressible": true },
  "application/mbms-register+xml": { "source": "iana", "compressible": true },
  "application/mbms-register-response+xml": { "source": "iana", "compressible": true },
  "application/mbms-schedule+xml": { "source": "iana", "compressible": true },
  "application/mbms-user-service-description+xml": { "source": "iana", "compressible": true },
  "application/mbox": { "source": "iana", "extensions": ["mbox"] },
  "application/media-policy-dataset+xml": { "source": "iana", "compressible": true, "extensions": ["mpf"] },
  "application/media_control+xml": { "source": "iana", "compressible": true },
  "application/mediaservercontrol+xml": { "source": "iana", "compressible": true, "extensions": ["mscml"] },
  "application/merge-patch+json": { "source": "iana", "compressible": true },
  "application/metalink+xml": { "source": "apache", "compressible": true, "extensions": ["metalink"] },
  "application/metalink4+xml": { "source": "iana", "compressible": true, "extensions": ["meta4"] },
  "application/mets+xml": { "source": "iana", "compressible": true, "extensions": ["mets"] },
  "application/mf4": { "source": "iana" },
  "application/mikey": { "source": "iana" },
  "application/mipc": { "source": "iana" },
  "application/missing-blocks+cbor-seq": { "source": "iana" },
  "application/mmt-aei+xml": { "source": "iana", "compressible": true, "extensions": ["maei"] },
  "application/mmt-usd+xml": { "source": "iana", "compressible": true, "extensions": ["musd"] },
  "application/mods+xml": { "source": "iana", "compressible": true, "extensions": ["mods"] },
  "application/moss-keys": { "source": "iana" },
  "application/moss-signature": { "source": "iana" },
  "application/mosskey-data": { "source": "iana" },
  "application/mosskey-request": { "source": "iana" },
  "application/mp21": { "source": "iana", "extensions": ["m21", "mp21"] },
  "application/mp4": { "source": "iana", "extensions": ["mp4s", "m4p"] },
  "application/mpeg4-generic": { "source": "iana" },
  "application/mpeg4-iod": { "source": "iana" },
  "application/mpeg4-iod-xmt": { "source": "iana" },
  "application/mrb-consumer+xml": { "source": "iana", "compressible": true },
  "application/mrb-publish+xml": { "source": "iana", "compressible": true },
  "application/msc-ivr+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/msc-mixer+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/msword": { "source": "iana", "compressible": false, "extensions": ["doc", "dot"] },
  "application/mud+json": { "source": "iana", "compressible": true },
  "application/multipart-core": { "source": "iana" },
  "application/mxf": { "source": "iana", "extensions": ["mxf"] },
  "application/n-quads": { "source": "iana", "extensions": ["nq"] },
  "application/n-triples": { "source": "iana", "extensions": ["nt"] },
  "application/nasdata": { "source": "iana" },
  "application/news-checkgroups": { "source": "iana", "charset": "US-ASCII" },
  "application/news-groupinfo": { "source": "iana", "charset": "US-ASCII" },
  "application/news-transmission": { "source": "iana" },
  "application/nlsml+xml": { "source": "iana", "compressible": true },
  "application/node": { "source": "iana", "extensions": ["cjs"] },
  "application/nss": { "source": "iana" },
  "application/oauth-authz-req+jwt": { "source": "iana" },
  "application/oblivious-dns-message": { "source": "iana" },
  "application/ocsp-request": { "source": "iana" },
  "application/ocsp-response": { "source": "iana" },
  "application/octet-stream": { "source": "iana", "compressible": false, "extensions": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"] },
  "application/oda": { "source": "iana", "extensions": ["oda"] },
  "application/odm+xml": { "source": "iana", "compressible": true },
  "application/odx": { "source": "iana" },
  "application/oebps-package+xml": { "source": "iana", "compressible": true, "extensions": ["opf"] },
  "application/ogg": { "source": "iana", "compressible": false, "extensions": ["ogx"] },
  "application/omdoc+xml": { "source": "apache", "compressible": true, "extensions": ["omdoc"] },
  "application/onenote": { "source": "apache", "extensions": ["onetoc", "onetoc2", "onetmp", "onepkg"] },
  "application/opc-nodeset+xml": { "source": "iana", "compressible": true },
  "application/oscore": { "source": "iana" },
  "application/oxps": { "source": "iana", "extensions": ["oxps"] },
  "application/p21": { "source": "iana" },
  "application/p21+zip": { "source": "iana", "compressible": false },
  "application/p2p-overlay+xml": { "source": "iana", "compressible": true, "extensions": ["relo"] },
  "application/parityfec": { "source": "iana" },
  "application/passport": { "source": "iana" },
  "application/patch-ops-error+xml": { "source": "iana", "compressible": true, "extensions": ["xer"] },
  "application/pdf": { "source": "iana", "compressible": false, "extensions": ["pdf"] },
  "application/pdx": { "source": "iana" },
  "application/pem-certificate-chain": { "source": "iana" },
  "application/pgp-encrypted": { "source": "iana", "compressible": false, "extensions": ["pgp"] },
  "application/pgp-keys": { "source": "iana", "extensions": ["asc"] },
  "application/pgp-signature": { "source": "iana", "extensions": ["asc", "sig"] },
  "application/pics-rules": { "source": "apache", "extensions": ["prf"] },
  "application/pidf+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/pidf-diff+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/pkcs10": { "source": "iana", "extensions": ["p10"] },
  "application/pkcs12": { "source": "iana" },
  "application/pkcs7-mime": { "source": "iana", "extensions": ["p7m", "p7c"] },
  "application/pkcs7-signature": { "source": "iana", "extensions": ["p7s"] },
  "application/pkcs8": { "source": "iana", "extensions": ["p8"] },
  "application/pkcs8-encrypted": { "source": "iana" },
  "application/pkix-attr-cert": { "source": "iana", "extensions": ["ac"] },
  "application/pkix-cert": { "source": "iana", "extensions": ["cer"] },
  "application/pkix-crl": { "source": "iana", "extensions": ["crl"] },
  "application/pkix-pkipath": { "source": "iana", "extensions": ["pkipath"] },
  "application/pkixcmp": { "source": "iana", "extensions": ["pki"] },
  "application/pls+xml": { "source": "iana", "compressible": true, "extensions": ["pls"] },
  "application/poc-settings+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/postscript": { "source": "iana", "compressible": true, "extensions": ["ai", "eps", "ps"] },
  "application/ppsp-tracker+json": { "source": "iana", "compressible": true },
  "application/problem+json": { "source": "iana", "compressible": true },
  "application/problem+xml": { "source": "iana", "compressible": true },
  "application/provenance+xml": { "source": "iana", "compressible": true, "extensions": ["provx"] },
  "application/prs.alvestrand.titrax-sheet": { "source": "iana" },
  "application/prs.cww": { "source": "iana", "extensions": ["cww"] },
  "application/prs.cyn": { "source": "iana", "charset": "7-BIT" },
  "application/prs.hpub+zip": { "source": "iana", "compressible": false },
  "application/prs.nprend": { "source": "iana" },
  "application/prs.plucker": { "source": "iana" },
  "application/prs.rdf-xml-crypt": { "source": "iana" },
  "application/prs.xsf+xml": { "source": "iana", "compressible": true },
  "application/pskc+xml": { "source": "iana", "compressible": true, "extensions": ["pskcxml"] },
  "application/pvd+json": { "source": "iana", "compressible": true },
  "application/qsig": { "source": "iana" },
  "application/raml+yaml": { "compressible": true, "extensions": ["raml"] },
  "application/raptorfec": { "source": "iana" },
  "application/rdap+json": { "source": "iana", "compressible": true },
  "application/rdf+xml": { "source": "iana", "compressible": true, "extensions": ["rdf", "owl"] },
  "application/reginfo+xml": { "source": "iana", "compressible": true, "extensions": ["rif"] },
  "application/relax-ng-compact-syntax": { "source": "iana", "extensions": ["rnc"] },
  "application/remote-printing": { "source": "iana" },
  "application/reputon+json": { "source": "iana", "compressible": true },
  "application/resource-lists+xml": { "source": "iana", "compressible": true, "extensions": ["rl"] },
  "application/resource-lists-diff+xml": { "source": "iana", "compressible": true, "extensions": ["rld"] },
  "application/rfc+xml": { "source": "iana", "compressible": true },
  "application/riscos": { "source": "iana" },
  "application/rlmi+xml": { "source": "iana", "compressible": true },
  "application/rls-services+xml": { "source": "iana", "compressible": true, "extensions": ["rs"] },
  "application/route-apd+xml": { "source": "iana", "compressible": true, "extensions": ["rapd"] },
  "application/route-s-tsid+xml": { "source": "iana", "compressible": true, "extensions": ["sls"] },
  "application/route-usd+xml": { "source": "iana", "compressible": true, "extensions": ["rusd"] },
  "application/rpki-ghostbusters": { "source": "iana", "extensions": ["gbr"] },
  "application/rpki-manifest": { "source": "iana", "extensions": ["mft"] },
  "application/rpki-publication": { "source": "iana" },
  "application/rpki-roa": { "source": "iana", "extensions": ["roa"] },
  "application/rpki-updown": { "source": "iana" },
  "application/rsd+xml": { "source": "apache", "compressible": true, "extensions": ["rsd"] },
  "application/rss+xml": { "source": "apache", "compressible": true, "extensions": ["rss"] },
  "application/rtf": { "source": "iana", "compressible": true, "extensions": ["rtf"] },
  "application/rtploopback": { "source": "iana" },
  "application/rtx": { "source": "iana" },
  "application/samlassertion+xml": { "source": "iana", "compressible": true },
  "application/samlmetadata+xml": { "source": "iana", "compressible": true },
  "application/sarif+json": { "source": "iana", "compressible": true },
  "application/sarif-external-properties+json": { "source": "iana", "compressible": true },
  "application/sbe": { "source": "iana" },
  "application/sbml+xml": { "source": "iana", "compressible": true, "extensions": ["sbml"] },
  "application/scaip+xml": { "source": "iana", "compressible": true },
  "application/scim+json": { "source": "iana", "compressible": true },
  "application/scvp-cv-request": { "source": "iana", "extensions": ["scq"] },
  "application/scvp-cv-response": { "source": "iana", "extensions": ["scs"] },
  "application/scvp-vp-request": { "source": "iana", "extensions": ["spq"] },
  "application/scvp-vp-response": { "source": "iana", "extensions": ["spp"] },
  "application/sdp": { "source": "iana", "extensions": ["sdp"] },
  "application/secevent+jwt": { "source": "iana" },
  "application/senml+cbor": { "source": "iana" },
  "application/senml+json": { "source": "iana", "compressible": true },
  "application/senml+xml": { "source": "iana", "compressible": true, "extensions": ["senmlx"] },
  "application/senml-etch+cbor": { "source": "iana" },
  "application/senml-etch+json": { "source": "iana", "compressible": true },
  "application/senml-exi": { "source": "iana" },
  "application/sensml+cbor": { "source": "iana" },
  "application/sensml+json": { "source": "iana", "compressible": true },
  "application/sensml+xml": { "source": "iana", "compressible": true, "extensions": ["sensmlx"] },
  "application/sensml-exi": { "source": "iana" },
  "application/sep+xml": { "source": "iana", "compressible": true },
  "application/sep-exi": { "source": "iana" },
  "application/session-info": { "source": "iana" },
  "application/set-payment": { "source": "iana" },
  "application/set-payment-initiation": { "source": "iana", "extensions": ["setpay"] },
  "application/set-registration": { "source": "iana" },
  "application/set-registration-initiation": { "source": "iana", "extensions": ["setreg"] },
  "application/sgml": { "source": "iana" },
  "application/sgml-open-catalog": { "source": "iana" },
  "application/shf+xml": { "source": "iana", "compressible": true, "extensions": ["shf"] },
  "application/sieve": { "source": "iana", "extensions": ["siv", "sieve"] },
  "application/simple-filter+xml": { "source": "iana", "compressible": true },
  "application/simple-message-summary": { "source": "iana" },
  "application/simplesymbolcontainer": { "source": "iana" },
  "application/sipc": { "source": "iana" },
  "application/slate": { "source": "iana" },
  "application/smil": { "source": "iana" },
  "application/smil+xml": { "source": "iana", "compressible": true, "extensions": ["smi", "smil"] },
  "application/smpte336m": { "source": "iana" },
  "application/soap+fastinfoset": { "source": "iana" },
  "application/soap+xml": { "source": "iana", "compressible": true },
  "application/sparql-query": { "source": "iana", "extensions": ["rq"] },
  "application/sparql-results+xml": { "source": "iana", "compressible": true, "extensions": ["srx"] },
  "application/spdx+json": { "source": "iana", "compressible": true },
  "application/spirits-event+xml": { "source": "iana", "compressible": true },
  "application/sql": { "source": "iana" },
  "application/srgs": { "source": "iana", "extensions": ["gram"] },
  "application/srgs+xml": { "source": "iana", "compressible": true, "extensions": ["grxml"] },
  "application/sru+xml": { "source": "iana", "compressible": true, "extensions": ["sru"] },
  "application/ssdl+xml": { "source": "apache", "compressible": true, "extensions": ["ssdl"] },
  "application/ssml+xml": { "source": "iana", "compressible": true, "extensions": ["ssml"] },
  "application/stix+json": { "source": "iana", "compressible": true },
  "application/swid+xml": { "source": "iana", "compressible": true, "extensions": ["swidtag"] },
  "application/tamp-apex-update": { "source": "iana" },
  "application/tamp-apex-update-confirm": { "source": "iana" },
  "application/tamp-community-update": { "source": "iana" },
  "application/tamp-community-update-confirm": { "source": "iana" },
  "application/tamp-error": { "source": "iana" },
  "application/tamp-sequence-adjust": { "source": "iana" },
  "application/tamp-sequence-adjust-confirm": { "source": "iana" },
  "application/tamp-status-query": { "source": "iana" },
  "application/tamp-status-response": { "source": "iana" },
  "application/tamp-update": { "source": "iana" },
  "application/tamp-update-confirm": { "source": "iana" },
  "application/tar": { "compressible": true },
  "application/taxii+json": { "source": "iana", "compressible": true },
  "application/td+json": { "source": "iana", "compressible": true },
  "application/tei+xml": { "source": "iana", "compressible": true, "extensions": ["tei", "teicorpus"] },
  "application/tetra_isi": { "source": "iana" },
  "application/thraud+xml": { "source": "iana", "compressible": true, "extensions": ["tfi"] },
  "application/timestamp-query": { "source": "iana" },
  "application/timestamp-reply": { "source": "iana" },
  "application/timestamped-data": { "source": "iana", "extensions": ["tsd"] },
  "application/tlsrpt+gzip": { "source": "iana" },
  "application/tlsrpt+json": { "source": "iana", "compressible": true },
  "application/tnauthlist": { "source": "iana" },
  "application/token-introspection+jwt": { "source": "iana" },
  "application/toml": { "compressible": true, "extensions": ["toml"] },
  "application/trickle-ice-sdpfrag": { "source": "iana" },
  "application/trig": { "source": "iana", "extensions": ["trig"] },
  "application/ttml+xml": { "source": "iana", "compressible": true, "extensions": ["ttml"] },
  "application/tve-trigger": { "source": "iana" },
  "application/tzif": { "source": "iana" },
  "application/tzif-leap": { "source": "iana" },
  "application/ubjson": { "compressible": false, "extensions": ["ubj"] },
  "application/ulpfec": { "source": "iana" },
  "application/urc-grpsheet+xml": { "source": "iana", "compressible": true },
  "application/urc-ressheet+xml": { "source": "iana", "compressible": true, "extensions": ["rsheet"] },
  "application/urc-targetdesc+xml": { "source": "iana", "compressible": true, "extensions": ["td"] },
  "application/urc-uisocketdesc+xml": { "source": "iana", "compressible": true },
  "application/vcard+json": { "source": "iana", "compressible": true },
  "application/vcard+xml": { "source": "iana", "compressible": true },
  "application/vemmi": { "source": "iana" },
  "application/vividence.scriptfile": { "source": "apache" },
  "application/vnd.1000minds.decision-model+xml": { "source": "iana", "compressible": true, "extensions": ["1km"] },
  "application/vnd.3gpp-prose+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp-prose-pc3ch+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp-v2x-local-service-information": { "source": "iana" },
  "application/vnd.3gpp.5gnas": { "source": "iana" },
  "application/vnd.3gpp.access-transfer-events+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.bsf+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.gmop+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.gtpc": { "source": "iana" },
  "application/vnd.3gpp.interworking-data": { "source": "iana" },
  "application/vnd.3gpp.lpp": { "source": "iana" },
  "application/vnd.3gpp.mc-signalling-ear": { "source": "iana" },
  "application/vnd.3gpp.mcdata-affiliation-command+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcdata-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcdata-payload": { "source": "iana" },
  "application/vnd.3gpp.mcdata-service-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcdata-signalling": { "source": "iana" },
  "application/vnd.3gpp.mcdata-ue-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcdata-user-profile+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-affiliation-command+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-floor-request+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-location-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-service-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-signed+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-ue-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-ue-init-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcptt-user-profile+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-affiliation-command+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-affiliation-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-location-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-service-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-transmission-request+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-ue-config+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mcvideo-user-profile+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.mid-call+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.ngap": { "source": "iana" },
  "application/vnd.3gpp.pfcp": { "source": "iana" },
  "application/vnd.3gpp.pic-bw-large": { "source": "iana", "extensions": ["plb"] },
  "application/vnd.3gpp.pic-bw-small": { "source": "iana", "extensions": ["psb"] },
  "application/vnd.3gpp.pic-bw-var": { "source": "iana", "extensions": ["pvb"] },
  "application/vnd.3gpp.s1ap": { "source": "iana" },
  "application/vnd.3gpp.sms": { "source": "iana" },
  "application/vnd.3gpp.sms+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.srvcc-ext+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.srvcc-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.state-and-event-info+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp.ussd+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp2.bcmcsinfo+xml": { "source": "iana", "compressible": true },
  "application/vnd.3gpp2.sms": { "source": "iana" },
  "application/vnd.3gpp2.tcap": { "source": "iana", "extensions": ["tcap"] },
  "application/vnd.3lightssoftware.imagescal": { "source": "iana" },
  "application/vnd.3m.post-it-notes": { "source": "iana", "extensions": ["pwn"] },
  "application/vnd.accpac.simply.aso": { "source": "iana", "extensions": ["aso"] },
  "application/vnd.accpac.simply.imp": { "source": "iana", "extensions": ["imp"] },
  "application/vnd.acucobol": { "source": "iana", "extensions": ["acu"] },
  "application/vnd.acucorp": { "source": "iana", "extensions": ["atc", "acutc"] },
  "application/vnd.adobe.air-application-installer-package+zip": { "source": "apache", "compressible": false, "extensions": ["air"] },
  "application/vnd.adobe.flash.movie": { "source": "iana" },
  "application/vnd.adobe.formscentral.fcdt": { "source": "iana", "extensions": ["fcdt"] },
  "application/vnd.adobe.fxp": { "source": "iana", "extensions": ["fxp", "fxpl"] },
  "application/vnd.adobe.partial-upload": { "source": "iana" },
  "application/vnd.adobe.xdp+xml": { "source": "iana", "compressible": true, "extensions": ["xdp"] },
  "application/vnd.adobe.xfdf": { "source": "iana", "extensions": ["xfdf"] },
  "application/vnd.aether.imp": { "source": "iana" },
  "application/vnd.afpc.afplinedata": { "source": "iana" },
  "application/vnd.afpc.afplinedata-pagedef": { "source": "iana" },
  "application/vnd.afpc.cmoca-cmresource": { "source": "iana" },
  "application/vnd.afpc.foca-charset": { "source": "iana" },
  "application/vnd.afpc.foca-codedfont": { "source": "iana" },
  "application/vnd.afpc.foca-codepage": { "source": "iana" },
  "application/vnd.afpc.modca": { "source": "iana" },
  "application/vnd.afpc.modca-cmtable": { "source": "iana" },
  "application/vnd.afpc.modca-formdef": { "source": "iana" },
  "application/vnd.afpc.modca-mediummap": { "source": "iana" },
  "application/vnd.afpc.modca-objectcontainer": { "source": "iana" },
  "application/vnd.afpc.modca-overlay": { "source": "iana" },
  "application/vnd.afpc.modca-pagesegment": { "source": "iana" },
  "application/vnd.age": { "source": "iana", "extensions": ["age"] },
  "application/vnd.ah-barcode": { "source": "iana" },
  "application/vnd.ahead.space": { "source": "iana", "extensions": ["ahead"] },
  "application/vnd.airzip.filesecure.azf": { "source": "iana", "extensions": ["azf"] },
  "application/vnd.airzip.filesecure.azs": { "source": "iana", "extensions": ["azs"] },
  "application/vnd.amadeus+json": { "source": "iana", "compressible": true },
  "application/vnd.amazon.ebook": { "source": "apache", "extensions": ["azw"] },
  "application/vnd.amazon.mobi8-ebook": { "source": "iana" },
  "application/vnd.americandynamics.acc": { "source": "iana", "extensions": ["acc"] },
  "application/vnd.amiga.ami": { "source": "iana", "extensions": ["ami"] },
  "application/vnd.amundsen.maze+xml": { "source": "iana", "compressible": true },
  "application/vnd.android.ota": { "source": "iana" },
  "application/vnd.android.package-archive": { "source": "apache", "compressible": false, "extensions": ["apk"] },
  "application/vnd.anki": { "source": "iana" },
  "application/vnd.anser-web-certificate-issue-initiation": { "source": "iana", "extensions": ["cii"] },
  "application/vnd.anser-web-funds-transfer-initiation": { "source": "apache", "extensions": ["fti"] },
  "application/vnd.antix.game-component": { "source": "iana", "extensions": ["atx"] },
  "application/vnd.apache.arrow.file": { "source": "iana" },
  "application/vnd.apache.arrow.stream": { "source": "iana" },
  "application/vnd.apache.thrift.binary": { "source": "iana" },
  "application/vnd.apache.thrift.compact": { "source": "iana" },
  "application/vnd.apache.thrift.json": { "source": "iana" },
  "application/vnd.api+json": { "source": "iana", "compressible": true },
  "application/vnd.aplextor.warrp+json": { "source": "iana", "compressible": true },
  "application/vnd.apothekende.reservation+json": { "source": "iana", "compressible": true },
  "application/vnd.apple.installer+xml": { "source": "iana", "compressible": true, "extensions": ["mpkg"] },
  "application/vnd.apple.keynote": { "source": "iana", "extensions": ["key"] },
  "application/vnd.apple.mpegurl": { "source": "iana", "extensions": ["m3u8"] },
  "application/vnd.apple.numbers": { "source": "iana", "extensions": ["numbers"] },
  "application/vnd.apple.pages": { "source": "iana", "extensions": ["pages"] },
  "application/vnd.apple.pkpass": { "compressible": false, "extensions": ["pkpass"] },
  "application/vnd.arastra.swi": { "source": "iana" },
  "application/vnd.aristanetworks.swi": { "source": "iana", "extensions": ["swi"] },
  "application/vnd.artisan+json": { "source": "iana", "compressible": true },
  "application/vnd.artsquare": { "source": "iana" },
  "application/vnd.astraea-software.iota": { "source": "iana", "extensions": ["iota"] },
  "application/vnd.audiograph": { "source": "iana", "extensions": ["aep"] },
  "application/vnd.autopackage": { "source": "iana" },
  "application/vnd.avalon+json": { "source": "iana", "compressible": true },
  "application/vnd.avistar+xml": { "source": "iana", "compressible": true },
  "application/vnd.balsamiq.bmml+xml": { "source": "iana", "compressible": true, "extensions": ["bmml"] },
  "application/vnd.balsamiq.bmpr": { "source": "iana" },
  "application/vnd.banana-accounting": { "source": "iana" },
  "application/vnd.bbf.usp.error": { "source": "iana" },
  "application/vnd.bbf.usp.msg": { "source": "iana" },
  "application/vnd.bbf.usp.msg+json": { "source": "iana", "compressible": true },
  "application/vnd.bekitzur-stech+json": { "source": "iana", "compressible": true },
  "application/vnd.bint.med-content": { "source": "iana" },
  "application/vnd.biopax.rdf+xml": { "source": "iana", "compressible": true },
  "application/vnd.blink-idb-value-wrapper": { "source": "iana" },
  "application/vnd.blueice.multipass": { "source": "iana", "extensions": ["mpm"] },
  "application/vnd.bluetooth.ep.oob": { "source": "iana" },
  "application/vnd.bluetooth.le.oob": { "source": "iana" },
  "application/vnd.bmi": { "source": "iana", "extensions": ["bmi"] },
  "application/vnd.bpf": { "source": "iana" },
  "application/vnd.bpf3": { "source": "iana" },
  "application/vnd.businessobjects": { "source": "iana", "extensions": ["rep"] },
  "application/vnd.byu.uapi+json": { "source": "iana", "compressible": true },
  "application/vnd.cab-jscript": { "source": "iana" },
  "application/vnd.canon-cpdl": { "source": "iana" },
  "application/vnd.canon-lips": { "source": "iana" },
  "application/vnd.capasystems-pg+json": { "source": "iana", "compressible": true },
  "application/vnd.cendio.thinlinc.clientconf": { "source": "iana" },
  "application/vnd.century-systems.tcp_stream": { "source": "iana" },
  "application/vnd.chemdraw+xml": { "source": "iana", "compressible": true, "extensions": ["cdxml"] },
  "application/vnd.chess-pgn": { "source": "iana" },
  "application/vnd.chipnuts.karaoke-mmd": { "source": "iana", "extensions": ["mmd"] },
  "application/vnd.ciedi": { "source": "iana" },
  "application/vnd.cinderella": { "source": "iana", "extensions": ["cdy"] },
  "application/vnd.cirpack.isdn-ext": { "source": "iana" },
  "application/vnd.citationstyles.style+xml": { "source": "iana", "compressible": true, "extensions": ["csl"] },
  "application/vnd.claymore": { "source": "iana", "extensions": ["cla"] },
  "application/vnd.cloanto.rp9": { "source": "iana", "extensions": ["rp9"] },
  "application/vnd.clonk.c4group": { "source": "iana", "extensions": ["c4g", "c4d", "c4f", "c4p", "c4u"] },
  "application/vnd.cluetrust.cartomobile-config": { "source": "iana", "extensions": ["c11amc"] },
  "application/vnd.cluetrust.cartomobile-config-pkg": { "source": "iana", "extensions": ["c11amz"] },
  "application/vnd.coffeescript": { "source": "iana" },
  "application/vnd.collabio.xodocuments.document": { "source": "iana" },
  "application/vnd.collabio.xodocuments.document-template": { "source": "iana" },
  "application/vnd.collabio.xodocuments.presentation": { "source": "iana" },
  "application/vnd.collabio.xodocuments.presentation-template": { "source": "iana" },
  "application/vnd.collabio.xodocuments.spreadsheet": { "source": "iana" },
  "application/vnd.collabio.xodocuments.spreadsheet-template": { "source": "iana" },
  "application/vnd.collection+json": { "source": "iana", "compressible": true },
  "application/vnd.collection.doc+json": { "source": "iana", "compressible": true },
  "application/vnd.collection.next+json": { "source": "iana", "compressible": true },
  "application/vnd.comicbook+zip": { "source": "iana", "compressible": false },
  "application/vnd.comicbook-rar": { "source": "iana" },
  "application/vnd.commerce-battelle": { "source": "iana" },
  "application/vnd.commonspace": { "source": "iana", "extensions": ["csp"] },
  "application/vnd.contact.cmsg": { "source": "iana", "extensions": ["cdbcmsg"] },
  "application/vnd.coreos.ignition+json": { "source": "iana", "compressible": true },
  "application/vnd.cosmocaller": { "source": "iana", "extensions": ["cmc"] },
  "application/vnd.crick.clicker": { "source": "iana", "extensions": ["clkx"] },
  "application/vnd.crick.clicker.keyboard": { "source": "iana", "extensions": ["clkk"] },
  "application/vnd.crick.clicker.palette": { "source": "iana", "extensions": ["clkp"] },
  "application/vnd.crick.clicker.template": { "source": "iana", "extensions": ["clkt"] },
  "application/vnd.crick.clicker.wordbank": { "source": "iana", "extensions": ["clkw"] },
  "application/vnd.criticaltools.wbs+xml": { "source": "iana", "compressible": true, "extensions": ["wbs"] },
  "application/vnd.cryptii.pipe+json": { "source": "iana", "compressible": true },
  "application/vnd.crypto-shade-file": { "source": "iana" },
  "application/vnd.cryptomator.encrypted": { "source": "iana" },
  "application/vnd.cryptomator.vault": { "source": "iana" },
  "application/vnd.ctc-posml": { "source": "iana", "extensions": ["pml"] },
  "application/vnd.ctct.ws+xml": { "source": "iana", "compressible": true },
  "application/vnd.cups-pdf": { "source": "iana" },
  "application/vnd.cups-postscript": { "source": "iana" },
  "application/vnd.cups-ppd": { "source": "iana", "extensions": ["ppd"] },
  "application/vnd.cups-raster": { "source": "iana" },
  "application/vnd.cups-raw": { "source": "iana" },
  "application/vnd.curl": { "source": "iana" },
  "application/vnd.curl.car": { "source": "apache", "extensions": ["car"] },
  "application/vnd.curl.pcurl": { "source": "apache", "extensions": ["pcurl"] },
  "application/vnd.cyan.dean.root+xml": { "source": "iana", "compressible": true },
  "application/vnd.cybank": { "source": "iana" },
  "application/vnd.cyclonedx+json": { "source": "iana", "compressible": true },
  "application/vnd.cyclonedx+xml": { "source": "iana", "compressible": true },
  "application/vnd.d2l.coursepackage1p0+zip": { "source": "iana", "compressible": false },
  "application/vnd.d3m-dataset": { "source": "iana" },
  "application/vnd.d3m-problem": { "source": "iana" },
  "application/vnd.dart": { "source": "iana", "compressible": true, "extensions": ["dart"] },
  "application/vnd.data-vision.rdz": { "source": "iana", "extensions": ["rdz"] },
  "application/vnd.datapackage+json": { "source": "iana", "compressible": true },
  "application/vnd.dataresource+json": { "source": "iana", "compressible": true },
  "application/vnd.dbf": { "source": "iana", "extensions": ["dbf"] },
  "application/vnd.debian.binary-package": { "source": "iana" },
  "application/vnd.dece.data": { "source": "iana", "extensions": ["uvf", "uvvf", "uvd", "uvvd"] },
  "application/vnd.dece.ttml+xml": { "source": "iana", "compressible": true, "extensions": ["uvt", "uvvt"] },
  "application/vnd.dece.unspecified": { "source": "iana", "extensions": ["uvx", "uvvx"] },
  "application/vnd.dece.zip": { "source": "iana", "extensions": ["uvz", "uvvz"] },
  "application/vnd.denovo.fcselayout-link": { "source": "iana", "extensions": ["fe_launch"] },
  "application/vnd.desmume.movie": { "source": "iana" },
  "application/vnd.dir-bi.plate-dl-nosuffix": { "source": "iana" },
  "application/vnd.dm.delegation+xml": { "source": "iana", "compressible": true },
  "application/vnd.dna": { "source": "iana", "extensions": ["dna"] },
  "application/vnd.document+json": { "source": "iana", "compressible": true },
  "application/vnd.dolby.mlp": { "source": "apache", "extensions": ["mlp"] },
  "application/vnd.dolby.mobile.1": { "source": "iana" },
  "application/vnd.dolby.mobile.2": { "source": "iana" },
  "application/vnd.doremir.scorecloud-binary-document": { "source": "iana" },
  "application/vnd.dpgraph": { "source": "iana", "extensions": ["dpg"] },
  "application/vnd.dreamfactory": { "source": "iana", "extensions": ["dfac"] },
  "application/vnd.drive+json": { "source": "iana", "compressible": true },
  "application/vnd.ds-keypoint": { "source": "apache", "extensions": ["kpxx"] },
  "application/vnd.dtg.local": { "source": "iana" },
  "application/vnd.dtg.local.flash": { "source": "iana" },
  "application/vnd.dtg.local.html": { "source": "iana" },
  "application/vnd.dvb.ait": { "source": "iana", "extensions": ["ait"] },
  "application/vnd.dvb.dvbisl+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.dvbj": { "source": "iana" },
  "application/vnd.dvb.esgcontainer": { "source": "iana" },
  "application/vnd.dvb.ipdcdftnotifaccess": { "source": "iana" },
  "application/vnd.dvb.ipdcesgaccess": { "source": "iana" },
  "application/vnd.dvb.ipdcesgaccess2": { "source": "iana" },
  "application/vnd.dvb.ipdcesgpdd": { "source": "iana" },
  "application/vnd.dvb.ipdcroaming": { "source": "iana" },
  "application/vnd.dvb.iptv.alfec-base": { "source": "iana" },
  "application/vnd.dvb.iptv.alfec-enhancement": { "source": "iana" },
  "application/vnd.dvb.notif-aggregate-root+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.notif-container+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.notif-generic+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.notif-ia-msglist+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.notif-ia-registration-request+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.notif-ia-registration-response+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.notif-init+xml": { "source": "iana", "compressible": true },
  "application/vnd.dvb.pfr": { "source": "iana" },
  "application/vnd.dvb.service": { "source": "iana", "extensions": ["svc"] },
  "application/vnd.dxr": { "source": "iana" },
  "application/vnd.dynageo": { "source": "iana", "extensions": ["geo"] },
  "application/vnd.dzr": { "source": "iana" },
  "application/vnd.easykaraoke.cdgdownload": { "source": "iana" },
  "application/vnd.ecdis-update": { "source": "iana" },
  "application/vnd.ecip.rlp": { "source": "iana" },
  "application/vnd.eclipse.ditto+json": { "source": "iana", "compressible": true },
  "application/vnd.ecowin.chart": { "source": "iana", "extensions": ["mag"] },
  "application/vnd.ecowin.filerequest": { "source": "iana" },
  "application/vnd.ecowin.fileupdate": { "source": "iana" },
  "application/vnd.ecowin.series": { "source": "iana" },
  "application/vnd.ecowin.seriesrequest": { "source": "iana" },
  "application/vnd.ecowin.seriesupdate": { "source": "iana" },
  "application/vnd.efi.img": { "source": "iana" },
  "application/vnd.efi.iso": { "source": "iana" },
  "application/vnd.emclient.accessrequest+xml": { "source": "iana", "compressible": true },
  "application/vnd.enliven": { "source": "iana", "extensions": ["nml"] },
  "application/vnd.enphase.envoy": { "source": "iana" },
  "application/vnd.eprints.data+xml": { "source": "iana", "compressible": true },
  "application/vnd.epson.esf": { "source": "iana", "extensions": ["esf"] },
  "application/vnd.epson.msf": { "source": "iana", "extensions": ["msf"] },
  "application/vnd.epson.quickanime": { "source": "iana", "extensions": ["qam"] },
  "application/vnd.epson.salt": { "source": "iana", "extensions": ["slt"] },
  "application/vnd.epson.ssf": { "source": "iana", "extensions": ["ssf"] },
  "application/vnd.ericsson.quickcall": { "source": "iana" },
  "application/vnd.espass-espass+zip": { "source": "iana", "compressible": false },
  "application/vnd.eszigno3+xml": { "source": "iana", "compressible": true, "extensions": ["es3", "et3"] },
  "application/vnd.etsi.aoc+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.asic-e+zip": { "source": "iana", "compressible": false },
  "application/vnd.etsi.asic-s+zip": { "source": "iana", "compressible": false },
  "application/vnd.etsi.cug+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvcommand+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvdiscovery+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvprofile+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvsad-bc+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvsad-cod+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvsad-npvr+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvservice+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvsync+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.iptvueprofile+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.mcid+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.mheg5": { "source": "iana" },
  "application/vnd.etsi.overload-control-policy-dataset+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.pstn+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.sci+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.simservs+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.timestamp-token": { "source": "iana" },
  "application/vnd.etsi.tsl+xml": { "source": "iana", "compressible": true },
  "application/vnd.etsi.tsl.der": { "source": "iana" },
  "application/vnd.eu.kasparian.car+json": { "source": "iana", "compressible": true },
  "application/vnd.eudora.data": { "source": "iana" },
  "application/vnd.evolv.ecig.profile": { "source": "iana" },
  "application/vnd.evolv.ecig.settings": { "source": "iana" },
  "application/vnd.evolv.ecig.theme": { "source": "iana" },
  "application/vnd.exstream-empower+zip": { "source": "iana", "compressible": false },
  "application/vnd.exstream-package": { "source": "iana" },
  "application/vnd.ezpix-album": { "source": "iana", "extensions": ["ez2"] },
  "application/vnd.ezpix-package": { "source": "iana", "extensions": ["ez3"] },
  "application/vnd.f-secure.mobile": { "source": "iana" },
  "application/vnd.familysearch.gedcom+zip": { "source": "iana", "compressible": false },
  "application/vnd.fastcopy-disk-image": { "source": "iana" },
  "application/vnd.fdf": { "source": "iana", "extensions": ["fdf"] },
  "application/vnd.fdsn.mseed": { "source": "iana", "extensions": ["mseed"] },
  "application/vnd.fdsn.seed": { "source": "iana", "extensions": ["seed", "dataless"] },
  "application/vnd.ffsns": { "source": "iana" },
  "application/vnd.ficlab.flb+zip": { "source": "iana", "compressible": false },
  "application/vnd.filmit.zfc": { "source": "iana" },
  "application/vnd.fints": { "source": "iana" },
  "application/vnd.firemonkeys.cloudcell": { "source": "iana" },
  "application/vnd.flographit": { "source": "iana", "extensions": ["gph"] },
  "application/vnd.fluxtime.clip": { "source": "iana", "extensions": ["ftc"] },
  "application/vnd.font-fontforge-sfd": { "source": "iana" },
  "application/vnd.framemaker": { "source": "iana", "extensions": ["fm", "frame", "maker", "book"] },
  "application/vnd.frogans.fnc": { "source": "iana", "extensions": ["fnc"] },
  "application/vnd.frogans.ltf": { "source": "iana", "extensions": ["ltf"] },
  "application/vnd.fsc.weblaunch": { "source": "iana", "extensions": ["fsc"] },
  "application/vnd.fujifilm.fb.docuworks": { "source": "iana" },
  "application/vnd.fujifilm.fb.docuworks.binder": { "source": "iana" },
  "application/vnd.fujifilm.fb.docuworks.container": { "source": "iana" },
  "application/vnd.fujifilm.fb.jfi+xml": { "source": "iana", "compressible": true },
  "application/vnd.fujitsu.oasys": { "source": "iana", "extensions": ["oas"] },
  "application/vnd.fujitsu.oasys2": { "source": "iana", "extensions": ["oa2"] },
  "application/vnd.fujitsu.oasys3": { "source": "iana", "extensions": ["oa3"] },
  "application/vnd.fujitsu.oasysgp": { "source": "iana", "extensions": ["fg5"] },
  "application/vnd.fujitsu.oasysprs": { "source": "iana", "extensions": ["bh2"] },
  "application/vnd.fujixerox.art-ex": { "source": "iana" },
  "application/vnd.fujixerox.art4": { "source": "iana" },
  "application/vnd.fujixerox.ddd": { "source": "iana", "extensions": ["ddd"] },
  "application/vnd.fujixerox.docuworks": { "source": "iana", "extensions": ["xdw"] },
  "application/vnd.fujixerox.docuworks.binder": { "source": "iana", "extensions": ["xbd"] },
  "application/vnd.fujixerox.docuworks.container": { "source": "iana" },
  "application/vnd.fujixerox.hbpl": { "source": "iana" },
  "application/vnd.fut-misnet": { "source": "iana" },
  "application/vnd.futoin+cbor": { "source": "iana" },
  "application/vnd.futoin+json": { "source": "iana", "compressible": true },
  "application/vnd.fuzzysheet": { "source": "iana", "extensions": ["fzs"] },
  "application/vnd.genomatix.tuxedo": { "source": "iana", "extensions": ["txd"] },
  "application/vnd.gentics.grd+json": { "source": "iana", "compressible": true },
  "application/vnd.geo+json": { "source": "iana", "compressible": true },
  "application/vnd.geocube+xml": { "source": "iana", "compressible": true },
  "application/vnd.geogebra.file": { "source": "iana", "extensions": ["ggb"] },
  "application/vnd.geogebra.slides": { "source": "iana" },
  "application/vnd.geogebra.tool": { "source": "iana", "extensions": ["ggt"] },
  "application/vnd.geometry-explorer": { "source": "iana", "extensions": ["gex", "gre"] },
  "application/vnd.geonext": { "source": "iana", "extensions": ["gxt"] },
  "application/vnd.geoplan": { "source": "iana", "extensions": ["g2w"] },
  "application/vnd.geospace": { "source": "iana", "extensions": ["g3w"] },
  "application/vnd.gerber": { "source": "iana" },
  "application/vnd.globalplatform.card-content-mgt": { "source": "iana" },
  "application/vnd.globalplatform.card-content-mgt-response": { "source": "iana" },
  "application/vnd.gmx": { "source": "iana", "extensions": ["gmx"] },
  "application/vnd.google-apps.document": { "compressible": false, "extensions": ["gdoc"] },
  "application/vnd.google-apps.presentation": { "compressible": false, "extensions": ["gslides"] },
  "application/vnd.google-apps.spreadsheet": { "compressible": false, "extensions": ["gsheet"] },
  "application/vnd.google-earth.kml+xml": { "source": "iana", "compressible": true, "extensions": ["kml"] },
  "application/vnd.google-earth.kmz": { "source": "iana", "compressible": false, "extensions": ["kmz"] },
  "application/vnd.gov.sk.e-form+xml": { "source": "iana", "compressible": true },
  "application/vnd.gov.sk.e-form+zip": { "source": "iana", "compressible": false },
  "application/vnd.gov.sk.xmldatacontainer+xml": { "source": "iana", "compressible": true },
  "application/vnd.grafeq": { "source": "iana", "extensions": ["gqf", "gqs"] },
  "application/vnd.gridmp": { "source": "iana" },
  "application/vnd.groove-account": { "source": "iana", "extensions": ["gac"] },
  "application/vnd.groove-help": { "source": "iana", "extensions": ["ghf"] },
  "application/vnd.groove-identity-message": { "source": "iana", "extensions": ["gim"] },
  "application/vnd.groove-injector": { "source": "iana", "extensions": ["grv"] },
  "application/vnd.groove-tool-message": { "source": "iana", "extensions": ["gtm"] },
  "application/vnd.groove-tool-template": { "source": "iana", "extensions": ["tpl"] },
  "application/vnd.groove-vcard": { "source": "iana", "extensions": ["vcg"] },
  "application/vnd.hal+json": { "source": "iana", "compressible": true },
  "application/vnd.hal+xml": { "source": "iana", "compressible": true, "extensions": ["hal"] },
  "application/vnd.handheld-entertainment+xml": { "source": "iana", "compressible": true, "extensions": ["zmm"] },
  "application/vnd.hbci": { "source": "iana", "extensions": ["hbci"] },
  "application/vnd.hc+json": { "source": "iana", "compressible": true },
  "application/vnd.hcl-bireports": { "source": "iana" },
  "application/vnd.hdt": { "source": "iana" },
  "application/vnd.heroku+json": { "source": "iana", "compressible": true },
  "application/vnd.hhe.lesson-player": { "source": "iana", "extensions": ["les"] },
  "application/vnd.hl7cda+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/vnd.hl7v2+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/vnd.hp-hpgl": { "source": "iana", "extensions": ["hpgl"] },
  "application/vnd.hp-hpid": { "source": "iana", "extensions": ["hpid"] },
  "application/vnd.hp-hps": { "source": "iana", "extensions": ["hps"] },
  "application/vnd.hp-jlyt": { "source": "iana", "extensions": ["jlt"] },
  "application/vnd.hp-pcl": { "source": "iana", "extensions": ["pcl"] },
  "application/vnd.hp-pclxl": { "source": "iana", "extensions": ["pclxl"] },
  "application/vnd.httphone": { "source": "iana" },
  "application/vnd.hydrostatix.sof-data": { "source": "iana", "extensions": ["sfd-hdstx"] },
  "application/vnd.hyper+json": { "source": "iana", "compressible": true },
  "application/vnd.hyper-item+json": { "source": "iana", "compressible": true },
  "application/vnd.hyperdrive+json": { "source": "iana", "compressible": true },
  "application/vnd.hzn-3d-crossword": { "source": "iana" },
  "application/vnd.ibm.afplinedata": { "source": "iana" },
  "application/vnd.ibm.electronic-media": { "source": "iana" },
  "application/vnd.ibm.minipay": { "source": "iana", "extensions": ["mpy"] },
  "application/vnd.ibm.modcap": { "source": "iana", "extensions": ["afp", "listafp", "list3820"] },
  "application/vnd.ibm.rights-management": { "source": "iana", "extensions": ["irm"] },
  "application/vnd.ibm.secure-container": { "source": "iana", "extensions": ["sc"] },
  "application/vnd.iccprofile": { "source": "iana", "extensions": ["icc", "icm"] },
  "application/vnd.ieee.1905": { "source": "iana" },
  "application/vnd.igloader": { "source": "iana", "extensions": ["igl"] },
  "application/vnd.imagemeter.folder+zip": { "source": "iana", "compressible": false },
  "application/vnd.imagemeter.image+zip": { "source": "iana", "compressible": false },
  "application/vnd.immervision-ivp": { "source": "iana", "extensions": ["ivp"] },
  "application/vnd.immervision-ivu": { "source": "iana", "extensions": ["ivu"] },
  "application/vnd.ims.imsccv1p1": { "source": "iana" },
  "application/vnd.ims.imsccv1p2": { "source": "iana" },
  "application/vnd.ims.imsccv1p3": { "source": "iana" },
  "application/vnd.ims.lis.v2.result+json": { "source": "iana", "compressible": true },
  "application/vnd.ims.lti.v2.toolconsumerprofile+json": { "source": "iana", "compressible": true },
  "application/vnd.ims.lti.v2.toolproxy+json": { "source": "iana", "compressible": true },
  "application/vnd.ims.lti.v2.toolproxy.id+json": { "source": "iana", "compressible": true },
  "application/vnd.ims.lti.v2.toolsettings+json": { "source": "iana", "compressible": true },
  "application/vnd.ims.lti.v2.toolsettings.simple+json": { "source": "iana", "compressible": true },
  "application/vnd.informedcontrol.rms+xml": { "source": "iana", "compressible": true },
  "application/vnd.informix-visionary": { "source": "iana" },
  "application/vnd.infotech.project": { "source": "iana" },
  "application/vnd.infotech.project+xml": { "source": "iana", "compressible": true },
  "application/vnd.innopath.wamp.notification": { "source": "iana" },
  "application/vnd.insors.igm": { "source": "iana", "extensions": ["igm"] },
  "application/vnd.intercon.formnet": { "source": "iana", "extensions": ["xpw", "xpx"] },
  "application/vnd.intergeo": { "source": "iana", "extensions": ["i2g"] },
  "application/vnd.intertrust.digibox": { "source": "iana" },
  "application/vnd.intertrust.nncp": { "source": "iana" },
  "application/vnd.intu.qbo": { "source": "iana", "extensions": ["qbo"] },
  "application/vnd.intu.qfx": { "source": "iana", "extensions": ["qfx"] },
  "application/vnd.iptc.g2.catalogitem+xml": { "source": "iana", "compressible": true },
  "application/vnd.iptc.g2.conceptitem+xml": { "source": "iana", "compressible": true },
  "application/vnd.iptc.g2.knowledgeitem+xml": { "source": "iana", "compressible": true },
  "application/vnd.iptc.g2.newsitem+xml": { "source": "iana", "compressible": true },
  "application/vnd.iptc.g2.newsmessage+xml": { "source": "iana", "compressible": true },
  "application/vnd.iptc.g2.packageitem+xml": { "source": "iana", "compressible": true },
  "application/vnd.iptc.g2.planningitem+xml": { "source": "iana", "compressible": true },
  "application/vnd.ipunplugged.rcprofile": { "source": "iana", "extensions": ["rcprofile"] },
  "application/vnd.irepository.package+xml": { "source": "iana", "compressible": true, "extensions": ["irp"] },
  "application/vnd.is-xpr": { "source": "iana", "extensions": ["xpr"] },
  "application/vnd.isac.fcs": { "source": "iana", "extensions": ["fcs"] },
  "application/vnd.iso11783-10+zip": { "source": "iana", "compressible": false },
  "application/vnd.jam": { "source": "iana", "extensions": ["jam"] },
  "application/vnd.japannet-directory-service": { "source": "iana" },
  "application/vnd.japannet-jpnstore-wakeup": { "source": "iana" },
  "application/vnd.japannet-payment-wakeup": { "source": "iana" },
  "application/vnd.japannet-registration": { "source": "iana" },
  "application/vnd.japannet-registration-wakeup": { "source": "iana" },
  "application/vnd.japannet-setstore-wakeup": { "source": "iana" },
  "application/vnd.japannet-verification": { "source": "iana" },
  "application/vnd.japannet-verification-wakeup": { "source": "iana" },
  "application/vnd.jcp.javame.midlet-rms": { "source": "iana", "extensions": ["rms"] },
  "application/vnd.jisp": { "source": "iana", "extensions": ["jisp"] },
  "application/vnd.joost.joda-archive": { "source": "iana", "extensions": ["joda"] },
  "application/vnd.jsk.isdn-ngn": { "source": "iana" },
  "application/vnd.kahootz": { "source": "iana", "extensions": ["ktz", "ktr"] },
  "application/vnd.kde.karbon": { "source": "iana", "extensions": ["karbon"] },
  "application/vnd.kde.kchart": { "source": "iana", "extensions": ["chrt"] },
  "application/vnd.kde.kformula": { "source": "iana", "extensions": ["kfo"] },
  "application/vnd.kde.kivio": { "source": "iana", "extensions": ["flw"] },
  "application/vnd.kde.kontour": { "source": "iana", "extensions": ["kon"] },
  "application/vnd.kde.kpresenter": { "source": "iana", "extensions": ["kpr", "kpt"] },
  "application/vnd.kde.kspread": { "source": "iana", "extensions": ["ksp"] },
  "application/vnd.kde.kword": { "source": "iana", "extensions": ["kwd", "kwt"] },
  "application/vnd.kenameaapp": { "source": "iana", "extensions": ["htke"] },
  "application/vnd.kidspiration": { "source": "iana", "extensions": ["kia"] },
  "application/vnd.kinar": { "source": "iana", "extensions": ["kne", "knp"] },
  "application/vnd.koan": { "source": "iana", "extensions": ["skp", "skd", "skt", "skm"] },
  "application/vnd.kodak-descriptor": { "source": "iana", "extensions": ["sse"] },
  "application/vnd.las": { "source": "iana" },
  "application/vnd.las.las+json": { "source": "iana", "compressible": true },
  "application/vnd.las.las+xml": { "source": "iana", "compressible": true, "extensions": ["lasxml"] },
  "application/vnd.laszip": { "source": "iana" },
  "application/vnd.leap+json": { "source": "iana", "compressible": true },
  "application/vnd.liberty-request+xml": { "source": "iana", "compressible": true },
  "application/vnd.llamagraphics.life-balance.desktop": { "source": "iana", "extensions": ["lbd"] },
  "application/vnd.llamagraphics.life-balance.exchange+xml": { "source": "iana", "compressible": true, "extensions": ["lbe"] },
  "application/vnd.logipipe.circuit+zip": { "source": "iana", "compressible": false },
  "application/vnd.loom": { "source": "iana" },
  "application/vnd.lotus-1-2-3": { "source": "iana", "extensions": ["123"] },
  "application/vnd.lotus-approach": { "source": "iana", "extensions": ["apr"] },
  "application/vnd.lotus-freelance": { "source": "iana", "extensions": ["pre"] },
  "application/vnd.lotus-notes": { "source": "iana", "extensions": ["nsf"] },
  "application/vnd.lotus-organizer": { "source": "iana", "extensions": ["org"] },
  "application/vnd.lotus-screencam": { "source": "iana", "extensions": ["scm"] },
  "application/vnd.lotus-wordpro": { "source": "iana", "extensions": ["lwp"] },
  "application/vnd.macports.portpkg": { "source": "iana", "extensions": ["portpkg"] },
  "application/vnd.mapbox-vector-tile": { "source": "iana", "extensions": ["mvt"] },
  "application/vnd.marlin.drm.actiontoken+xml": { "source": "iana", "compressible": true },
  "application/vnd.marlin.drm.conftoken+xml": { "source": "iana", "compressible": true },
  "application/vnd.marlin.drm.license+xml": { "source": "iana", "compressible": true },
  "application/vnd.marlin.drm.mdcf": { "source": "iana" },
  "application/vnd.mason+json": { "source": "iana", "compressible": true },
  "application/vnd.maxar.archive.3tz+zip": { "source": "iana", "compressible": false },
  "application/vnd.maxmind.maxmind-db": { "source": "iana" },
  "application/vnd.mcd": { "source": "iana", "extensions": ["mcd"] },
  "application/vnd.medcalcdata": { "source": "iana", "extensions": ["mc1"] },
  "application/vnd.mediastation.cdkey": { "source": "iana", "extensions": ["cdkey"] },
  "application/vnd.meridian-slingshot": { "source": "iana" },
  "application/vnd.mfer": { "source": "iana", "extensions": ["mwf"] },
  "application/vnd.mfmp": { "source": "iana", "extensions": ["mfm"] },
  "application/vnd.micro+json": { "source": "iana", "compressible": true },
  "application/vnd.micrografx.flo": { "source": "iana", "extensions": ["flo"] },
  "application/vnd.micrografx.igx": { "source": "iana", "extensions": ["igx"] },
  "application/vnd.microsoft.portable-executable": { "source": "iana" },
  "application/vnd.microsoft.windows.thumbnail-cache": { "source": "iana" },
  "application/vnd.miele+json": { "source": "iana", "compressible": true },
  "application/vnd.mif": { "source": "iana", "extensions": ["mif"] },
  "application/vnd.minisoft-hp3000-save": { "source": "iana" },
  "application/vnd.mitsubishi.misty-guard.trustweb": { "source": "iana" },
  "application/vnd.mobius.daf": { "source": "iana", "extensions": ["daf"] },
  "application/vnd.mobius.dis": { "source": "iana", "extensions": ["dis"] },
  "application/vnd.mobius.mbk": { "source": "iana", "extensions": ["mbk"] },
  "application/vnd.mobius.mqy": { "source": "iana", "extensions": ["mqy"] },
  "application/vnd.mobius.msl": { "source": "iana", "extensions": ["msl"] },
  "application/vnd.mobius.plc": { "source": "iana", "extensions": ["plc"] },
  "application/vnd.mobius.txf": { "source": "iana", "extensions": ["txf"] },
  "application/vnd.mophun.application": { "source": "iana", "extensions": ["mpn"] },
  "application/vnd.mophun.certificate": { "source": "iana", "extensions": ["mpc"] },
  "application/vnd.motorola.flexsuite": { "source": "iana" },
  "application/vnd.motorola.flexsuite.adsi": { "source": "iana" },
  "application/vnd.motorola.flexsuite.fis": { "source": "iana" },
  "application/vnd.motorola.flexsuite.gotap": { "source": "iana" },
  "application/vnd.motorola.flexsuite.kmr": { "source": "iana" },
  "application/vnd.motorola.flexsuite.ttc": { "source": "iana" },
  "application/vnd.motorola.flexsuite.wem": { "source": "iana" },
  "application/vnd.motorola.iprm": { "source": "iana" },
  "application/vnd.mozilla.xul+xml": { "source": "iana", "compressible": true, "extensions": ["xul"] },
  "application/vnd.ms-3mfdocument": { "source": "iana" },
  "application/vnd.ms-artgalry": { "source": "iana", "extensions": ["cil"] },
  "application/vnd.ms-asf": { "source": "iana" },
  "application/vnd.ms-cab-compressed": { "source": "iana", "extensions": ["cab"] },
  "application/vnd.ms-color.iccprofile": { "source": "apache" },
  "application/vnd.ms-excel": { "source": "iana", "compressible": false, "extensions": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"] },
  "application/vnd.ms-excel.addin.macroenabled.12": { "source": "iana", "extensions": ["xlam"] },
  "application/vnd.ms-excel.sheet.binary.macroenabled.12": { "source": "iana", "extensions": ["xlsb"] },
  "application/vnd.ms-excel.sheet.macroenabled.12": { "source": "iana", "extensions": ["xlsm"] },
  "application/vnd.ms-excel.template.macroenabled.12": { "source": "iana", "extensions": ["xltm"] },
  "application/vnd.ms-fontobject": { "source": "iana", "compressible": true, "extensions": ["eot"] },
  "application/vnd.ms-htmlhelp": { "source": "iana", "extensions": ["chm"] },
  "application/vnd.ms-ims": { "source": "iana", "extensions": ["ims"] },
  "application/vnd.ms-lrm": { "source": "iana", "extensions": ["lrm"] },
  "application/vnd.ms-office.activex+xml": { "source": "iana", "compressible": true },
  "application/vnd.ms-officetheme": { "source": "iana", "extensions": ["thmx"] },
  "application/vnd.ms-opentype": { "source": "apache", "compressible": true },
  "application/vnd.ms-outlook": { "compressible": false, "extensions": ["msg"] },
  "application/vnd.ms-package.obfuscated-opentype": { "source": "apache" },
  "application/vnd.ms-pki.seccat": { "source": "apache", "extensions": ["cat"] },
  "application/vnd.ms-pki.stl": { "source": "apache", "extensions": ["stl"] },
  "application/vnd.ms-playready.initiator+xml": { "source": "iana", "compressible": true },
  "application/vnd.ms-powerpoint": { "source": "iana", "compressible": false, "extensions": ["ppt", "pps", "pot"] },
  "application/vnd.ms-powerpoint.addin.macroenabled.12": { "source": "iana", "extensions": ["ppam"] },
  "application/vnd.ms-powerpoint.presentation.macroenabled.12": { "source": "iana", "extensions": ["pptm"] },
  "application/vnd.ms-powerpoint.slide.macroenabled.12": { "source": "iana", "extensions": ["sldm"] },
  "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { "source": "iana", "extensions": ["ppsm"] },
  "application/vnd.ms-powerpoint.template.macroenabled.12": { "source": "iana", "extensions": ["potm"] },
  "application/vnd.ms-printdevicecapabilities+xml": { "source": "iana", "compressible": true },
  "application/vnd.ms-printing.printticket+xml": { "source": "apache", "compressible": true },
  "application/vnd.ms-printschematicket+xml": { "source": "iana", "compressible": true },
  "application/vnd.ms-project": { "source": "iana", "extensions": ["mpp", "mpt"] },
  "application/vnd.ms-tnef": { "source": "iana" },
  "application/vnd.ms-windows.devicepairing": { "source": "iana" },
  "application/vnd.ms-windows.nwprinting.oob": { "source": "iana" },
  "application/vnd.ms-windows.printerpairing": { "source": "iana" },
  "application/vnd.ms-windows.wsd.oob": { "source": "iana" },
  "application/vnd.ms-wmdrm.lic-chlg-req": { "source": "iana" },
  "application/vnd.ms-wmdrm.lic-resp": { "source": "iana" },
  "application/vnd.ms-wmdrm.meter-chlg-req": { "source": "iana" },
  "application/vnd.ms-wmdrm.meter-resp": { "source": "iana" },
  "application/vnd.ms-word.document.macroenabled.12": { "source": "iana", "extensions": ["docm"] },
  "application/vnd.ms-word.template.macroenabled.12": { "source": "iana", "extensions": ["dotm"] },
  "application/vnd.ms-works": { "source": "iana", "extensions": ["wps", "wks", "wcm", "wdb"] },
  "application/vnd.ms-wpl": { "source": "iana", "extensions": ["wpl"] },
  "application/vnd.ms-xpsdocument": { "source": "iana", "compressible": false, "extensions": ["xps"] },
  "application/vnd.msa-disk-image": { "source": "iana" },
  "application/vnd.mseq": { "source": "iana", "extensions": ["mseq"] },
  "application/vnd.msign": { "source": "iana" },
  "application/vnd.multiad.creator": { "source": "iana" },
  "application/vnd.multiad.creator.cif": { "source": "iana" },
  "application/vnd.music-niff": { "source": "iana" },
  "application/vnd.musician": { "source": "iana", "extensions": ["mus"] },
  "application/vnd.muvee.style": { "source": "iana", "extensions": ["msty"] },
  "application/vnd.mynfc": { "source": "iana", "extensions": ["taglet"] },
  "application/vnd.nacamar.ybrid+json": { "source": "iana", "compressible": true },
  "application/vnd.ncd.control": { "source": "iana" },
  "application/vnd.ncd.reference": { "source": "iana" },
  "application/vnd.nearst.inv+json": { "source": "iana", "compressible": true },
  "application/vnd.nebumind.line": { "source": "iana" },
  "application/vnd.nervana": { "source": "iana" },
  "application/vnd.netfpx": { "source": "iana" },
  "application/vnd.neurolanguage.nlu": { "source": "iana", "extensions": ["nlu"] },
  "application/vnd.nimn": { "source": "iana" },
  "application/vnd.nintendo.nitro.rom": { "source": "iana" },
  "application/vnd.nintendo.snes.rom": { "source": "iana" },
  "application/vnd.nitf": { "source": "iana", "extensions": ["ntf", "nitf"] },
  "application/vnd.noblenet-directory": { "source": "iana", "extensions": ["nnd"] },
  "application/vnd.noblenet-sealer": { "source": "iana", "extensions": ["nns"] },
  "application/vnd.noblenet-web": { "source": "iana", "extensions": ["nnw"] },
  "application/vnd.nokia.catalogs": { "source": "iana" },
  "application/vnd.nokia.conml+wbxml": { "source": "iana" },
  "application/vnd.nokia.conml+xml": { "source": "iana", "compressible": true },
  "application/vnd.nokia.iptv.config+xml": { "source": "iana", "compressible": true },
  "application/vnd.nokia.isds-radio-presets": { "source": "iana" },
  "application/vnd.nokia.landmark+wbxml": { "source": "iana" },
  "application/vnd.nokia.landmark+xml": { "source": "iana", "compressible": true },
  "application/vnd.nokia.landmarkcollection+xml": { "source": "iana", "compressible": true },
  "application/vnd.nokia.n-gage.ac+xml": { "source": "iana", "compressible": true, "extensions": ["ac"] },
  "application/vnd.nokia.n-gage.data": { "source": "iana", "extensions": ["ngdat"] },
  "application/vnd.nokia.n-gage.symbian.install": { "source": "iana", "extensions": ["n-gage"] },
  "application/vnd.nokia.ncd": { "source": "iana" },
  "application/vnd.nokia.pcd+wbxml": { "source": "iana" },
  "application/vnd.nokia.pcd+xml": { "source": "iana", "compressible": true },
  "application/vnd.nokia.radio-preset": { "source": "iana", "extensions": ["rpst"] },
  "application/vnd.nokia.radio-presets": { "source": "iana", "extensions": ["rpss"] },
  "application/vnd.novadigm.edm": { "source": "iana", "extensions": ["edm"] },
  "application/vnd.novadigm.edx": { "source": "iana", "extensions": ["edx"] },
  "application/vnd.novadigm.ext": { "source": "iana", "extensions": ["ext"] },
  "application/vnd.ntt-local.content-share": { "source": "iana" },
  "application/vnd.ntt-local.file-transfer": { "source": "iana" },
  "application/vnd.ntt-local.ogw_remote-access": { "source": "iana" },
  "application/vnd.ntt-local.sip-ta_remote": { "source": "iana" },
  "application/vnd.ntt-local.sip-ta_tcp_stream": { "source": "iana" },
  "application/vnd.oasis.opendocument.chart": { "source": "iana", "extensions": ["odc"] },
  "application/vnd.oasis.opendocument.chart-template": { "source": "iana", "extensions": ["otc"] },
  "application/vnd.oasis.opendocument.database": { "source": "iana", "extensions": ["odb"] },
  "application/vnd.oasis.opendocument.formula": { "source": "iana", "extensions": ["odf"] },
  "application/vnd.oasis.opendocument.formula-template": { "source": "iana", "extensions": ["odft"] },
  "application/vnd.oasis.opendocument.graphics": { "source": "iana", "compressible": false, "extensions": ["odg"] },
  "application/vnd.oasis.opendocument.graphics-template": { "source": "iana", "extensions": ["otg"] },
  "application/vnd.oasis.opendocument.image": { "source": "iana", "extensions": ["odi"] },
  "application/vnd.oasis.opendocument.image-template": { "source": "iana", "extensions": ["oti"] },
  "application/vnd.oasis.opendocument.presentation": { "source": "iana", "compressible": false, "extensions": ["odp"] },
  "application/vnd.oasis.opendocument.presentation-template": { "source": "iana", "extensions": ["otp"] },
  "application/vnd.oasis.opendocument.spreadsheet": { "source": "iana", "compressible": false, "extensions": ["ods"] },
  "application/vnd.oasis.opendocument.spreadsheet-template": { "source": "iana", "extensions": ["ots"] },
  "application/vnd.oasis.opendocument.text": { "source": "iana", "compressible": false, "extensions": ["odt"] },
  "application/vnd.oasis.opendocument.text-master": { "source": "iana", "extensions": ["odm"] },
  "application/vnd.oasis.opendocument.text-template": { "source": "iana", "extensions": ["ott"] },
  "application/vnd.oasis.opendocument.text-web": { "source": "iana", "extensions": ["oth"] },
  "application/vnd.obn": { "source": "iana" },
  "application/vnd.ocf+cbor": { "source": "iana" },
  "application/vnd.oci.image.manifest.v1+json": { "source": "iana", "compressible": true },
  "application/vnd.oftn.l10n+json": { "source": "iana", "compressible": true },
  "application/vnd.oipf.contentaccessdownload+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.contentaccessstreaming+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.cspg-hexbinary": { "source": "iana" },
  "application/vnd.oipf.dae.svg+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.dae.xhtml+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.mippvcontrolmessage+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.pae.gem": { "source": "iana" },
  "application/vnd.oipf.spdiscovery+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.spdlist+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.ueprofile+xml": { "source": "iana", "compressible": true },
  "application/vnd.oipf.userprofile+xml": { "source": "iana", "compressible": true },
  "application/vnd.olpc-sugar": { "source": "iana", "extensions": ["xo"] },
  "application/vnd.oma-scws-config": { "source": "iana" },
  "application/vnd.oma-scws-http-request": { "source": "iana" },
  "application/vnd.oma-scws-http-response": { "source": "iana" },
  "application/vnd.oma.bcast.associated-procedure-parameter+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.drm-trigger+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.imd+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.ltkm": { "source": "iana" },
  "application/vnd.oma.bcast.notification+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.provisioningtrigger": { "source": "iana" },
  "application/vnd.oma.bcast.sgboot": { "source": "iana" },
  "application/vnd.oma.bcast.sgdd+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.sgdu": { "source": "iana" },
  "application/vnd.oma.bcast.simple-symbol-container": { "source": "iana" },
  "application/vnd.oma.bcast.smartcard-trigger+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.sprov+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.bcast.stkm": { "source": "iana" },
  "application/vnd.oma.cab-address-book+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.cab-feature-handler+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.cab-pcc+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.cab-subs-invite+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.cab-user-prefs+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.dcd": { "source": "iana" },
  "application/vnd.oma.dcdc": { "source": "iana" },
  "application/vnd.oma.dd2+xml": { "source": "iana", "compressible": true, "extensions": ["dd2"] },
  "application/vnd.oma.drm.risd+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.group-usage-list+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.lwm2m+cbor": { "source": "iana" },
  "application/vnd.oma.lwm2m+json": { "source": "iana", "compressible": true },
  "application/vnd.oma.lwm2m+tlv": { "source": "iana" },
  "application/vnd.oma.pal+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.poc.detailed-progress-report+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.poc.final-report+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.poc.groups+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.poc.invocation-descriptor+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.poc.optimized-progress-report+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.push": { "source": "iana" },
  "application/vnd.oma.scidm.messages+xml": { "source": "iana", "compressible": true },
  "application/vnd.oma.xcap-directory+xml": { "source": "iana", "compressible": true },
  "application/vnd.omads-email+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/vnd.omads-file+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/vnd.omads-folder+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/vnd.omaloc-supl-init": { "source": "iana" },
  "application/vnd.onepager": { "source": "iana" },
  "application/vnd.onepagertamp": { "source": "iana" },
  "application/vnd.onepagertamx": { "source": "iana" },
  "application/vnd.onepagertat": { "source": "iana" },
  "application/vnd.onepagertatp": { "source": "iana" },
  "application/vnd.onepagertatx": { "source": "iana" },
  "application/vnd.openblox.game+xml": { "source": "iana", "compressible": true, "extensions": ["obgx"] },
  "application/vnd.openblox.game-binary": { "source": "iana" },
  "application/vnd.openeye.oeb": { "source": "iana" },
  "application/vnd.openofficeorg.extension": { "source": "apache", "extensions": ["oxt"] },
  "application/vnd.openstreetmap.data+xml": { "source": "iana", "compressible": true, "extensions": ["osm"] },
  "application/vnd.opentimestamps.ots": { "source": "iana" },
  "application/vnd.openxmlformats-officedocument.custom-properties+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawing+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.extended-properties+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.presentation": { "source": "iana", "compressible": false, "extensions": ["pptx"] },
  "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.slide": { "source": "iana", "extensions": ["sldx"] },
  "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { "source": "iana", "extensions": ["ppsx"] },
  "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.template": { "source": "iana", "extensions": ["potx"] },
  "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { "source": "iana", "compressible": false, "extensions": ["xlsx"] },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { "source": "iana", "extensions": ["xltx"] },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.theme+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.themeoverride+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.vmldrawing": { "source": "iana" },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { "source": "iana", "compressible": false, "extensions": ["docx"] },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { "source": "iana", "extensions": ["dotx"] },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-package.core-properties+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { "source": "iana", "compressible": true },
  "application/vnd.openxmlformats-package.relationships+xml": { "source": "iana", "compressible": true },
  "application/vnd.oracle.resource+json": { "source": "iana", "compressible": true },
  "application/vnd.orange.indata": { "source": "iana" },
  "application/vnd.osa.netdeploy": { "source": "iana" },
  "application/vnd.osgeo.mapguide.package": { "source": "iana", "extensions": ["mgp"] },
  "application/vnd.osgi.bundle": { "source": "iana" },
  "application/vnd.osgi.dp": { "source": "iana", "extensions": ["dp"] },
  "application/vnd.osgi.subsystem": { "source": "iana", "extensions": ["esa"] },
  "application/vnd.otps.ct-kip+xml": { "source": "iana", "compressible": true },
  "application/vnd.oxli.countgraph": { "source": "iana" },
  "application/vnd.pagerduty+json": { "source": "iana", "compressible": true },
  "application/vnd.palm": { "source": "iana", "extensions": ["pdb", "pqa", "oprc"] },
  "application/vnd.panoply": { "source": "iana" },
  "application/vnd.paos.xml": { "source": "iana" },
  "application/vnd.patentdive": { "source": "iana" },
  "application/vnd.patientecommsdoc": { "source": "iana" },
  "application/vnd.pawaafile": { "source": "iana", "extensions": ["paw"] },
  "application/vnd.pcos": { "source": "iana" },
  "application/vnd.pg.format": { "source": "iana", "extensions": ["str"] },
  "application/vnd.pg.osasli": { "source": "iana", "extensions": ["ei6"] },
  "application/vnd.piaccess.application-licence": { "source": "iana" },
  "application/vnd.picsel": { "source": "iana", "extensions": ["efif"] },
  "application/vnd.pmi.widget": { "source": "iana", "extensions": ["wg"] },
  "application/vnd.poc.group-advertisement+xml": { "source": "iana", "compressible": true },
  "application/vnd.pocketlearn": { "source": "iana", "extensions": ["plf"] },
  "application/vnd.powerbuilder6": { "source": "iana", "extensions": ["pbd"] },
  "application/vnd.powerbuilder6-s": { "source": "iana" },
  "application/vnd.powerbuilder7": { "source": "iana" },
  "application/vnd.powerbuilder7-s": { "source": "iana" },
  "application/vnd.powerbuilder75": { "source": "iana" },
  "application/vnd.powerbuilder75-s": { "source": "iana" },
  "application/vnd.preminet": { "source": "iana" },
  "application/vnd.previewsystems.box": { "source": "iana", "extensions": ["box"] },
  "application/vnd.proteus.magazine": { "source": "iana", "extensions": ["mgz"] },
  "application/vnd.psfs": { "source": "iana" },
  "application/vnd.publishare-delta-tree": { "source": "iana", "extensions": ["qps"] },
  "application/vnd.pvi.ptid1": { "source": "iana", "extensions": ["ptid"] },
  "application/vnd.pwg-multiplexed": { "source": "iana" },
  "application/vnd.pwg-xhtml-print+xml": { "source": "iana", "compressible": true },
  "application/vnd.qualcomm.brew-app-res": { "source": "iana" },
  "application/vnd.quarantainenet": { "source": "iana" },
  "application/vnd.quark.quarkxpress": { "source": "iana", "extensions": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"] },
  "application/vnd.quobject-quoxdocument": { "source": "iana" },
  "application/vnd.radisys.moml+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-audit+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-audit-conf+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-audit-conn+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-audit-dialog+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-audit-stream+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-conf+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog-base+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog-fax-detect+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog-group+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog-speech+xml": { "source": "iana", "compressible": true },
  "application/vnd.radisys.msml-dialog-transform+xml": { "source": "iana", "compressible": true },
  "application/vnd.rainstor.data": { "source": "iana" },
  "application/vnd.rapid": { "source": "iana" },
  "application/vnd.rar": { "source": "iana", "extensions": ["rar"] },
  "application/vnd.realvnc.bed": { "source": "iana", "extensions": ["bed"] },
  "application/vnd.recordare.musicxml": { "source": "iana", "extensions": ["mxl"] },
  "application/vnd.recordare.musicxml+xml": { "source": "iana", "compressible": true, "extensions": ["musicxml"] },
  "application/vnd.renlearn.rlprint": { "source": "iana" },
  "application/vnd.resilient.logic": { "source": "iana" },
  "application/vnd.restful+json": { "source": "iana", "compressible": true },
  "application/vnd.rig.cryptonote": { "source": "iana", "extensions": ["cryptonote"] },
  "application/vnd.rim.cod": { "source": "apache", "extensions": ["cod"] },
  "application/vnd.rn-realmedia": { "source": "apache", "extensions": ["rm"] },
  "application/vnd.rn-realmedia-vbr": { "source": "apache", "extensions": ["rmvb"] },
  "application/vnd.route66.link66+xml": { "source": "iana", "compressible": true, "extensions": ["link66"] },
  "application/vnd.rs-274x": { "source": "iana" },
  "application/vnd.ruckus.download": { "source": "iana" },
  "application/vnd.s3sms": { "source": "iana" },
  "application/vnd.sailingtracker.track": { "source": "iana", "extensions": ["st"] },
  "application/vnd.sar": { "source": "iana" },
  "application/vnd.sbm.cid": { "source": "iana" },
  "application/vnd.sbm.mid2": { "source": "iana" },
  "application/vnd.scribus": { "source": "iana" },
  "application/vnd.sealed.3df": { "source": "iana" },
  "application/vnd.sealed.csf": { "source": "iana" },
  "application/vnd.sealed.doc": { "source": "iana" },
  "application/vnd.sealed.eml": { "source": "iana" },
  "application/vnd.sealed.mht": { "source": "iana" },
  "application/vnd.sealed.net": { "source": "iana" },
  "application/vnd.sealed.ppt": { "source": "iana" },
  "application/vnd.sealed.tiff": { "source": "iana" },
  "application/vnd.sealed.xls": { "source": "iana" },
  "application/vnd.sealedmedia.softseal.html": { "source": "iana" },
  "application/vnd.sealedmedia.softseal.pdf": { "source": "iana" },
  "application/vnd.seemail": { "source": "iana", "extensions": ["see"] },
  "application/vnd.seis+json": { "source": "iana", "compressible": true },
  "application/vnd.sema": { "source": "iana", "extensions": ["sema"] },
  "application/vnd.semd": { "source": "iana", "extensions": ["semd"] },
  "application/vnd.semf": { "source": "iana", "extensions": ["semf"] },
  "application/vnd.shade-save-file": { "source": "iana" },
  "application/vnd.shana.informed.formdata": { "source": "iana", "extensions": ["ifm"] },
  "application/vnd.shana.informed.formtemplate": { "source": "iana", "extensions": ["itp"] },
  "application/vnd.shana.informed.interchange": { "source": "iana", "extensions": ["iif"] },
  "application/vnd.shana.informed.package": { "source": "iana", "extensions": ["ipk"] },
  "application/vnd.shootproof+json": { "source": "iana", "compressible": true },
  "application/vnd.shopkick+json": { "source": "iana", "compressible": true },
  "application/vnd.shp": { "source": "iana" },
  "application/vnd.shx": { "source": "iana" },
  "application/vnd.sigrok.session": { "source": "iana" },
  "application/vnd.simtech-mindmapper": { "source": "iana", "extensions": ["twd", "twds"] },
  "application/vnd.siren+json": { "source": "iana", "compressible": true },
  "application/vnd.smaf": { "source": "iana", "extensions": ["mmf"] },
  "application/vnd.smart.notebook": { "source": "iana" },
  "application/vnd.smart.teacher": { "source": "iana", "extensions": ["teacher"] },
  "application/vnd.snesdev-page-table": { "source": "iana" },
  "application/vnd.software602.filler.form+xml": { "source": "iana", "compressible": true, "extensions": ["fo"] },
  "application/vnd.software602.filler.form-xml-zip": { "source": "iana" },
  "application/vnd.solent.sdkm+xml": { "source": "iana", "compressible": true, "extensions": ["sdkm", "sdkd"] },
  "application/vnd.spotfire.dxp": { "source": "iana", "extensions": ["dxp"] },
  "application/vnd.spotfire.sfs": { "source": "iana", "extensions": ["sfs"] },
  "application/vnd.sqlite3": { "source": "iana" },
  "application/vnd.sss-cod": { "source": "iana" },
  "application/vnd.sss-dtf": { "source": "iana" },
  "application/vnd.sss-ntf": { "source": "iana" },
  "application/vnd.stardivision.calc": { "source": "apache", "extensions": ["sdc"] },
  "application/vnd.stardivision.draw": { "source": "apache", "extensions": ["sda"] },
  "application/vnd.stardivision.impress": { "source": "apache", "extensions": ["sdd"] },
  "application/vnd.stardivision.math": { "source": "apache", "extensions": ["smf"] },
  "application/vnd.stardivision.writer": { "source": "apache", "extensions": ["sdw", "vor"] },
  "application/vnd.stardivision.writer-global": { "source": "apache", "extensions": ["sgl"] },
  "application/vnd.stepmania.package": { "source": "iana", "extensions": ["smzip"] },
  "application/vnd.stepmania.stepchart": { "source": "iana", "extensions": ["sm"] },
  "application/vnd.street-stream": { "source": "iana" },
  "application/vnd.sun.wadl+xml": { "source": "iana", "compressible": true, "extensions": ["wadl"] },
  "application/vnd.sun.xml.calc": { "source": "apache", "extensions": ["sxc"] },
  "application/vnd.sun.xml.calc.template": { "source": "apache", "extensions": ["stc"] },
  "application/vnd.sun.xml.draw": { "source": "apache", "extensions": ["sxd"] },
  "application/vnd.sun.xml.draw.template": { "source": "apache", "extensions": ["std"] },
  "application/vnd.sun.xml.impress": { "source": "apache", "extensions": ["sxi"] },
  "application/vnd.sun.xml.impress.template": { "source": "apache", "extensions": ["sti"] },
  "application/vnd.sun.xml.math": { "source": "apache", "extensions": ["sxm"] },
  "application/vnd.sun.xml.writer": { "source": "apache", "extensions": ["sxw"] },
  "application/vnd.sun.xml.writer.global": { "source": "apache", "extensions": ["sxg"] },
  "application/vnd.sun.xml.writer.template": { "source": "apache", "extensions": ["stw"] },
  "application/vnd.sus-calendar": { "source": "iana", "extensions": ["sus", "susp"] },
  "application/vnd.svd": { "source": "iana", "extensions": ["svd"] },
  "application/vnd.swiftview-ics": { "source": "iana" },
  "application/vnd.sycle+xml": { "source": "iana", "compressible": true },
  "application/vnd.syft+json": { "source": "iana", "compressible": true },
  "application/vnd.symbian.install": { "source": "apache", "extensions": ["sis", "sisx"] },
  "application/vnd.syncml+xml": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["xsm"] },
  "application/vnd.syncml.dm+wbxml": { "source": "iana", "charset": "UTF-8", "extensions": ["bdm"] },
  "application/vnd.syncml.dm+xml": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["xdm"] },
  "application/vnd.syncml.dm.notification": { "source": "iana" },
  "application/vnd.syncml.dmddf+wbxml": { "source": "iana" },
  "application/vnd.syncml.dmddf+xml": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["ddf"] },
  "application/vnd.syncml.dmtnds+wbxml": { "source": "iana" },
  "application/vnd.syncml.dmtnds+xml": { "source": "iana", "charset": "UTF-8", "compressible": true },
  "application/vnd.syncml.ds.notification": { "source": "iana" },
  "application/vnd.tableschema+json": { "source": "iana", "compressible": true },
  "application/vnd.tao.intent-module-archive": { "source": "iana", "extensions": ["tao"] },
  "application/vnd.tcpdump.pcap": { "source": "iana", "extensions": ["pcap", "cap", "dmp"] },
  "application/vnd.think-cell.ppttc+json": { "source": "iana", "compressible": true },
  "application/vnd.tmd.mediaflex.api+xml": { "source": "iana", "compressible": true },
  "application/vnd.tml": { "source": "iana" },
  "application/vnd.tmobile-livetv": { "source": "iana", "extensions": ["tmo"] },
  "application/vnd.tri.onesource": { "source": "iana" },
  "application/vnd.trid.tpt": { "source": "iana", "extensions": ["tpt"] },
  "application/vnd.triscape.mxs": { "source": "iana", "extensions": ["mxs"] },
  "application/vnd.trueapp": { "source": "iana", "extensions": ["tra"] },
  "application/vnd.truedoc": { "source": "iana" },
  "application/vnd.ubisoft.webplayer": { "source": "iana" },
  "application/vnd.ufdl": { "source": "iana", "extensions": ["ufd", "ufdl"] },
  "application/vnd.uiq.theme": { "source": "iana", "extensions": ["utz"] },
  "application/vnd.umajin": { "source": "iana", "extensions": ["umj"] },
  "application/vnd.unity": { "source": "iana", "extensions": ["unityweb"] },
  "application/vnd.uoml+xml": { "source": "iana", "compressible": true, "extensions": ["uoml"] },
  "application/vnd.uplanet.alert": { "source": "iana" },
  "application/vnd.uplanet.alert-wbxml": { "source": "iana" },
  "application/vnd.uplanet.bearer-choice": { "source": "iana" },
  "application/vnd.uplanet.bearer-choice-wbxml": { "source": "iana" },
  "application/vnd.uplanet.cacheop": { "source": "iana" },
  "application/vnd.uplanet.cacheop-wbxml": { "source": "iana" },
  "application/vnd.uplanet.channel": { "source": "iana" },
  "application/vnd.uplanet.channel-wbxml": { "source": "iana" },
  "application/vnd.uplanet.list": { "source": "iana" },
  "application/vnd.uplanet.list-wbxml": { "source": "iana" },
  "application/vnd.uplanet.listcmd": { "source": "iana" },
  "application/vnd.uplanet.listcmd-wbxml": { "source": "iana" },
  "application/vnd.uplanet.signal": { "source": "iana" },
  "application/vnd.uri-map": { "source": "iana" },
  "application/vnd.valve.source.material": { "source": "iana" },
  "application/vnd.vcx": { "source": "iana", "extensions": ["vcx"] },
  "application/vnd.vd-study": { "source": "iana" },
  "application/vnd.vectorworks": { "source": "iana" },
  "application/vnd.vel+json": { "source": "iana", "compressible": true },
  "application/vnd.verimatrix.vcas": { "source": "iana" },
  "application/vnd.veritone.aion+json": { "source": "iana", "compressible": true },
  "application/vnd.veryant.thin": { "source": "iana" },
  "application/vnd.ves.encrypted": { "source": "iana" },
  "application/vnd.vidsoft.vidconference": { "source": "iana" },
  "application/vnd.visio": { "source": "iana", "extensions": ["vsd", "vst", "vss", "vsw"] },
  "application/vnd.visionary": { "source": "iana", "extensions": ["vis"] },
  "application/vnd.vividence.scriptfile": { "source": "iana" },
  "application/vnd.vsf": { "source": "iana", "extensions": ["vsf"] },
  "application/vnd.wap.sic": { "source": "iana" },
  "application/vnd.wap.slc": { "source": "iana" },
  "application/vnd.wap.wbxml": { "source": "iana", "charset": "UTF-8", "extensions": ["wbxml"] },
  "application/vnd.wap.wmlc": { "source": "iana", "extensions": ["wmlc"] },
  "application/vnd.wap.wmlscriptc": { "source": "iana", "extensions": ["wmlsc"] },
  "application/vnd.webturbo": { "source": "iana", "extensions": ["wtb"] },
  "application/vnd.wfa.dpp": { "source": "iana" },
  "application/vnd.wfa.p2p": { "source": "iana" },
  "application/vnd.wfa.wsc": { "source": "iana" },
  "application/vnd.windows.devicepairing": { "source": "iana" },
  "application/vnd.wmc": { "source": "iana" },
  "application/vnd.wmf.bootstrap": { "source": "iana" },
  "application/vnd.wolfram.mathematica": { "source": "iana" },
  "application/vnd.wolfram.mathematica.package": { "source": "iana" },
  "application/vnd.wolfram.player": { "source": "iana", "extensions": ["nbp"] },
  "application/vnd.wordperfect": { "source": "iana", "extensions": ["wpd"] },
  "application/vnd.wqd": { "source": "iana", "extensions": ["wqd"] },
  "application/vnd.wrq-hp3000-labelled": { "source": "iana" },
  "application/vnd.wt.stf": { "source": "iana", "extensions": ["stf"] },
  "application/vnd.wv.csp+wbxml": { "source": "iana" },
  "application/vnd.wv.csp+xml": { "source": "iana", "compressible": true },
  "application/vnd.wv.ssp+xml": { "source": "iana", "compressible": true },
  "application/vnd.xacml+json": { "source": "iana", "compressible": true },
  "application/vnd.xara": { "source": "iana", "extensions": ["xar"] },
  "application/vnd.xfdl": { "source": "iana", "extensions": ["xfdl"] },
  "application/vnd.xfdl.webform": { "source": "iana" },
  "application/vnd.xmi+xml": { "source": "iana", "compressible": true },
  "application/vnd.xmpie.cpkg": { "source": "iana" },
  "application/vnd.xmpie.dpkg": { "source": "iana" },
  "application/vnd.xmpie.plan": { "source": "iana" },
  "application/vnd.xmpie.ppkg": { "source": "iana" },
  "application/vnd.xmpie.xlim": { "source": "iana" },
  "application/vnd.yamaha.hv-dic": { "source": "iana", "extensions": ["hvd"] },
  "application/vnd.yamaha.hv-script": { "source": "iana", "extensions": ["hvs"] },
  "application/vnd.yamaha.hv-voice": { "source": "iana", "extensions": ["hvp"] },
  "application/vnd.yamaha.openscoreformat": { "source": "iana", "extensions": ["osf"] },
  "application/vnd.yamaha.openscoreformat.osfpvg+xml": { "source": "iana", "compressible": true, "extensions": ["osfpvg"] },
  "application/vnd.yamaha.remote-setup": { "source": "iana" },
  "application/vnd.yamaha.smaf-audio": { "source": "iana", "extensions": ["saf"] },
  "application/vnd.yamaha.smaf-phrase": { "source": "iana", "extensions": ["spf"] },
  "application/vnd.yamaha.through-ngn": { "source": "iana" },
  "application/vnd.yamaha.tunnel-udpencap": { "source": "iana" },
  "application/vnd.yaoweme": { "source": "iana" },
  "application/vnd.yellowriver-custom-menu": { "source": "iana", "extensions": ["cmp"] },
  "application/vnd.youtube.yt": { "source": "iana" },
  "application/vnd.zul": { "source": "iana", "extensions": ["zir", "zirz"] },
  "application/vnd.zzazz.deck+xml": { "source": "iana", "compressible": true, "extensions": ["zaz"] },
  "application/voicexml+xml": { "source": "iana", "compressible": true, "extensions": ["vxml"] },
  "application/voucher-cms+json": { "source": "iana", "compressible": true },
  "application/vq-rtcpxr": { "source": "iana" },
  "application/wasm": { "source": "iana", "compressible": true, "extensions": ["wasm"] },
  "application/watcherinfo+xml": { "source": "iana", "compressible": true, "extensions": ["wif"] },
  "application/webpush-options+json": { "source": "iana", "compressible": true },
  "application/whoispp-query": { "source": "iana" },
  "application/whoispp-response": { "source": "iana" },
  "application/widget": { "source": "iana", "extensions": ["wgt"] },
  "application/winhlp": { "source": "apache", "extensions": ["hlp"] },
  "application/wita": { "source": "iana" },
  "application/wordperfect5.1": { "source": "iana" },
  "application/wsdl+xml": { "source": "iana", "compressible": true, "extensions": ["wsdl"] },
  "application/wspolicy+xml": { "source": "iana", "compressible": true, "extensions": ["wspolicy"] },
  "application/x-7z-compressed": { "source": "apache", "compressible": false, "extensions": ["7z"] },
  "application/x-abiword": { "source": "apache", "extensions": ["abw"] },
  "application/x-ace-compressed": { "source": "apache", "extensions": ["ace"] },
  "application/x-amf": { "source": "apache" },
  "application/x-apple-diskimage": { "source": "apache", "extensions": ["dmg"] },
  "application/x-arj": { "compressible": false, "extensions": ["arj"] },
  "application/x-authorware-bin": { "source": "apache", "extensions": ["aab", "x32", "u32", "vox"] },
  "application/x-authorware-map": { "source": "apache", "extensions": ["aam"] },
  "application/x-authorware-seg": { "source": "apache", "extensions": ["aas"] },
  "application/x-bcpio": { "source": "apache", "extensions": ["bcpio"] },
  "application/x-bdoc": { "compressible": false, "extensions": ["bdoc"] },
  "application/x-bittorrent": { "source": "apache", "extensions": ["torrent"] },
  "application/x-blorb": { "source": "apache", "extensions": ["blb", "blorb"] },
  "application/x-bzip": { "source": "apache", "compressible": false, "extensions": ["bz"] },
  "application/x-bzip2": { "source": "apache", "compressible": false, "extensions": ["bz2", "boz"] },
  "application/x-cbr": { "source": "apache", "extensions": ["cbr", "cba", "cbt", "cbz", "cb7"] },
  "application/x-cdlink": { "source": "apache", "extensions": ["vcd"] },
  "application/x-cfs-compressed": { "source": "apache", "extensions": ["cfs"] },
  "application/x-chat": { "source": "apache", "extensions": ["chat"] },
  "application/x-chess-pgn": { "source": "apache", "extensions": ["pgn"] },
  "application/x-chrome-extension": { "extensions": ["crx"] },
  "application/x-cocoa": { "source": "nginx", "extensions": ["cco"] },
  "application/x-compress": { "source": "apache" },
  "application/x-conference": { "source": "apache", "extensions": ["nsc"] },
  "application/x-cpio": { "source": "apache", "extensions": ["cpio"] },
  "application/x-csh": { "source": "apache", "extensions": ["csh"] },
  "application/x-deb": { "compressible": false },
  "application/x-debian-package": { "source": "apache", "extensions": ["deb", "udeb"] },
  "application/x-dgc-compressed": { "source": "apache", "extensions": ["dgc"] },
  "application/x-director": { "source": "apache", "extensions": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"] },
  "application/x-doom": { "source": "apache", "extensions": ["wad"] },
  "application/x-dtbncx+xml": { "source": "apache", "compressible": true, "extensions": ["ncx"] },
  "application/x-dtbook+xml": { "source": "apache", "compressible": true, "extensions": ["dtb"] },
  "application/x-dtbresource+xml": { "source": "apache", "compressible": true, "extensions": ["res"] },
  "application/x-dvi": { "source": "apache", "compressible": false, "extensions": ["dvi"] },
  "application/x-envoy": { "source": "apache", "extensions": ["evy"] },
  "application/x-eva": { "source": "apache", "extensions": ["eva"] },
  "application/x-font-bdf": { "source": "apache", "extensions": ["bdf"] },
  "application/x-font-dos": { "source": "apache" },
  "application/x-font-framemaker": { "source": "apache" },
  "application/x-font-ghostscript": { "source": "apache", "extensions": ["gsf"] },
  "application/x-font-libgrx": { "source": "apache" },
  "application/x-font-linux-psf": { "source": "apache", "extensions": ["psf"] },
  "application/x-font-pcf": { "source": "apache", "extensions": ["pcf"] },
  "application/x-font-snf": { "source": "apache", "extensions": ["snf"] },
  "application/x-font-speedo": { "source": "apache" },
  "application/x-font-sunos-news": { "source": "apache" },
  "application/x-font-type1": { "source": "apache", "extensions": ["pfa", "pfb", "pfm", "afm"] },
  "application/x-font-vfont": { "source": "apache" },
  "application/x-freearc": { "source": "apache", "extensions": ["arc"] },
  "application/x-futuresplash": { "source": "apache", "extensions": ["spl"] },
  "application/x-gca-compressed": { "source": "apache", "extensions": ["gca"] },
  "application/x-glulx": { "source": "apache", "extensions": ["ulx"] },
  "application/x-gnumeric": { "source": "apache", "extensions": ["gnumeric"] },
  "application/x-gramps-xml": { "source": "apache", "extensions": ["gramps"] },
  "application/x-gtar": { "source": "apache", "extensions": ["gtar"] },
  "application/x-gzip": { "source": "apache" },
  "application/x-hdf": { "source": "apache", "extensions": ["hdf"] },
  "application/x-httpd-php": { "compressible": true, "extensions": ["php"] },
  "application/x-install-instructions": { "source": "apache", "extensions": ["install"] },
  "application/x-iso9660-image": { "source": "apache", "extensions": ["iso"] },
  "application/x-iwork-keynote-sffkey": { "extensions": ["key"] },
  "application/x-iwork-numbers-sffnumbers": { "extensions": ["numbers"] },
  "application/x-iwork-pages-sffpages": { "extensions": ["pages"] },
  "application/x-java-archive-diff": { "source": "nginx", "extensions": ["jardiff"] },
  "application/x-java-jnlp-file": { "source": "apache", "compressible": false, "extensions": ["jnlp"] },
  "application/x-javascript": { "compressible": true },
  "application/x-keepass2": { "extensions": ["kdbx"] },
  "application/x-latex": { "source": "apache", "compressible": false, "extensions": ["latex"] },
  "application/x-lua-bytecode": { "extensions": ["luac"] },
  "application/x-lzh-compressed": { "source": "apache", "extensions": ["lzh", "lha"] },
  "application/x-makeself": { "source": "nginx", "extensions": ["run"] },
  "application/x-mie": { "source": "apache", "extensions": ["mie"] },
  "application/x-mobipocket-ebook": { "source": "apache", "extensions": ["prc", "mobi"] },
  "application/x-mpegurl": { "compressible": false },
  "application/x-ms-application": { "source": "apache", "extensions": ["application"] },
  "application/x-ms-shortcut": { "source": "apache", "extensions": ["lnk"] },
  "application/x-ms-wmd": { "source": "apache", "extensions": ["wmd"] },
  "application/x-ms-wmz": { "source": "apache", "extensions": ["wmz"] },
  "application/x-ms-xbap": { "source": "apache", "extensions": ["xbap"] },
  "application/x-msaccess": { "source": "apache", "extensions": ["mdb"] },
  "application/x-msbinder": { "source": "apache", "extensions": ["obd"] },
  "application/x-mscardfile": { "source": "apache", "extensions": ["crd"] },
  "application/x-msclip": { "source": "apache", "extensions": ["clp"] },
  "application/x-msdos-program": { "extensions": ["exe"] },
  "application/x-msdownload": { "source": "apache", "extensions": ["exe", "dll", "com", "bat", "msi"] },
  "application/x-msmediaview": { "source": "apache", "extensions": ["mvb", "m13", "m14"] },
  "application/x-msmetafile": { "source": "apache", "extensions": ["wmf", "wmz", "emf", "emz"] },
  "application/x-msmoney": { "source": "apache", "extensions": ["mny"] },
  "application/x-mspublisher": { "source": "apache", "extensions": ["pub"] },
  "application/x-msschedule": { "source": "apache", "extensions": ["scd"] },
  "application/x-msterminal": { "source": "apache", "extensions": ["trm"] },
  "application/x-mswrite": { "source": "apache", "extensions": ["wri"] },
  "application/x-netcdf": { "source": "apache", "extensions": ["nc", "cdf"] },
  "application/x-ns-proxy-autoconfig": { "compressible": true, "extensions": ["pac"] },
  "application/x-nzb": { "source": "apache", "extensions": ["nzb"] },
  "application/x-perl": { "source": "nginx", "extensions": ["pl", "pm"] },
  "application/x-pilot": { "source": "nginx", "extensions": ["prc", "pdb"] },
  "application/x-pkcs12": { "source": "apache", "compressible": false, "extensions": ["p12", "pfx"] },
  "application/x-pkcs7-certificates": { "source": "apache", "extensions": ["p7b", "spc"] },
  "application/x-pkcs7-certreqresp": { "source": "apache", "extensions": ["p7r"] },
  "application/x-pki-message": { "source": "iana" },
  "application/x-rar-compressed": { "source": "apache", "compressible": false, "extensions": ["rar"] },
  "application/x-redhat-package-manager": { "source": "nginx", "extensions": ["rpm"] },
  "application/x-research-info-systems": { "source": "apache", "extensions": ["ris"] },
  "application/x-sea": { "source": "nginx", "extensions": ["sea"] },
  "application/x-sh": { "source": "apache", "compressible": true, "extensions": ["sh"] },
  "application/x-shar": { "source": "apache", "extensions": ["shar"] },
  "application/x-shockwave-flash": { "source": "apache", "compressible": false, "extensions": ["swf"] },
  "application/x-silverlight-app": { "source": "apache", "extensions": ["xap"] },
  "application/x-sql": { "source": "apache", "extensions": ["sql"] },
  "application/x-stuffit": { "source": "apache", "compressible": false, "extensions": ["sit"] },
  "application/x-stuffitx": { "source": "apache", "extensions": ["sitx"] },
  "application/x-subrip": { "source": "apache", "extensions": ["srt"] },
  "application/x-sv4cpio": { "source": "apache", "extensions": ["sv4cpio"] },
  "application/x-sv4crc": { "source": "apache", "extensions": ["sv4crc"] },
  "application/x-t3vm-image": { "source": "apache", "extensions": ["t3"] },
  "application/x-tads": { "source": "apache", "extensions": ["gam"] },
  "application/x-tar": { "source": "apache", "compressible": true, "extensions": ["tar"] },
  "application/x-tcl": { "source": "apache", "extensions": ["tcl", "tk"] },
  "application/x-tex": { "source": "apache", "extensions": ["tex"] },
  "application/x-tex-tfm": { "source": "apache", "extensions": ["tfm"] },
  "application/x-texinfo": { "source": "apache", "extensions": ["texinfo", "texi"] },
  "application/x-tgif": { "source": "apache", "extensions": ["obj"] },
  "application/x-ustar": { "source": "apache", "extensions": ["ustar"] },
  "application/x-virtualbox-hdd": { "compressible": true, "extensions": ["hdd"] },
  "application/x-virtualbox-ova": { "compressible": true, "extensions": ["ova"] },
  "application/x-virtualbox-ovf": { "compressible": true, "extensions": ["ovf"] },
  "application/x-virtualbox-vbox": { "compressible": true, "extensions": ["vbox"] },
  "application/x-virtualbox-vbox-extpack": { "compressible": false, "extensions": ["vbox-extpack"] },
  "application/x-virtualbox-vdi": { "compressible": true, "extensions": ["vdi"] },
  "application/x-virtualbox-vhd": { "compressible": true, "extensions": ["vhd"] },
  "application/x-virtualbox-vmdk": { "compressible": true, "extensions": ["vmdk"] },
  "application/x-wais-source": { "source": "apache", "extensions": ["src"] },
  "application/x-web-app-manifest+json": { "compressible": true, "extensions": ["webapp"] },
  "application/x-www-form-urlencoded": { "source": "iana", "compressible": true },
  "application/x-x509-ca-cert": { "source": "iana", "extensions": ["der", "crt", "pem"] },
  "application/x-x509-ca-ra-cert": { "source": "iana" },
  "application/x-x509-next-ca-cert": { "source": "iana" },
  "application/x-xfig": { "source": "apache", "extensions": ["fig"] },
  "application/x-xliff+xml": { "source": "apache", "compressible": true, "extensions": ["xlf"] },
  "application/x-xpinstall": { "source": "apache", "compressible": false, "extensions": ["xpi"] },
  "application/x-xz": { "source": "apache", "extensions": ["xz"] },
  "application/x-zmachine": { "source": "apache", "extensions": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"] },
  "application/x400-bp": { "source": "iana" },
  "application/xacml+xml": { "source": "iana", "compressible": true },
  "application/xaml+xml": { "source": "apache", "compressible": true, "extensions": ["xaml"] },
  "application/xcap-att+xml": { "source": "iana", "compressible": true, "extensions": ["xav"] },
  "application/xcap-caps+xml": { "source": "iana", "compressible": true, "extensions": ["xca"] },
  "application/xcap-diff+xml": { "source": "iana", "compressible": true, "extensions": ["xdf"] },
  "application/xcap-el+xml": { "source": "iana", "compressible": true, "extensions": ["xel"] },
  "application/xcap-error+xml": { "source": "iana", "compressible": true },
  "application/xcap-ns+xml": { "source": "iana", "compressible": true, "extensions": ["xns"] },
  "application/xcon-conference-info+xml": { "source": "iana", "compressible": true },
  "application/xcon-conference-info-diff+xml": { "source": "iana", "compressible": true },
  "application/xenc+xml": { "source": "iana", "compressible": true, "extensions": ["xenc"] },
  "application/xhtml+xml": { "source": "iana", "compressible": true, "extensions": ["xhtml", "xht"] },
  "application/xhtml-voice+xml": { "source": "apache", "compressible": true },
  "application/xliff+xml": { "source": "iana", "compressible": true, "extensions": ["xlf"] },
  "application/xml": { "source": "iana", "compressible": true, "extensions": ["xml", "xsl", "xsd", "rng"] },
  "application/xml-dtd": { "source": "iana", "compressible": true, "extensions": ["dtd"] },
  "application/xml-external-parsed-entity": { "source": "iana" },
  "application/xml-patch+xml": { "source": "iana", "compressible": true },
  "application/xmpp+xml": { "source": "iana", "compressible": true },
  "application/xop+xml": { "source": "iana", "compressible": true, "extensions": ["xop"] },
  "application/xproc+xml": { "source": "apache", "compressible": true, "extensions": ["xpl"] },
  "application/xslt+xml": { "source": "iana", "compressible": true, "extensions": ["xsl", "xslt"] },
  "application/xspf+xml": { "source": "apache", "compressible": true, "extensions": ["xspf"] },
  "application/xv+xml": { "source": "iana", "compressible": true, "extensions": ["mxml", "xhvml", "xvml", "xvm"] },
  "application/yang": { "source": "iana", "extensions": ["yang"] },
  "application/yang-data+json": { "source": "iana", "compressible": true },
  "application/yang-data+xml": { "source": "iana", "compressible": true },
  "application/yang-patch+json": { "source": "iana", "compressible": true },
  "application/yang-patch+xml": { "source": "iana", "compressible": true },
  "application/yin+xml": { "source": "iana", "compressible": true, "extensions": ["yin"] },
  "application/zip": { "source": "iana", "compressible": false, "extensions": ["zip"] },
  "application/zlib": { "source": "iana" },
  "application/zstd": { "source": "iana" },
  "audio/1d-interleaved-parityfec": { "source": "iana" },
  "audio/32kadpcm": { "source": "iana" },
  "audio/3gpp": { "source": "iana", "compressible": false, "extensions": ["3gpp"] },
  "audio/3gpp2": { "source": "iana" },
  "audio/aac": { "source": "iana" },
  "audio/ac3": { "source": "iana" },
  "audio/adpcm": { "source": "apache", "extensions": ["adp"] },
  "audio/amr": { "source": "iana", "extensions": ["amr"] },
  "audio/amr-wb": { "source": "iana" },
  "audio/amr-wb+": { "source": "iana" },
  "audio/aptx": { "source": "iana" },
  "audio/asc": { "source": "iana" },
  "audio/atrac-advanced-lossless": { "source": "iana" },
  "audio/atrac-x": { "source": "iana" },
  "audio/atrac3": { "source": "iana" },
  "audio/basic": { "source": "iana", "compressible": false, "extensions": ["au", "snd"] },
  "audio/bv16": { "source": "iana" },
  "audio/bv32": { "source": "iana" },
  "audio/clearmode": { "source": "iana" },
  "audio/cn": { "source": "iana" },
  "audio/dat12": { "source": "iana" },
  "audio/dls": { "source": "iana" },
  "audio/dsr-es201108": { "source": "iana" },
  "audio/dsr-es202050": { "source": "iana" },
  "audio/dsr-es202211": { "source": "iana" },
  "audio/dsr-es202212": { "source": "iana" },
  "audio/dv": { "source": "iana" },
  "audio/dvi4": { "source": "iana" },
  "audio/eac3": { "source": "iana" },
  "audio/encaprtp": { "source": "iana" },
  "audio/evrc": { "source": "iana" },
  "audio/evrc-qcp": { "source": "iana" },
  "audio/evrc0": { "source": "iana" },
  "audio/evrc1": { "source": "iana" },
  "audio/evrcb": { "source": "iana" },
  "audio/evrcb0": { "source": "iana" },
  "audio/evrcb1": { "source": "iana" },
  "audio/evrcnw": { "source": "iana" },
  "audio/evrcnw0": { "source": "iana" },
  "audio/evrcnw1": { "source": "iana" },
  "audio/evrcwb": { "source": "iana" },
  "audio/evrcwb0": { "source": "iana" },
  "audio/evrcwb1": { "source": "iana" },
  "audio/evs": { "source": "iana" },
  "audio/flexfec": { "source": "iana" },
  "audio/fwdred": { "source": "iana" },
  "audio/g711-0": { "source": "iana" },
  "audio/g719": { "source": "iana" },
  "audio/g722": { "source": "iana" },
  "audio/g7221": { "source": "iana" },
  "audio/g723": { "source": "iana" },
  "audio/g726-16": { "source": "iana" },
  "audio/g726-24": { "source": "iana" },
  "audio/g726-32": { "source": "iana" },
  "audio/g726-40": { "source": "iana" },
  "audio/g728": { "source": "iana" },
  "audio/g729": { "source": "iana" },
  "audio/g7291": { "source": "iana" },
  "audio/g729d": { "source": "iana" },
  "audio/g729e": { "source": "iana" },
  "audio/gsm": { "source": "iana" },
  "audio/gsm-efr": { "source": "iana" },
  "audio/gsm-hr-08": { "source": "iana" },
  "audio/ilbc": { "source": "iana" },
  "audio/ip-mr_v2.5": { "source": "iana" },
  "audio/isac": { "source": "apache" },
  "audio/l16": { "source": "iana" },
  "audio/l20": { "source": "iana" },
  "audio/l24": { "source": "iana", "compressible": false },
  "audio/l8": { "source": "iana" },
  "audio/lpc": { "source": "iana" },
  "audio/melp": { "source": "iana" },
  "audio/melp1200": { "source": "iana" },
  "audio/melp2400": { "source": "iana" },
  "audio/melp600": { "source": "iana" },
  "audio/mhas": { "source": "iana" },
  "audio/midi": { "source": "apache", "extensions": ["mid", "midi", "kar", "rmi"] },
  "audio/mobile-xmf": { "source": "iana", "extensions": ["mxmf"] },
  "audio/mp3": { "compressible": false, "extensions": ["mp3"] },
  "audio/mp4": { "source": "iana", "compressible": false, "extensions": ["m4a", "mp4a"] },
  "audio/mp4a-latm": { "source": "iana" },
  "audio/mpa": { "source": "iana" },
  "audio/mpa-robust": { "source": "iana" },
  "audio/mpeg": { "source": "iana", "compressible": false, "extensions": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"] },
  "audio/mpeg4-generic": { "source": "iana" },
  "audio/musepack": { "source": "apache" },
  "audio/ogg": { "source": "iana", "compressible": false, "extensions": ["oga", "ogg", "spx", "opus"] },
  "audio/opus": { "source": "iana" },
  "audio/parityfec": { "source": "iana" },
  "audio/pcma": { "source": "iana" },
  "audio/pcma-wb": { "source": "iana" },
  "audio/pcmu": { "source": "iana" },
  "audio/pcmu-wb": { "source": "iana" },
  "audio/prs.sid": { "source": "iana" },
  "audio/qcelp": { "source": "iana" },
  "audio/raptorfec": { "source": "iana" },
  "audio/red": { "source": "iana" },
  "audio/rtp-enc-aescm128": { "source": "iana" },
  "audio/rtp-midi": { "source": "iana" },
  "audio/rtploopback": { "source": "iana" },
  "audio/rtx": { "source": "iana" },
  "audio/s3m": { "source": "apache", "extensions": ["s3m"] },
  "audio/scip": { "source": "iana" },
  "audio/silk": { "source": "apache", "extensions": ["sil"] },
  "audio/smv": { "source": "iana" },
  "audio/smv-qcp": { "source": "iana" },
  "audio/smv0": { "source": "iana" },
  "audio/sofa": { "source": "iana" },
  "audio/sp-midi": { "source": "iana" },
  "audio/speex": { "source": "iana" },
  "audio/t140c": { "source": "iana" },
  "audio/t38": { "source": "iana" },
  "audio/telephone-event": { "source": "iana" },
  "audio/tetra_acelp": { "source": "iana" },
  "audio/tetra_acelp_bb": { "source": "iana" },
  "audio/tone": { "source": "iana" },
  "audio/tsvcis": { "source": "iana" },
  "audio/uemclip": { "source": "iana" },
  "audio/ulpfec": { "source": "iana" },
  "audio/usac": { "source": "iana" },
  "audio/vdvi": { "source": "iana" },
  "audio/vmr-wb": { "source": "iana" },
  "audio/vnd.3gpp.iufp": { "source": "iana" },
  "audio/vnd.4sb": { "source": "iana" },
  "audio/vnd.audiokoz": { "source": "iana" },
  "audio/vnd.celp": { "source": "iana" },
  "audio/vnd.cisco.nse": { "source": "iana" },
  "audio/vnd.cmles.radio-events": { "source": "iana" },
  "audio/vnd.cns.anp1": { "source": "iana" },
  "audio/vnd.cns.inf1": { "source": "iana" },
  "audio/vnd.dece.audio": { "source": "iana", "extensions": ["uva", "uvva"] },
  "audio/vnd.digital-winds": { "source": "iana", "extensions": ["eol"] },
  "audio/vnd.dlna.adts": { "source": "iana" },
  "audio/vnd.dolby.heaac.1": { "source": "iana" },
  "audio/vnd.dolby.heaac.2": { "source": "iana" },
  "audio/vnd.dolby.mlp": { "source": "iana" },
  "audio/vnd.dolby.mps": { "source": "iana" },
  "audio/vnd.dolby.pl2": { "source": "iana" },
  "audio/vnd.dolby.pl2x": { "source": "iana" },
  "audio/vnd.dolby.pl2z": { "source": "iana" },
  "audio/vnd.dolby.pulse.1": { "source": "iana" },
  "audio/vnd.dra": { "source": "iana", "extensions": ["dra"] },
  "audio/vnd.dts": { "source": "iana", "extensions": ["dts"] },
  "audio/vnd.dts.hd": { "source": "iana", "extensions": ["dtshd"] },
  "audio/vnd.dts.uhd": { "source": "iana" },
  "audio/vnd.dvb.file": { "source": "iana" },
  "audio/vnd.everad.plj": { "source": "iana" },
  "audio/vnd.hns.audio": { "source": "iana" },
  "audio/vnd.lucent.voice": { "source": "iana", "extensions": ["lvp"] },
  "audio/vnd.ms-playready.media.pya": { "source": "iana", "extensions": ["pya"] },
  "audio/vnd.nokia.mobile-xmf": { "source": "iana" },
  "audio/vnd.nortel.vbk": { "source": "iana" },
  "audio/vnd.nuera.ecelp4800": { "source": "iana", "extensions": ["ecelp4800"] },
  "audio/vnd.nuera.ecelp7470": { "source": "iana", "extensions": ["ecelp7470"] },
  "audio/vnd.nuera.ecelp9600": { "source": "iana", "extensions": ["ecelp9600"] },
  "audio/vnd.octel.sbc": { "source": "iana" },
  "audio/vnd.presonus.multitrack": { "source": "iana" },
  "audio/vnd.qcelp": { "source": "iana" },
  "audio/vnd.rhetorex.32kadpcm": { "source": "iana" },
  "audio/vnd.rip": { "source": "iana", "extensions": ["rip"] },
  "audio/vnd.rn-realaudio": { "compressible": false },
  "audio/vnd.sealedmedia.softseal.mpeg": { "source": "iana" },
  "audio/vnd.vmx.cvsd": { "source": "iana" },
  "audio/vnd.wave": { "compressible": false },
  "audio/vorbis": { "source": "iana", "compressible": false },
  "audio/vorbis-config": { "source": "iana" },
  "audio/wav": { "compressible": false, "extensions": ["wav"] },
  "audio/wave": { "compressible": false, "extensions": ["wav"] },
  "audio/webm": { "source": "apache", "compressible": false, "extensions": ["weba"] },
  "audio/x-aac": { "source": "apache", "compressible": false, "extensions": ["aac"] },
  "audio/x-aiff": { "source": "apache", "extensions": ["aif", "aiff", "aifc"] },
  "audio/x-caf": { "source": "apache", "compressible": false, "extensions": ["caf"] },
  "audio/x-flac": { "source": "apache", "extensions": ["flac"] },
  "audio/x-m4a": { "source": "nginx", "extensions": ["m4a"] },
  "audio/x-matroska": { "source": "apache", "extensions": ["mka"] },
  "audio/x-mpegurl": { "source": "apache", "extensions": ["m3u"] },
  "audio/x-ms-wax": { "source": "apache", "extensions": ["wax"] },
  "audio/x-ms-wma": { "source": "apache", "extensions": ["wma"] },
  "audio/x-pn-realaudio": { "source": "apache", "extensions": ["ram", "ra"] },
  "audio/x-pn-realaudio-plugin": { "source": "apache", "extensions": ["rmp"] },
  "audio/x-realaudio": { "source": "nginx", "extensions": ["ra"] },
  "audio/x-tta": { "source": "apache" },
  "audio/x-wav": { "source": "apache", "extensions": ["wav"] },
  "audio/xm": { "source": "apache", "extensions": ["xm"] },
  "chemical/x-cdx": { "source": "apache", "extensions": ["cdx"] },
  "chemical/x-cif": { "source": "apache", "extensions": ["cif"] },
  "chemical/x-cmdf": { "source": "apache", "extensions": ["cmdf"] },
  "chemical/x-cml": { "source": "apache", "extensions": ["cml"] },
  "chemical/x-csml": { "source": "apache", "extensions": ["csml"] },
  "chemical/x-pdb": { "source": "apache" },
  "chemical/x-xyz": { "source": "apache", "extensions": ["xyz"] },
  "font/collection": { "source": "iana", "extensions": ["ttc"] },
  "font/otf": { "source": "iana", "compressible": true, "extensions": ["otf"] },
  "font/sfnt": { "source": "iana" },
  "font/ttf": { "source": "iana", "compressible": true, "extensions": ["ttf"] },
  "font/woff": { "source": "iana", "extensions": ["woff"] },
  "font/woff2": { "source": "iana", "extensions": ["woff2"] },
  "image/aces": { "source": "iana", "extensions": ["exr"] },
  "image/apng": { "compressible": false, "extensions": ["apng"] },
  "image/avci": { "source": "iana", "extensions": ["avci"] },
  "image/avcs": { "source": "iana", "extensions": ["avcs"] },
  "image/avif": { "source": "iana", "compressible": false, "extensions": ["avif"] },
  "image/bmp": { "source": "iana", "compressible": true, "extensions": ["bmp"] },
  "image/cgm": { "source": "iana", "extensions": ["cgm"] },
  "image/dicom-rle": { "source": "iana", "extensions": ["drle"] },
  "image/emf": { "source": "iana", "extensions": ["emf"] },
  "image/fits": { "source": "iana", "extensions": ["fits"] },
  "image/g3fax": { "source": "iana", "extensions": ["g3"] },
  "image/gif": { "source": "iana", "compressible": false, "extensions": ["gif"] },
  "image/heic": { "source": "iana", "extensions": ["heic"] },
  "image/heic-sequence": { "source": "iana", "extensions": ["heics"] },
  "image/heif": { "source": "iana", "extensions": ["heif"] },
  "image/heif-sequence": { "source": "iana", "extensions": ["heifs"] },
  "image/hej2k": { "source": "iana", "extensions": ["hej2"] },
  "image/hsj2": { "source": "iana", "extensions": ["hsj2"] },
  "image/ief": { "source": "iana", "extensions": ["ief"] },
  "image/jls": { "source": "iana", "extensions": ["jls"] },
  "image/jp2": { "source": "iana", "compressible": false, "extensions": ["jp2", "jpg2"] },
  "image/jpeg": { "source": "iana", "compressible": false, "extensions": ["jpeg", "jpg", "jpe"] },
  "image/jph": { "source": "iana", "extensions": ["jph"] },
  "image/jphc": { "source": "iana", "extensions": ["jhc"] },
  "image/jpm": { "source": "iana", "compressible": false, "extensions": ["jpm"] },
  "image/jpx": { "source": "iana", "compressible": false, "extensions": ["jpx", "jpf"] },
  "image/jxr": { "source": "iana", "extensions": ["jxr"] },
  "image/jxra": { "source": "iana", "extensions": ["jxra"] },
  "image/jxrs": { "source": "iana", "extensions": ["jxrs"] },
  "image/jxs": { "source": "iana", "extensions": ["jxs"] },
  "image/jxsc": { "source": "iana", "extensions": ["jxsc"] },
  "image/jxsi": { "source": "iana", "extensions": ["jxsi"] },
  "image/jxss": { "source": "iana", "extensions": ["jxss"] },
  "image/ktx": { "source": "iana", "extensions": ["ktx"] },
  "image/ktx2": { "source": "iana", "extensions": ["ktx2"] },
  "image/naplps": { "source": "iana" },
  "image/pjpeg": { "compressible": false },
  "image/png": { "source": "iana", "compressible": false, "extensions": ["png"] },
  "image/prs.btif": { "source": "iana", "extensions": ["btif"] },
  "image/prs.pti": { "source": "iana", "extensions": ["pti"] },
  "image/pwg-raster": { "source": "iana" },
  "image/sgi": { "source": "apache", "extensions": ["sgi"] },
  "image/svg+xml": { "source": "iana", "compressible": true, "extensions": ["svg", "svgz"] },
  "image/t38": { "source": "iana", "extensions": ["t38"] },
  "image/tiff": { "source": "iana", "compressible": false, "extensions": ["tif", "tiff"] },
  "image/tiff-fx": { "source": "iana", "extensions": ["tfx"] },
  "image/vnd.adobe.photoshop": { "source": "iana", "compressible": true, "extensions": ["psd"] },
  "image/vnd.airzip.accelerator.azv": { "source": "iana", "extensions": ["azv"] },
  "image/vnd.cns.inf2": { "source": "iana" },
  "image/vnd.dece.graphic": { "source": "iana", "extensions": ["uvi", "uvvi", "uvg", "uvvg"] },
  "image/vnd.djvu": { "source": "iana", "extensions": ["djvu", "djv"] },
  "image/vnd.dvb.subtitle": { "source": "iana", "extensions": ["sub"] },
  "image/vnd.dwg": { "source": "iana", "extensions": ["dwg"] },
  "image/vnd.dxf": { "source": "iana", "extensions": ["dxf"] },
  "image/vnd.fastbidsheet": { "source": "iana", "extensions": ["fbs"] },
  "image/vnd.fpx": { "source": "iana", "extensions": ["fpx"] },
  "image/vnd.fst": { "source": "iana", "extensions": ["fst"] },
  "image/vnd.fujixerox.edmics-mmr": { "source": "iana", "extensions": ["mmr"] },
  "image/vnd.fujixerox.edmics-rlc": { "source": "iana", "extensions": ["rlc"] },
  "image/vnd.globalgraphics.pgb": { "source": "iana" },
  "image/vnd.microsoft.icon": { "source": "iana", "compressible": true, "extensions": ["ico"] },
  "image/vnd.mix": { "source": "iana" },
  "image/vnd.mozilla.apng": { "source": "iana" },
  "image/vnd.ms-dds": { "compressible": true, "extensions": ["dds"] },
  "image/vnd.ms-modi": { "source": "iana", "extensions": ["mdi"] },
  "image/vnd.ms-photo": { "source": "apache", "extensions": ["wdp"] },
  "image/vnd.net-fpx": { "source": "iana", "extensions": ["npx"] },
  "image/vnd.pco.b16": { "source": "iana", "extensions": ["b16"] },
  "image/vnd.radiance": { "source": "iana" },
  "image/vnd.sealed.png": { "source": "iana" },
  "image/vnd.sealedmedia.softseal.gif": { "source": "iana" },
  "image/vnd.sealedmedia.softseal.jpg": { "source": "iana" },
  "image/vnd.svf": { "source": "iana" },
  "image/vnd.tencent.tap": { "source": "iana", "extensions": ["tap"] },
  "image/vnd.valve.source.texture": { "source": "iana", "extensions": ["vtf"] },
  "image/vnd.wap.wbmp": { "source": "iana", "extensions": ["wbmp"] },
  "image/vnd.xiff": { "source": "iana", "extensions": ["xif"] },
  "image/vnd.zbrush.pcx": { "source": "iana", "extensions": ["pcx"] },
  "image/webp": { "source": "apache", "extensions": ["webp"] },
  "image/wmf": { "source": "iana", "extensions": ["wmf"] },
  "image/x-3ds": { "source": "apache", "extensions": ["3ds"] },
  "image/x-cmu-raster": { "source": "apache", "extensions": ["ras"] },
  "image/x-cmx": { "source": "apache", "extensions": ["cmx"] },
  "image/x-freehand": { "source": "apache", "extensions": ["fh", "fhc", "fh4", "fh5", "fh7"] },
  "image/x-icon": { "source": "apache", "compressible": true, "extensions": ["ico"] },
  "image/x-jng": { "source": "nginx", "extensions": ["jng"] },
  "image/x-mrsid-image": { "source": "apache", "extensions": ["sid"] },
  "image/x-ms-bmp": { "source": "nginx", "compressible": true, "extensions": ["bmp"] },
  "image/x-pcx": { "source": "apache", "extensions": ["pcx"] },
  "image/x-pict": { "source": "apache", "extensions": ["pic", "pct"] },
  "image/x-portable-anymap": { "source": "apache", "extensions": ["pnm"] },
  "image/x-portable-bitmap": { "source": "apache", "extensions": ["pbm"] },
  "image/x-portable-graymap": { "source": "apache", "extensions": ["pgm"] },
  "image/x-portable-pixmap": { "source": "apache", "extensions": ["ppm"] },
  "image/x-rgb": { "source": "apache", "extensions": ["rgb"] },
  "image/x-tga": { "source": "apache", "extensions": ["tga"] },
  "image/x-xbitmap": { "source": "apache", "extensions": ["xbm"] },
  "image/x-xcf": { "compressible": false },
  "image/x-xpixmap": { "source": "apache", "extensions": ["xpm"] },
  "image/x-xwindowdump": { "source": "apache", "extensions": ["xwd"] },
  "message/cpim": { "source": "iana" },
  "message/delivery-status": { "source": "iana" },
  "message/disposition-notification": { "source": "iana", "extensions": ["disposition-notification"] },
  "message/external-body": { "source": "iana" },
  "message/feedback-report": { "source": "iana" },
  "message/global": { "source": "iana", "extensions": ["u8msg"] },
  "message/global-delivery-status": { "source": "iana", "extensions": ["u8dsn"] },
  "message/global-disposition-notification": { "source": "iana", "extensions": ["u8mdn"] },
  "message/global-headers": { "source": "iana", "extensions": ["u8hdr"] },
  "message/http": { "source": "iana", "compressible": false },
  "message/imdn+xml": { "source": "iana", "compressible": true },
  "message/news": { "source": "iana" },
  "message/partial": { "source": "iana", "compressible": false },
  "message/rfc822": { "source": "iana", "compressible": true, "extensions": ["eml", "mime"] },
  "message/s-http": { "source": "iana" },
  "message/sip": { "source": "iana" },
  "message/sipfrag": { "source": "iana" },
  "message/tracking-status": { "source": "iana" },
  "message/vnd.si.simp": { "source": "iana" },
  "message/vnd.wfa.wsc": { "source": "iana", "extensions": ["wsc"] },
  "model/3mf": { "source": "iana", "extensions": ["3mf"] },
  "model/e57": { "source": "iana" },
  "model/gltf+json": { "source": "iana", "compressible": true, "extensions": ["gltf"] },
  "model/gltf-binary": { "source": "iana", "compressible": true, "extensions": ["glb"] },
  "model/iges": { "source": "iana", "compressible": false, "extensions": ["igs", "iges"] },
  "model/mesh": { "source": "iana", "compressible": false, "extensions": ["msh", "mesh", "silo"] },
  "model/mtl": { "source": "iana", "extensions": ["mtl"] },
  "model/obj": { "source": "iana", "extensions": ["obj"] },
  "model/step": { "source": "iana" },
  "model/step+xml": { "source": "iana", "compressible": true, "extensions": ["stpx"] },
  "model/step+zip": { "source": "iana", "compressible": false, "extensions": ["stpz"] },
  "model/step-xml+zip": { "source": "iana", "compressible": false, "extensions": ["stpxz"] },
  "model/stl": { "source": "iana", "extensions": ["stl"] },
  "model/vnd.collada+xml": { "source": "iana", "compressible": true, "extensions": ["dae"] },
  "model/vnd.dwf": { "source": "iana", "extensions": ["dwf"] },
  "model/vnd.flatland.3dml": { "source": "iana" },
  "model/vnd.gdl": { "source": "iana", "extensions": ["gdl"] },
  "model/vnd.gs-gdl": { "source": "apache" },
  "model/vnd.gs.gdl": { "source": "iana" },
  "model/vnd.gtw": { "source": "iana", "extensions": ["gtw"] },
  "model/vnd.moml+xml": { "source": "iana", "compressible": true },
  "model/vnd.mts": { "source": "iana", "extensions": ["mts"] },
  "model/vnd.opengex": { "source": "iana", "extensions": ["ogex"] },
  "model/vnd.parasolid.transmit.binary": { "source": "iana", "extensions": ["x_b"] },
  "model/vnd.parasolid.transmit.text": { "source": "iana", "extensions": ["x_t"] },
  "model/vnd.pytha.pyox": { "source": "iana" },
  "model/vnd.rosette.annotated-data-model": { "source": "iana" },
  "model/vnd.sap.vds": { "source": "iana", "extensions": ["vds"] },
  "model/vnd.usdz+zip": { "source": "iana", "compressible": false, "extensions": ["usdz"] },
  "model/vnd.valve.source.compiled-map": { "source": "iana", "extensions": ["bsp"] },
  "model/vnd.vtu": { "source": "iana", "extensions": ["vtu"] },
  "model/vrml": { "source": "iana", "compressible": false, "extensions": ["wrl", "vrml"] },
  "model/x3d+binary": { "source": "apache", "compressible": false, "extensions": ["x3db", "x3dbz"] },
  "model/x3d+fastinfoset": { "source": "iana", "extensions": ["x3db"] },
  "model/x3d+vrml": { "source": "apache", "compressible": false, "extensions": ["x3dv", "x3dvz"] },
  "model/x3d+xml": { "source": "iana", "compressible": true, "extensions": ["x3d", "x3dz"] },
  "model/x3d-vrml": { "source": "iana", "extensions": ["x3dv"] },
  "multipart/alternative": { "source": "iana", "compressible": false },
  "multipart/appledouble": { "source": "iana" },
  "multipart/byteranges": { "source": "iana" },
  "multipart/digest": { "source": "iana" },
  "multipart/encrypted": { "source": "iana", "compressible": false },
  "multipart/form-data": { "source": "iana", "compressible": false },
  "multipart/header-set": { "source": "iana" },
  "multipart/mixed": { "source": "iana" },
  "multipart/multilingual": { "source": "iana" },
  "multipart/parallel": { "source": "iana" },
  "multipart/related": { "source": "iana", "compressible": false },
  "multipart/report": { "source": "iana" },
  "multipart/signed": { "source": "iana", "compressible": false },
  "multipart/vnd.bint.med-plus": { "source": "iana" },
  "multipart/voice-message": { "source": "iana" },
  "multipart/x-mixed-replace": { "source": "iana" },
  "text/1d-interleaved-parityfec": { "source": "iana" },
  "text/cache-manifest": { "source": "iana", "compressible": true, "extensions": ["appcache", "manifest"] },
  "text/calendar": { "source": "iana", "extensions": ["ics", "ifb"] },
  "text/calender": { "compressible": true },
  "text/cmd": { "compressible": true },
  "text/coffeescript": { "extensions": ["coffee", "litcoffee"] },
  "text/cql": { "source": "iana" },
  "text/cql-expression": { "source": "iana" },
  "text/cql-identifier": { "source": "iana" },
  "text/css": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["css"] },
  "text/csv": { "source": "iana", "compressible": true, "extensions": ["csv"] },
  "text/csv-schema": { "source": "iana" },
  "text/directory": { "source": "iana" },
  "text/dns": { "source": "iana" },
  "text/ecmascript": { "source": "iana" },
  "text/encaprtp": { "source": "iana" },
  "text/enriched": { "source": "iana" },
  "text/fhirpath": { "source": "iana" },
  "text/flexfec": { "source": "iana" },
  "text/fwdred": { "source": "iana" },
  "text/gff3": { "source": "iana" },
  "text/grammar-ref-list": { "source": "iana" },
  "text/html": { "source": "iana", "compressible": true, "extensions": ["html", "htm", "shtml"] },
  "text/jade": { "extensions": ["jade"] },
  "text/javascript": { "source": "iana", "compressible": true },
  "text/jcr-cnd": { "source": "iana" },
  "text/jsx": { "compressible": true, "extensions": ["jsx"] },
  "text/less": { "compressible": true, "extensions": ["less"] },
  "text/markdown": { "source": "iana", "compressible": true, "extensions": ["markdown", "md"] },
  "text/mathml": { "source": "nginx", "extensions": ["mml"] },
  "text/mdx": { "compressible": true, "extensions": ["mdx"] },
  "text/mizar": { "source": "iana" },
  "text/n3": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["n3"] },
  "text/parameters": { "source": "iana", "charset": "UTF-8" },
  "text/parityfec": { "source": "iana" },
  "text/plain": { "source": "iana", "compressible": true, "extensions": ["txt", "text", "conf", "def", "list", "log", "in", "ini"] },
  "text/provenance-notation": { "source": "iana", "charset": "UTF-8" },
  "text/prs.fallenstein.rst": { "source": "iana" },
  "text/prs.lines.tag": { "source": "iana", "extensions": ["dsc"] },
  "text/prs.prop.logic": { "source": "iana" },
  "text/raptorfec": { "source": "iana" },
  "text/red": { "source": "iana" },
  "text/rfc822-headers": { "source": "iana" },
  "text/richtext": { "source": "iana", "compressible": true, "extensions": ["rtx"] },
  "text/rtf": { "source": "iana", "compressible": true, "extensions": ["rtf"] },
  "text/rtp-enc-aescm128": { "source": "iana" },
  "text/rtploopback": { "source": "iana" },
  "text/rtx": { "source": "iana" },
  "text/sgml": { "source": "iana", "extensions": ["sgml", "sgm"] },
  "text/shaclc": { "source": "iana" },
  "text/shex": { "source": "iana", "extensions": ["shex"] },
  "text/slim": { "extensions": ["slim", "slm"] },
  "text/spdx": { "source": "iana", "extensions": ["spdx"] },
  "text/strings": { "source": "iana" },
  "text/stylus": { "extensions": ["stylus", "styl"] },
  "text/t140": { "source": "iana" },
  "text/tab-separated-values": { "source": "iana", "compressible": true, "extensions": ["tsv"] },
  "text/troff": { "source": "iana", "extensions": ["t", "tr", "roff", "man", "me", "ms"] },
  "text/turtle": { "source": "iana", "charset": "UTF-8", "extensions": ["ttl"] },
  "text/ulpfec": { "source": "iana" },
  "text/uri-list": { "source": "iana", "compressible": true, "extensions": ["uri", "uris", "urls"] },
  "text/vcard": { "source": "iana", "compressible": true, "extensions": ["vcard"] },
  "text/vnd.a": { "source": "iana" },
  "text/vnd.abc": { "source": "iana" },
  "text/vnd.ascii-art": { "source": "iana" },
  "text/vnd.curl": { "source": "iana", "extensions": ["curl"] },
  "text/vnd.curl.dcurl": { "source": "apache", "extensions": ["dcurl"] },
  "text/vnd.curl.mcurl": { "source": "apache", "extensions": ["mcurl"] },
  "text/vnd.curl.scurl": { "source": "apache", "extensions": ["scurl"] },
  "text/vnd.debian.copyright": { "source": "iana", "charset": "UTF-8" },
  "text/vnd.dmclientscript": { "source": "iana" },
  "text/vnd.dvb.subtitle": { "source": "iana", "extensions": ["sub"] },
  "text/vnd.esmertec.theme-descriptor": { "source": "iana", "charset": "UTF-8" },
  "text/vnd.familysearch.gedcom": { "source": "iana", "extensions": ["ged"] },
  "text/vnd.ficlab.flt": { "source": "iana" },
  "text/vnd.fly": { "source": "iana", "extensions": ["fly"] },
  "text/vnd.fmi.flexstor": { "source": "iana", "extensions": ["flx"] },
  "text/vnd.gml": { "source": "iana" },
  "text/vnd.graphviz": { "source": "iana", "extensions": ["gv"] },
  "text/vnd.hans": { "source": "iana" },
  "text/vnd.hgl": { "source": "iana" },
  "text/vnd.in3d.3dml": { "source": "iana", "extensions": ["3dml"] },
  "text/vnd.in3d.spot": { "source": "iana", "extensions": ["spot"] },
  "text/vnd.iptc.newsml": { "source": "iana" },
  "text/vnd.iptc.nitf": { "source": "iana" },
  "text/vnd.latex-z": { "source": "iana" },
  "text/vnd.motorola.reflex": { "source": "iana" },
  "text/vnd.ms-mediapackage": { "source": "iana" },
  "text/vnd.net2phone.commcenter.command": { "source": "iana" },
  "text/vnd.radisys.msml-basic-layout": { "source": "iana" },
  "text/vnd.senx.warpscript": { "source": "iana" },
  "text/vnd.si.uricatalogue": { "source": "iana" },
  "text/vnd.sosi": { "source": "iana" },
  "text/vnd.sun.j2me.app-descriptor": { "source": "iana", "charset": "UTF-8", "extensions": ["jad"] },
  "text/vnd.trolltech.linguist": { "source": "iana", "charset": "UTF-8" },
  "text/vnd.wap.si": { "source": "iana" },
  "text/vnd.wap.sl": { "source": "iana" },
  "text/vnd.wap.wml": { "source": "iana", "extensions": ["wml"] },
  "text/vnd.wap.wmlscript": { "source": "iana", "extensions": ["wmls"] },
  "text/vtt": { "source": "iana", "charset": "UTF-8", "compressible": true, "extensions": ["vtt"] },
  "text/x-asm": { "source": "apache", "extensions": ["s", "asm"] },
  "text/x-c": { "source": "apache", "extensions": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"] },
  "text/x-component": { "source": "nginx", "extensions": ["htc"] },
  "text/x-fortran": { "source": "apache", "extensions": ["f", "for", "f77", "f90"] },
  "text/x-gwt-rpc": { "compressible": true },
  "text/x-handlebars-template": { "extensions": ["hbs"] },
  "text/x-java-source": { "source": "apache", "extensions": ["java"] },
  "text/x-jquery-tmpl": { "compressible": true },
  "text/x-lua": { "extensions": ["lua"] },
  "text/x-markdown": { "compressible": true, "extensions": ["mkd"] },
  "text/x-nfo": { "source": "apache", "extensions": ["nfo"] },
  "text/x-opml": { "source": "apache", "extensions": ["opml"] },
  "text/x-org": { "compressible": true, "extensions": ["org"] },
  "text/x-pascal": { "source": "apache", "extensions": ["p", "pas"] },
  "text/x-processing": { "compressible": true, "extensions": ["pde"] },
  "text/x-sass": { "extensions": ["sass"] },
  "text/x-scss": { "extensions": ["scss"] },
  "text/x-setext": { "source": "apache", "extensions": ["etx"] },
  "text/x-sfv": { "source": "apache", "extensions": ["sfv"] },
  "text/x-suse-ymp": { "compressible": true, "extensions": ["ymp"] },
  "text/x-uuencode": { "source": "apache", "extensions": ["uu"] },
  "text/x-vcalendar": { "source": "apache", "extensions": ["vcs"] },
  "text/x-vcard": { "source": "apache", "extensions": ["vcf"] },
  "text/xml": { "source": "iana", "compressible": true, "extensions": ["xml"] },
  "text/xml-external-parsed-entity": { "source": "iana" },
  "text/yaml": { "compressible": true, "extensions": ["yaml", "yml"] },
  "video/1d-interleaved-parityfec": { "source": "iana" },
  "video/3gpp": { "source": "iana", "extensions": ["3gp", "3gpp"] },
  "video/3gpp-tt": { "source": "iana" },
  "video/3gpp2": { "source": "iana", "extensions": ["3g2"] },
  "video/av1": { "source": "iana" },
  "video/bmpeg": { "source": "iana" },
  "video/bt656": { "source": "iana" },
  "video/celb": { "source": "iana" },
  "video/dv": { "source": "iana" },
  "video/encaprtp": { "source": "iana" },
  "video/ffv1": { "source": "iana" },
  "video/flexfec": { "source": "iana" },
  "video/h261": { "source": "iana", "extensions": ["h261"] },
  "video/h263": { "source": "iana", "extensions": ["h263"] },
  "video/h263-1998": { "source": "iana" },
  "video/h263-2000": { "source": "iana" },
  "video/h264": { "source": "iana", "extensions": ["h264"] },
  "video/h264-rcdo": { "source": "iana" },
  "video/h264-svc": { "source": "iana" },
  "video/h265": { "source": "iana" },
  "video/iso.segment": { "source": "iana", "extensions": ["m4s"] },
  "video/jpeg": { "source": "iana", "extensions": ["jpgv"] },
  "video/jpeg2000": { "source": "iana" },
  "video/jpm": { "source": "apache", "extensions": ["jpm", "jpgm"] },
  "video/jxsv": { "source": "iana" },
  "video/mj2": { "source": "iana", "extensions": ["mj2", "mjp2"] },
  "video/mp1s": { "source": "iana" },
  "video/mp2p": { "source": "iana" },
  "video/mp2t": { "source": "iana", "extensions": ["ts"] },
  "video/mp4": { "source": "iana", "compressible": false, "extensions": ["mp4", "mp4v", "mpg4"] },
  "video/mp4v-es": { "source": "iana" },
  "video/mpeg": { "source": "iana", "compressible": false, "extensions": ["mpeg", "mpg", "mpe", "m1v", "m2v"] },
  "video/mpeg4-generic": { "source": "iana" },
  "video/mpv": { "source": "iana" },
  "video/nv": { "source": "iana" },
  "video/ogg": { "source": "iana", "compressible": false, "extensions": ["ogv"] },
  "video/parityfec": { "source": "iana" },
  "video/pointer": { "source": "iana" },
  "video/quicktime": { "source": "iana", "compressible": false, "extensions": ["qt", "mov"] },
  "video/raptorfec": { "source": "iana" },
  "video/raw": { "source": "iana" },
  "video/rtp-enc-aescm128": { "source": "iana" },
  "video/rtploopback": { "source": "iana" },
  "video/rtx": { "source": "iana" },
  "video/scip": { "source": "iana" },
  "video/smpte291": { "source": "iana" },
  "video/smpte292m": { "source": "iana" },
  "video/ulpfec": { "source": "iana" },
  "video/vc1": { "source": "iana" },
  "video/vc2": { "source": "iana" },
  "video/vnd.cctv": { "source": "iana" },
  "video/vnd.dece.hd": { "source": "iana", "extensions": ["uvh", "uvvh"] },
  "video/vnd.dece.mobile": { "source": "iana", "extensions": ["uvm", "uvvm"] },
  "video/vnd.dece.mp4": { "source": "iana" },
  "video/vnd.dece.pd": { "source": "iana", "extensions": ["uvp", "uvvp"] },
  "video/vnd.dece.sd": { "source": "iana", "extensions": ["uvs", "uvvs"] },
  "video/vnd.dece.video": { "source": "iana", "extensions": ["uvv", "uvvv"] },
  "video/vnd.directv.mpeg": { "source": "iana" },
  "video/vnd.directv.mpeg-tts": { "source": "iana" },
  "video/vnd.dlna.mpeg-tts": { "source": "iana" },
  "video/vnd.dvb.file": { "source": "iana", "extensions": ["dvb"] },
  "video/vnd.fvt": { "source": "iana", "extensions": ["fvt"] },
  "video/vnd.hns.video": { "source": "iana" },
  "video/vnd.iptvforum.1dparityfec-1010": { "source": "iana" },
  "video/vnd.iptvforum.1dparityfec-2005": { "source": "iana" },
  "video/vnd.iptvforum.2dparityfec-1010": { "source": "iana" },
  "video/vnd.iptvforum.2dparityfec-2005": { "source": "iana" },
  "video/vnd.iptvforum.ttsavc": { "source": "iana" },
  "video/vnd.iptvforum.ttsmpeg2": { "source": "iana" },
  "video/vnd.motorola.video": { "source": "iana" },
  "video/vnd.motorola.videop": { "source": "iana" },
  "video/vnd.mpegurl": { "source": "iana", "extensions": ["mxu", "m4u"] },
  "video/vnd.ms-playready.media.pyv": { "source": "iana", "extensions": ["pyv"] },
  "video/vnd.nokia.interleaved-multimedia": { "source": "iana" },
  "video/vnd.nokia.mp4vr": { "source": "iana" },
  "video/vnd.nokia.videovoip": { "source": "iana" },
  "video/vnd.objectvideo": { "source": "iana" },
  "video/vnd.radgamettools.bink": { "source": "iana" },
  "video/vnd.radgamettools.smacker": { "source": "iana" },
  "video/vnd.sealed.mpeg1": { "source": "iana" },
  "video/vnd.sealed.mpeg4": { "source": "iana" },
  "video/vnd.sealed.swf": { "source": "iana" },
  "video/vnd.sealedmedia.softseal.mov": { "source": "iana" },
  "video/vnd.uvvu.mp4": { "source": "iana", "extensions": ["uvu", "uvvu"] },
  "video/vnd.vivo": { "source": "iana", "extensions": ["viv"] },
  "video/vnd.youtube.yt": { "source": "iana" },
  "video/vp8": { "source": "iana" },
  "video/vp9": { "source": "iana" },
  "video/webm": { "source": "apache", "compressible": false, "extensions": ["webm"] },
  "video/x-f4v": { "source": "apache", "extensions": ["f4v"] },
  "video/x-fli": { "source": "apache", "extensions": ["fli"] },
  "video/x-flv": { "source": "apache", "compressible": false, "extensions": ["flv"] },
  "video/x-m4v": { "source": "apache", "extensions": ["m4v"] },
  "video/x-matroska": { "source": "apache", "compressible": false, "extensions": ["mkv", "mk3d", "mks"] },
  "video/x-mng": { "source": "apache", "extensions": ["mng"] },
  "video/x-ms-asf": { "source": "apache", "extensions": ["asf", "asx"] },
  "video/x-ms-vob": { "source": "apache", "extensions": ["vob"] },
  "video/x-ms-wm": { "source": "apache", "extensions": ["wm"] },
  "video/x-ms-wmv": { "source": "apache", "compressible": false, "extensions": ["wmv"] },
  "video/x-ms-wmx": { "source": "apache", "extensions": ["wmx"] },
  "video/x-ms-wvx": { "source": "apache", "extensions": ["wvx"] },
  "video/x-msvideo": { "source": "apache", "extensions": ["avi"] },
  "video/x-sgi-movie": { "source": "apache", "extensions": ["movie"] },
  "video/x-smv": { "source": "apache", "extensions": ["smv"] },
  "x-conference/x-cooltalk": { "source": "apache", "extensions": ["ice"] },
  "x-shader/x-fragment": { "compressible": true },
  "x-shader/x-vertex": { "compressible": true }
};
var mimeDb;
var hasRequiredMimeDb;
function requireMimeDb() {
  if (hasRequiredMimeDb) return mimeDb;
  hasRequiredMimeDb = 1;
  mimeDb = require$$0;
  return mimeDb;
}
var hasRequiredMimeTypes;
function requireMimeTypes() {
  if (hasRequiredMimeTypes) return mimeTypes;
  hasRequiredMimeTypes = 1;
  (function(exports$1) {
    var db = requireMimeDb();
    var extname = require$$1.extname;
    var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/;
    var TEXT_TYPE_REGEXP = /^text\//i;
    exports$1.charset = charset;
    exports$1.charsets = { lookup: charset };
    exports$1.contentType = contentType;
    exports$1.extension = extension2;
    exports$1.extensions = /* @__PURE__ */ Object.create(null);
    exports$1.lookup = lookup;
    exports$1.types = /* @__PURE__ */ Object.create(null);
    populateMaps(exports$1.extensions, exports$1.types);
    function charset(type2) {
      if (!type2 || typeof type2 !== "string") {
        return false;
      }
      var match = EXTRACT_TYPE_REGEXP.exec(type2);
      var mime = match && db[match[1].toLowerCase()];
      if (mime && mime.charset) {
        return mime.charset;
      }
      if (match && TEXT_TYPE_REGEXP.test(match[1])) {
        return "UTF-8";
      }
      return false;
    }
    function contentType(str) {
      if (!str || typeof str !== "string") {
        return false;
      }
      var mime = str.indexOf("/") === -1 ? exports$1.lookup(str) : str;
      if (!mime) {
        return false;
      }
      if (mime.indexOf("charset") === -1) {
        var charset2 = exports$1.charset(mime);
        if (charset2) mime += "; charset=" + charset2.toLowerCase();
      }
      return mime;
    }
    function extension2(type2) {
      if (!type2 || typeof type2 !== "string") {
        return false;
      }
      var match = EXTRACT_TYPE_REGEXP.exec(type2);
      var exts = match && exports$1.extensions[match[1].toLowerCase()];
      if (!exts || !exts.length) {
        return false;
      }
      return exts[0];
    }
    function lookup(path) {
      if (!path || typeof path !== "string") {
        return false;
      }
      var extension3 = extname("x." + path).toLowerCase().substr(1);
      if (!extension3) {
        return false;
      }
      return exports$1.types[extension3] || false;
    }
    function populateMaps(extensions, types2) {
      var preference = ["nginx", "apache", void 0, "iana"];
      Object.keys(db).forEach(function forEachMimeType(type2) {
        var mime = db[type2];
        var exts = mime.extensions;
        if (!exts || !exts.length) {
          return;
        }
        extensions[type2] = exts;
        for (var i = 0; i < exts.length; i++) {
          var extension3 = exts[i];
          if (types2[extension3]) {
            var from = preference.indexOf(db[types2[extension3]].source);
            var to = preference.indexOf(mime.source);
            if (types2[extension3] !== "application/octet-stream" && (from > to || from === to && types2[extension3].substr(0, 12) === "application/")) {
              continue;
            }
          }
          types2[extension3] = type2;
        }
      });
    }
  })(mimeTypes);
  return mimeTypes;
}
var defer_1;
var hasRequiredDefer;
function requireDefer() {
  if (hasRequiredDefer) return defer_1;
  hasRequiredDefer = 1;
  defer_1 = defer;
  function defer(fn) {
    var nextTick = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null;
    if (nextTick) {
      nextTick(fn);
    } else {
      setTimeout(fn, 0);
    }
  }
  return defer_1;
}
var async_1;
var hasRequiredAsync;
function requireAsync() {
  if (hasRequiredAsync) return async_1;
  hasRequiredAsync = 1;
  var defer = requireDefer();
  async_1 = async;
  function async(callback) {
    var isAsync = false;
    defer(function() {
      isAsync = true;
    });
    return function async_callback(err, result) {
      if (isAsync) {
        callback(err, result);
      } else {
        defer(function nextTick_callback() {
          callback(err, result);
        });
      }
    };
  }
  return async_1;
}
var abort_1;
var hasRequiredAbort;
function requireAbort() {
  if (hasRequiredAbort) return abort_1;
  hasRequiredAbort = 1;
  abort_1 = abort;
  function abort(state) {
    Object.keys(state.jobs).forEach(clean.bind(state));
    state.jobs = {};
  }
  function clean(key) {
    if (typeof this.jobs[key] == "function") {
      this.jobs[key]();
    }
  }
  return abort_1;
}
var iterate_1;
var hasRequiredIterate;
function requireIterate() {
  if (hasRequiredIterate) return iterate_1;
  hasRequiredIterate = 1;
  var async = requireAsync(), abort = requireAbort();
  iterate_1 = iterate;
  function iterate(list2, iterator2, state, callback) {
    var key = state["keyedList"] ? state["keyedList"][state.index] : state.index;
    state.jobs[key] = runJob(iterator2, key, list2[key], function(error, output) {
      if (!(key in state.jobs)) {
        return;
      }
      delete state.jobs[key];
      if (error) {
        abort(state);
      } else {
        state.results[key] = output;
      }
      callback(error, state.results);
    });
  }
  function runJob(iterator2, key, item, callback) {
    var aborter;
    if (iterator2.length == 2) {
      aborter = iterator2(item, async(callback));
    } else {
      aborter = iterator2(item, key, async(callback));
    }
    return aborter;
  }
  return iterate_1;
}
var state_1;
var hasRequiredState;
function requireState() {
  if (hasRequiredState) return state_1;
  hasRequiredState = 1;
  state_1 = state;
  function state(list2, sortMethod) {
    var isNamedList = !Array.isArray(list2), initState = {
      index: 0,
      keyedList: isNamedList || sortMethod ? Object.keys(list2) : null,
      jobs: {},
      results: isNamedList ? {} : [],
      size: isNamedList ? Object.keys(list2).length : list2.length
    };
    if (sortMethod) {
      initState.keyedList.sort(isNamedList ? sortMethod : function(a, b2) {
        return sortMethod(list2[a], list2[b2]);
      });
    }
    return initState;
  }
  return state_1;
}
var terminator_1;
var hasRequiredTerminator;
function requireTerminator() {
  if (hasRequiredTerminator) return terminator_1;
  hasRequiredTerminator = 1;
  var abort = requireAbort(), async = requireAsync();
  terminator_1 = terminator;
  function terminator(callback) {
    if (!Object.keys(this.jobs).length) {
      return;
    }
    this.index = this.size;
    abort(this);
    async(callback)(null, this.results);
  }
  return terminator_1;
}
var parallel_1;
var hasRequiredParallel;
function requireParallel() {
  if (hasRequiredParallel) return parallel_1;
  hasRequiredParallel = 1;
  var iterate = requireIterate(), initState = requireState(), terminator = requireTerminator();
  parallel_1 = parallel;
  function parallel(list2, iterator2, callback) {
    var state = initState(list2);
    while (state.index < (state["keyedList"] || list2).length) {
      iterate(list2, iterator2, state, function(error, result) {
        if (error) {
          callback(error, result);
          return;
        }
        if (Object.keys(state.jobs).length === 0) {
          callback(null, state.results);
          return;
        }
      });
      state.index++;
    }
    return terminator.bind(state, callback);
  }
  return parallel_1;
}
var serialOrdered = { exports: {} };
var hasRequiredSerialOrdered;
function requireSerialOrdered() {
  if (hasRequiredSerialOrdered) return serialOrdered.exports;
  hasRequiredSerialOrdered = 1;
  var iterate = requireIterate(), initState = requireState(), terminator = requireTerminator();
  serialOrdered.exports = serialOrdered$1;
  serialOrdered.exports.ascending = ascending;
  serialOrdered.exports.descending = descending;
  function serialOrdered$1(list2, iterator2, sortMethod, callback) {
    var state = initState(list2, sortMethod);
    iterate(list2, iterator2, state, function iteratorHandler(error, result) {
      if (error) {
        callback(error, result);
        return;
      }
      state.index++;
      if (state.index < (state["keyedList"] || list2).length) {
        iterate(list2, iterator2, state, iteratorHandler);
        return;
      }
      callback(null, state.results);
    });
    return terminator.bind(state, callback);
  }
  function ascending(a, b2) {
    return a < b2 ? -1 : a > b2 ? 1 : 0;
  }
  function descending(a, b2) {
    return -1 * ascending(a, b2);
  }
  return serialOrdered.exports;
}
var serial_1;
var hasRequiredSerial;
function requireSerial() {
  if (hasRequiredSerial) return serial_1;
  hasRequiredSerial = 1;
  var serialOrdered2 = requireSerialOrdered();
  serial_1 = serial;
  function serial(list2, iterator2, callback) {
    return serialOrdered2(list2, iterator2, null, callback);
  }
  return serial_1;
}
var asynckit;
var hasRequiredAsynckit;
function requireAsynckit() {
  if (hasRequiredAsynckit) return asynckit;
  hasRequiredAsynckit = 1;
  asynckit = {
    parallel: requireParallel(),
    serial: requireSerial(),
    serialOrdered: requireSerialOrdered()
  };
  return asynckit;
}
var esObjectAtoms;
var hasRequiredEsObjectAtoms;
function requireEsObjectAtoms() {
  if (hasRequiredEsObjectAtoms) return esObjectAtoms;
  hasRequiredEsObjectAtoms = 1;
  esObjectAtoms = Object;
  return esObjectAtoms;
}
var esErrors;
var hasRequiredEsErrors;
function requireEsErrors() {
  if (hasRequiredEsErrors) return esErrors;
  hasRequiredEsErrors = 1;
  esErrors = Error;
  return esErrors;
}
var _eval;
var hasRequired_eval;
function require_eval() {
  if (hasRequired_eval) return _eval;
  hasRequired_eval = 1;
  _eval = EvalError;
  return _eval;
}
var range;
var hasRequiredRange;
function requireRange() {
  if (hasRequiredRange) return range;
  hasRequiredRange = 1;
  range = RangeError;
  return range;
}
var ref;
var hasRequiredRef;
function requireRef() {
  if (hasRequiredRef) return ref;
  hasRequiredRef = 1;
  ref = ReferenceError;
  return ref;
}
var syntax;
var hasRequiredSyntax;
function requireSyntax() {
  if (hasRequiredSyntax) return syntax;
  hasRequiredSyntax = 1;
  syntax = SyntaxError;
  return syntax;
}
var type;
var hasRequiredType;
function requireType() {
  if (hasRequiredType) return type;
  hasRequiredType = 1;
  type = TypeError;
  return type;
}
var uri;
var hasRequiredUri;
function requireUri() {
  if (hasRequiredUri) return uri;
  hasRequiredUri = 1;
  uri = URIError;
  return uri;
}
var abs;
var hasRequiredAbs;
function requireAbs() {
  if (hasRequiredAbs) return abs;
  hasRequiredAbs = 1;
  abs = Math.abs;
  return abs;
}
var floor;
var hasRequiredFloor;
function requireFloor() {
  if (hasRequiredFloor) return floor;
  hasRequiredFloor = 1;
  floor = Math.floor;
  return floor;
}
var max;
var hasRequiredMax;
function requireMax() {
  if (hasRequiredMax) return max;
  hasRequiredMax = 1;
  max = Math.max;
  return max;
}
var min;
var hasRequiredMin;
function requireMin() {
  if (hasRequiredMin) return min;
  hasRequiredMin = 1;
  min = Math.min;
  return min;
}
var pow;
var hasRequiredPow;
function requirePow() {
  if (hasRequiredPow) return pow;
  hasRequiredPow = 1;
  pow = Math.pow;
  return pow;
}
var round;
var hasRequiredRound;
function requireRound() {
  if (hasRequiredRound) return round;
  hasRequiredRound = 1;
  round = Math.round;
  return round;
}
var _isNaN;
var hasRequired_isNaN;
function require_isNaN() {
  if (hasRequired_isNaN) return _isNaN;
  hasRequired_isNaN = 1;
  _isNaN = Number.isNaN || function isNaN2(a) {
    return a !== a;
  };
  return _isNaN;
}
var sign;
var hasRequiredSign;
function requireSign() {
  if (hasRequiredSign) return sign;
  hasRequiredSign = 1;
  var $isNaN = /* @__PURE__ */ require_isNaN();
  sign = function sign2(number2) {
    if ($isNaN(number2) || number2 === 0) {
      return number2;
    }
    return number2 < 0 ? -1 : 1;
  };
  return sign;
}
var gOPD;
var hasRequiredGOPD;
function requireGOPD() {
  if (hasRequiredGOPD) return gOPD;
  hasRequiredGOPD = 1;
  gOPD = Object.getOwnPropertyDescriptor;
  return gOPD;
}
var gopd;
var hasRequiredGopd;
function requireGopd() {
  if (hasRequiredGopd) return gopd;
  hasRequiredGopd = 1;
  var $gOPD = /* @__PURE__ */ requireGOPD();
  if ($gOPD) {
    try {
      $gOPD([], "length");
    } catch (e) {
      $gOPD = null;
    }
  }
  gopd = $gOPD;
  return gopd;
}
var esDefineProperty;
var hasRequiredEsDefineProperty;
function requireEsDefineProperty() {
  if (hasRequiredEsDefineProperty) return esDefineProperty;
  hasRequiredEsDefineProperty = 1;
  var $defineProperty = Object.defineProperty || false;
  if ($defineProperty) {
    try {
      $defineProperty({}, "a", { value: 1 });
    } catch (e) {
      $defineProperty = false;
    }
  }
  esDefineProperty = $defineProperty;
  return esDefineProperty;
}
var shams$1;
var hasRequiredShams$1;
function requireShams$1() {
  if (hasRequiredShams$1) return shams$1;
  hasRequiredShams$1 = 1;
  shams$1 = function hasSymbols2() {
    if (typeof Symbol !== "function" || typeof Object.getOwnPropertySymbols !== "function") {
      return false;
    }
    if (typeof Symbol.iterator === "symbol") {
      return true;
    }
    var obj = {};
    var sym = /* @__PURE__ */ Symbol("test");
    var symObj = Object(sym);
    if (typeof sym === "string") {
      return false;
    }
    if (Object.prototype.toString.call(sym) !== "[object Symbol]") {
      return false;
    }
    if (Object.prototype.toString.call(symObj) !== "[object Symbol]") {
      return false;
    }
    var symVal = 42;
    obj[sym] = symVal;
    for (var _2 in obj) {
      return false;
    }
    if (typeof Object.keys === "function" && Object.keys(obj).length !== 0) {
      return false;
    }
    if (typeof Object.getOwnPropertyNames === "function" && Object.getOwnPropertyNames(obj).length !== 0) {
      return false;
    }
    var syms = Object.getOwnPropertySymbols(obj);
    if (syms.length !== 1 || syms[0] !== sym) {
      return false;
    }
    if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) {
      return false;
    }
    if (typeof Object.getOwnPropertyDescriptor === "function") {
      var descriptor = (
        /** @type {PropertyDescriptor} */
        Object.getOwnPropertyDescriptor(obj, sym)
      );
      if (descriptor.value !== symVal || descriptor.enumerable !== true) {
        return false;
      }
    }
    return true;
  };
  return shams$1;
}
var hasSymbols;
var hasRequiredHasSymbols;
function requireHasSymbols() {
  if (hasRequiredHasSymbols) return hasSymbols;
  hasRequiredHasSymbols = 1;
  var origSymbol = typeof Symbol !== "undefined" && Symbol;
  var hasSymbolSham = requireShams$1();
  hasSymbols = function hasNativeSymbols() {
    if (typeof origSymbol !== "function") {
      return false;
    }
    if (typeof Symbol !== "function") {
      return false;
    }
    if (typeof origSymbol("foo") !== "symbol") {
      return false;
    }
    if (typeof /* @__PURE__ */ Symbol("bar") !== "symbol") {
      return false;
    }
    return hasSymbolSham();
  };
  return hasSymbols;
}
var Reflect_getPrototypeOf;
var hasRequiredReflect_getPrototypeOf;
function requireReflect_getPrototypeOf() {
  if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf;
  hasRequiredReflect_getPrototypeOf = 1;
  Reflect_getPrototypeOf = typeof Reflect !== "undefined" && Reflect.getPrototypeOf || null;
  return Reflect_getPrototypeOf;
}
var Object_getPrototypeOf;
var hasRequiredObject_getPrototypeOf;
function requireObject_getPrototypeOf() {
  if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf;
  hasRequiredObject_getPrototypeOf = 1;
  var $Object = /* @__PURE__ */ requireEsObjectAtoms();
  Object_getPrototypeOf = $Object.getPrototypeOf || null;
  return Object_getPrototypeOf;
}
var implementation;
var hasRequiredImplementation;
function requireImplementation() {
  if (hasRequiredImplementation) return implementation;
  hasRequiredImplementation = 1;
  var ERROR_MESSAGE = "Function.prototype.bind called on incompatible ";
  var toStr = Object.prototype.toString;
  var max2 = Math.max;
  var funcType = "[object Function]";
  var concatty = function concatty2(a, b2) {
    var arr = [];
    for (var i = 0; i < a.length; i += 1) {
      arr[i] = a[i];
    }
    for (var j2 = 0; j2 < b2.length; j2 += 1) {
      arr[j2 + a.length] = b2[j2];
    }
    return arr;
  };
  var slicy = function slicy2(arrLike, offset) {
    var arr = [];
    for (var i = offset, j2 = 0; i < arrLike.length; i += 1, j2 += 1) {
      arr[j2] = arrLike[i];
    }
    return arr;
  };
  var joiny = function(arr, joiner) {
    var str = "";
    for (var i = 0; i < arr.length; i += 1) {
      str += arr[i];
      if (i + 1 < arr.length) {
        str += joiner;
      }
    }
    return str;
  };
  implementation = function bind2(that) {
    var target = this;
    if (typeof target !== "function" || toStr.apply(target) !== funcType) {
      throw new TypeError(ERROR_MESSAGE + target);
    }
    var args = slicy(arguments, 1);
    var bound;
    var binder = function() {
      if (this instanceof bound) {
        var result = target.apply(
          this,
          concatty(args, arguments)
        );
        if (Object(result) === result) {
          return result;
        }
        return this;
      }
      return target.apply(
        that,
        concatty(args, arguments)
      );
    };
    var boundLength = max2(0, target.length - args.length);
    var boundArgs = [];
    for (var i = 0; i < boundLength; i++) {
      boundArgs[i] = "$" + i;
    }
    bound = Function("binder", "return function (" + joiny(boundArgs, ",") + "){ return binder.apply(this,arguments); }")(binder);
    if (target.prototype) {
      var Empty = function Empty2() {
      };
      Empty.prototype = target.prototype;
      bound.prototype = new Empty();
      Empty.prototype = null;
    }
    return bound;
  };
  return implementation;
}
var functionBind;
var hasRequiredFunctionBind;
function requireFunctionBind() {
  if (hasRequiredFunctionBind) return functionBind;
  hasRequiredFunctionBind = 1;
  var implementation2 = requireImplementation();
  functionBind = Function.prototype.bind || implementation2;
  return functionBind;
}
var functionCall;
var hasRequiredFunctionCall;
function requireFunctionCall() {
  if (hasRequiredFunctionCall) return functionCall;
  hasRequiredFunctionCall = 1;
  functionCall = Function.prototype.call;
  return functionCall;
}
var functionApply;
var hasRequiredFunctionApply;
function requireFunctionApply() {
  if (hasRequiredFunctionApply) return functionApply;
  hasRequiredFunctionApply = 1;
  functionApply = Function.prototype.apply;
  return functionApply;
}
var reflectApply;
var hasRequiredReflectApply;
function requireReflectApply() {
  if (hasRequiredReflectApply) return reflectApply;
  hasRequiredReflectApply = 1;
  reflectApply = typeof Reflect !== "undefined" && Reflect && Reflect.apply;
  return reflectApply;
}
var actualApply;
var hasRequiredActualApply;
function requireActualApply() {
  if (hasRequiredActualApply) return actualApply;
  hasRequiredActualApply = 1;
  var bind2 = requireFunctionBind();
  var $apply = requireFunctionApply();
  var $call = requireFunctionCall();
  var $reflectApply = requireReflectApply();
  actualApply = $reflectApply || bind2.call($call, $apply);
  return actualApply;
}
var callBindApplyHelpers;
var hasRequiredCallBindApplyHelpers;
function requireCallBindApplyHelpers() {
  if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers;
  hasRequiredCallBindApplyHelpers = 1;
  var bind2 = requireFunctionBind();
  var $TypeError = /* @__PURE__ */ requireType();
  var $call = requireFunctionCall();
  var $actualApply = requireActualApply();
  callBindApplyHelpers = function callBindBasic(args) {
    if (args.length < 1 || typeof args[0] !== "function") {
      throw new $TypeError("a function is required");
    }
    return $actualApply(bind2, $call, args);
  };
  return callBindApplyHelpers;
}
var get;
var hasRequiredGet;
function requireGet() {
  if (hasRequiredGet) return get;
  hasRequiredGet = 1;
  var callBind = requireCallBindApplyHelpers();
  var gOPD2 = /* @__PURE__ */ requireGopd();
  var hasProtoAccessor;
  try {
    hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */
    [].__proto__ === Array.prototype;
  } catch (e) {
    if (!e || typeof e !== "object" || !("code" in e) || e.code !== "ERR_PROTO_ACCESS") {
      throw e;
    }
  }
  var desc = !!hasProtoAccessor && gOPD2 && gOPD2(
    Object.prototype,
    /** @type {keyof typeof Object.prototype} */
    "__proto__"
  );
  var $Object = Object;
  var $getPrototypeOf = $Object.getPrototypeOf;
  get = desc && typeof desc.get === "function" ? callBind([desc.get]) : typeof $getPrototypeOf === "function" ? (
    /** @type {import('./get')} */
    function getDunder(value) {
      return $getPrototypeOf(value == null ? value : $Object(value));
    }
  ) : false;
  return get;
}
var getProto;
var hasRequiredGetProto;
function requireGetProto() {
  if (hasRequiredGetProto) return getProto;
  hasRequiredGetProto = 1;
  var reflectGetProto = requireReflect_getPrototypeOf();
  var originalGetProto = requireObject_getPrototypeOf();
  var getDunderProto = /* @__PURE__ */ requireGet();
  getProto = reflectGetProto ? function getProto2(O2) {
    return reflectGetProto(O2);
  } : originalGetProto ? function getProto2(O2) {
    if (!O2 || typeof O2 !== "object" && typeof O2 !== "function") {
      throw new TypeError("getProto: not an object");
    }
    return originalGetProto(O2);
  } : getDunderProto ? function getProto2(O2) {
    return getDunderProto(O2);
  } : null;
  return getProto;
}
var hasown;
var hasRequiredHasown;
function requireHasown() {
  if (hasRequiredHasown) return hasown;
  hasRequiredHasown = 1;
  var call = Function.prototype.call;
  var $hasOwn = Object.prototype.hasOwnProperty;
  var bind2 = requireFunctionBind();
  hasown = bind2.call(call, $hasOwn);
  return hasown;
}
var getIntrinsic;
var hasRequiredGetIntrinsic;
function requireGetIntrinsic() {
  if (hasRequiredGetIntrinsic) return getIntrinsic;
  hasRequiredGetIntrinsic = 1;
  var undefined$1;
  var $Object = /* @__PURE__ */ requireEsObjectAtoms();
  var $Error = /* @__PURE__ */ requireEsErrors();
  var $EvalError = /* @__PURE__ */ require_eval();
  var $RangeError = /* @__PURE__ */ requireRange();
  var $ReferenceError = /* @__PURE__ */ requireRef();
  var $SyntaxError = /* @__PURE__ */ requireSyntax();
  var $TypeError = /* @__PURE__ */ requireType();
  var $URIError = /* @__PURE__ */ requireUri();
  var abs2 = /* @__PURE__ */ requireAbs();
  var floor2 = /* @__PURE__ */ requireFloor();
  var max2 = /* @__PURE__ */ requireMax();
  var min2 = /* @__PURE__ */ requireMin();
  var pow2 = /* @__PURE__ */ requirePow();
  var round2 = /* @__PURE__ */ requireRound();
  var sign2 = /* @__PURE__ */ requireSign();
  var $Function = Function;
  var getEvalledConstructor = function(expressionSyntax) {
    try {
      return $Function('"use strict"; return (' + expressionSyntax + ").constructor;")();
    } catch (e) {
    }
  };
  var $gOPD = /* @__PURE__ */ requireGopd();
  var $defineProperty = /* @__PURE__ */ requireEsDefineProperty();
  var throwTypeError = function() {
    throw new $TypeError();
  };
  var ThrowTypeError = $gOPD ? (function() {
    try {
      arguments.callee;
      return throwTypeError;
    } catch (calleeThrows) {
      try {
        return $gOPD(arguments, "callee").get;
      } catch (gOPDthrows) {
        return throwTypeError;
      }
    }
  })() : throwTypeError;
  var hasSymbols2 = requireHasSymbols()();
  var getProto2 = requireGetProto();
  var $ObjectGPO = requireObject_getPrototypeOf();
  var $ReflectGPO = requireReflect_getPrototypeOf();
  var $apply = requireFunctionApply();
  var $call = requireFunctionCall();
  var needsEval = {};
  var TypedArray = typeof Uint8Array === "undefined" || !getProto2 ? undefined$1 : getProto2(Uint8Array);
  var INTRINSICS = {
    __proto__: null,
    "%AggregateError%": typeof AggregateError === "undefined" ? undefined$1 : AggregateError,
    "%Array%": Array,
    "%ArrayBuffer%": typeof ArrayBuffer === "undefined" ? undefined$1 : ArrayBuffer,
    "%ArrayIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2([][Symbol.iterator]()) : undefined$1,
    "%AsyncFromSyncIteratorPrototype%": undefined$1,
    "%AsyncFunction%": needsEval,
    "%AsyncGenerator%": needsEval,
    "%AsyncGeneratorFunction%": needsEval,
    "%AsyncIteratorPrototype%": needsEval,
    "%Atomics%": typeof Atomics === "undefined" ? undefined$1 : Atomics,
    "%BigInt%": typeof BigInt === "undefined" ? undefined$1 : BigInt,
    "%BigInt64Array%": typeof BigInt64Array === "undefined" ? undefined$1 : BigInt64Array,
    "%BigUint64Array%": typeof BigUint64Array === "undefined" ? undefined$1 : BigUint64Array,
    "%Boolean%": Boolean,
    "%DataView%": typeof DataView === "undefined" ? undefined$1 : DataView,
    "%Date%": Date,
    "%decodeURI%": decodeURI,
    "%decodeURIComponent%": decodeURIComponent,
    "%encodeURI%": encodeURI,
    "%encodeURIComponent%": encodeURIComponent,
    "%Error%": $Error,
    "%eval%": eval,
    // eslint-disable-line no-eval
    "%EvalError%": $EvalError,
    "%Float16Array%": typeof Float16Array === "undefined" ? undefined$1 : Float16Array,
    "%Float32Array%": typeof Float32Array === "undefined" ? undefined$1 : Float32Array,
    "%Float64Array%": typeof Float64Array === "undefined" ? undefined$1 : Float64Array,
    "%FinalizationRegistry%": typeof FinalizationRegistry === "undefined" ? undefined$1 : FinalizationRegistry,
    "%Function%": $Function,
    "%GeneratorFunction%": needsEval,
    "%Int8Array%": typeof Int8Array === "undefined" ? undefined$1 : Int8Array,
    "%Int16Array%": typeof Int16Array === "undefined" ? undefined$1 : Int16Array,
    "%Int32Array%": typeof Int32Array === "undefined" ? undefined$1 : Int32Array,
    "%isFinite%": isFinite,
    "%isNaN%": isNaN,
    "%IteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(getProto2([][Symbol.iterator]())) : undefined$1,
    "%JSON%": typeof JSON === "object" ? JSON : undefined$1,
    "%Map%": typeof Map === "undefined" ? undefined$1 : Map,
    "%MapIteratorPrototype%": typeof Map === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
    "%Math%": Math,
    "%Number%": Number,
    "%Object%": $Object,
    "%Object.getOwnPropertyDescriptor%": $gOPD,
    "%parseFloat%": parseFloat,
    "%parseInt%": parseInt,
    "%Promise%": typeof Promise === "undefined" ? undefined$1 : Promise,
    "%Proxy%": typeof Proxy === "undefined" ? undefined$1 : Proxy,
    "%RangeError%": $RangeError,
    "%ReferenceError%": $ReferenceError,
    "%Reflect%": typeof Reflect === "undefined" ? undefined$1 : Reflect,
    "%RegExp%": RegExp,
    "%Set%": typeof Set === "undefined" ? undefined$1 : Set,
    "%SetIteratorPrototype%": typeof Set === "undefined" || !hasSymbols2 || !getProto2 ? undefined$1 : getProto2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
    "%SharedArrayBuffer%": typeof SharedArrayBuffer === "undefined" ? undefined$1 : SharedArrayBuffer,
    "%String%": String,
    "%StringIteratorPrototype%": hasSymbols2 && getProto2 ? getProto2(""[Symbol.iterator]()) : undefined$1,
    "%Symbol%": hasSymbols2 ? Symbol : undefined$1,
    "%SyntaxError%": $SyntaxError,
    "%ThrowTypeError%": ThrowTypeError,
    "%TypedArray%": TypedArray,
    "%TypeError%": $TypeError,
    "%Uint8Array%": typeof Uint8Array === "undefined" ? undefined$1 : Uint8Array,
    "%Uint8ClampedArray%": typeof Uint8ClampedArray === "undefined" ? undefined$1 : Uint8ClampedArray,
    "%Uint16Array%": typeof Uint16Array === "undefined" ? undefined$1 : Uint16Array,
    "%Uint32Array%": typeof Uint32Array === "undefined" ? undefined$1 : Uint32Array,
    "%URIError%": $URIError,
    "%WeakMap%": typeof WeakMap === "undefined" ? undefined$1 : WeakMap,
    "%WeakRef%": typeof WeakRef === "undefined" ? undefined$1 : WeakRef,
    "%WeakSet%": typeof WeakSet === "undefined" ? undefined$1 : WeakSet,
    "%Function.prototype.call%": $call,
    "%Function.prototype.apply%": $apply,
    "%Object.defineProperty%": $defineProperty,
    "%Object.getPrototypeOf%": $ObjectGPO,
    "%Math.abs%": abs2,
    "%Math.floor%": floor2,
    "%Math.max%": max2,
    "%Math.min%": min2,
    "%Math.pow%": pow2,
    "%Math.round%": round2,
    "%Math.sign%": sign2,
    "%Reflect.getPrototypeOf%": $ReflectGPO
  };
  if (getProto2) {
    try {
      null.error;
    } catch (e) {
      var errorProto = getProto2(getProto2(e));
      INTRINSICS["%Error.prototype%"] = errorProto;
    }
  }
  var doEval = function doEval2(name2) {
    var value;
    if (name2 === "%AsyncFunction%") {
      value = getEvalledConstructor("async function () {}");
    } else if (name2 === "%GeneratorFunction%") {
      value = getEvalledConstructor("function* () {}");
    } else if (name2 === "%AsyncGeneratorFunction%") {
      value = getEvalledConstructor("async function* () {}");
    } else if (name2 === "%AsyncGenerator%") {
      var fn = doEval2("%AsyncGeneratorFunction%");
      if (fn) {
        value = fn.prototype;
      }
    } else if (name2 === "%AsyncIteratorPrototype%") {
      var gen = doEval2("%AsyncGenerator%");
      if (gen && getProto2) {
        value = getProto2(gen.prototype);
      }
    }
    INTRINSICS[name2] = value;
    return value;
  };
  var LEGACY_ALIASES = {
    __proto__: null,
    "%ArrayBufferPrototype%": ["ArrayBuffer", "prototype"],
    "%ArrayPrototype%": ["Array", "prototype"],
    "%ArrayProto_entries%": ["Array", "prototype", "entries"],
    "%ArrayProto_forEach%": ["Array", "prototype", "forEach"],
    "%ArrayProto_keys%": ["Array", "prototype", "keys"],
    "%ArrayProto_values%": ["Array", "prototype", "values"],
    "%AsyncFunctionPrototype%": ["AsyncFunction", "prototype"],
    "%AsyncGenerator%": ["AsyncGeneratorFunction", "prototype"],
    "%AsyncGeneratorPrototype%": ["AsyncGeneratorFunction", "prototype", "prototype"],
    "%BooleanPrototype%": ["Boolean", "prototype"],
    "%DataViewPrototype%": ["DataView", "prototype"],
    "%DatePrototype%": ["Date", "prototype"],
    "%ErrorPrototype%": ["Error", "prototype"],
    "%EvalErrorPrototype%": ["EvalError", "prototype"],
    "%Float32ArrayPrototype%": ["Float32Array", "prototype"],
    "%Float64ArrayPrototype%": ["Float64Array", "prototype"],
    "%FunctionPrototype%": ["Function", "prototype"],
    "%Generator%": ["GeneratorFunction", "prototype"],
    "%GeneratorPrototype%": ["GeneratorFunction", "prototype", "prototype"],
    "%Int8ArrayPrototype%": ["Int8Array", "prototype"],
    "%Int16ArrayPrototype%": ["Int16Array", "prototype"],
    "%Int32ArrayPrototype%": ["Int32Array", "prototype"],
    "%JSONParse%": ["JSON", "parse"],
    "%JSONStringify%": ["JSON", "stringify"],
    "%MapPrototype%": ["Map", "prototype"],
    "%NumberPrototype%": ["Number", "prototype"],
    "%ObjectPrototype%": ["Object", "prototype"],
    "%ObjProto_toString%": ["Object", "prototype", "toString"],
    "%ObjProto_valueOf%": ["Object", "prototype", "valueOf"],
    "%PromisePrototype%": ["Promise", "prototype"],
    "%PromiseProto_then%": ["Promise", "prototype", "then"],
    "%Promise_all%": ["Promise", "all"],
    "%Promise_reject%": ["Promise", "reject"],
    "%Promise_resolve%": ["Promise", "resolve"],
    "%RangeErrorPrototype%": ["RangeError", "prototype"],
    "%ReferenceErrorPrototype%": ["ReferenceError", "prototype"],
    "%RegExpPrototype%": ["RegExp", "prototype"],
    "%SetPrototype%": ["Set", "prototype"],
    "%SharedArrayBufferPrototype%": ["SharedArrayBuffer", "prototype"],
    "%StringPrototype%": ["String", "prototype"],
    "%SymbolPrototype%": ["Symbol", "prototype"],
    "%SyntaxErrorPrototype%": ["SyntaxError", "prototype"],
    "%TypedArrayPrototype%": ["TypedArray", "prototype"],
    "%TypeErrorPrototype%": ["TypeError", "prototype"],
    "%Uint8ArrayPrototype%": ["Uint8Array", "prototype"],
    "%Uint8ClampedArrayPrototype%": ["Uint8ClampedArray", "prototype"],
    "%Uint16ArrayPrototype%": ["Uint16Array", "prototype"],
    "%Uint32ArrayPrototype%": ["Uint32Array", "prototype"],
    "%URIErrorPrototype%": ["URIError", "prototype"],
    "%WeakMapPrototype%": ["WeakMap", "prototype"],
    "%WeakSetPrototype%": ["WeakSet", "prototype"]
  };
  var bind2 = requireFunctionBind();
  var hasOwn = /* @__PURE__ */ requireHasown();
  var $concat = bind2.call($call, Array.prototype.concat);
  var $spliceApply = bind2.call($apply, Array.prototype.splice);
  var $replace = bind2.call($call, String.prototype.replace);
  var $strSlice = bind2.call($call, String.prototype.slice);
  var $exec = bind2.call($call, RegExp.prototype.exec);
  var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
  var reEscapeChar = /\\(\\)?/g;
  var stringToPath = function stringToPath2(string2) {
    var first = $strSlice(string2, 0, 1);
    var last = $strSlice(string2, -1);
    if (first === "%" && last !== "%") {
      throw new $SyntaxError("invalid intrinsic syntax, expected closing `%`");
    } else if (last === "%" && first !== "%") {
      throw new $SyntaxError("invalid intrinsic syntax, expected opening `%`");
    }
    var result = [];
    $replace(string2, rePropName, function(match, number2, quote, subString) {
      result[result.length] = quote ? $replace(subString, reEscapeChar, "$1") : number2 || match;
    });
    return result;
  };
  var getBaseIntrinsic = function getBaseIntrinsic2(name2, allowMissing) {
    var intrinsicName = name2;
    var alias;
    if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
      alias = LEGACY_ALIASES[intrinsicName];
      intrinsicName = "%" + alias[0] + "%";
    }
    if (hasOwn(INTRINSICS, intrinsicName)) {
      var value = INTRINSICS[intrinsicName];
      if (value === needsEval) {
        value = doEval(intrinsicName);
      }
      if (typeof value === "undefined" && !allowMissing) {
        throw new $TypeError("intrinsic " + name2 + " exists, but is not available. Please file an issue!");
      }
      return {
        alias,
        name: intrinsicName,
        value
      };
    }
    throw new $SyntaxError("intrinsic " + name2 + " does not exist!");
  };
  getIntrinsic = function GetIntrinsic(name2, allowMissing) {
    if (typeof name2 !== "string" || name2.length === 0) {
      throw new $TypeError("intrinsic name must be a non-empty string");
    }
    if (arguments.length > 1 && typeof allowMissing !== "boolean") {
      throw new $TypeError('"allowMissing" argument must be a boolean');
    }
    if ($exec(/^%?[^%]*%?$/, name2) === null) {
      throw new $SyntaxError("`%` may not be present anywhere but at the beginning and end of the intrinsic name");
    }
    var parts = stringToPath(name2);
    var intrinsicBaseName = parts.length > 0 ? parts[0] : "";
    var intrinsic = getBaseIntrinsic("%" + intrinsicBaseName + "%", allowMissing);
    var intrinsicRealName = intrinsic.name;
    var value = intrinsic.value;
    var skipFurtherCaching = false;
    var alias = intrinsic.alias;
    if (alias) {
      intrinsicBaseName = alias[0];
      $spliceApply(parts, $concat([0, 1], alias));
    }
    for (var i = 1, isOwn = true; i < parts.length; i += 1) {
      var part = parts[i];
      var first = $strSlice(part, 0, 1);
      var last = $strSlice(part, -1);
      if ((first === '"' || first === "'" || first === "`" || (last === '"' || last === "'" || last === "`")) && first !== last) {
        throw new $SyntaxError("property names with quotes must have matching quotes");
      }
      if (part === "constructor" || !isOwn) {
        skipFurtherCaching = true;
      }
      intrinsicBaseName += "." + part;
      intrinsicRealName = "%" + intrinsicBaseName + "%";
      if (hasOwn(INTRINSICS, intrinsicRealName)) {
        value = INTRINSICS[intrinsicRealName];
      } else if (value != null) {
        if (!(part in value)) {
          if (!allowMissing) {
            throw new $TypeError("base intrinsic for " + name2 + " exists, but the property is not available.");
          }
          return void undefined$1;
        }
        if ($gOPD && i + 1 >= parts.length) {
          var desc = $gOPD(value, part);
          isOwn = !!desc;
          if (isOwn && "get" in desc && !("originalValue" in desc.get)) {
            value = desc.get;
          } else {
            value = value[part];
          }
        } else {
          isOwn = hasOwn(value, part);
          value = value[part];
        }
        if (isOwn && !skipFurtherCaching) {
          INTRINSICS[intrinsicRealName] = value;
        }
      }
    }
    return value;
  };
  return getIntrinsic;
}
var shams;
var hasRequiredShams;
function requireShams() {
  if (hasRequiredShams) return shams;
  hasRequiredShams = 1;
  var hasSymbols2 = requireShams$1();
  shams = function hasToStringTagShams() {
    return hasSymbols2() && !!Symbol.toStringTag;
  };
  return shams;
}
var esSetTostringtag;
var hasRequiredEsSetTostringtag;
function requireEsSetTostringtag() {
  if (hasRequiredEsSetTostringtag) return esSetTostringtag;
  hasRequiredEsSetTostringtag = 1;
  var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic();
  var $defineProperty = GetIntrinsic("%Object.defineProperty%", true);
  var hasToStringTag = requireShams()();
  var hasOwn = /* @__PURE__ */ requireHasown();
  var $TypeError = /* @__PURE__ */ requireType();
  var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null;
  esSetTostringtag = function setToStringTag(object, value) {
    var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force;
    var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable;
    if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") {
      throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans");
    }
    if (toStringTag2 && (overrideIfSet || !hasOwn(object, toStringTag2))) {
      if ($defineProperty) {
        $defineProperty(object, toStringTag2, {
          configurable: !nonConfigurable,
          enumerable: false,
          value,
          writable: false
        });
      } else {
        object[toStringTag2] = value;
      }
    }
  };
  return esSetTostringtag;
}
var populate;
var hasRequiredPopulate;
function requirePopulate() {
  if (hasRequiredPopulate) return populate;
  hasRequiredPopulate = 1;
  populate = function(dst, src2) {
    Object.keys(src2).forEach(function(prop) {
      dst[prop] = dst[prop] || src2[prop];
    });
    return dst;
  };
  return populate;
}
var form_data;
var hasRequiredForm_data;
function requireForm_data() {
  if (hasRequiredForm_data) return form_data;
  hasRequiredForm_data = 1;
  var CombinedStream = requireCombined_stream();
  var util = require$$0$1;
  var path = require$$1;
  var http = require$$3;
  var https = require$$4;
  var parseUrl2 = require$$5.parse;
  var fs = require$$6;
  var Stream = stream.Stream;
  var crypto2 = require$$1$1;
  var mime = requireMimeTypes();
  var asynckit2 = requireAsynckit();
  var setToStringTag = /* @__PURE__ */ requireEsSetTostringtag();
  var hasOwn = /* @__PURE__ */ requireHasown();
  var populate2 = requirePopulate();
  function FormData2(options) {
    if (!(this instanceof FormData2)) {
      return new FormData2(options);
    }
    this._overheadLength = 0;
    this._valueLength = 0;
    this._valuesToMeasure = [];
    CombinedStream.call(this);
    options = options || {};
    for (var option in options) {
      this[option] = options[option];
    }
  }
  util.inherits(FormData2, CombinedStream);
  FormData2.LINE_BREAK = "\r\n";
  FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream";
  FormData2.prototype.append = function(field, value, options) {
    options = options || {};
    if (typeof options === "string") {
      options = { filename: options };
    }
    var append2 = CombinedStream.prototype.append.bind(this);
    if (typeof value === "number" || value == null) {
      value = String(value);
    }
    if (Array.isArray(value)) {
      this._error(new Error("Arrays are not supported."));
      return;
    }
    var header = this._multiPartHeader(field, value, options);
    var footer2 = this._multiPartFooter();
    append2(header);
    append2(value);
    append2(footer2);
    this._trackLength(header, value, options);
  };
  FormData2.prototype._trackLength = function(header, value, options) {
    var valueLength = 0;
    if (options.knownLength != null) {
      valueLength += Number(options.knownLength);
    } else if (Buffer.isBuffer(value)) {
      valueLength = value.length;
    } else if (typeof value === "string") {
      valueLength = Buffer.byteLength(value);
    }
    this._valueLength += valueLength;
    this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length;
    if (!value || !value.path && !(value.readable && hasOwn(value, "httpVersion")) && !(value instanceof Stream)) {
      return;
    }
    if (!options.knownLength) {
      this._valuesToMeasure.push(value);
    }
  };
  FormData2.prototype._lengthRetriever = function(value, callback) {
    if (hasOwn(value, "fd")) {
      if (value.end != void 0 && value.end != Infinity && value.start != void 0) {
        callback(null, value.end + 1 - (value.start ? value.start : 0));
      } else {
        fs.stat(value.path, function(err, stat) {
          if (err) {
            callback(err);
            return;
          }
          var fileSize = stat.size - (value.start ? value.start : 0);
          callback(null, fileSize);
        });
      }
    } else if (hasOwn(value, "httpVersion")) {
      callback(null, Number(value.headers["content-length"]));
    } else if (hasOwn(value, "httpModule")) {
      value.on("response", function(response) {
        value.pause();
        callback(null, Number(response.headers["content-length"]));
      });
      value.resume();
    } else {
      callback("Unknown stream");
    }
  };
  FormData2.prototype._multiPartHeader = function(field, value, options) {
    if (typeof options.header === "string") {
      return options.header;
    }
    var contentDisposition = this._getContentDisposition(value, options);
    var contentType = this._getContentType(value, options);
    var contents = "";
    var headers = {
      // add custom disposition as third element or keep it two elements if not
      "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []),
      // if no content type. allow it to be empty array
      "Content-Type": [].concat(contentType || [])
    };
    if (typeof options.header === "object") {
      populate2(headers, options.header);
    }
    var header;
    for (var prop in headers) {
      if (hasOwn(headers, prop)) {
        header = headers[prop];
        if (header == null) {
          continue;
        }
        if (!Array.isArray(header)) {
          header = [header];
        }
        if (header.length) {
          contents += prop + ": " + header.join("; ") + FormData2.LINE_BREAK;
        }
      }
    }
    return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK;
  };
  FormData2.prototype._getContentDisposition = function(value, options) {
    var filename;
    if (typeof options.filepath === "string") {
      filename = path.normalize(options.filepath).replace(/\\/g, "/");
    } else if (options.filename || value && (value.name || value.path)) {
      filename = path.basename(options.filename || value && (value.name || value.path));
    } else if (value && value.readable && hasOwn(value, "httpVersion")) {
      filename = path.basename(value.client._httpMessage.path || "");
    }
    if (filename) {
      return 'filename="' + filename + '"';
    }
  };
  FormData2.prototype._getContentType = function(value, options) {
    var contentType = options.contentType;
    if (!contentType && value && value.name) {
      contentType = mime.lookup(value.name);
    }
    if (!contentType && value && value.path) {
      contentType = mime.lookup(value.path);
    }
    if (!contentType && value && value.readable && hasOwn(value, "httpVersion")) {
      contentType = value.headers["content-type"];
    }
    if (!contentType && (options.filepath || options.filename)) {
      contentType = mime.lookup(options.filepath || options.filename);
    }
    if (!contentType && value && typeof value === "object") {
      contentType = FormData2.DEFAULT_CONTENT_TYPE;
    }
    return contentType;
  };
  FormData2.prototype._multiPartFooter = function() {
    return (function(next) {
      var footer2 = FormData2.LINE_BREAK;
      var lastPart = this._streams.length === 0;
      if (lastPart) {
        footer2 += this._lastBoundary();
      }
      next(footer2);
    }).bind(this);
  };
  FormData2.prototype._lastBoundary = function() {
    return "--" + this.getBoundary() + "--" + FormData2.LINE_BREAK;
  };
  FormData2.prototype.getHeaders = function(userHeaders) {
    var header;
    var formHeaders = {
      "content-type": "multipart/form-data; boundary=" + this.getBoundary()
    };
    for (header in userHeaders) {
      if (hasOwn(userHeaders, header)) {
        formHeaders[header.toLowerCase()] = userHeaders[header];
      }
    }
    return formHeaders;
  };
  FormData2.prototype.setBoundary = function(boundary) {
    if (typeof boundary !== "string") {
      throw new TypeError("FormData boundary must be a string");
    }
    this._boundary = boundary;
  };
  FormData2.prototype.getBoundary = function() {
    if (!this._boundary) {
      this._generateBoundary();
    }
    return this._boundary;
  };
  FormData2.prototype.getBuffer = function() {
    var dataBuffer = new Buffer.alloc(0);
    var boundary = this.getBoundary();
    for (var i = 0, len = this._streams.length; i < len; i++) {
      if (typeof this._streams[i] !== "function") {
        if (Buffer.isBuffer(this._streams[i])) {
          dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]);
        } else {
          dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]);
        }
        if (typeof this._streams[i] !== "string" || this._streams[i].substring(2, boundary.length + 2) !== boundary) {
          dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData2.LINE_BREAK)]);
        }
      }
    }
    return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]);
  };
  FormData2.prototype._generateBoundary = function() {
    this._boundary = "--------------------------" + crypto2.randomBytes(12).toString("hex");
  };
  FormData2.prototype.getLengthSync = function() {
    var knownLength = this._overheadLength + this._valueLength;
    if (this._streams.length) {
      knownLength += this._lastBoundary().length;
    }
    if (!this.hasKnownLength()) {
      this._error(new Error("Cannot calculate proper length in synchronous way."));
    }
    return knownLength;
  };
  FormData2.prototype.hasKnownLength = function() {
    var hasKnownLength = true;
    if (this._valuesToMeasure.length) {
      hasKnownLength = false;
    }
    return hasKnownLength;
  };
  FormData2.prototype.getLength = function(cb) {
    var knownLength = this._overheadLength + this._valueLength;
    if (this._streams.length) {
      knownLength += this._lastBoundary().length;
    }
    if (!this._valuesToMeasure.length) {
      process.nextTick(cb.bind(this, null, knownLength));
      return;
    }
    asynckit2.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {
      if (err) {
        cb(err);
        return;
      }
      values.forEach(function(length) {
        knownLength += length;
      });
      cb(null, knownLength);
    });
  };
  FormData2.prototype.submit = function(params, cb) {
    var request;
    var options;
    var defaults2 = { method: "post" };
    if (typeof params === "string") {
      params = parseUrl2(params);
      options = populate2({
        port: params.port,
        path: params.pathname,
        host: params.hostname,
        protocol: params.protocol
      }, defaults2);
    } else {
      options = populate2(params, defaults2);
      if (!options.port) {
        options.port = options.protocol === "https:" ? 443 : 80;
      }
    }
    options.headers = this.getHeaders(params.headers);
    if (options.protocol === "https:") {
      request = https.request(options);
    } else {
      request = http.request(options);
    }
    this.getLength((function(err, length) {
      if (err && err !== "Unknown stream") {
        this._error(err);
        return;
      }
      if (length) {
        request.setHeader("Content-Length", length);
      }
      this.pipe(request);
      if (cb) {
        var onResponse;
        var callback = function(error, responce) {
          request.removeListener("error", callback);
          request.removeListener("response", onResponse);
          return cb.call(this, error, responce);
        };
        onResponse = callback.bind(this, null);
        request.on("error", callback);
        request.on("response", onResponse);
      }
    }).bind(this));
    return request;
  };
  FormData2.prototype._error = function(err) {
    if (!this.error) {
      this.error = err;
      this.pause();
      this.emit("error", err);
    }
  };
  FormData2.prototype.toString = function() {
    return "[object FormData]";
  };
  setToStringTag(FormData2.prototype, "FormData");
  form_data = FormData2;
  return form_data;
}
var form_dataExports = requireForm_data();
const FormData$1 = /* @__PURE__ */ getDefaultExportFromCjs(form_dataExports);
function isVisitable(thing) {
  return utils$2.isPlainObject(thing) || utils$2.isArray(thing);
}
function removeBrackets(key) {
  return utils$2.endsWith(key, "[]") ? key.slice(0, -2) : key;
}
function renderKey(path, key, dots) {
  if (!path) return key;
  return path.concat(key).map(function each(token, i) {
    token = removeBrackets(token);
    return !dots && i ? "[" + token + "]" : token;
  }).join(dots ? "." : "");
}
function isFlatArray(arr) {
  return utils$2.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$2.toFlatObject(utils$2, {}, null, function filter(prop) {
  return /^is[A-Z]/.test(prop);
});
function toFormData$1(obj, formData, options) {
  if (!utils$2.isObject(obj)) {
    throw new TypeError("target must be an object");
  }
  formData = formData || new (FormData$1 || FormData)();
  options = utils$2.toFlatObject(
    options,
    {
      metaTokens: true,
      dots: false,
      indexes: false
    },
    false,
    function defined(option, source) {
      return !utils$2.isUndefined(source[option]);
    }
  );
  const metaTokens = options.metaTokens;
  const visitor = options.visitor || defaultVisitor;
  const dots = options.dots;
  const indexes = options.indexes;
  const _Blob = options.Blob || typeof Blob !== "undefined" && Blob;
  const useBlob = _Blob && utils$2.isSpecCompliantForm(formData);
  if (!utils$2.isFunction(visitor)) {
    throw new TypeError("visitor must be a function");
  }
  function convertValue(value) {
    if (value === null) return "";
    if (utils$2.isDate(value)) {
      return value.toISOString();
    }
    if (utils$2.isBoolean(value)) {
      return value.toString();
    }
    if (!useBlob && utils$2.isBlob(value)) {
      throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");
    }
    if (utils$2.isArrayBuffer(value) || utils$2.isTypedArray(value)) {
      return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value);
    }
    return value;
  }
  function defaultVisitor(value, key, path) {
    let arr = value;
    if (utils$2.isReactNative(formData) && utils$2.isReactNativeBlob(value)) {
      formData.append(renderKey(path, key, dots), convertValue(value));
      return false;
    }
    if (value && !path && typeof value === "object") {
      if (utils$2.endsWith(key, "{}")) {
        key = metaTokens ? key : key.slice(0, -2);
        value = JSON.stringify(value);
      } else if (utils$2.isArray(value) && isFlatArray(value) || (utils$2.isFileList(value) || utils$2.endsWith(key, "[]")) && (arr = utils$2.toArray(value))) {
        key = removeBrackets(key);
        arr.forEach(function each(el, index2) {
          !(utils$2.isUndefined(el) || el === null) && formData.append(
            // eslint-disable-next-line no-nested-ternary
            indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]",
            convertValue(el)
          );
        });
        return false;
      }
    }
    if (isVisitable(value)) {
      return true;
    }
    formData.append(renderKey(path, key, dots), convertValue(value));
    return false;
  }
  const stack = [];
  const exposedHelpers = Object.assign(predicates, {
    defaultVisitor,
    convertValue,
    isVisitable
  });
  function build(value, path) {
    if (utils$2.isUndefined(value)) return;
    if (stack.indexOf(value) !== -1) {
      throw Error("Circular reference detected in " + path.join("."));
    }
    stack.push(value);
    utils$2.forEach(value, function each(el, key) {
      const result = !(utils$2.isUndefined(el) || el === null) && visitor.call(formData, el, utils$2.isString(key) ? key.trim() : key, path, exposedHelpers);
      if (result === true) {
        build(el, path ? path.concat(key) : [key]);
      }
    });
    stack.pop();
  }
  if (!utils$2.isObject(obj)) {
    throw new TypeError("data must be an object");
  }
  build(obj);
  return formData;
}
function encode$1(str) {
  const charMap = {
    "!": "%21",
    "'": "%27",
    "(": "%28",
    ")": "%29",
    "~": "%7E",
    "%20": "+",
    "%00": "\0"
  };
  return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
    return charMap[match];
  });
}
function AxiosURLSearchParams(params, options) {
  this._pairs = [];
  params && toFormData$1(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name2, value) {
  this._pairs.push([name2, value]);
};
prototype.toString = function toString(encoder) {
  const _encode = encoder ? function(value) {
    return encoder.call(this, value, encode$1);
  } : encode$1;
  return this._pairs.map(function each(pair) {
    return _encode(pair[0]) + "=" + _encode(pair[1]);
  }, "").join("&");
};
function encode(val) {
  return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+");
}
function buildURL(url, params, options) {
  if (!params) {
    return url;
  }
  const _encode = options && options.encode || encode;
  const _options = utils$2.isFunction(options) ? {
    serialize: options
  } : options;
  const serializeFn = _options && _options.serialize;
  let serializedParams;
  if (serializeFn) {
    serializedParams = serializeFn(params, _options);
  } else {
    serializedParams = utils$2.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
  }
  if (serializedParams) {
    const hashmarkIndex = url.indexOf("#");
    if (hashmarkIndex !== -1) {
      url = url.slice(0, hashmarkIndex);
    }
    url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams;
  }
  return url;
}
class InterceptorManager {
  constructor() {
    this.handlers = [];
  }
  /**
   * Add a new interceptor to the stack
   *
   * @param {Function} fulfilled The function to handle `then` for a `Promise`
   * @param {Function} rejected The function to handle `reject` for a `Promise`
   * @param {Object} options The options for the interceptor, synchronous and runWhen
   *
   * @return {Number} An ID used to remove interceptor later
   */
  use(fulfilled, rejected, options) {
    this.handlers.push({
      fulfilled,
      rejected,
      synchronous: options ? options.synchronous : false,
      runWhen: options ? options.runWhen : null
    });
    return this.handlers.length - 1;
  }
  /**
   * Remove an interceptor from the stack
   *
   * @param {Number} id The ID that was returned by `use`
   *
   * @returns {void}
   */
  eject(id) {
    if (this.handlers[id]) {
      this.handlers[id] = null;
    }
  }
  /**
   * Clear all interceptors from the stack
   *
   * @returns {void}
   */
  clear() {
    if (this.handlers) {
      this.handlers = [];
    }
  }
  /**
   * Iterate over all the registered interceptors
   *
   * This method is particularly useful for skipping over any
   * interceptors that may have become `null` calling `eject`.
   *
   * @param {Function} fn The function to call for each interceptor
   *
   * @returns {void}
   */
  forEach(fn) {
    utils$2.forEach(this.handlers, function forEachHandler(h) {
      if (h !== null) {
        fn(h);
      }
    });
  }
}
const transitionalDefaults = {
  silentJSONParsing: true,
  forcedJSONParsing: true,
  clarifyTimeoutError: false,
  legacyInterceptorReqResOrdering: true
};
const URLSearchParams$1 = require$$5.URLSearchParams;
const ALPHA = "abcdefghijklmnopqrstuvwxyz";
const DIGIT = "0123456789";
const ALPHABET = {
  DIGIT,
  ALPHA,
  ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
  let str = "";
  const { length } = alphabet;
  const randomValues = new Uint32Array(size);
  require$$1$1.randomFillSync(randomValues);
  for (let i = 0; i < size; i++) {
    str += alphabet[randomValues[i] % length];
  }
  return str;
};
const platform$1 = {
  isNode: true,
  classes: {
    URLSearchParams: URLSearchParams$1,
    FormData: FormData$1,
    Blob: typeof Blob !== "undefined" && Blob || null
  },
  ALPHABET,
  generateString,
  protocols: ["http", "https", "file", "data"]
};
const hasBrowserEnv = typeof window !== "undefined" && typeof document !== "undefined";
const _navigator = typeof navigator === "object" && navigator || void 0;
const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ["ReactNative", "NativeScript", "NS"].indexOf(_navigator.product) < 0);
const hasStandardBrowserWebWorkerEnv = (() => {
  return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef
  self instanceof WorkerGlobalScope && typeof self.importScripts === "function";
})();
const origin = hasBrowserEnv && window.location.href || "http://localhost";
const utils$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  hasBrowserEnv,
  hasStandardBrowserEnv,
  hasStandardBrowserWebWorkerEnv,
  navigator: _navigator,
  origin
}, Symbol.toStringTag, { value: "Module" }));
const platform = {
  ...utils$1,
  ...platform$1
};
function toURLEncodedForm(data, options) {
  return toFormData$1(data, new platform.classes.URLSearchParams(), {
    visitor: function(value, key, path, helpers) {
      if (platform.isNode && utils$2.isBuffer(value)) {
        this.append(key, value.toString("base64"));
        return false;
      }
      return helpers.defaultVisitor.apply(this, arguments);
    },
    ...options
  });
}
function parsePropPath(name2) {
  return utils$2.matchAll(/\w+|\[(\w*)]/g, name2).map((match) => {
    return match[0] === "[]" ? "" : match[1] || match[0];
  });
}
function arrayToObject(arr) {
  const obj = {};
  const keys2 = Object.keys(arr);
  let i;
  const len = keys2.length;
  let key;
  for (i = 0; i < len; i++) {
    key = keys2[i];
    obj[key] = arr[key];
  }
  return obj;
}
function formDataToJSON(formData) {
  function buildPath(path, value, target, index2) {
    let name2 = path[index2++];
    if (name2 === "__proto__") return true;
    const isNumericKey = Number.isFinite(+name2);
    const isLast = index2 >= path.length;
    name2 = !name2 && utils$2.isArray(target) ? target.length : name2;
    if (isLast) {
      if (utils$2.hasOwnProp(target, name2)) {
        target[name2] = [target[name2], value];
      } else {
        target[name2] = value;
      }
      return !isNumericKey;
    }
    if (!target[name2] || !utils$2.isObject(target[name2])) {
      target[name2] = [];
    }
    const result = buildPath(path, value, target[name2], index2);
    if (result && utils$2.isArray(target[name2])) {
      target[name2] = arrayToObject(target[name2]);
    }
    return !isNumericKey;
  }
  if (utils$2.isFormData(formData) && utils$2.isFunction(formData.entries)) {
    const obj = {};
    utils$2.forEachEntry(formData, (name2, value) => {
      buildPath(parsePropPath(name2), value, obj, 0);
    });
    return obj;
  }
  return null;
}
function stringifySafely(rawValue, parser, encoder) {
  if (utils$2.isString(rawValue)) {
    try {
      (parser || JSON.parse)(rawValue);
      return utils$2.trim(rawValue);
    } catch (e) {
      if (e.name !== "SyntaxError") {
        throw e;
      }
    }
  }
  return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
  transitional: transitionalDefaults,
  adapter: ["xhr", "http", "fetch"],
  transformRequest: [
    function transformRequest(data, headers) {
      const contentType = headers.getContentType() || "";
      const hasJSONContentType = contentType.indexOf("application/json") > -1;
      const isObjectPayload = utils$2.isObject(data);
      if (isObjectPayload && utils$2.isHTMLForm(data)) {
        data = new FormData(data);
      }
      const isFormData2 = utils$2.isFormData(data);
      if (isFormData2) {
        return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
      }
      if (utils$2.isArrayBuffer(data) || utils$2.isBuffer(data) || utils$2.isStream(data) || utils$2.isFile(data) || utils$2.isBlob(data) || utils$2.isReadableStream(data)) {
        return data;
      }
      if (utils$2.isArrayBufferView(data)) {
        return data.buffer;
      }
      if (utils$2.isURLSearchParams(data)) {
        headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false);
        return data.toString();
      }
      let isFileList2;
      if (isObjectPayload) {
        if (contentType.indexOf("application/x-www-form-urlencoded") > -1) {
          return toURLEncodedForm(data, this.formSerializer).toString();
        }
        if ((isFileList2 = utils$2.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) {
          const _FormData = this.env && this.env.FormData;
          return toFormData$1(
            isFileList2 ? { "files[]": data } : data,
            _FormData && new _FormData(),
            this.formSerializer
          );
        }
      }
      if (isObjectPayload || hasJSONContentType) {
        headers.setContentType("application/json", false);
        return stringifySafely(data);
      }
      return data;
    }
  ],
  transformResponse: [
    function transformResponse(data) {
      const transitional2 = this.transitional || defaults.transitional;
      const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing;
      const JSONRequested = this.responseType === "json";
      if (utils$2.isResponse(data) || utils$2.isReadableStream(data)) {
        return data;
      }
      if (data && utils$2.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) {
        const silentJSONParsing = transitional2 && transitional2.silentJSONParsing;
        const strictJSONParsing = !silentJSONParsing && JSONRequested;
        try {
          return JSON.parse(data, this.parseReviver);
        } catch (e) {
          if (strictJSONParsing) {
            if (e.name === "SyntaxError") {
              throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response);
            }
            throw e;
          }
        }
      }
      return data;
    }
  ],
  /**
   * A timeout in milliseconds to abort a request. If set to 0 (default) a
   * timeout is not created.
   */
  timeout: 0,
  xsrfCookieName: "XSRF-TOKEN",
  xsrfHeaderName: "X-XSRF-TOKEN",
  maxContentLength: -1,
  maxBodyLength: -1,
  env: {
    FormData: platform.classes.FormData,
    Blob: platform.classes.Blob
  },
  validateStatus: function validateStatus(status2) {
    return status2 >= 200 && status2 < 300;
  },
  headers: {
    common: {
      Accept: "application/json, text/plain, */*",
      "Content-Type": void 0
    }
  }
};
utils$2.forEach(["delete", "get", "head", "post", "put", "patch"], (method) => {
  defaults.headers[method] = {};
});
const ignoreDuplicateOf = utils$2.toObjectSet([
  "age",
  "authorization",
  "content-length",
  "content-type",
  "etag",
  "expires",
  "from",
  "host",
  "if-modified-since",
  "if-unmodified-since",
  "last-modified",
  "location",
  "max-forwards",
  "proxy-authorization",
  "referer",
  "retry-after",
  "user-agent"
]);
const parseHeaders = (rawHeaders) => {
  const parsed = {};
  let key;
  let val;
  let i;
  rawHeaders && rawHeaders.split("\n").forEach(function parser(line) {
    i = line.indexOf(":");
    key = line.substring(0, i).trim().toLowerCase();
    val = line.substring(i + 1).trim();
    if (!key || parsed[key] && ignoreDuplicateOf[key]) {
      return;
    }
    if (key === "set-cookie") {
      if (parsed[key]) {
        parsed[key].push(val);
      } else {
        parsed[key] = [val];
      }
    } else {
      parsed[key] = parsed[key] ? parsed[key] + ", " + val : val;
    }
  });
  return parsed;
};
const $internals = /* @__PURE__ */ Symbol("internals");
function normalizeHeader(header) {
  return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
  if (value === false || value == null) {
    return value;
  }
  return utils$2.isArray(value) ? value.map(normalizeValue) : String(value).replace(/[\r\n]+$/, "");
}
function parseTokens(str) {
  const tokens = /* @__PURE__ */ Object.create(null);
  const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
  let match;
  while (match = tokensRE.exec(str)) {
    tokens[match[1]] = match[2];
  }
  return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) {
  if (utils$2.isFunction(filter2)) {
    return filter2.call(this, value, header);
  }
  if (isHeaderNameFilter) {
    value = header;
  }
  if (!utils$2.isString(value)) return;
  if (utils$2.isString(filter2)) {
    return value.indexOf(filter2) !== -1;
  }
  if (utils$2.isRegExp(filter2)) {
    return filter2.test(value);
  }
}
function formatHeader(header) {
  return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char, str) => {
    return char.toUpperCase() + str;
  });
}
function buildAccessors(obj, header) {
  const accessorName = utils$2.toCamelCase(" " + header);
  ["get", "set", "has"].forEach((methodName) => {
    Object.defineProperty(obj, methodName + accessorName, {
      value: function(arg1, arg2, arg3) {
        return this[methodName].call(this, header, arg1, arg2, arg3);
      },
      configurable: true
    });
  });
}
let AxiosHeaders$1 = class AxiosHeaders {
  constructor(headers) {
    headers && this.set(headers);
  }
  set(header, valueOrRewrite, rewrite) {
    const self2 = this;
    function setHeader(_value, _header, _rewrite) {
      const lHeader = normalizeHeader(_header);
      if (!lHeader) {
        throw new Error("header name must be a non-empty string");
      }
      const key = utils$2.findKey(self2, lHeader);
      if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) {
        self2[key || _header] = normalizeValue(_value);
      }
    }
    const setHeaders = (headers, _rewrite) => utils$2.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
    if (utils$2.isPlainObject(header) || header instanceof this.constructor) {
      setHeaders(header, valueOrRewrite);
    } else if (utils$2.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
      setHeaders(parseHeaders(header), valueOrRewrite);
    } else if (utils$2.isObject(header) && utils$2.isIterable(header)) {
      let obj = {}, dest, key;
      for (const entry of header) {
        if (!utils$2.isArray(entry)) {
          throw TypeError("Object iterator must return a key-value pair");
        }
        obj[key = entry[0]] = (dest = obj[key]) ? utils$2.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]] : entry[1];
      }
      setHeaders(obj, valueOrRewrite);
    } else {
      header != null && setHeader(valueOrRewrite, header, rewrite);
    }
    return this;
  }
  get(header, parser) {
    header = normalizeHeader(header);
    if (header) {
      const key = utils$2.findKey(this, header);
      if (key) {
        const value = this[key];
        if (!parser) {
          return value;
        }
        if (parser === true) {
          return parseTokens(value);
        }
        if (utils$2.isFunction(parser)) {
          return parser.call(this, value, key);
        }
        if (utils$2.isRegExp(parser)) {
          return parser.exec(value);
        }
        throw new TypeError("parser must be boolean|regexp|function");
      }
    }
  }
  has(header, matcher) {
    header = normalizeHeader(header);
    if (header) {
      const key = utils$2.findKey(this, header);
      return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
    }
    return false;
  }
  delete(header, matcher) {
    const self2 = this;
    let deleted = false;
    function deleteHeader(_header) {
      _header = normalizeHeader(_header);
      if (_header) {
        const key = utils$2.findKey(self2, _header);
        if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) {
          delete self2[key];
          deleted = true;
        }
      }
    }
    if (utils$2.isArray(header)) {
      header.forEach(deleteHeader);
    } else {
      deleteHeader(header);
    }
    return deleted;
  }
  clear(matcher) {
    const keys2 = Object.keys(this);
    let i = keys2.length;
    let deleted = false;
    while (i--) {
      const key = keys2[i];
      if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
        delete this[key];
        deleted = true;
      }
    }
    return deleted;
  }
  normalize(format) {
    const self2 = this;
    const headers = {};
    utils$2.forEach(this, (value, header) => {
      const key = utils$2.findKey(headers, header);
      if (key) {
        self2[key] = normalizeValue(value);
        delete self2[header];
        return;
      }
      const normalized = format ? formatHeader(header) : String(header).trim();
      if (normalized !== header) {
        delete self2[header];
      }
      self2[normalized] = normalizeValue(value);
      headers[normalized] = true;
    });
    return this;
  }
  concat(...targets) {
    return this.constructor.concat(this, ...targets);
  }
  toJSON(asStrings) {
    const obj = /* @__PURE__ */ Object.create(null);
    utils$2.forEach(this, (value, header) => {
      value != null && value !== false && (obj[header] = asStrings && utils$2.isArray(value) ? value.join(", ") : value);
    });
    return obj;
  }
  [Symbol.iterator]() {
    return Object.entries(this.toJSON())[Symbol.iterator]();
  }
  toString() {
    return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n");
  }
  getSetCookie() {
    return this.get("set-cookie") || [];
  }
  get [Symbol.toStringTag]() {
    return "AxiosHeaders";
  }
  static from(thing) {
    return thing instanceof this ? thing : new this(thing);
  }
  static concat(first, ...targets) {
    const computed = new this(first);
    targets.forEach((target) => computed.set(target));
    return computed;
  }
  static accessor(header) {
    const internals = this[$internals] = this[$internals] = {
      accessors: {}
    };
    const accessors = internals.accessors;
    const prototype2 = this.prototype;
    function defineAccessor(_header) {
      const lHeader = normalizeHeader(_header);
      if (!accessors[lHeader]) {
        buildAccessors(prototype2, _header);
        accessors[lHeader] = true;
      }
    }
    utils$2.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
    return this;
  }
};
AxiosHeaders$1.accessor([
  "Content-Type",
  "Content-Length",
  "Accept",
  "Accept-Encoding",
  "User-Agent",
  "Authorization"
]);
utils$2.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
  let mapped = key[0].toUpperCase() + key.slice(1);
  return {
    get: () => value,
    set(headerValue) {
      this[mapped] = headerValue;
    }
  };
});
utils$2.freezeMethods(AxiosHeaders$1);
function transformData(fns, response) {
  const config = this || defaults;
  const context = response || config;
  const headers = AxiosHeaders$1.from(context.headers);
  let data = context.data;
  utils$2.forEach(fns, function transform(fn) {
    data = fn.call(config, data, headers.normalize(), response ? response.status : void 0);
  });
  headers.normalize();
  return data;
}
function isCancel$1(value) {
  return !!(value && value.__CANCEL__);
}
let CanceledError$1 = class CanceledError extends AxiosError$1 {
  /**
   * A `CanceledError` is an object that is thrown when an operation is canceled.
   *
   * @param {string=} message The message.
   * @param {Object=} config The config.
   * @param {Object=} request The request.
   *
   * @returns {CanceledError} The created error.
   */
  constructor(message, config, request) {
    super(message == null ? "canceled" : message, AxiosError$1.ERR_CANCELED, config, request);
    this.name = "CanceledError";
    this.__CANCEL__ = true;
  }
};
function settle(resolve, reject, response) {
  const validateStatus2 = response.config.validateStatus;
  if (!response.status || !validateStatus2 || validateStatus2(response.status)) {
    resolve(response);
  } else {
    reject(
      new AxiosError$1(
        "Request failed with status code " + response.status,
        [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
        response.config,
        response.request,
        response
      )
    );
  }
}
function isAbsoluteURL(url) {
  if (typeof url !== "string") {
    return false;
  }
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
function combineURLs(baseURL, relativeURL) {
  return relativeURL ? baseURL.replace(/\/?\/$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
}
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls) {
  let isRelativeUrl = !isAbsoluteURL(requestedURL);
  if (baseURL && (isRelativeUrl || allowAbsoluteUrls == false)) {
    return combineURLs(baseURL, requestedURL);
  }
  return requestedURL;
}
var DEFAULT_PORTS = {
  ftp: 21,
  gopher: 70,
  http: 80,
  https: 443,
  ws: 80,
  wss: 443
};
function parseUrl(urlString) {
  try {
    return new URL(urlString);
  } catch {
    return null;
  }
}
function getProxyForUrl(url) {
  var parsedUrl = (typeof url === "string" ? parseUrl(url) : url) || {};
  var proto = parsedUrl.protocol;
  var hostname = parsedUrl.host;
  var port = parsedUrl.port;
  if (typeof hostname !== "string" || !hostname || typeof proto !== "string") {
    return "";
  }
  proto = proto.split(":", 1)[0];
  hostname = hostname.replace(/:\d*$/, "");
  port = parseInt(port) || DEFAULT_PORTS[proto] || 0;
  if (!shouldProxy(hostname, port)) {
    return "";
  }
  var proxy = getEnv(proto + "_proxy") || getEnv("all_proxy");
  if (proxy && proxy.indexOf("://") === -1) {
    proxy = proto + "://" + proxy;
  }
  return proxy;
}
function shouldProxy(hostname, port) {
  var NO_PROXY = getEnv("no_proxy").toLowerCase();
  if (!NO_PROXY) {
    return true;
  }
  if (NO_PROXY === "*") {
    return false;
  }
  return NO_PROXY.split(/[,\s]/).every(function(proxy) {
    if (!proxy) {
      return true;
    }
    var parsedProxy = proxy.match(/^(.+):(\d+)$/);
    var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
    var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
    if (parsedProxyPort && parsedProxyPort !== port) {
      return true;
    }
    if (!/^[.*]/.test(parsedProxyHostname)) {
      return hostname !== parsedProxyHostname;
    }
    if (parsedProxyHostname.charAt(0) === "*") {
      parsedProxyHostname = parsedProxyHostname.slice(1);
    }
    return !hostname.endsWith(parsedProxyHostname);
  });
}
function getEnv(key) {
  return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || "";
}
var followRedirects$1 = { exports: {} };
var src = { exports: {} };
var browser = { exports: {} };
var ms;
var hasRequiredMs;
function requireMs() {
  if (hasRequiredMs) return ms;
  hasRequiredMs = 1;
  var s2 = 1e3;
  var m2 = s2 * 60;
  var h = m2 * 60;
  var d2 = h * 24;
  var w2 = d2 * 7;
  var y2 = d2 * 365.25;
  ms = function(val, options) {
    options = options || {};
    var type2 = typeof val;
    if (type2 === "string" && val.length > 0) {
      return parse2(val);
    } else if (type2 === "number" && isFinite(val)) {
      return options.long ? fmtLong(val) : fmtShort(val);
    }
    throw new Error(
      "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
    );
  };
  function parse2(str) {
    str = String(str);
    if (str.length > 100) {
      return;
    }
    var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
      str
    );
    if (!match) {
      return;
    }
    var n = parseFloat(match[1]);
    var type2 = (match[2] || "ms").toLowerCase();
    switch (type2) {
      case "years":
      case "year":
      case "yrs":
      case "yr":
      case "y":
        return n * y2;
      case "weeks":
      case "week":
      case "w":
        return n * w2;
      case "days":
      case "day":
      case "d":
        return n * d2;
      case "hours":
      case "hour":
      case "hrs":
      case "hr":
      case "h":
        return n * h;
      case "minutes":
      case "minute":
      case "mins":
      case "min":
      case "m":
        return n * m2;
      case "seconds":
      case "second":
      case "secs":
      case "sec":
      case "s":
        return n * s2;
      case "milliseconds":
      case "millisecond":
      case "msecs":
      case "msec":
      case "ms":
        return n;
      default:
        return void 0;
    }
  }
  function fmtShort(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d2) {
      return Math.round(ms2 / d2) + "d";
    }
    if (msAbs >= h) {
      return Math.round(ms2 / h) + "h";
    }
    if (msAbs >= m2) {
      return Math.round(ms2 / m2) + "m";
    }
    if (msAbs >= s2) {
      return Math.round(ms2 / s2) + "s";
    }
    return ms2 + "ms";
  }
  function fmtLong(ms2) {
    var msAbs = Math.abs(ms2);
    if (msAbs >= d2) {
      return plural(ms2, msAbs, d2, "day");
    }
    if (msAbs >= h) {
      return plural(ms2, msAbs, h, "hour");
    }
    if (msAbs >= m2) {
      return plural(ms2, msAbs, m2, "minute");
    }
    if (msAbs >= s2) {
      return plural(ms2, msAbs, s2, "second");
    }
    return ms2 + " ms";
  }
  function plural(ms2, msAbs, n, name2) {
    var isPlural = msAbs >= n * 1.5;
    return Math.round(ms2 / n) + " " + name2 + (isPlural ? "s" : "");
  }
  return ms;
}
var common;
var hasRequiredCommon;
function requireCommon() {
  if (hasRequiredCommon) return common;
  hasRequiredCommon = 1;
  function setup(env2) {
    createDebug.debug = createDebug;
    createDebug.default = createDebug;
    createDebug.coerce = coerce;
    createDebug.disable = disable2;
    createDebug.enable = enable;
    createDebug.enabled = enabled;
    createDebug.humanize = requireMs();
    createDebug.destroy = destroy;
    Object.keys(env2).forEach((key) => {
      createDebug[key] = env2[key];
    });
    createDebug.names = [];
    createDebug.skips = [];
    createDebug.formatters = {};
    function selectColor(namespace) {
      let hash = 0;
      for (let i = 0; i < namespace.length; i++) {
        hash = (hash << 5) - hash + namespace.charCodeAt(i);
        hash |= 0;
      }
      return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
    }
    createDebug.selectColor = selectColor;
    function createDebug(namespace) {
      let prevTime;
      let enableOverride = null;
      let namespacesCache;
      let enabledCache;
      function debug(...args) {
        if (!debug.enabled) {
          return;
        }
        const self2 = debug;
        const curr = Number(/* @__PURE__ */ new Date());
        const ms2 = curr - (prevTime || curr);
        self2.diff = ms2;
        self2.prev = prevTime;
        self2.curr = curr;
        prevTime = curr;
        args[0] = createDebug.coerce(args[0]);
        if (typeof args[0] !== "string") {
          args.unshift("%O");
        }
        let index2 = 0;
        args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
          if (match === "%%") {
            return "%";
          }
          index2++;
          const formatter = createDebug.formatters[format];
          if (typeof formatter === "function") {
            const val = args[index2];
            match = formatter.call(self2, val);
            args.splice(index2, 1);
            index2--;
          }
          return match;
        });
        createDebug.formatArgs.call(self2, args);
        const logFn = self2.log || createDebug.log;
        logFn.apply(self2, args);
      }
      debug.namespace = namespace;
      debug.useColors = createDebug.useColors();
      debug.color = createDebug.selectColor(namespace);
      debug.extend = extend2;
      debug.destroy = createDebug.destroy;
      Object.defineProperty(debug, "enabled", {
        enumerable: true,
        configurable: false,
        get: () => {
          if (enableOverride !== null) {
            return enableOverride;
          }
          if (namespacesCache !== createDebug.namespaces) {
            namespacesCache = createDebug.namespaces;
            enabledCache = createDebug.enabled(namespace);
          }
          return enabledCache;
        },
        set: (v2) => {
          enableOverride = v2;
        }
      });
      if (typeof createDebug.init === "function") {
        createDebug.init(debug);
      }
      return debug;
    }
    function extend2(namespace, delimiter) {
      const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
      newDebug.log = this.log;
      return newDebug;
    }
    function enable(namespaces) {
      createDebug.save(namespaces);
      createDebug.namespaces = namespaces;
      createDebug.names = [];
      createDebug.skips = [];
      const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean);
      for (const ns of split) {
        if (ns[0] === "-") {
          createDebug.skips.push(ns.slice(1));
        } else {
          createDebug.names.push(ns);
        }
      }
    }
    function matchesTemplate(search2, template) {
      let searchIndex = 0;
      let templateIndex = 0;
      let starIndex = -1;
      let matchIndex = 0;
      while (searchIndex < search2.length) {
        if (templateIndex < template.length && (template[templateIndex] === search2[searchIndex] || template[templateIndex] === "*")) {
          if (template[templateIndex] === "*") {
            starIndex = templateIndex;
            matchIndex = searchIndex;
            templateIndex++;
          } else {
            searchIndex++;
            templateIndex++;
          }
        } else if (starIndex !== -1) {
          templateIndex = starIndex + 1;
          matchIndex++;
          searchIndex = matchIndex;
        } else {
          return false;
        }
      }
      while (templateIndex < template.length && template[templateIndex] === "*") {
        templateIndex++;
      }
      return templateIndex === template.length;
    }
    function disable2() {
      const namespaces = [
        ...createDebug.names,
        ...createDebug.skips.map((namespace) => "-" + namespace)
      ].join(",");
      createDebug.enable("");
      return namespaces;
    }
    function enabled(name2) {
      for (const skip of createDebug.skips) {
        if (matchesTemplate(name2, skip)) {
          return false;
        }
      }
      for (const ns of createDebug.names) {
        if (matchesTemplate(name2, ns)) {
          return true;
        }
      }
      return false;
    }
    function coerce(val) {
      if (val instanceof Error) {
        return val.stack || val.message;
      }
      return val;
    }
    function destroy() {
      console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
    }
    createDebug.enable(createDebug.load());
    return createDebug;
  }
  common = setup;
  return common;
}
var hasRequiredBrowser;
function requireBrowser() {
  if (hasRequiredBrowser) return browser.exports;
  hasRequiredBrowser = 1;
  (function(module, exports$1) {
    exports$1.formatArgs = formatArgs;
    exports$1.save = save;
    exports$1.load = load;
    exports$1.useColors = useColors;
    exports$1.storage = localstorage();
    exports$1.destroy = /* @__PURE__ */ (() => {
      let warned = false;
      return () => {
        if (!warned) {
          warned = true;
          console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
        }
      };
    })();
    exports$1.colors = [
      "#0000CC",
      "#0000FF",
      "#0033CC",
      "#0033FF",
      "#0066CC",
      "#0066FF",
      "#0099CC",
      "#0099FF",
      "#00CC00",
      "#00CC33",
      "#00CC66",
      "#00CC99",
      "#00CCCC",
      "#00CCFF",
      "#3300CC",
      "#3300FF",
      "#3333CC",
      "#3333FF",
      "#3366CC",
      "#3366FF",
      "#3399CC",
      "#3399FF",
      "#33CC00",
      "#33CC33",
      "#33CC66",
      "#33CC99",
      "#33CCCC",
      "#33CCFF",
      "#6600CC",
      "#6600FF",
      "#6633CC",
      "#6633FF",
      "#66CC00",
      "#66CC33",
      "#9900CC",
      "#9900FF",
      "#9933CC",
      "#9933FF",
      "#99CC00",
      "#99CC33",
      "#CC0000",
      "#CC0033",
      "#CC0066",
      "#CC0099",
      "#CC00CC",
      "#CC00FF",
      "#CC3300",
      "#CC3333",
      "#CC3366",
      "#CC3399",
      "#CC33CC",
      "#CC33FF",
      "#CC6600",
      "#CC6633",
      "#CC9900",
      "#CC9933",
      "#CCCC00",
      "#CCCC33",
      "#FF0000",
      "#FF0033",
      "#FF0066",
      "#FF0099",
      "#FF00CC",
      "#FF00FF",
      "#FF3300",
      "#FF3333",
      "#FF3366",
      "#FF3399",
      "#FF33CC",
      "#FF33FF",
      "#FF6600",
      "#FF6633",
      "#FF9900",
      "#FF9933",
      "#FFCC00",
      "#FFCC33"
    ];
    function useColors() {
      if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) {
        return true;
      }
      if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
        return false;
      }
      let m2;
      return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
      typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
      // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
      typeof navigator !== "undefined" && navigator.userAgent && (m2 = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m2[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
      typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
    }
    function formatArgs(args) {
      args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
      if (!this.useColors) {
        return;
      }
      const c = "color: " + this.color;
      args.splice(1, 0, c, "color: inherit");
      let index2 = 0;
      let lastC = 0;
      args[0].replace(/%[a-zA-Z%]/g, (match) => {
        if (match === "%%") {
          return;
        }
        index2++;
        if (match === "%c") {
          lastC = index2;
        }
      });
      args.splice(lastC, 0, c);
    }
    exports$1.log = console.debug || console.log || (() => {
    });
    function save(namespaces) {
      try {
        if (namespaces) {
          exports$1.storage.setItem("debug", namespaces);
        } else {
          exports$1.storage.removeItem("debug");
        }
      } catch (error) {
      }
    }
    function load() {
      let r;
      try {
        r = exports$1.storage.getItem("debug") || exports$1.storage.getItem("DEBUG");
      } catch (error) {
      }
      if (!r && typeof process !== "undefined" && "env" in process) {
        r = process.env.DEBUG;
      }
      return r;
    }
    function localstorage() {
      try {
        return localStorage;
      } catch (error) {
      }
    }
    module.exports = requireCommon()(exports$1);
    const { formatters } = module.exports;
    formatters.j = function(v2) {
      try {
        return JSON.stringify(v2);
      } catch (error) {
        return "[UnexpectedJSONParseError]: " + error.message;
      }
    };
  })(browser, browser.exports);
  return browser.exports;
}
var node$1 = { exports: {} };
var hasFlag;
var hasRequiredHasFlag;
function requireHasFlag() {
  if (hasRequiredHasFlag) return hasFlag;
  hasRequiredHasFlag = 1;
  hasFlag = (flag, argv = process.argv) => {
    const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
    const position2 = argv.indexOf(prefix + flag);
    const terminatorPosition = argv.indexOf("--");
    return position2 !== -1 && (terminatorPosition === -1 || position2 < terminatorPosition);
  };
  return hasFlag;
}
var supportsColor_1;
var hasRequiredSupportsColor;
function requireSupportsColor() {
  if (hasRequiredSupportsColor) return supportsColor_1;
  hasRequiredSupportsColor = 1;
  const os = require$$0$2;
  const tty = require$$1$2;
  const hasFlag2 = requireHasFlag();
  const { env: env2 } = process;
  let flagForceColor;
  if (hasFlag2("no-color") || hasFlag2("no-colors") || hasFlag2("color=false") || hasFlag2("color=never")) {
    flagForceColor = 0;
  } else if (hasFlag2("color") || hasFlag2("colors") || hasFlag2("color=true") || hasFlag2("color=always")) {
    flagForceColor = 1;
  }
  function envForceColor() {
    if ("FORCE_COLOR" in env2) {
      if (env2.FORCE_COLOR === "true") {
        return 1;
      }
      if (env2.FORCE_COLOR === "false") {
        return 0;
      }
      return env2.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env2.FORCE_COLOR, 10), 3);
    }
  }
  function translateLevel(level) {
    if (level === 0) {
      return false;
    }
    return {
      level,
      hasBasic: true,
      has256: level >= 2,
      has16m: level >= 3
    };
  }
  function supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
    const noFlagForceColor = envForceColor();
    if (noFlagForceColor !== void 0) {
      flagForceColor = noFlagForceColor;
    }
    const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
    if (forceColor === 0) {
      return 0;
    }
    if (sniffFlags) {
      if (hasFlag2("color=16m") || hasFlag2("color=full") || hasFlag2("color=truecolor")) {
        return 3;
      }
      if (hasFlag2("color=256")) {
        return 2;
      }
    }
    if (haveStream && !streamIsTTY && forceColor === void 0) {
      return 0;
    }
    const min2 = forceColor || 0;
    if (env2.TERM === "dumb") {
      return min2;
    }
    if (process.platform === "win32") {
      const osRelease = os.release().split(".");
      if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
        return Number(osRelease[2]) >= 14931 ? 3 : 2;
      }
      return 1;
    }
    if ("CI" in env2) {
      if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign2) => sign2 in env2) || env2.CI_NAME === "codeship") {
        return 1;
      }
      return min2;
    }
    if ("TEAMCITY_VERSION" in env2) {
      return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env2.TEAMCITY_VERSION) ? 1 : 0;
    }
    if (env2.COLORTERM === "truecolor") {
      return 3;
    }
    if ("TERM_PROGRAM" in env2) {
      const version = Number.parseInt((env2.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
      switch (env2.TERM_PROGRAM) {
        case "iTerm.app":
          return version >= 3 ? 3 : 2;
        case "Apple_Terminal":
          return 2;
      }
    }
    if (/-256(color)?$/i.test(env2.TERM)) {
      return 2;
    }
    if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env2.TERM)) {
      return 1;
    }
    if ("COLORTERM" in env2) {
      return 1;
    }
    return min2;
  }
  function getSupportLevel(stream2, options = {}) {
    const level = supportsColor(stream2, {
      streamIsTTY: stream2 && stream2.isTTY,
      ...options
    });
    return translateLevel(level);
  }
  supportsColor_1 = {
    supportsColor: getSupportLevel,
    stdout: getSupportLevel({ isTTY: tty.isatty(1) }),
    stderr: getSupportLevel({ isTTY: tty.isatty(2) })
  };
  return supportsColor_1;
}
var hasRequiredNode;
function requireNode() {
  if (hasRequiredNode) return node$1.exports;
  hasRequiredNode = 1;
  (function(module, exports$1) {
    const tty = require$$1$2;
    const util = require$$0$1;
    exports$1.init = init2;
    exports$1.log = log;
    exports$1.formatArgs = formatArgs;
    exports$1.save = save;
    exports$1.load = load;
    exports$1.useColors = useColors;
    exports$1.destroy = util.deprecate(
      () => {
      },
      "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."
    );
    exports$1.colors = [6, 2, 3, 4, 5, 1];
    try {
      const supportsColor = requireSupportsColor();
      if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
        exports$1.colors = [
          20,
          21,
          26,
          27,
          32,
          33,
          38,
          39,
          40,
          41,
          42,
          43,
          44,
          45,
          56,
          57,
          62,
          63,
          68,
          69,
          74,
          75,
          76,
          77,
          78,
          79,
          80,
          81,
          92,
          93,
          98,
          99,
          112,
          113,
          128,
          129,
          134,
          135,
          148,
          149,
          160,
          161,
          162,
          163,
          164,
          165,
          166,
          167,
          168,
          169,
          170,
          171,
          172,
          173,
          178,
          179,
          184,
          185,
          196,
          197,
          198,
          199,
          200,
          201,
          202,
          203,
          204,
          205,
          206,
          207,
          208,
          209,
          214,
          215,
          220,
          221
        ];
      }
    } catch (error) {
    }
    exports$1.inspectOpts = Object.keys(process.env).filter((key) => {
      return /^debug_/i.test(key);
    }).reduce((obj, key) => {
      const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_2, k2) => {
        return k2.toUpperCase();
      });
      let val = process.env[key];
      if (/^(yes|on|true|enabled)$/i.test(val)) {
        val = true;
      } else if (/^(no|off|false|disabled)$/i.test(val)) {
        val = false;
      } else if (val === "null") {
        val = null;
      } else {
        val = Number(val);
      }
      obj[prop] = val;
      return obj;
    }, {});
    function useColors() {
      return "colors" in exports$1.inspectOpts ? Boolean(exports$1.inspectOpts.colors) : tty.isatty(process.stderr.fd);
    }
    function formatArgs(args) {
      const { namespace: name2, useColors: useColors2 } = this;
      if (useColors2) {
        const c = this.color;
        const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
        const prefix = `  ${colorCode};1m${name2} \x1B[0m`;
        args[0] = prefix + args[0].split("\n").join("\n" + prefix);
        args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
      } else {
        args[0] = getDate() + name2 + " " + args[0];
      }
    }
    function getDate() {
      if (exports$1.inspectOpts.hideDate) {
        return "";
      }
      return (/* @__PURE__ */ new Date()).toISOString() + " ";
    }
    function log(...args) {
      return process.stderr.write(util.formatWithOptions(exports$1.inspectOpts, ...args) + "\n");
    }
    function save(namespaces) {
      if (namespaces) {
        process.env.DEBUG = namespaces;
      } else {
        delete process.env.DEBUG;
      }
    }
    function load() {
      return process.env.DEBUG;
    }
    function init2(debug) {
      debug.inspectOpts = {};
      const keys2 = Object.keys(exports$1.inspectOpts);
      for (let i = 0; i < keys2.length; i++) {
        debug.inspectOpts[keys2[i]] = exports$1.inspectOpts[keys2[i]];
      }
    }
    module.exports = requireCommon()(exports$1);
    const { formatters } = module.exports;
    formatters.o = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v2, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
    };
    formatters.O = function(v2) {
      this.inspectOpts.colors = this.useColors;
      return util.inspect(v2, this.inspectOpts);
    };
  })(node$1, node$1.exports);
  return node$1.exports;
}
var hasRequiredSrc;
function requireSrc() {
  if (hasRequiredSrc) return src.exports;
  hasRequiredSrc = 1;
  if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) {
    src.exports = requireBrowser();
  } else {
    src.exports = requireNode();
  }
  return src.exports;
}
var debug_1;
var hasRequiredDebug;
function requireDebug() {
  if (hasRequiredDebug) return debug_1;
  hasRequiredDebug = 1;
  var debug;
  debug_1 = function() {
    if (!debug) {
      try {
        debug = requireSrc()("follow-redirects");
      } catch (error) {
      }
      if (typeof debug !== "function") {
        debug = function() {
        };
      }
    }
    debug.apply(null, arguments);
  };
  return debug_1;
}
var hasRequiredFollowRedirects;
function requireFollowRedirects() {
  if (hasRequiredFollowRedirects) return followRedirects$1.exports;
  hasRequiredFollowRedirects = 1;
  var url = require$$5;
  var URL2 = url.URL;
  var http = require$$3;
  var https = require$$4;
  var Writable = stream.Writable;
  var assert = require$$4$1;
  var debug = requireDebug();
  (function detectUnsupportedEnvironment() {
    var looksLikeNode = typeof process !== "undefined";
    var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined";
    var looksLikeV8 = isFunction2(Error.captureStackTrace);
    if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) {
      console.warn("The follow-redirects package should be excluded from browser builds.");
    }
  })();
  var useNativeURL = false;
  try {
    assert(new URL2(""));
  } catch (error) {
    useNativeURL = error.code === "ERR_INVALID_URL";
  }
  var preservedUrlFields = [
    "auth",
    "host",
    "hostname",
    "href",
    "path",
    "pathname",
    "port",
    "protocol",
    "query",
    "search",
    "hash"
  ];
  var events = ["abort", "aborted", "connect", "error", "socket", "timeout"];
  var eventHandlers = /* @__PURE__ */ Object.create(null);
  events.forEach(function(event) {
    eventHandlers[event] = function(arg1, arg2, arg3) {
      this._redirectable.emit(event, arg1, arg2, arg3);
    };
  });
  var InvalidUrlError = createErrorType(
    "ERR_INVALID_URL",
    "Invalid URL",
    TypeError
  );
  var RedirectionError = createErrorType(
    "ERR_FR_REDIRECTION_FAILURE",
    "Redirected request failed"
  );
  var TooManyRedirectsError = createErrorType(
    "ERR_FR_TOO_MANY_REDIRECTS",
    "Maximum number of redirects exceeded",
    RedirectionError
  );
  var MaxBodyLengthExceededError = createErrorType(
    "ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
    "Request body larger than maxBodyLength limit"
  );
  var WriteAfterEndError = createErrorType(
    "ERR_STREAM_WRITE_AFTER_END",
    "write after end"
  );
  var destroy = Writable.prototype.destroy || noop2;
  function RedirectableRequest(options, responseCallback) {
    Writable.call(this);
    this._sanitizeOptions(options);
    this._options = options;
    this._ended = false;
    this._ending = false;
    this._redirectCount = 0;
    this._redirects = [];
    this._requestBodyLength = 0;
    this._requestBodyBuffers = [];
    if (responseCallback) {
      this.on("response", responseCallback);
    }
    var self2 = this;
    this._onNativeResponse = function(response) {
      try {
        self2._processResponse(response);
      } catch (cause) {
        self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause }));
      }
    };
    this._performRequest();
  }
  RedirectableRequest.prototype = Object.create(Writable.prototype);
  RedirectableRequest.prototype.abort = function() {
    destroyRequest(this._currentRequest);
    this._currentRequest.abort();
    this.emit("abort");
  };
  RedirectableRequest.prototype.destroy = function(error) {
    destroyRequest(this._currentRequest, error);
    destroy.call(this, error);
    return this;
  };
  RedirectableRequest.prototype.write = function(data, encoding, callback) {
    if (this._ending) {
      throw new WriteAfterEndError();
    }
    if (!isString2(data) && !isBuffer2(data)) {
      throw new TypeError("data should be a string, Buffer or Uint8Array");
    }
    if (isFunction2(encoding)) {
      callback = encoding;
      encoding = null;
    }
    if (data.length === 0) {
      if (callback) {
        callback();
      }
      return;
    }
    if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
      this._requestBodyLength += data.length;
      this._requestBodyBuffers.push({ data, encoding });
      this._currentRequest.write(data, encoding, callback);
    } else {
      this.emit("error", new MaxBodyLengthExceededError());
      this.abort();
    }
  };
  RedirectableRequest.prototype.end = function(data, encoding, callback) {
    if (isFunction2(data)) {
      callback = data;
      data = encoding = null;
    } else if (isFunction2(encoding)) {
      callback = encoding;
      encoding = null;
    }
    if (!data) {
      this._ended = this._ending = true;
      this._currentRequest.end(null, null, callback);
    } else {
      var self2 = this;
      var currentRequest = this._currentRequest;
      this.write(data, encoding, function() {
        self2._ended = true;
        currentRequest.end(null, null, callback);
      });
      this._ending = true;
    }
  };
  RedirectableRequest.prototype.setHeader = function(name2, value) {
    this._options.headers[name2] = value;
    this._currentRequest.setHeader(name2, value);
  };
  RedirectableRequest.prototype.removeHeader = function(name2) {
    delete this._options.headers[name2];
    this._currentRequest.removeHeader(name2);
  };
  RedirectableRequest.prototype.setTimeout = function(msecs, callback) {
    var self2 = this;
    function destroyOnTimeout(socket) {
      socket.setTimeout(msecs);
      socket.removeListener("timeout", socket.destroy);
      socket.addListener("timeout", socket.destroy);
    }
    function startTimer(socket) {
      if (self2._timeout) {
        clearTimeout(self2._timeout);
      }
      self2._timeout = setTimeout(function() {
        self2.emit("timeout");
        clearTimer();
      }, msecs);
      destroyOnTimeout(socket);
    }
    function clearTimer() {
      if (self2._timeout) {
        clearTimeout(self2._timeout);
        self2._timeout = null;
      }
      self2.removeListener("abort", clearTimer);
      self2.removeListener("error", clearTimer);
      self2.removeListener("response", clearTimer);
      self2.removeListener("close", clearTimer);
      if (callback) {
        self2.removeListener("timeout", callback);
      }
      if (!self2.socket) {
        self2._currentRequest.removeListener("socket", startTimer);
      }
    }
    if (callback) {
      this.on("timeout", callback);
    }
    if (this.socket) {
      startTimer(this.socket);
    } else {
      this._currentRequest.once("socket", startTimer);
    }
    this.on("socket", destroyOnTimeout);
    this.on("abort", clearTimer);
    this.on("error", clearTimer);
    this.on("response", clearTimer);
    this.on("close", clearTimer);
    return this;
  };
  [
    "flushHeaders",
    "getHeader",
    "setNoDelay",
    "setSocketKeepAlive"
  ].forEach(function(method) {
    RedirectableRequest.prototype[method] = function(a, b2) {
      return this._currentRequest[method](a, b2);
    };
  });
  ["aborted", "connection", "socket"].forEach(function(property) {
    Object.defineProperty(RedirectableRequest.prototype, property, {
      get: function() {
        return this._currentRequest[property];
      }
    });
  });
  RedirectableRequest.prototype._sanitizeOptions = function(options) {
    if (!options.headers) {
      options.headers = {};
    }
    if (options.host) {
      if (!options.hostname) {
        options.hostname = options.host;
      }
      delete options.host;
    }
    if (!options.pathname && options.path) {
      var searchPos = options.path.indexOf("?");
      if (searchPos < 0) {
        options.pathname = options.path;
      } else {
        options.pathname = options.path.substring(0, searchPos);
        options.search = options.path.substring(searchPos);
      }
    }
  };
  RedirectableRequest.prototype._performRequest = function() {
    var protocol = this._options.protocol;
    var nativeProtocol = this._options.nativeProtocols[protocol];
    if (!nativeProtocol) {
      throw new TypeError("Unsupported protocol " + protocol);
    }
    if (this._options.agents) {
      var scheme = protocol.slice(0, -1);
      this._options.agent = this._options.agents[scheme];
    }
    var request = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse);
    request._redirectable = this;
    for (var event of events) {
      request.on(event, eventHandlers[event]);
    }
    this._currentUrl = /^\//.test(this._options.path) ? url.format(this._options) : (
      // When making a request to a proxy, […]
      // a client MUST send the target URI in absolute-form […].
      this._options.path
    );
    if (this._isRedirect) {
      var i = 0;
      var self2 = this;
      var buffers = this._requestBodyBuffers;
      (function writeNext(error) {
        if (request === self2._currentRequest) {
          if (error) {
            self2.emit("error", error);
          } else if (i < buffers.length) {
            var buffer = buffers[i++];
            if (!request.finished) {
              request.write(buffer.data, buffer.encoding, writeNext);
            }
          } else if (self2._ended) {
            request.end();
          }
        }
      })();
    }
  };
  RedirectableRequest.prototype._processResponse = function(response) {
    var statusCode = response.statusCode;
    if (this._options.trackRedirects) {
      this._redirects.push({
        url: this._currentUrl,
        headers: response.headers,
        statusCode
      });
    }
    var location = response.headers.location;
    if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) {
      response.responseUrl = this._currentUrl;
      response.redirects = this._redirects;
      this.emit("response", response);
      this._requestBodyBuffers = [];
      return;
    }
    destroyRequest(this._currentRequest);
    response.destroy();
    if (++this._redirectCount > this._options.maxRedirects) {
      throw new TooManyRedirectsError();
    }
    var requestHeaders;
    var beforeRedirect = this._options.beforeRedirect;
    if (beforeRedirect) {
      requestHeaders = Object.assign({
        // The Host header was set by nativeProtocol.request
        Host: response.req.getHeader("host")
      }, this._options.headers);
    }
    var method = this._options.method;
    if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || // RFC7231§6.4.4: The 303 (See Other) status code indicates that
    // the server is redirecting the user agent to a different resource […]
    // A user agent can perform a retrieval request targeting that URI
    // (a GET or HEAD request if using HTTP) […]
    statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) {
      this._options.method = "GET";
      this._requestBodyBuffers = [];
      removeMatchingHeaders(/^content-/i, this._options.headers);
    }
    var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);
    var currentUrlParts = parseUrl2(this._currentUrl);
    var currentHost = currentHostHeader || currentUrlParts.host;
    var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url.format(Object.assign(currentUrlParts, { host: currentHost }));
    var redirectUrl = resolveUrl(location, currentUrl);
    debug("redirecting to", redirectUrl.href);
    this._isRedirect = true;
    spreadUrlObject(redirectUrl, this._options);
    if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) {
      removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers);
    }
    if (isFunction2(beforeRedirect)) {
      var responseDetails = {
        headers: response.headers,
        statusCode
      };
      var requestDetails = {
        url: currentUrl,
        method,
        headers: requestHeaders
      };
      beforeRedirect(this._options, responseDetails, requestDetails);
      this._sanitizeOptions(this._options);
    }
    this._performRequest();
  };
  function wrap2(protocols) {
    var exports$1 = {
      maxRedirects: 21,
      maxBodyLength: 10 * 1024 * 1024
    };
    var nativeProtocols = {};
    Object.keys(protocols).forEach(function(scheme) {
      var protocol = scheme + ":";
      var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
      var wrappedProtocol = exports$1[scheme] = Object.create(nativeProtocol);
      function request(input, options, callback) {
        if (isURL(input)) {
          input = spreadUrlObject(input);
        } else if (isString2(input)) {
          input = spreadUrlObject(parseUrl2(input));
        } else {
          callback = options;
          options = validateUrl(input);
          input = { protocol };
        }
        if (isFunction2(options)) {
          callback = options;
          options = null;
        }
        options = Object.assign({
          maxRedirects: exports$1.maxRedirects,
          maxBodyLength: exports$1.maxBodyLength
        }, input, options);
        options.nativeProtocols = nativeProtocols;
        if (!isString2(options.host) && !isString2(options.hostname)) {
          options.hostname = "::1";
        }
        assert.equal(options.protocol, protocol, "protocol mismatch");
        debug("options", options);
        return new RedirectableRequest(options, callback);
      }
      function get2(input, options, callback) {
        var wrappedRequest = wrappedProtocol.request(input, options, callback);
        wrappedRequest.end();
        return wrappedRequest;
      }
      Object.defineProperties(wrappedProtocol, {
        request: { value: request, configurable: true, enumerable: true, writable: true },
        get: { value: get2, configurable: true, enumerable: true, writable: true }
      });
    });
    return exports$1;
  }
  function noop2() {
  }
  function parseUrl2(input) {
    var parsed;
    if (useNativeURL) {
      parsed = new URL2(input);
    } else {
      parsed = validateUrl(url.parse(input));
      if (!isString2(parsed.protocol)) {
        throw new InvalidUrlError({ input });
      }
    }
    return parsed;
  }
  function resolveUrl(relative, base) {
    return useNativeURL ? new URL2(relative, base) : parseUrl2(url.resolve(base, relative));
  }
  function validateUrl(input) {
    if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) {
      throw new InvalidUrlError({ input: input.href || input });
    }
    if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) {
      throw new InvalidUrlError({ input: input.href || input });
    }
    return input;
  }
  function spreadUrlObject(urlObject, target) {
    var spread2 = target || {};
    for (var key of preservedUrlFields) {
      spread2[key] = urlObject[key];
    }
    if (spread2.hostname.startsWith("[")) {
      spread2.hostname = spread2.hostname.slice(1, -1);
    }
    if (spread2.port !== "") {
      spread2.port = Number(spread2.port);
    }
    spread2.path = spread2.search ? spread2.pathname + spread2.search : spread2.pathname;
    return spread2;
  }
  function removeMatchingHeaders(regex, headers) {
    var lastValue;
    for (var header in headers) {
      if (regex.test(header)) {
        lastValue = headers[header];
        delete headers[header];
      }
    }
    return lastValue === null || typeof lastValue === "undefined" ? void 0 : String(lastValue).trim();
  }
  function createErrorType(code2, message, baseClass) {
    function CustomError(properties) {
      if (isFunction2(Error.captureStackTrace)) {
        Error.captureStackTrace(this, this.constructor);
      }
      Object.assign(this, properties || {});
      this.code = code2;
      this.message = this.cause ? message + ": " + this.cause.message : message;
    }
    CustomError.prototype = new (baseClass || Error)();
    Object.defineProperties(CustomError.prototype, {
      constructor: {
        value: CustomError,
        enumerable: false
      },
      name: {
        value: "Error [" + code2 + "]",
        enumerable: false
      }
    });
    return CustomError;
  }
  function destroyRequest(request, error) {
    for (var event of events) {
      request.removeListener(event, eventHandlers[event]);
    }
    request.on("error", noop2);
    request.destroy(error);
  }
  function isSubdomain(subdomain, domain) {
    assert(isString2(subdomain) && isString2(domain));
    var dot = subdomain.length - domain.length - 1;
    return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain);
  }
  function isString2(value) {
    return typeof value === "string" || value instanceof String;
  }
  function isFunction2(value) {
    return typeof value === "function";
  }
  function isBuffer2(value) {
    return typeof value === "object" && "length" in value;
  }
  function isURL(value) {
    return URL2 && value instanceof URL2;
  }
  followRedirects$1.exports = wrap2({ http, https });
  followRedirects$1.exports.wrap = wrap2;
  return followRedirects$1.exports;
}
var followRedirectsExports = requireFollowRedirects();
const followRedirects = /* @__PURE__ */ getDefaultExportFromCjs(followRedirectsExports);
const VERSION$1 = "1.14.0";
function parseProtocol(url) {
  const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  return match && match[1] || "";
}
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
function fromDataURI(uri2, asBlob, options) {
  const _Blob = options && options.Blob || platform.classes.Blob;
  const protocol = parseProtocol(uri2);
  if (asBlob === void 0 && _Blob) {
    asBlob = true;
  }
  if (protocol === "data") {
    uri2 = protocol.length ? uri2.slice(protocol.length + 1) : uri2;
    const match = DATA_URL_PATTERN.exec(uri2);
    if (!match) {
      throw new AxiosError$1("Invalid URL", AxiosError$1.ERR_INVALID_URL);
    }
    const mime = match[1];
    const isBase64 = match[2];
    const body2 = match[3];
    const buffer = Buffer.from(decodeURIComponent(body2), isBase64 ? "base64" : "utf8");
    if (asBlob) {
      if (!_Blob) {
        throw new AxiosError$1("Blob is not supported", AxiosError$1.ERR_NOT_SUPPORT);
      }
      return new _Blob([buffer], { type: mime });
    }
    return buffer;
  }
  throw new AxiosError$1("Unsupported protocol " + protocol, AxiosError$1.ERR_NOT_SUPPORT);
}
const kInternals = /* @__PURE__ */ Symbol("internals");
class AxiosTransformStream extends stream.Transform {
  constructor(options) {
    options = utils$2.toFlatObject(
      options,
      {
        maxRate: 0,
        chunkSize: 64 * 1024,
        minChunkSize: 100,
        timeWindow: 500,
        ticksRate: 2,
        samplesCount: 15
      },
      null,
      (prop, source) => {
        return !utils$2.isUndefined(source[prop]);
      }
    );
    super({
      readableHighWaterMark: options.chunkSize
    });
    const internals = this[kInternals] = {
      timeWindow: options.timeWindow,
      chunkSize: options.chunkSize,
      maxRate: options.maxRate,
      minChunkSize: options.minChunkSize,
      bytesSeen: 0,
      isCaptured: false,
      notifiedBytesLoaded: 0,
      ts: Date.now(),
      bytes: 0,
      onReadCallback: null
    };
    this.on("newListener", (event) => {
      if (event === "progress") {
        if (!internals.isCaptured) {
          internals.isCaptured = true;
        }
      }
    });
  }
  _read(size) {
    const internals = this[kInternals];
    if (internals.onReadCallback) {
      internals.onReadCallback();
    }
    return super._read(size);
  }
  _transform(chunk2, encoding, callback) {
    const internals = this[kInternals];
    const maxRate = internals.maxRate;
    const readableHighWaterMark = this.readableHighWaterMark;
    const timeWindow = internals.timeWindow;
    const divider = 1e3 / timeWindow;
    const bytesThreshold = maxRate / divider;
    const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
    const pushChunk = (_chunk, _callback) => {
      const bytes = Buffer.byteLength(_chunk);
      internals.bytesSeen += bytes;
      internals.bytes += bytes;
      internals.isCaptured && this.emit("progress", internals.bytesSeen);
      if (this.push(_chunk)) {
        process.nextTick(_callback);
      } else {
        internals.onReadCallback = () => {
          internals.onReadCallback = null;
          process.nextTick(_callback);
        };
      }
    };
    const transformChunk = (_chunk, _callback) => {
      const chunkSize = Buffer.byteLength(_chunk);
      let chunkRemainder = null;
      let maxChunkSize = readableHighWaterMark;
      let bytesLeft;
      let passed = 0;
      if (maxRate) {
        const now = Date.now();
        if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
          internals.ts = now;
          bytesLeft = bytesThreshold - internals.bytes;
          internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
          passed = 0;
        }
        bytesLeft = bytesThreshold - internals.bytes;
      }
      if (maxRate) {
        if (bytesLeft <= 0) {
          return setTimeout(() => {
            _callback(null, _chunk);
          }, timeWindow - passed);
        }
        if (bytesLeft < maxChunkSize) {
          maxChunkSize = bytesLeft;
        }
      }
      if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
        chunkRemainder = _chunk.subarray(maxChunkSize);
        _chunk = _chunk.subarray(0, maxChunkSize);
      }
      pushChunk(
        _chunk,
        chunkRemainder ? () => {
          process.nextTick(_callback, null, chunkRemainder);
        } : _callback
      );
    };
    transformChunk(chunk2, function transformNextChunk(err, _chunk) {
      if (err) {
        return callback(err);
      }
      if (_chunk) {
        transformChunk(_chunk, transformNextChunk);
      } else {
        callback(null);
      }
    });
  }
}
const { asyncIterator } = Symbol;
const readBlob = async function* (blob) {
  if (blob.stream) {
    yield* blob.stream();
  } else if (blob.arrayBuffer) {
    yield await blob.arrayBuffer();
  } else if (blob[asyncIterator]) {
    yield* blob[asyncIterator]();
  } else {
    yield blob;
  }
};
const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + "-_";
const textEncoder = typeof TextEncoder === "function" ? new TextEncoder() : new require$$0$1.TextEncoder();
const CRLF = "\r\n";
const CRLF_BYTES = textEncoder.encode(CRLF);
const CRLF_BYTES_COUNT = 2;
class FormDataPart {
  constructor(name2, value) {
    const { escapeName } = this.constructor;
    const isStringValue = utils$2.isString(value);
    let headers = `Content-Disposition: form-data; name="${escapeName(name2)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`;
    if (isStringValue) {
      value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
    } else {
      headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`;
    }
    this.headers = textEncoder.encode(headers + CRLF);
    this.contentLength = isStringValue ? value.byteLength : value.size;
    this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
    this.name = name2;
    this.value = value;
  }
  async *encode() {
    yield this.headers;
    const { value } = this;
    if (utils$2.isTypedArray(value)) {
      yield value;
    } else {
      yield* readBlob(value);
    }
    yield CRLF_BYTES;
  }
  static escapeName(name2) {
    return String(name2).replace(
      /[\r\n"]/g,
      (match) => ({
        "\r": "%0D",
        "\n": "%0A",
        '"': "%22"
      })[match]
    );
  }
}
const formDataToStream = (form, headersHandler, options) => {
  const {
    tag = "form-data-boundary",
    size = 25,
    boundary = tag + "-" + platform.generateString(size, BOUNDARY_ALPHABET)
  } = options || {};
  if (!utils$2.isFormData(form)) {
    throw TypeError("FormData instance required");
  }
  if (boundary.length < 1 || boundary.length > 70) {
    throw Error("boundary must be 10-70 characters long");
  }
  const boundaryBytes = textEncoder.encode("--" + boundary + CRLF);
  const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF);
  let contentLength = footerBytes.byteLength;
  const parts = Array.from(form.entries()).map(([name2, value]) => {
    const part = new FormDataPart(name2, value);
    contentLength += part.size;
    return part;
  });
  contentLength += boundaryBytes.byteLength * parts.length;
  contentLength = utils$2.toFiniteNumber(contentLength);
  const computedHeaders = {
    "Content-Type": `multipart/form-data; boundary=${boundary}`
  };
  if (Number.isFinite(contentLength)) {
    computedHeaders["Content-Length"] = contentLength;
  }
  headersHandler && headersHandler(computedHeaders);
  return Readable.from(
    (async function* () {
      for (const part of parts) {
        yield boundaryBytes;
        yield* part.encode();
      }
      yield footerBytes;
    })()
  );
};
class ZlibHeaderTransformStream extends stream.Transform {
  __transform(chunk2, encoding, callback) {
    this.push(chunk2);
    callback();
  }
  _transform(chunk2, encoding, callback) {
    if (chunk2.length !== 0) {
      this._transform = this.__transform;
      if (chunk2[0] !== 120) {
        const header = Buffer.alloc(2);
        header[0] = 120;
        header[1] = 156;
        this.push(header, encoding);
      }
    }
    this.__transform(chunk2, encoding, callback);
  }
}
const callbackify = (fn, reducer2) => {
  return utils$2.isAsyncFn(fn) ? function(...args) {
    const cb = args.pop();
    fn.apply(this, args).then((value) => {
      try {
        reducer2 ? cb(null, ...reducer2(value)) : cb(null, value);
      } catch (err) {
        cb(err);
      }
    }, cb);
  } : fn;
};
function speedometer(samplesCount, min2) {
  samplesCount = samplesCount || 10;
  const bytes = new Array(samplesCount);
  const timestamps = new Array(samplesCount);
  let head = 0;
  let tail = 0;
  let firstSampleTS;
  min2 = min2 !== void 0 ? min2 : 1e3;
  return function push2(chunkLength) {
    const now = Date.now();
    const startedAt = timestamps[tail];
    if (!firstSampleTS) {
      firstSampleTS = now;
    }
    bytes[head] = chunkLength;
    timestamps[head] = now;
    let i = tail;
    let bytesCount = 0;
    while (i !== head) {
      bytesCount += bytes[i++];
      i = i % samplesCount;
    }
    head = (head + 1) % samplesCount;
    if (head === tail) {
      tail = (tail + 1) % samplesCount;
    }
    if (now - firstSampleTS < min2) {
      return;
    }
    const passed = startedAt && now - startedAt;
    return passed ? Math.round(bytesCount * 1e3 / passed) : void 0;
  };
}
function throttle(fn, freq) {
  let timestamp = 0;
  let threshold = 1e3 / freq;
  let lastArgs;
  let timer;
  const invoke = (args, now = Date.now()) => {
    timestamp = now;
    lastArgs = null;
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    fn(...args);
  };
  const throttled = (...args) => {
    const now = Date.now();
    const passed = now - timestamp;
    if (passed >= threshold) {
      invoke(args, now);
    } else {
      lastArgs = args;
      if (!timer) {
        timer = setTimeout(() => {
          timer = null;
          invoke(lastArgs);
        }, threshold - passed);
      }
    }
  };
  const flush = () => lastArgs && invoke(lastArgs);
  return [throttled, flush];
}
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
  let bytesNotified = 0;
  const _speedometer = speedometer(50, 250);
  return throttle((e) => {
    const loaded = e.loaded;
    const total = e.lengthComputable ? e.total : void 0;
    const progressBytes = loaded - bytesNotified;
    const rate = _speedometer(progressBytes);
    const inRange = loaded <= total;
    bytesNotified = loaded;
    const data = {
      loaded,
      total,
      progress: total ? loaded / total : void 0,
      bytes: progressBytes,
      rate: rate ? rate : void 0,
      estimated: rate && total && inRange ? (total - loaded) / rate : void 0,
      event: e,
      lengthComputable: total != null,
      [isDownloadStream ? "download" : "upload"]: true
    };
    listener(data);
  }, freq);
};
const progressEventDecorator = (total, throttled) => {
  const lengthComputable = total != null;
  return [
    (loaded) => throttled[0]({
      lengthComputable,
      total,
      loaded
    }),
    throttled[1]
  ];
};
const asyncDecorator = (fn) => (...args) => utils$2.asap(() => fn(...args));
function estimateDataURLDecodedBytes(url) {
  if (!url || typeof url !== "string") return 0;
  if (!url.startsWith("data:")) return 0;
  const comma = url.indexOf(",");
  if (comma < 0) return 0;
  const meta = url.slice(5, comma);
  const body2 = url.slice(comma + 1);
  const isBase64 = /;base64/i.test(meta);
  if (isBase64) {
    let effectiveLen = body2.length;
    const len = body2.length;
    for (let i = 0; i < len; i++) {
      if (body2.charCodeAt(i) === 37 && i + 2 < len) {
        const a = body2.charCodeAt(i + 1);
        const b2 = body2.charCodeAt(i + 2);
        const isHex = (a >= 48 && a <= 57 || a >= 65 && a <= 70 || a >= 97 && a <= 102) && (b2 >= 48 && b2 <= 57 || b2 >= 65 && b2 <= 70 || b2 >= 97 && b2 <= 102);
        if (isHex) {
          effectiveLen -= 2;
          i += 2;
        }
      }
    }
    let pad2 = 0;
    let idx = len - 1;
    const tailIsPct3D = (j2) => j2 >= 2 && body2.charCodeAt(j2 - 2) === 37 && // '%'
    body2.charCodeAt(j2 - 1) === 51 && // '3'
    (body2.charCodeAt(j2) === 68 || body2.charCodeAt(j2) === 100);
    if (idx >= 0) {
      if (body2.charCodeAt(idx) === 61) {
        pad2++;
        idx--;
      } else if (tailIsPct3D(idx)) {
        pad2++;
        idx -= 3;
      }
    }
    if (pad2 === 1 && idx >= 0) {
      if (body2.charCodeAt(idx) === 61) {
        pad2++;
      } else if (tailIsPct3D(idx)) {
        pad2++;
      }
    }
    const groups = Math.floor(effectiveLen / 4);
    const bytes = groups * 3 - (pad2 || 0);
    return bytes > 0 ? bytes : 0;
  }
  return Buffer.byteLength(body2, "utf8");
}
const zlibOptions = {
  flush: zlib.constants.Z_SYNC_FLUSH,
  finishFlush: zlib.constants.Z_SYNC_FLUSH
};
const brotliOptions = {
  flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
};
const isBrotliSupported = utils$2.isFunction(zlib.createBrotliDecompress);
const { http: httpFollow, https: httpsFollow } = followRedirects;
const isHttps = /https:?/;
const supportedProtocols = platform.protocols.map((protocol) => {
  return protocol + ":";
});
const flushOnFinish = (stream2, [throttled, flush]) => {
  stream2.on("end", flush).on("error", flush);
  return throttled;
};
class Http2Sessions {
  constructor() {
    this.sessions = /* @__PURE__ */ Object.create(null);
  }
  getSession(authority, options) {
    options = Object.assign(
      {
        sessionTimeout: 1e3
      },
      options
    );
    let authoritySessions = this.sessions[authority];
    if (authoritySessions) {
      let len = authoritySessions.length;
      for (let i = 0; i < len; i++) {
        const [sessionHandle, sessionOptions] = authoritySessions[i];
        if (!sessionHandle.destroyed && !sessionHandle.closed && require$$0$1.isDeepStrictEqual(sessionOptions, options)) {
          return sessionHandle;
        }
      }
    }
    const session = http2.connect(authority, options);
    let removed;
    const removeSession = () => {
      if (removed) {
        return;
      }
      removed = true;
      let entries = authoritySessions, len = entries.length, i = len;
      while (i--) {
        if (entries[i][0] === session) {
          if (len === 1) {
            delete this.sessions[authority];
          } else {
            entries.splice(i, 1);
          }
          if (!session.closed) {
            session.close();
          }
          return;
        }
      }
    };
    const originalRequestFn = session.request;
    const { sessionTimeout } = options;
    if (sessionTimeout != null) {
      let timer;
      let streamsCount = 0;
      session.request = function() {
        const stream2 = originalRequestFn.apply(this, arguments);
        streamsCount++;
        if (timer) {
          clearTimeout(timer);
          timer = null;
        }
        stream2.once("close", () => {
          if (!--streamsCount) {
            timer = setTimeout(() => {
              timer = null;
              removeSession();
            }, sessionTimeout);
          }
        });
        return stream2;
      };
    }
    session.once("close", removeSession);
    let entry = [session, options];
    authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
    return session;
  }
}
const http2Sessions = new Http2Sessions();
function dispatchBeforeRedirect(options, responseDetails) {
  if (options.beforeRedirects.proxy) {
    options.beforeRedirects.proxy(options);
  }
  if (options.beforeRedirects.config) {
    options.beforeRedirects.config(options, responseDetails);
  }
}
function setProxy(options, configProxy, location) {
  let proxy = configProxy;
  if (!proxy && proxy !== false) {
    const proxyUrl = getProxyForUrl(location);
    if (proxyUrl) {
      proxy = new URL(proxyUrl);
    }
  }
  if (proxy) {
    if (proxy.username) {
      proxy.auth = (proxy.username || "") + ":" + (proxy.password || "");
    }
    if (proxy.auth) {
      const validProxyAuth = Boolean(proxy.auth.username || proxy.auth.password);
      if (validProxyAuth) {
        proxy.auth = (proxy.auth.username || "") + ":" + (proxy.auth.password || "");
      } else if (typeof proxy.auth === "object") {
        throw new AxiosError$1("Invalid proxy authorization", AxiosError$1.ERR_BAD_OPTION, { proxy });
      }
      const base64 = Buffer.from(proxy.auth, "utf8").toString("base64");
      options.headers["Proxy-Authorization"] = "Basic " + base64;
    }
    options.headers.host = options.hostname + (options.port ? ":" + options.port : "");
    const proxyHost = proxy.hostname || proxy.host;
    options.hostname = proxyHost;
    options.host = proxyHost;
    options.port = proxy.port;
    options.path = location;
    if (proxy.protocol) {
      options.protocol = proxy.protocol.includes(":") ? proxy.protocol : `${proxy.protocol}:`;
    }
  }
  options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
    setProxy(redirectOptions, configProxy, redirectOptions.href);
  };
}
const isHttpAdapterSupported = typeof process !== "undefined" && utils$2.kindOf(process) === "process";
const wrapAsync = (asyncExecutor) => {
  return new Promise((resolve, reject) => {
    let onDone;
    let isDone;
    const done = (value, isRejected) => {
      if (isDone) return;
      isDone = true;
      onDone && onDone(value, isRejected);
    };
    const _resolve = (value) => {
      done(value);
      resolve(value);
    };
    const _reject = (reason) => {
      done(reason, true);
      reject(reason);
    };
    asyncExecutor(_resolve, _reject, (onDoneHandler) => onDone = onDoneHandler).catch(_reject);
  });
};
const resolveFamily = ({ address, family }) => {
  if (!utils$2.isString(address)) {
    throw TypeError("address must be a string");
  }
  return {
    address,
    family: family || (address.indexOf(".") < 0 ? 6 : 4)
  };
};
const buildAddressEntry = (address, family) => resolveFamily(utils$2.isObject(address) ? address : { address, family });
const http2Transport = {
  request(options, cb) {
    const authority = options.protocol + "//" + options.hostname + ":" + (options.port || (options.protocol === "https:" ? 443 : 80));
    const { http2Options, headers } = options;
    const session = http2Sessions.getSession(authority, http2Options);
    const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants;
    const http2Headers = {
      [HTTP2_HEADER_SCHEME]: options.protocol.replace(":", ""),
      [HTTP2_HEADER_METHOD]: options.method,
      [HTTP2_HEADER_PATH]: options.path
    };
    utils$2.forEach(headers, (header, name2) => {
      name2.charAt(0) !== ":" && (http2Headers[name2] = header);
    });
    const req = session.request(http2Headers);
    req.once("response", (responseHeaders) => {
      const response = req;
      responseHeaders = Object.assign({}, responseHeaders);
      const status2 = responseHeaders[HTTP2_HEADER_STATUS];
      delete responseHeaders[HTTP2_HEADER_STATUS];
      response.headers = responseHeaders;
      response.statusCode = +status2;
      cb(response);
    });
    return req;
  }
};
const httpAdapter = isHttpAdapterSupported && function httpAdapter2(config) {
  return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
    let { data, lookup, family, httpVersion = 1, http2Options } = config;
    const { responseType, responseEncoding } = config;
    const method = config.method.toUpperCase();
    let isDone;
    let rejected = false;
    let req;
    httpVersion = +httpVersion;
    if (Number.isNaN(httpVersion)) {
      throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
    }
    if (httpVersion !== 1 && httpVersion !== 2) {
      throw TypeError(`Unsupported protocol version '${httpVersion}'`);
    }
    const isHttp2 = httpVersion === 2;
    if (lookup) {
      const _lookup = callbackify(lookup, (value) => utils$2.isArray(value) ? value : [value]);
      lookup = (hostname, opt, cb) => {
        _lookup(hostname, opt, (err, arg0, arg1) => {
          if (err) {
            return cb(err);
          }
          const addresses = utils$2.isArray(arg0) ? arg0.map((addr) => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
          opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
        });
      };
    }
    const abortEmitter = new EventEmitter();
    function abort(reason) {
      try {
        abortEmitter.emit(
          "abort",
          !reason || reason.type ? new CanceledError$1(null, config, req) : reason
        );
      } catch (err) {
        console.warn("emit error", err);
      }
    }
    abortEmitter.once("abort", reject);
    const onFinished = () => {
      if (config.cancelToken) {
        config.cancelToken.unsubscribe(abort);
      }
      if (config.signal) {
        config.signal.removeEventListener("abort", abort);
      }
      abortEmitter.removeAllListeners();
    };
    if (config.cancelToken || config.signal) {
      config.cancelToken && config.cancelToken.subscribe(abort);
      if (config.signal) {
        config.signal.aborted ? abort() : config.signal.addEventListener("abort", abort);
      }
    }
    onDone((response, isRejected) => {
      isDone = true;
      if (isRejected) {
        rejected = true;
        onFinished();
        return;
      }
      const { data: data2 } = response;
      if (data2 instanceof stream.Readable || data2 instanceof stream.Duplex) {
        const offListeners = stream.finished(data2, () => {
          offListeners();
          onFinished();
        });
      } else {
        onFinished();
      }
    });
    const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
    const parsed = new URL(fullPath, platform.hasBrowserEnv ? platform.origin : void 0);
    const protocol = parsed.protocol || supportedProtocols[0];
    if (protocol === "data:") {
      if (config.maxContentLength > -1) {
        const dataUrl = String(config.url || fullPath || "");
        const estimated = estimateDataURLDecodedBytes(dataUrl);
        if (estimated > config.maxContentLength) {
          return reject(
            new AxiosError$1(
              "maxContentLength size of " + config.maxContentLength + " exceeded",
              AxiosError$1.ERR_BAD_RESPONSE,
              config
            )
          );
        }
      }
      let convertedData;
      if (method !== "GET") {
        return settle(resolve, reject, {
          status: 405,
          statusText: "method not allowed",
          headers: {},
          config
        });
      }
      try {
        convertedData = fromDataURI(config.url, responseType === "blob", {
          Blob: config.env && config.env.Blob
        });
      } catch (err) {
        throw AxiosError$1.from(err, AxiosError$1.ERR_BAD_REQUEST, config);
      }
      if (responseType === "text") {
        convertedData = convertedData.toString(responseEncoding);
        if (!responseEncoding || responseEncoding === "utf8") {
          convertedData = utils$2.stripBOM(convertedData);
        }
      } else if (responseType === "stream") {
        convertedData = stream.Readable.from(convertedData);
      }
      return settle(resolve, reject, {
        data: convertedData,
        status: 200,
        statusText: "OK",
        headers: new AxiosHeaders$1(),
        config
      });
    }
    if (supportedProtocols.indexOf(protocol) === -1) {
      return reject(
        new AxiosError$1("Unsupported protocol " + protocol, AxiosError$1.ERR_BAD_REQUEST, config)
      );
    }
    const headers = AxiosHeaders$1.from(config.headers).normalize();
    headers.set("User-Agent", "axios/" + VERSION$1, false);
    const { onUploadProgress, onDownloadProgress } = config;
    const maxRate = config.maxRate;
    let maxUploadRate = void 0;
    let maxDownloadRate = void 0;
    if (utils$2.isSpecCompliantForm(data)) {
      const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
      data = formDataToStream(
        data,
        (formHeaders) => {
          headers.set(formHeaders);
        },
        {
          tag: `axios-${VERSION$1}-boundary`,
          boundary: userBoundary && userBoundary[1] || void 0
        }
      );
    } else if (utils$2.isFormData(data) && utils$2.isFunction(data.getHeaders)) {
      headers.set(data.getHeaders());
      if (!headers.hasContentLength()) {
        try {
          const knownLength = await require$$0$1.promisify(data.getLength).call(data);
          Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
        } catch (e) {
        }
      }
    } else if (utils$2.isBlob(data) || utils$2.isFile(data)) {
      data.size && headers.setContentType(data.type || "application/octet-stream");
      headers.setContentLength(data.size || 0);
      data = stream.Readable.from(readBlob(data));
    } else if (data && !utils$2.isStream(data)) {
      if (Buffer.isBuffer(data)) ;
      else if (utils$2.isArrayBuffer(data)) {
        data = Buffer.from(new Uint8Array(data));
      } else if (utils$2.isString(data)) {
        data = Buffer.from(data, "utf-8");
      } else {
        return reject(
          new AxiosError$1(
            "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",
            AxiosError$1.ERR_BAD_REQUEST,
            config
          )
        );
      }
      headers.setContentLength(data.length, false);
      if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
        return reject(
          new AxiosError$1(
            "Request body larger than maxBodyLength limit",
            AxiosError$1.ERR_BAD_REQUEST,
            config
          )
        );
      }
    }
    const contentLength = utils$2.toFiniteNumber(headers.getContentLength());
    if (utils$2.isArray(maxRate)) {
      maxUploadRate = maxRate[0];
      maxDownloadRate = maxRate[1];
    } else {
      maxUploadRate = maxDownloadRate = maxRate;
    }
    if (data && (onUploadProgress || maxUploadRate)) {
      if (!utils$2.isStream(data)) {
        data = stream.Readable.from(data, { objectMode: false });
      }
      data = stream.pipeline(
        [
          data,
          new AxiosTransformStream({
            maxRate: utils$2.toFiniteNumber(maxUploadRate)
          })
        ],
        utils$2.noop
      );
      onUploadProgress && data.on(
        "progress",
        flushOnFinish(
          data,
          progressEventDecorator(
            contentLength,
            progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
          )
        )
      );
    }
    let auth = void 0;
    if (config.auth) {
      const username = config.auth.username || "";
      const password = config.auth.password || "";
      auth = username + ":" + password;
    }
    if (!auth && parsed.username) {
      const urlUsername = parsed.username;
      const urlPassword = parsed.password;
      auth = urlUsername + ":" + urlPassword;
    }
    auth && headers.delete("authorization");
    let path;
    try {
      path = buildURL(
        parsed.pathname + parsed.search,
        config.params,
        config.paramsSerializer
      ).replace(/^\?/, "");
    } catch (err) {
      const customErr = new Error(err.message);
      customErr.config = config;
      customErr.url = config.url;
      customErr.exists = true;
      return reject(customErr);
    }
    headers.set(
      "Accept-Encoding",
      "gzip, compress, deflate" + (isBrotliSupported ? ", br" : ""),
      false
    );
    const options = {
      path,
      method,
      headers: headers.toJSON(),
      agents: { http: config.httpAgent, https: config.httpsAgent },
      auth,
      protocol,
      family,
      beforeRedirect: dispatchBeforeRedirect,
      beforeRedirects: {},
      http2Options
    };
    !utils$2.isUndefined(lookup) && (options.lookup = lookup);
    if (config.socketPath) {
      options.socketPath = config.socketPath;
    } else {
      options.hostname = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;
      options.port = parsed.port;
      setProxy(
        options,
        config.proxy,
        protocol + "//" + parsed.hostname + (parsed.port ? ":" + parsed.port : "") + options.path
      );
    }
    let transport;
    const isHttpsRequest = isHttps.test(options.protocol);
    options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
    if (isHttp2) {
      transport = http2Transport;
    } else {
      if (config.transport) {
        transport = config.transport;
      } else if (config.maxRedirects === 0) {
        transport = isHttpsRequest ? require$$4 : require$$3;
      } else {
        if (config.maxRedirects) {
          options.maxRedirects = config.maxRedirects;
        }
        if (config.beforeRedirect) {
          options.beforeRedirects.config = config.beforeRedirect;
        }
        transport = isHttpsRequest ? httpsFollow : httpFollow;
      }
    }
    if (config.maxBodyLength > -1) {
      options.maxBodyLength = config.maxBodyLength;
    } else {
      options.maxBodyLength = Infinity;
    }
    if (config.insecureHTTPParser) {
      options.insecureHTTPParser = config.insecureHTTPParser;
    }
    req = transport.request(options, function handleResponse(res) {
      if (req.destroyed) return;
      const streams = [res];
      const responseLength = utils$2.toFiniteNumber(res.headers["content-length"]);
      if (onDownloadProgress || maxDownloadRate) {
        const transformStream = new AxiosTransformStream({
          maxRate: utils$2.toFiniteNumber(maxDownloadRate)
        });
        onDownloadProgress && transformStream.on(
          "progress",
          flushOnFinish(
            transformStream,
            progressEventDecorator(
              responseLength,
              progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
            )
          )
        );
        streams.push(transformStream);
      }
      let responseStream = res;
      const lastRequest = res.req || req;
      if (config.decompress !== false && res.headers["content-encoding"]) {
        if (method === "HEAD" || res.statusCode === 204) {
          delete res.headers["content-encoding"];
        }
        switch ((res.headers["content-encoding"] || "").toLowerCase()) {
          /*eslint default-case:0*/
          case "gzip":
          case "x-gzip":
          case "compress":
          case "x-compress":
            streams.push(zlib.createUnzip(zlibOptions));
            delete res.headers["content-encoding"];
            break;
          case "deflate":
            streams.push(new ZlibHeaderTransformStream());
            streams.push(zlib.createUnzip(zlibOptions));
            delete res.headers["content-encoding"];
            break;
          case "br":
            if (isBrotliSupported) {
              streams.push(zlib.createBrotliDecompress(brotliOptions));
              delete res.headers["content-encoding"];
            }
        }
      }
      responseStream = streams.length > 1 ? stream.pipeline(streams, utils$2.noop) : streams[0];
      const response = {
        status: res.statusCode,
        statusText: res.statusMessage,
        headers: new AxiosHeaders$1(res.headers),
        config,
        request: lastRequest
      };
      if (responseType === "stream") {
        response.data = responseStream;
        settle(resolve, reject, response);
      } else {
        const responseBuffer = [];
        let totalResponseBytes = 0;
        responseStream.on("data", function handleStreamData(chunk2) {
          responseBuffer.push(chunk2);
          totalResponseBytes += chunk2.length;
          if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
            rejected = true;
            responseStream.destroy();
            abort(
              new AxiosError$1(
                "maxContentLength size of " + config.maxContentLength + " exceeded",
                AxiosError$1.ERR_BAD_RESPONSE,
                config,
                lastRequest
              )
            );
          }
        });
        responseStream.on("aborted", function handlerStreamAborted() {
          if (rejected) {
            return;
          }
          const err = new AxiosError$1(
            "stream has been aborted",
            AxiosError$1.ERR_BAD_RESPONSE,
            config,
            lastRequest
          );
          responseStream.destroy(err);
          reject(err);
        });
        responseStream.on("error", function handleStreamError(err) {
          if (req.destroyed) return;
          reject(AxiosError$1.from(err, null, config, lastRequest));
        });
        responseStream.on("end", function handleStreamEnd() {
          try {
            let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
            if (responseType !== "arraybuffer") {
              responseData = responseData.toString(responseEncoding);
              if (!responseEncoding || responseEncoding === "utf8") {
                responseData = utils$2.stripBOM(responseData);
              }
            }
            response.data = responseData;
          } catch (err) {
            return reject(AxiosError$1.from(err, null, config, response.request, response));
          }
          settle(resolve, reject, response);
        });
      }
      abortEmitter.once("abort", (err) => {
        if (!responseStream.destroyed) {
          responseStream.emit("error", err);
          responseStream.destroy();
        }
      });
    });
    abortEmitter.once("abort", (err) => {
      if (req.close) {
        req.close();
      } else {
        req.destroy(err);
      }
    });
    req.on("error", function handleRequestError(err) {
      reject(AxiosError$1.from(err, null, config, req));
    });
    req.on("socket", function handleRequestSocket(socket) {
      socket.setKeepAlive(true, 1e3 * 60);
    });
    if (config.timeout) {
      const timeout = parseInt(config.timeout, 10);
      if (Number.isNaN(timeout)) {
        abort(
          new AxiosError$1(
            "error trying to parse `config.timeout` to int",
            AxiosError$1.ERR_BAD_OPTION_VALUE,
            config,
            req
          )
        );
        return;
      }
      req.setTimeout(timeout, function handleRequestTimeout() {
        if (isDone) return;
        let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded";
        const transitional2 = config.transitional || transitionalDefaults;
        if (config.timeoutErrorMessage) {
          timeoutErrorMessage = config.timeoutErrorMessage;
        }
        abort(
          new AxiosError$1(
            timeoutErrorMessage,
            transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
            config,
            req
          )
        );
      });
    } else {
      req.setTimeout(0);
    }
    if (utils$2.isStream(data)) {
      let ended = false;
      let errored = false;
      data.on("end", () => {
        ended = true;
      });
      data.once("error", (err) => {
        errored = true;
        req.destroy(err);
      });
      data.on("close", () => {
        if (!ended && !errored) {
          abort(new CanceledError$1("Request stream has been aborted", config, req));
        }
      });
      data.pipe(req);
    } else {
      data && req.write(data);
      req.end();
    }
  });
};
const isURLSameOrigin = platform.hasStandardBrowserEnv ? /* @__PURE__ */ ((origin2, isMSIE) => (url) => {
  url = new URL(url, platform.origin);
  return origin2.protocol === url.protocol && origin2.host === url.host && (isMSIE || origin2.port === url.port);
})(
  new URL(platform.origin),
  platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
) : () => true;
const cookies = platform.hasStandardBrowserEnv ? (
  // Standard browser envs support document.cookie
  {
    write(name2, value, expires, path, domain, secure, sameSite) {
      if (typeof document === "undefined") return;
      const cookie = [`${name2}=${encodeURIComponent(value)}`];
      if (utils$2.isNumber(expires)) {
        cookie.push(`expires=${new Date(expires).toUTCString()}`);
      }
      if (utils$2.isString(path)) {
        cookie.push(`path=${path}`);
      }
      if (utils$2.isString(domain)) {
        cookie.push(`domain=${domain}`);
      }
      if (secure === true) {
        cookie.push("secure");
      }
      if (utils$2.isString(sameSite)) {
        cookie.push(`SameSite=${sameSite}`);
      }
      document.cookie = cookie.join("; ");
    },
    read(name2) {
      if (typeof document === "undefined") return null;
      const match = document.cookie.match(new RegExp("(?:^|; )" + name2 + "=([^;]*)"));
      return match ? decodeURIComponent(match[1]) : null;
    },
    remove(name2) {
      this.write(name2, "", Date.now() - 864e5, "/");
    }
  }
) : (
  // Non-standard browser env (web workers, react-native) lack needed support.
  {
    write() {
    },
    read() {
      return null;
    },
    remove() {
    }
  }
);
const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? { ...thing } : thing;
function mergeConfig$1(config1, config2) {
  config2 = config2 || {};
  const config = {};
  function getMergedValue(target, source, prop, caseless) {
    if (utils$2.isPlainObject(target) && utils$2.isPlainObject(source)) {
      return utils$2.merge.call({ caseless }, target, source);
    } else if (utils$2.isPlainObject(source)) {
      return utils$2.merge({}, source);
    } else if (utils$2.isArray(source)) {
      return source.slice();
    }
    return source;
  }
  function mergeDeepProperties(a, b2, prop, caseless) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(a, b2, prop, caseless);
    } else if (!utils$2.isUndefined(a)) {
      return getMergedValue(void 0, a, prop, caseless);
    }
  }
  function valueFromConfig2(a, b2) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    }
  }
  function defaultToConfig2(a, b2) {
    if (!utils$2.isUndefined(b2)) {
      return getMergedValue(void 0, b2);
    } else if (!utils$2.isUndefined(a)) {
      return getMergedValue(void 0, a);
    }
  }
  function mergeDirectKeys(a, b2, prop) {
    if (prop in config2) {
      return getMergedValue(a, b2);
    } else if (prop in config1) {
      return getMergedValue(void 0, a);
    }
  }
  const mergeMap = {
    url: valueFromConfig2,
    method: valueFromConfig2,
    data: valueFromConfig2,
    baseURL: defaultToConfig2,
    transformRequest: defaultToConfig2,
    transformResponse: defaultToConfig2,
    paramsSerializer: defaultToConfig2,
    timeout: defaultToConfig2,
    timeoutMessage: defaultToConfig2,
    withCredentials: defaultToConfig2,
    withXSRFToken: defaultToConfig2,
    adapter: defaultToConfig2,
    responseType: defaultToConfig2,
    xsrfCookieName: defaultToConfig2,
    xsrfHeaderName: defaultToConfig2,
    onUploadProgress: defaultToConfig2,
    onDownloadProgress: defaultToConfig2,
    decompress: defaultToConfig2,
    maxContentLength: defaultToConfig2,
    maxBodyLength: defaultToConfig2,
    beforeRedirect: defaultToConfig2,
    transport: defaultToConfig2,
    httpAgent: defaultToConfig2,
    httpsAgent: defaultToConfig2,
    cancelToken: defaultToConfig2,
    socketPath: defaultToConfig2,
    responseEncoding: defaultToConfig2,
    validateStatus: mergeDirectKeys,
    headers: (a, b2, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b2), prop, true)
  };
  utils$2.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
    if (prop === "__proto__" || prop === "constructor" || prop === "prototype") return;
    const merge2 = utils$2.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
    const configValue = merge2(config1[prop], config2[prop], prop);
    utils$2.isUndefined(configValue) && merge2 !== mergeDirectKeys || (config[prop] = configValue);
  });
  return config;
}
const resolveConfig = (config) => {
  const newConfig = mergeConfig$1({}, config);
  let { data, withXSRFToken, xsrfHeaderName, xsrfCookieName, headers, auth } = newConfig;
  newConfig.headers = headers = AxiosHeaders$1.from(headers);
  newConfig.url = buildURL(
    buildFullPath(newConfig.baseURL, newConfig.url, newConfig.allowAbsoluteUrls),
    config.params,
    config.paramsSerializer
  );
  if (auth) {
    headers.set(
      "Authorization",
      "Basic " + btoa(
        (auth.username || "") + ":" + (auth.password ? unescape(encodeURIComponent(auth.password)) : "")
      )
    );
  }
  if (utils$2.isFormData(data)) {
    if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
      headers.setContentType(void 0);
    } else if (utils$2.isFunction(data.getHeaders)) {
      const formHeaders = data.getHeaders();
      const allowedHeaders = ["content-type", "content-length"];
      Object.entries(formHeaders).forEach(([key, val]) => {
        if (allowedHeaders.includes(key.toLowerCase())) {
          headers.set(key, val);
        }
      });
    }
  }
  if (platform.hasStandardBrowserEnv) {
    withXSRFToken && utils$2.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(newConfig));
    if (withXSRFToken || withXSRFToken !== false && isURLSameOrigin(newConfig.url)) {
      const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
      if (xsrfValue) {
        headers.set(xsrfHeaderName, xsrfValue);
      }
    }
  }
  return newConfig;
};
const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
const xhrAdapter = isXHRAdapterSupported && function(config) {
  return new Promise(function dispatchXhrRequest(resolve, reject) {
    const _config = resolveConfig(config);
    let requestData = _config.data;
    const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
    let { responseType, onUploadProgress, onDownloadProgress } = _config;
    let onCanceled;
    let uploadThrottled, downloadThrottled;
    let flushUpload, flushDownload;
    function done() {
      flushUpload && flushUpload();
      flushDownload && flushDownload();
      _config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
      _config.signal && _config.signal.removeEventListener("abort", onCanceled);
    }
    let request = new XMLHttpRequest();
    request.open(_config.method.toUpperCase(), _config.url, true);
    request.timeout = _config.timeout;
    function onloadend() {
      if (!request) {
        return;
      }
      const responseHeaders = AxiosHeaders$1.from(
        "getAllResponseHeaders" in request && request.getAllResponseHeaders()
      );
      const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response;
      const response = {
        data: responseData,
        status: request.status,
        statusText: request.statusText,
        headers: responseHeaders,
        config,
        request
      };
      settle(
        function _resolve(value) {
          resolve(value);
          done();
        },
        function _reject(err) {
          reject(err);
          done();
        },
        response
      );
      request = null;
    }
    if ("onloadend" in request) {
      request.onloadend = onloadend;
    } else {
      request.onreadystatechange = function handleLoad() {
        if (!request || request.readyState !== 4) {
          return;
        }
        if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) {
          return;
        }
        setTimeout(onloadend);
      };
    }
    request.onabort = function handleAbort() {
      if (!request) {
        return;
      }
      reject(new AxiosError$1("Request aborted", AxiosError$1.ECONNABORTED, config, request));
      request = null;
    };
    request.onerror = function handleError(event) {
      const msg = event && event.message ? event.message : "Network Error";
      const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request);
      err.event = event || null;
      reject(err);
      request = null;
    };
    request.ontimeout = function handleTimeout() {
      let timeoutErrorMessage = _config.timeout ? "timeout of " + _config.timeout + "ms exceeded" : "timeout exceeded";
      const transitional2 = _config.transitional || transitionalDefaults;
      if (_config.timeoutErrorMessage) {
        timeoutErrorMessage = _config.timeoutErrorMessage;
      }
      reject(
        new AxiosError$1(
          timeoutErrorMessage,
          transitional2.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
          config,
          request
        )
      );
      request = null;
    };
    requestData === void 0 && requestHeaders.setContentType(null);
    if ("setRequestHeader" in request) {
      utils$2.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
        request.setRequestHeader(key, val);
      });
    }
    if (!utils$2.isUndefined(_config.withCredentials)) {
      request.withCredentials = !!_config.withCredentials;
    }
    if (responseType && responseType !== "json") {
      request.responseType = _config.responseType;
    }
    if (onDownloadProgress) {
      [downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
      request.addEventListener("progress", downloadThrottled);
    }
    if (onUploadProgress && request.upload) {
      [uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
      request.upload.addEventListener("progress", uploadThrottled);
      request.upload.addEventListener("loadend", flushUpload);
    }
    if (_config.cancelToken || _config.signal) {
      onCanceled = (cancel2) => {
        if (!request) {
          return;
        }
        reject(!cancel2 || cancel2.type ? new CanceledError$1(null, config, request) : cancel2);
        request.abort();
        request = null;
      };
      _config.cancelToken && _config.cancelToken.subscribe(onCanceled);
      if (_config.signal) {
        _config.signal.aborted ? onCanceled() : _config.signal.addEventListener("abort", onCanceled);
      }
    }
    const protocol = parseProtocol(_config.url);
    if (protocol && platform.protocols.indexOf(protocol) === -1) {
      reject(
        new AxiosError$1(
          "Unsupported protocol " + protocol + ":",
          AxiosError$1.ERR_BAD_REQUEST,
          config
        )
      );
      return;
    }
    request.send(requestData || null);
  });
};
const composeSignals = (signals, timeout) => {
  const { length } = signals = signals ? signals.filter(Boolean) : [];
  if (timeout || length) {
    let controller = new AbortController();
    let aborted;
    const onabort = function(reason) {
      if (!aborted) {
        aborted = true;
        unsubscribe();
        const err = reason instanceof Error ? reason : this.reason;
        controller.abort(
          err instanceof AxiosError$1 ? err : new CanceledError$1(err instanceof Error ? err.message : err)
        );
      }
    };
    let timer = timeout && setTimeout(() => {
      timer = null;
      onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT));
    }, timeout);
    const unsubscribe = () => {
      if (signals) {
        timer && clearTimeout(timer);
        timer = null;
        signals.forEach((signal2) => {
          signal2.unsubscribe ? signal2.unsubscribe(onabort) : signal2.removeEventListener("abort", onabort);
        });
        signals = null;
      }
    };
    signals.forEach((signal2) => signal2.addEventListener("abort", onabort));
    const { signal } = controller;
    signal.unsubscribe = () => utils$2.asap(unsubscribe);
    return signal;
  }
};
const streamChunk = function* (chunk2, chunkSize) {
  let len = chunk2.byteLength;
  if (len < chunkSize) {
    yield chunk2;
    return;
  }
  let pos = 0;
  let end;
  while (pos < len) {
    end = pos + chunkSize;
    yield chunk2.slice(pos, end);
    pos = end;
  }
};
const readBytes = async function* (iterable, chunkSize) {
  for await (const chunk2 of readStream(iterable)) {
    yield* streamChunk(chunk2, chunkSize);
  }
};
const readStream = async function* (stream2) {
  if (stream2[Symbol.asyncIterator]) {
    yield* stream2;
    return;
  }
  const reader = stream2.getReader();
  try {
    for (; ; ) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }
      yield value;
    }
  } finally {
    await reader.cancel();
  }
};
const trackStream = (stream2, chunkSize, onProgress, onFinish) => {
  const iterator2 = readBytes(stream2, chunkSize);
  let bytes = 0;
  let done;
  let _onFinish = (e) => {
    if (!done) {
      done = true;
      onFinish && onFinish(e);
    }
  };
  return new ReadableStream(
    {
      async pull(controller) {
        try {
          const { done: done2, value } = await iterator2.next();
          if (done2) {
            _onFinish();
            controller.close();
            return;
          }
          let len = value.byteLength;
          if (onProgress) {
            let loadedBytes = bytes += len;
            onProgress(loadedBytes);
          }
          controller.enqueue(new Uint8Array(value));
        } catch (err) {
          _onFinish(err);
          throw err;
        }
      },
      cancel(reason) {
        _onFinish(reason);
        return iterator2.return();
      }
    },
    {
      highWaterMark: 2
    }
  );
};
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const { isFunction } = utils$2;
const globalFetchAPI = (({ Request, Response }) => ({
  Request,
  Response
}))(utils$2.global);
const { ReadableStream: ReadableStream$1, TextEncoder: TextEncoder$1 } = utils$2.global;
const test = (fn, ...args) => {
  try {
    return !!fn(...args);
  } catch (e) {
    return false;
  }
};
const factory = (env2) => {
  env2 = utils$2.merge.call(
    {
      skipUndefined: true
    },
    globalFetchAPI,
    env2
  );
  const { fetch: envFetch, Request, Response } = env2;
  const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === "function";
  const isRequestSupported = isFunction(Request);
  const isResponseSupported = isFunction(Response);
  if (!isFetchSupported) {
    return false;
  }
  const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream$1);
  const encodeText = isFetchSupported && (typeof TextEncoder$1 === "function" ? /* @__PURE__ */ ((encoder) => (str) => encoder.encode(str))(new TextEncoder$1()) : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
  const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
    let duplexAccessed = false;
    const body2 = new ReadableStream$1();
    const hasContentType = new Request(platform.origin, {
      body: body2,
      method: "POST",
      get duplex() {
        duplexAccessed = true;
        return "half";
      }
    }).headers.has("Content-Type");
    body2.cancel();
    return duplexAccessed && !hasContentType;
  });
  const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$2.isReadableStream(new Response("").body));
  const resolvers = {
    stream: supportsResponseStream && ((res) => res.body)
  };
  isFetchSupported && (() => {
    ["text", "arrayBuffer", "blob", "formData", "stream"].forEach((type2) => {
      !resolvers[type2] && (resolvers[type2] = (res, config) => {
        let method = res && res[type2];
        if (method) {
          return method.call(res);
        }
        throw new AxiosError$1(
          `Response type '${type2}' is not supported`,
          AxiosError$1.ERR_NOT_SUPPORT,
          config
        );
      });
    });
  })();
  const getBodyLength = async (body2) => {
    if (body2 == null) {
      return 0;
    }
    if (utils$2.isBlob(body2)) {
      return body2.size;
    }
    if (utils$2.isSpecCompliantForm(body2)) {
      const _request = new Request(platform.origin, {
        method: "POST",
        body: body2
      });
      return (await _request.arrayBuffer()).byteLength;
    }
    if (utils$2.isArrayBufferView(body2) || utils$2.isArrayBuffer(body2)) {
      return body2.byteLength;
    }
    if (utils$2.isURLSearchParams(body2)) {
      body2 = body2 + "";
    }
    if (utils$2.isString(body2)) {
      return (await encodeText(body2)).byteLength;
    }
  };
  const resolveBodyLength = async (headers, body2) => {
    const length = utils$2.toFiniteNumber(headers.getContentLength());
    return length == null ? getBodyLength(body2) : length;
  };
  return async (config) => {
    let {
      url,
      method,
      data,
      signal,
      cancelToken,
      timeout,
      onDownloadProgress,
      onUploadProgress,
      responseType,
      headers,
      withCredentials = "same-origin",
      fetchOptions
    } = resolveConfig(config);
    let _fetch = envFetch || fetch;
    responseType = responseType ? (responseType + "").toLowerCase() : "text";
    let composedSignal = composeSignals(
      [signal, cancelToken && cancelToken.toAbortSignal()],
      timeout
    );
    let request = null;
    const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
      composedSignal.unsubscribe();
    });
    let requestContentLength;
    try {
      if (onUploadProgress && supportsRequestStream && method !== "get" && method !== "head" && (requestContentLength = await resolveBodyLength(headers, data)) !== 0) {
        let _request = new Request(url, {
          method: "POST",
          body: data,
          duplex: "half"
        });
        let contentTypeHeader;
        if (utils$2.isFormData(data) && (contentTypeHeader = _request.headers.get("content-type"))) {
          headers.setContentType(contentTypeHeader);
        }
        if (_request.body) {
          const [onProgress, flush] = progressEventDecorator(
            requestContentLength,
            progressEventReducer(asyncDecorator(onUploadProgress))
          );
          data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
        }
      }
      if (!utils$2.isString(withCredentials)) {
        withCredentials = withCredentials ? "include" : "omit";
      }
      const isCredentialsSupported = isRequestSupported && "credentials" in Request.prototype;
      const resolvedOptions = {
        ...fetchOptions,
        signal: composedSignal,
        method: method.toUpperCase(),
        headers: headers.normalize().toJSON(),
        body: data,
        duplex: "half",
        credentials: isCredentialsSupported ? withCredentials : void 0
      };
      request = isRequestSupported && new Request(url, resolvedOptions);
      let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
      const isStreamResponse = supportsResponseStream && (responseType === "stream" || responseType === "response");
      if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
        const options = {};
        ["status", "statusText", "headers"].forEach((prop) => {
          options[prop] = response[prop];
        });
        const responseContentLength = utils$2.toFiniteNumber(response.headers.get("content-length"));
        const [onProgress, flush] = onDownloadProgress && progressEventDecorator(
          responseContentLength,
          progressEventReducer(asyncDecorator(onDownloadProgress), true)
        ) || [];
        response = new Response(
          trackStream(response.body, DEFAULT_CHUNK_SIZE, onProgress, () => {
            flush && flush();
            unsubscribe && unsubscribe();
          }),
          options
        );
      }
      responseType = responseType || "text";
      let responseData = await resolvers[utils$2.findKey(resolvers, responseType) || "text"](
        response,
        config
      );
      !isStreamResponse && unsubscribe && unsubscribe();
      return await new Promise((resolve, reject) => {
        settle(resolve, reject, {
          data: responseData,
          headers: AxiosHeaders$1.from(response.headers),
          status: response.status,
          statusText: response.statusText,
          config,
          request
        });
      });
    } catch (err) {
      unsubscribe && unsubscribe();
      if (err && err.name === "TypeError" && /Load failed|fetch/i.test(err.message)) {
        throw Object.assign(
          new AxiosError$1(
            "Network Error",
            AxiosError$1.ERR_NETWORK,
            config,
            request,
            err && err.response
          ),
          {
            cause: err.cause || err
          }
        );
      }
      throw AxiosError$1.from(err, err && err.code, config, request, err && err.response);
    }
  };
};
const seedCache = /* @__PURE__ */ new Map();
const getFetch = (config) => {
  let env2 = config && config.env || {};
  const { fetch: fetch2, Request, Response } = env2;
  const seeds = [Request, Response, fetch2];
  let len = seeds.length, i = len, seed, target, map = seedCache;
  while (i--) {
    seed = seeds[i];
    target = map.get(seed);
    target === void 0 && map.set(seed, target = i ? /* @__PURE__ */ new Map() : factory(env2));
    map = target;
  }
  return target;
};
getFetch();
const knownAdapters = {
  http: httpAdapter,
  xhr: xhrAdapter,
  fetch: {
    get: getFetch
  }
};
utils$2.forEach(knownAdapters, (fn, value) => {
  if (fn) {
    try {
      Object.defineProperty(fn, "name", { value });
    } catch (e) {
    }
    Object.defineProperty(fn, "adapterName", { value });
  }
});
const renderReason = (reason) => `- ${reason}`;
const isResolvedHandle = (adapter) => utils$2.isFunction(adapter) || adapter === null || adapter === false;
function getAdapter$1(adapters2, config) {
  adapters2 = utils$2.isArray(adapters2) ? adapters2 : [adapters2];
  const { length } = adapters2;
  let nameOrAdapter;
  let adapter;
  const rejectedReasons = {};
  for (let i = 0; i < length; i++) {
    nameOrAdapter = adapters2[i];
    let id;
    adapter = nameOrAdapter;
    if (!isResolvedHandle(nameOrAdapter)) {
      adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
      if (adapter === void 0) {
        throw new AxiosError$1(`Unknown adapter '${id}'`);
      }
    }
    if (adapter && (utils$2.isFunction(adapter) || (adapter = adapter.get(config)))) {
      break;
    }
    rejectedReasons[id || "#" + i] = adapter;
  }
  if (!adapter) {
    const reasons = Object.entries(rejectedReasons).map(
      ([id, state]) => `adapter ${id} ` + (state === false ? "is not supported by the environment" : "is not available in the build")
    );
    let s2 = length ? reasons.length > 1 ? "since :\n" + reasons.map(renderReason).join("\n") : " " + renderReason(reasons[0]) : "as no adapter specified";
    throw new AxiosError$1(
      `There is no suitable adapter to dispatch the request ` + s2,
      "ERR_NOT_SUPPORT"
    );
  }
  return adapter;
}
const adapters = {
  /**
   * Resolve an adapter from a list of adapter names or functions.
   * @type {Function}
   */
  getAdapter: getAdapter$1,
  /**
   * Exposes all known adapters
   * @type {Object<string, Function|Object>}
   */
  adapters: knownAdapters
};
function throwIfCancellationRequested(config) {
  if (config.cancelToken) {
    config.cancelToken.throwIfRequested();
  }
  if (config.signal && config.signal.aborted) {
    throw new CanceledError$1(null, config);
  }
}
function dispatchRequest(config) {
  throwIfCancellationRequested(config);
  config.headers = AxiosHeaders$1.from(config.headers);
  config.data = transformData.call(config, config.transformRequest);
  if (["post", "put", "patch"].indexOf(config.method) !== -1) {
    config.headers.setContentType("application/x-www-form-urlencoded", false);
  }
  const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
  return adapter(config).then(
    function onAdapterResolution(response) {
      throwIfCancellationRequested(config);
      response.data = transformData.call(config, config.transformResponse, response);
      response.headers = AxiosHeaders$1.from(response.headers);
      return response;
    },
    function onAdapterRejection(reason) {
      if (!isCancel$1(reason)) {
        throwIfCancellationRequested(config);
        if (reason && reason.response) {
          reason.response.data = transformData.call(
            config,
            config.transformResponse,
            reason.response
          );
          reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
        }
      }
      return Promise.reject(reason);
    }
  );
}
const validators$1 = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach((type2, i) => {
  validators$1[type2] = function validator2(thing) {
    return typeof thing === type2 || "a" + (i < 1 ? "n " : " ") + type2;
  };
});
const deprecatedWarnings = {};
validators$1.transitional = function transitional(validator2, version, message) {
  function formatMessage(opt, desc) {
    return "[Axios v" + VERSION$1 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : "");
  }
  return (value, opt, opts) => {
    if (validator2 === false) {
      throw new AxiosError$1(
        formatMessage(opt, " has been removed" + (version ? " in " + version : "")),
        AxiosError$1.ERR_DEPRECATED
      );
    }
    if (version && !deprecatedWarnings[opt]) {
      deprecatedWarnings[opt] = true;
      console.warn(
        formatMessage(
          opt,
          " has been deprecated since v" + version + " and will be removed in the near future"
        )
      );
    }
    return validator2 ? validator2(value, opt, opts) : true;
  };
};
validators$1.spelling = function spelling(correctSpelling) {
  return (value, opt) => {
    console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
    return true;
  };
};
function assertOptions(options, schema, allowUnknown) {
  if (typeof options !== "object") {
    throw new AxiosError$1("options must be an object", AxiosError$1.ERR_BAD_OPTION_VALUE);
  }
  const keys2 = Object.keys(options);
  let i = keys2.length;
  while (i-- > 0) {
    const opt = keys2[i];
    const validator2 = schema[opt];
    if (validator2) {
      const value = options[opt];
      const result = value === void 0 || validator2(value, opt, options);
      if (result !== true) {
        throw new AxiosError$1(
          "option " + opt + " must be " + result,
          AxiosError$1.ERR_BAD_OPTION_VALUE
        );
      }
      continue;
    }
    if (allowUnknown !== true) {
      throw new AxiosError$1("Unknown option " + opt, AxiosError$1.ERR_BAD_OPTION);
    }
  }
}
const validator = {
  assertOptions,
  validators: validators$1
};
const validators = validator.validators;
let Axios$1 = class Axios {
  constructor(instanceConfig) {
    this.defaults = instanceConfig || {};
    this.interceptors = {
      request: new InterceptorManager(),
      response: new InterceptorManager()
    };
  }
  /**
   * Dispatch a request
   *
   * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
   * @param {?Object} config
   *
   * @returns {Promise} The Promise to be fulfilled
   */
  async request(configOrUrl, config) {
    try {
      return await this._request(configOrUrl, config);
    } catch (err) {
      if (err instanceof Error) {
        let dummy = {};
        Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
        const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, "") : "";
        try {
          if (!err.stack) {
            err.stack = stack;
          } else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ""))) {
            err.stack += "\n" + stack;
          }
        } catch (e) {
        }
      }
      throw err;
    }
  }
  _request(configOrUrl, config) {
    if (typeof configOrUrl === "string") {
      config = config || {};
      config.url = configOrUrl;
    } else {
      config = configOrUrl || {};
    }
    config = mergeConfig$1(this.defaults, config);
    const { transitional: transitional2, paramsSerializer, headers } = config;
    if (transitional2 !== void 0) {
      validator.assertOptions(
        transitional2,
        {
          silentJSONParsing: validators.transitional(validators.boolean),
          forcedJSONParsing: validators.transitional(validators.boolean),
          clarifyTimeoutError: validators.transitional(validators.boolean),
          legacyInterceptorReqResOrdering: validators.transitional(validators.boolean)
        },
        false
      );
    }
    if (paramsSerializer != null) {
      if (utils$2.isFunction(paramsSerializer)) {
        config.paramsSerializer = {
          serialize: paramsSerializer
        };
      } else {
        validator.assertOptions(
          paramsSerializer,
          {
            encode: validators.function,
            serialize: validators.function
          },
          true
        );
      }
    }
    if (config.allowAbsoluteUrls !== void 0) ;
    else if (this.defaults.allowAbsoluteUrls !== void 0) {
      config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
    } else {
      config.allowAbsoluteUrls = true;
    }
    validator.assertOptions(
      config,
      {
        baseUrl: validators.spelling("baseURL"),
        withXsrfToken: validators.spelling("withXSRFToken")
      },
      true
    );
    config.method = (config.method || this.defaults.method || "get").toLowerCase();
    let contextHeaders = headers && utils$2.merge(headers.common, headers[config.method]);
    headers && utils$2.forEach(["delete", "get", "head", "post", "put", "patch", "common"], (method) => {
      delete headers[method];
    });
    config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
    const requestInterceptorChain = [];
    let synchronousRequestInterceptors = true;
    this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
      if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) {
        return;
      }
      synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
      const transitional3 = config.transitional || transitionalDefaults;
      const legacyInterceptorReqResOrdering = transitional3 && transitional3.legacyInterceptorReqResOrdering;
      if (legacyInterceptorReqResOrdering) {
        requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
      } else {
        requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
      }
    });
    const responseInterceptorChain = [];
    this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
      responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
    });
    let promise;
    let i = 0;
    let len;
    if (!synchronousRequestInterceptors) {
      const chain = [dispatchRequest.bind(this), void 0];
      chain.unshift(...requestInterceptorChain);
      chain.push(...responseInterceptorChain);
      len = chain.length;
      promise = Promise.resolve(config);
      while (i < len) {
        promise = promise.then(chain[i++], chain[i++]);
      }
      return promise;
    }
    len = requestInterceptorChain.length;
    let newConfig = config;
    while (i < len) {
      const onFulfilled = requestInterceptorChain[i++];
      const onRejected = requestInterceptorChain[i++];
      try {
        newConfig = onFulfilled(newConfig);
      } catch (error) {
        onRejected.call(this, error);
        break;
      }
    }
    try {
      promise = dispatchRequest.call(this, newConfig);
    } catch (error) {
      return Promise.reject(error);
    }
    i = 0;
    len = responseInterceptorChain.length;
    while (i < len) {
      promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
    }
    return promise;
  }
  getUri(config) {
    config = mergeConfig$1(this.defaults, config);
    const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
    return buildURL(fullPath, config.params, config.paramsSerializer);
  }
};
utils$2.forEach(["delete", "get", "head", "options"], function forEachMethodNoData(method) {
  Axios$1.prototype[method] = function(url, config) {
    return this.request(
      mergeConfig$1(config || {}, {
        method,
        url,
        data: (config || {}).data
      })
    );
  };
});
utils$2.forEach(["post", "put", "patch"], function forEachMethodWithData(method) {
  function generateHTTPMethod(isForm) {
    return function httpMethod(url, data, config) {
      return this.request(
        mergeConfig$1(config || {}, {
          method,
          headers: isForm ? {
            "Content-Type": "multipart/form-data"
          } : {},
          url,
          data
        })
      );
    };
  }
  Axios$1.prototype[method] = generateHTTPMethod();
  Axios$1.prototype[method + "Form"] = generateHTTPMethod(true);
});
let CancelToken$1 = class CancelToken {
  constructor(executor) {
    if (typeof executor !== "function") {
      throw new TypeError("executor must be a function.");
    }
    let resolvePromise;
    this.promise = new Promise(function promiseExecutor(resolve) {
      resolvePromise = resolve;
    });
    const token = this;
    this.promise.then((cancel2) => {
      if (!token._listeners) return;
      let i = token._listeners.length;
      while (i-- > 0) {
        token._listeners[i](cancel2);
      }
      token._listeners = null;
    });
    this.promise.then = (onfulfilled) => {
      let _resolve;
      const promise = new Promise((resolve) => {
        token.subscribe(resolve);
        _resolve = resolve;
      }).then(onfulfilled);
      promise.cancel = function reject() {
        token.unsubscribe(_resolve);
      };
      return promise;
    };
    executor(function cancel2(message, config, request) {
      if (token.reason) {
        return;
      }
      token.reason = new CanceledError$1(message, config, request);
      resolvePromise(token.reason);
    });
  }
  /**
   * Throws a `CanceledError` if cancellation has been requested.
   */
  throwIfRequested() {
    if (this.reason) {
      throw this.reason;
    }
  }
  /**
   * Subscribe to the cancel signal
   */
  subscribe(listener) {
    if (this.reason) {
      listener(this.reason);
      return;
    }
    if (this._listeners) {
      this._listeners.push(listener);
    } else {
      this._listeners = [listener];
    }
  }
  /**
   * Unsubscribe from the cancel signal
   */
  unsubscribe(listener) {
    if (!this._listeners) {
      return;
    }
    const index2 = this._listeners.indexOf(listener);
    if (index2 !== -1) {
      this._listeners.splice(index2, 1);
    }
  }
  toAbortSignal() {
    const controller = new AbortController();
    const abort = (err) => {
      controller.abort(err);
    };
    this.subscribe(abort);
    controller.signal.unsubscribe = () => this.unsubscribe(abort);
    return controller.signal;
  }
  /**
   * Returns an object that contains a new `CancelToken` and a function that, when called,
   * cancels the `CancelToken`.
   */
  static source() {
    let cancel2;
    const token = new CancelToken(function executor(c) {
      cancel2 = c;
    });
    return {
      token,
      cancel: cancel2
    };
  }
};
function spread$1(callback) {
  return function wrap2(arr) {
    return callback.apply(null, arr);
  };
}
function isAxiosError$1(payload) {
  return utils$2.isObject(payload) && payload.isAxiosError === true;
}
const HttpStatusCode$1 = {
  Continue: 100,
  SwitchingProtocols: 101,
  Processing: 102,
  EarlyHints: 103,
  Ok: 200,
  Created: 201,
  Accepted: 202,
  NonAuthoritativeInformation: 203,
  NoContent: 204,
  ResetContent: 205,
  PartialContent: 206,
  MultiStatus: 207,
  AlreadyReported: 208,
  ImUsed: 226,
  MultipleChoices: 300,
  MovedPermanently: 301,
  Found: 302,
  SeeOther: 303,
  NotModified: 304,
  UseProxy: 305,
  Unused: 306,
  TemporaryRedirect: 307,
  PermanentRedirect: 308,
  BadRequest: 400,
  Unauthorized: 401,
  PaymentRequired: 402,
  Forbidden: 403,
  NotFound: 404,
  MethodNotAllowed: 405,
  NotAcceptable: 406,
  ProxyAuthenticationRequired: 407,
  RequestTimeout: 408,
  Conflict: 409,
  Gone: 410,
  LengthRequired: 411,
  PreconditionFailed: 412,
  PayloadTooLarge: 413,
  UriTooLong: 414,
  UnsupportedMediaType: 415,
  RangeNotSatisfiable: 416,
  ExpectationFailed: 417,
  ImATeapot: 418,
  MisdirectedRequest: 421,
  UnprocessableEntity: 422,
  Locked: 423,
  FailedDependency: 424,
  TooEarly: 425,
  UpgradeRequired: 426,
  PreconditionRequired: 428,
  TooManyRequests: 429,
  RequestHeaderFieldsTooLarge: 431,
  UnavailableForLegalReasons: 451,
  InternalServerError: 500,
  NotImplemented: 501,
  BadGateway: 502,
  ServiceUnavailable: 503,
  GatewayTimeout: 504,
  HttpVersionNotSupported: 505,
  VariantAlsoNegotiates: 506,
  InsufficientStorage: 507,
  LoopDetected: 508,
  NotExtended: 510,
  NetworkAuthenticationRequired: 511,
  WebServerIsDown: 521,
  ConnectionTimedOut: 522,
  OriginIsUnreachable: 523,
  TimeoutOccurred: 524,
  SslHandshakeFailed: 525,
  InvalidSslCertificate: 526
};
Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
  HttpStatusCode$1[value] = key;
});
function createInstance(defaultConfig) {
  const context = new Axios$1(defaultConfig);
  const instance = bind(Axios$1.prototype.request, context);
  utils$2.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
  utils$2.extend(instance, context, null, { allOwnKeys: true });
  instance.create = function create2(instanceConfig) {
    return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
  };
  return instance;
}
const axios = createInstance(defaults);
axios.Axios = Axios$1;
axios.CanceledError = CanceledError$1;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel$1;
axios.VERSION = VERSION$1;
axios.toFormData = toFormData$1;
axios.AxiosError = AxiosError$1;
axios.Cancel = axios.CanceledError;
axios.all = function all(promises) {
  return Promise.all(promises);
};
axios.spread = spread$1;
axios.isAxiosError = isAxiosError$1;
axios.mergeConfig = mergeConfig$1;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = (thing) => formDataToJSON(utils$2.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
const {
  Axios: Axios2,
  AxiosError: AxiosError2,
  CanceledError: CanceledError2,
  isCancel,
  CancelToken: CancelToken2,
  VERSION,
  all: all$1,
  Cancel,
  isAxiosError,
  spread,
  toFormData,
  AxiosHeaders: AxiosHeaders2,
  HttpStatusCode,
  formToJSON,
  getAdapter,
  mergeConfig
} = axios;
var cjs$3;
var hasRequiredCjs$3;
function requireCjs$3() {
  if (hasRequiredCjs$3) return cjs$3;
  hasRequiredCjs$3 = 1;
  var isMergeableObject = function isMergeableObject2(value) {
    return isNonNullObject(value) && !isSpecial(value);
  };
  function isNonNullObject(value) {
    return !!value && typeof value === "object";
  }
  function isSpecial(value) {
    var stringValue = Object.prototype.toString.call(value);
    return stringValue === "[object RegExp]" || stringValue === "[object Date]" || isReactElement(value);
  }
  var canUseSymbol = typeof Symbol === "function" && Symbol.for;
  var REACT_ELEMENT_TYPE = canUseSymbol ? /* @__PURE__ */ Symbol.for("react.element") : 60103;
  function isReactElement(value) {
    return value.$$typeof === REACT_ELEMENT_TYPE;
  }
  function emptyTarget(val) {
    return Array.isArray(val) ? [] : {};
  }
  function cloneUnlessOtherwiseSpecified(value, options) {
    return options.clone !== false && options.isMergeableObject(value) ? deepmerge(emptyTarget(value), value, options) : value;
  }
  function defaultArrayMerge(target, source, options) {
    return target.concat(source).map(function(element2) {
      return cloneUnlessOtherwiseSpecified(element2, options);
    });
  }
  function getMergeFunction(key, options) {
    if (!options.customMerge) {
      return deepmerge;
    }
    var customMerge = options.customMerge(key);
    return typeof customMerge === "function" ? customMerge : deepmerge;
  }
  function getEnumerableOwnPropertySymbols(target) {
    return Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
      return Object.propertyIsEnumerable.call(target, symbol);
    }) : [];
  }
  function getKeys(target) {
    return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target));
  }
  function propertyIsOnObject(object, property) {
    try {
      return property in object;
    } catch (_2) {
      return false;
    }
  }
  function propertyIsUnsafe(target, key) {
    return propertyIsOnObject(target, key) && !(Object.hasOwnProperty.call(target, key) && Object.propertyIsEnumerable.call(target, key));
  }
  function mergeObject(target, source, options) {
    var destination = {};
    if (options.isMergeableObject(target)) {
      getKeys(target).forEach(function(key) {
        destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
      });
    }
    getKeys(source).forEach(function(key) {
      if (propertyIsUnsafe(target, key)) {
        return;
      }
      if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
        destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
      } else {
        destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
      }
    });
    return destination;
  }
  function deepmerge(target, source, options) {
    options = options || {};
    options.arrayMerge = options.arrayMerge || defaultArrayMerge;
    options.isMergeableObject = options.isMergeableObject || isMergeableObject;
    options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
    var sourceIsArray = Array.isArray(source);
    var targetIsArray = Array.isArray(target);
    var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
    if (!sourceAndTargetTypesMatch) {
      return cloneUnlessOtherwiseSpecified(source, options);
    } else if (sourceIsArray) {
      return options.arrayMerge(target, source, options);
    } else {
      return mergeObject(target, source, options);
    }
  }
  deepmerge.all = function deepmergeAll(array, options) {
    if (!Array.isArray(array)) {
      throw new Error("first argument should be an array");
    }
    return array.reduce(function(prev, next) {
      return deepmerge(prev, next, options);
    }, {});
  };
  var deepmerge_1 = deepmerge;
  cjs$3 = deepmerge_1;
  return cjs$3;
}
var cjsExports$1 = requireCjs$3();
const oe$1 = /* @__PURE__ */ getDefaultExportFromCjs(cjsExports$1);
var util_inspect;
var hasRequiredUtil_inspect;
function requireUtil_inspect() {
  if (hasRequiredUtil_inspect) return util_inspect;
  hasRequiredUtil_inspect = 1;
  util_inspect = require$$0$1.inspect;
  return util_inspect;
}
var objectInspect;
var hasRequiredObjectInspect;
function requireObjectInspect() {
  if (hasRequiredObjectInspect) return objectInspect;
  hasRequiredObjectInspect = 1;
  var hasMap = typeof Map === "function" && Map.prototype;
  var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, "size") : null;
  var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === "function" ? mapSizeDescriptor.get : null;
  var mapForEach = hasMap && Map.prototype.forEach;
  var hasSet = typeof Set === "function" && Set.prototype;
  var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, "size") : null;
  var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === "function" ? setSizeDescriptor.get : null;
  var setForEach = hasSet && Set.prototype.forEach;
  var hasWeakMap = typeof WeakMap === "function" && WeakMap.prototype;
  var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
  var hasWeakSet = typeof WeakSet === "function" && WeakSet.prototype;
  var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
  var hasWeakRef = typeof WeakRef === "function" && WeakRef.prototype;
  var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;
  var booleanValueOf = Boolean.prototype.valueOf;
  var objectToString = Object.prototype.toString;
  var functionToString = Function.prototype.toString;
  var $match = String.prototype.match;
  var $slice = String.prototype.slice;
  var $replace = String.prototype.replace;
  var $toUpperCase = String.prototype.toUpperCase;
  var $toLowerCase = String.prototype.toLowerCase;
  var $test = RegExp.prototype.test;
  var $concat = Array.prototype.concat;
  var $join = Array.prototype.join;
  var $arrSlice = Array.prototype.slice;
  var $floor = Math.floor;
  var bigIntValueOf = typeof BigInt === "function" ? BigInt.prototype.valueOf : null;
  var gOPS = Object.getOwnPropertySymbols;
  var symToString = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol.prototype.toString : null;
  var hasShammedSymbols = typeof Symbol === "function" && typeof Symbol.iterator === "object";
  var toStringTag2 = typeof Symbol === "function" && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? "object" : "symbol") ? Symbol.toStringTag : null;
  var isEnumerable = Object.prototype.propertyIsEnumerable;
  var gPO = (typeof Reflect === "function" ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ([].__proto__ === Array.prototype ? function(O2) {
    return O2.__proto__;
  } : null);
  function addNumericSeparator(num, str) {
    if (num === Infinity || num === -Infinity || num !== num || num && num > -1e3 && num < 1e3 || $test.call(/e/, str)) {
      return str;
    }
    var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;
    if (typeof num === "number") {
      var int = num < 0 ? -$floor(-num) : $floor(num);
      if (int !== num) {
        var intStr = String(int);
        var dec = $slice.call(str, intStr.length + 1);
        return $replace.call(intStr, sepRegex, "$&_") + "." + $replace.call($replace.call(dec, /([0-9]{3})/g, "$&_"), /_$/, "");
      }
    }
    return $replace.call(str, sepRegex, "$&_");
  }
  var utilInspect = /* @__PURE__ */ requireUtil_inspect();
  var inspectCustom = utilInspect.custom;
  var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;
  var quotes = {
    __proto__: null,
    "double": '"',
    single: "'"
  };
  var quoteREs = {
    __proto__: null,
    "double": /(["\\])/g,
    single: /(['\\])/g
  };
  objectInspect = function inspect_(obj, options, depth, seen) {
    var opts = options || {};
    if (has(opts, "quoteStyle") && !has(quotes, opts.quoteStyle)) {
      throw new TypeError('option "quoteStyle" must be "single" or "double"');
    }
    if (has(opts, "maxStringLength") && (typeof opts.maxStringLength === "number" ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null)) {
      throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');
    }
    var customInspect = has(opts, "customInspect") ? opts.customInspect : true;
    if (typeof customInspect !== "boolean" && customInspect !== "symbol") {
      throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");
    }
    if (has(opts, "indent") && opts.indent !== null && opts.indent !== "	" && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)) {
      throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');
    }
    if (has(opts, "numericSeparator") && typeof opts.numericSeparator !== "boolean") {
      throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');
    }
    var numericSeparator = opts.numericSeparator;
    if (typeof obj === "undefined") {
      return "undefined";
    }
    if (obj === null) {
      return "null";
    }
    if (typeof obj === "boolean") {
      return obj ? "true" : "false";
    }
    if (typeof obj === "string") {
      return inspectString(obj, opts);
    }
    if (typeof obj === "number") {
      if (obj === 0) {
        return Infinity / obj > 0 ? "0" : "-0";
      }
      var str = String(obj);
      return numericSeparator ? addNumericSeparator(obj, str) : str;
    }
    if (typeof obj === "bigint") {
      var bigIntStr = String(obj) + "n";
      return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;
    }
    var maxDepth = typeof opts.depth === "undefined" ? 5 : opts.depth;
    if (typeof depth === "undefined") {
      depth = 0;
    }
    if (depth >= maxDepth && maxDepth > 0 && typeof obj === "object") {
      return isArray2(obj) ? "[Array]" : "[Object]";
    }
    var indent = getIndent(opts, depth);
    if (typeof seen === "undefined") {
      seen = [];
    } else if (indexOf(seen, obj) >= 0) {
      return "[Circular]";
    }
    function inspect(value, from, noIndent) {
      if (from) {
        seen = $arrSlice.call(seen);
        seen.push(from);
      }
      if (noIndent) {
        var newOpts = {
          depth: opts.depth
        };
        if (has(opts, "quoteStyle")) {
          newOpts.quoteStyle = opts.quoteStyle;
        }
        return inspect_(value, newOpts, depth + 1, seen);
      }
      return inspect_(value, opts, depth + 1, seen);
    }
    if (typeof obj === "function" && !isRegExp2(obj)) {
      var name2 = nameOf(obj);
      var keys2 = arrObjKeys(obj, inspect);
      return "[Function" + (name2 ? ": " + name2 : " (anonymous)") + "]" + (keys2.length > 0 ? " { " + $join.call(keys2, ", ") + " }" : "");
    }
    if (isSymbol(obj)) {
      var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, "$1") : symToString.call(obj);
      return typeof obj === "object" && !hasShammedSymbols ? markBoxed(symString) : symString;
    }
    if (isElement(obj)) {
      var s2 = "<" + $toLowerCase.call(String(obj.nodeName));
      var attrs = obj.attributes || [];
      for (var i = 0; i < attrs.length; i++) {
        s2 += " " + attrs[i].name + "=" + wrapQuotes(quote(attrs[i].value), "double", opts);
      }
      s2 += ">";
      if (obj.childNodes && obj.childNodes.length) {
        s2 += "...";
      }
      s2 += "</" + $toLowerCase.call(String(obj.nodeName)) + ">";
      return s2;
    }
    if (isArray2(obj)) {
      if (obj.length === 0) {
        return "[]";
      }
      var xs = arrObjKeys(obj, inspect);
      if (indent && !singleLineValues(xs)) {
        return "[" + indentedJoin(xs, indent) + "]";
      }
      return "[ " + $join.call(xs, ", ") + " ]";
    }
    if (isError(obj)) {
      var parts = arrObjKeys(obj, inspect);
      if (!("cause" in Error.prototype) && "cause" in obj && !isEnumerable.call(obj, "cause")) {
        return "{ [" + String(obj) + "] " + $join.call($concat.call("[cause]: " + inspect(obj.cause), parts), ", ") + " }";
      }
      if (parts.length === 0) {
        return "[" + String(obj) + "]";
      }
      return "{ [" + String(obj) + "] " + $join.call(parts, ", ") + " }";
    }
    if (typeof obj === "object" && customInspect) {
      if (inspectSymbol && typeof obj[inspectSymbol] === "function" && utilInspect) {
        return utilInspect(obj, { depth: maxDepth - depth });
      } else if (customInspect !== "symbol" && typeof obj.inspect === "function") {
        return obj.inspect();
      }
    }
    if (isMap(obj)) {
      var mapParts = [];
      if (mapForEach) {
        mapForEach.call(obj, function(value, key) {
          mapParts.push(inspect(key, obj, true) + " => " + inspect(value, obj));
        });
      }
      return collectionOf("Map", mapSize.call(obj), mapParts, indent);
    }
    if (isSet(obj)) {
      var setParts = [];
      if (setForEach) {
        setForEach.call(obj, function(value) {
          setParts.push(inspect(value, obj));
        });
      }
      return collectionOf("Set", setSize.call(obj), setParts, indent);
    }
    if (isWeakMap(obj)) {
      return weakCollectionOf("WeakMap");
    }
    if (isWeakSet(obj)) {
      return weakCollectionOf("WeakSet");
    }
    if (isWeakRef(obj)) {
      return weakCollectionOf("WeakRef");
    }
    if (isNumber2(obj)) {
      return markBoxed(inspect(Number(obj)));
    }
    if (isBigInt(obj)) {
      return markBoxed(inspect(bigIntValueOf.call(obj)));
    }
    if (isBoolean2(obj)) {
      return markBoxed(booleanValueOf.call(obj));
    }
    if (isString2(obj)) {
      return markBoxed(inspect(String(obj)));
    }
    if (typeof window !== "undefined" && obj === window) {
      return "{ [object Window] }";
    }
    if (typeof globalThis !== "undefined" && obj === globalThis || typeof commonjsGlobal !== "undefined" && obj === commonjsGlobal) {
      return "{ [object globalThis] }";
    }
    if (!isDate2(obj) && !isRegExp2(obj)) {
      var ys = arrObjKeys(obj, inspect);
      var isPlainObject2 = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;
      var protoTag = obj instanceof Object ? "" : "null prototype";
      var stringTag = !isPlainObject2 && toStringTag2 && Object(obj) === obj && toStringTag2 in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? "Object" : "";
      var constructorTag = isPlainObject2 || typeof obj.constructor !== "function" ? "" : obj.constructor.name ? obj.constructor.name + " " : "";
      var tag = constructorTag + (stringTag || protoTag ? "[" + $join.call($concat.call([], stringTag || [], protoTag || []), ": ") + "] " : "");
      if (ys.length === 0) {
        return tag + "{}";
      }
      if (indent) {
        return tag + "{" + indentedJoin(ys, indent) + "}";
      }
      return tag + "{ " + $join.call(ys, ", ") + " }";
    }
    return String(obj);
  };
  function wrapQuotes(s2, defaultStyle, opts) {
    var style = opts.quoteStyle || defaultStyle;
    var quoteChar = quotes[style];
    return quoteChar + s2 + quoteChar;
  }
  function quote(s2) {
    return $replace.call(String(s2), /"/g, "&quot;");
  }
  function canTrustToString(obj) {
    return !toStringTag2 || !(typeof obj === "object" && (toStringTag2 in obj || typeof obj[toStringTag2] !== "undefined"));
  }
  function isArray2(obj) {
    return toStr(obj) === "[object Array]" && canTrustToString(obj);
  }
  function isDate2(obj) {
    return toStr(obj) === "[object Date]" && canTrustToString(obj);
  }
  function isRegExp2(obj) {
    return toStr(obj) === "[object RegExp]" && canTrustToString(obj);
  }
  function isError(obj) {
    return toStr(obj) === "[object Error]" && canTrustToString(obj);
  }
  function isString2(obj) {
    return toStr(obj) === "[object String]" && canTrustToString(obj);
  }
  function isNumber2(obj) {
    return toStr(obj) === "[object Number]" && canTrustToString(obj);
  }
  function isBoolean2(obj) {
    return toStr(obj) === "[object Boolean]" && canTrustToString(obj);
  }
  function isSymbol(obj) {
    if (hasShammedSymbols) {
      return obj && typeof obj === "object" && obj instanceof Symbol;
    }
    if (typeof obj === "symbol") {
      return true;
    }
    if (!obj || typeof obj !== "object" || !symToString) {
      return false;
    }
    try {
      symToString.call(obj);
      return true;
    } catch (e) {
    }
    return false;
  }
  function isBigInt(obj) {
    if (!obj || typeof obj !== "object" || !bigIntValueOf) {
      return false;
    }
    try {
      bigIntValueOf.call(obj);
      return true;
    } catch (e) {
    }
    return false;
  }
  var hasOwn = Object.prototype.hasOwnProperty || function(key) {
    return key in this;
  };
  function has(obj, key) {
    return hasOwn.call(obj, key);
  }
  function toStr(obj) {
    return objectToString.call(obj);
  }
  function nameOf(f2) {
    if (f2.name) {
      return f2.name;
    }
    var m2 = $match.call(functionToString.call(f2), /^function\s*([\w$]+)/);
    if (m2) {
      return m2[1];
    }
    return null;
  }
  function indexOf(xs, x2) {
    if (xs.indexOf) {
      return xs.indexOf(x2);
    }
    for (var i = 0, l3 = xs.length; i < l3; i++) {
      if (xs[i] === x2) {
        return i;
      }
    }
    return -1;
  }
  function isMap(x2) {
    if (!mapSize || !x2 || typeof x2 !== "object") {
      return false;
    }
    try {
      mapSize.call(x2);
      try {
        setSize.call(x2);
      } catch (s2) {
        return true;
      }
      return x2 instanceof Map;
    } catch (e) {
    }
    return false;
  }
  function isWeakMap(x2) {
    if (!weakMapHas || !x2 || typeof x2 !== "object") {
      return false;
    }
    try {
      weakMapHas.call(x2, weakMapHas);
      try {
        weakSetHas.call(x2, weakSetHas);
      } catch (s2) {
        return true;
      }
      return x2 instanceof WeakMap;
    } catch (e) {
    }
    return false;
  }
  function isWeakRef(x2) {
    if (!weakRefDeref || !x2 || typeof x2 !== "object") {
      return false;
    }
    try {
      weakRefDeref.call(x2);
      return true;
    } catch (e) {
    }
    return false;
  }
  function isSet(x2) {
    if (!setSize || !x2 || typeof x2 !== "object") {
      return false;
    }
    try {
      setSize.call(x2);
      try {
        mapSize.call(x2);
      } catch (m2) {
        return true;
      }
      return x2 instanceof Set;
    } catch (e) {
    }
    return false;
  }
  function isWeakSet(x2) {
    if (!weakSetHas || !x2 || typeof x2 !== "object") {
      return false;
    }
    try {
      weakSetHas.call(x2, weakSetHas);
      try {
        weakMapHas.call(x2, weakMapHas);
      } catch (s2) {
        return true;
      }
      return x2 instanceof WeakSet;
    } catch (e) {
    }
    return false;
  }
  function isElement(x2) {
    if (!x2 || typeof x2 !== "object") {
      return false;
    }
    if (typeof HTMLElement !== "undefined" && x2 instanceof HTMLElement) {
      return true;
    }
    return typeof x2.nodeName === "string" && typeof x2.getAttribute === "function";
  }
  function inspectString(str, opts) {
    if (str.length > opts.maxStringLength) {
      var remaining = str.length - opts.maxStringLength;
      var trailer = "... " + remaining + " more character" + (remaining > 1 ? "s" : "");
      return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;
    }
    var quoteRE = quoteREs[opts.quoteStyle || "single"];
    quoteRE.lastIndex = 0;
    var s2 = $replace.call($replace.call(str, quoteRE, "\\$1"), /[\x00-\x1f]/g, lowbyte);
    return wrapQuotes(s2, "single", opts);
  }
  function lowbyte(c) {
    var n = c.charCodeAt(0);
    var x2 = {
      8: "b",
      9: "t",
      10: "n",
      12: "f",
      13: "r"
    }[n];
    if (x2) {
      return "\\" + x2;
    }
    return "\\x" + (n < 16 ? "0" : "") + $toUpperCase.call(n.toString(16));
  }
  function markBoxed(str) {
    return "Object(" + str + ")";
  }
  function weakCollectionOf(type2) {
    return type2 + " { ? }";
  }
  function collectionOf(type2, size, entries, indent) {
    var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ", ");
    return type2 + " (" + size + ") {" + joinedEntries + "}";
  }
  function singleLineValues(xs) {
    for (var i = 0; i < xs.length; i++) {
      if (indexOf(xs[i], "\n") >= 0) {
        return false;
      }
    }
    return true;
  }
  function getIndent(opts, depth) {
    var baseIndent;
    if (opts.indent === "	") {
      baseIndent = "	";
    } else if (typeof opts.indent === "number" && opts.indent > 0) {
      baseIndent = $join.call(Array(opts.indent + 1), " ");
    } else {
      return null;
    }
    return {
      base: baseIndent,
      prev: $join.call(Array(depth + 1), baseIndent)
    };
  }
  function indentedJoin(xs, indent) {
    if (xs.length === 0) {
      return "";
    }
    var lineJoiner = "\n" + indent.prev + indent.base;
    return lineJoiner + $join.call(xs, "," + lineJoiner) + "\n" + indent.prev;
  }
  function arrObjKeys(obj, inspect) {
    var isArr = isArray2(obj);
    var xs = [];
    if (isArr) {
      xs.length = obj.length;
      for (var i = 0; i < obj.length; i++) {
        xs[i] = has(obj, i) ? inspect(obj[i], obj) : "";
      }
    }
    var syms = typeof gOPS === "function" ? gOPS(obj) : [];
    var symMap;
    if (hasShammedSymbols) {
      symMap = {};
      for (var k2 = 0; k2 < syms.length; k2++) {
        symMap["$" + syms[k2]] = syms[k2];
      }
    }
    for (var key in obj) {
      if (!has(obj, key)) {
        continue;
      }
      if (isArr && String(Number(key)) === key && key < obj.length) {
        continue;
      }
      if (hasShammedSymbols && symMap["$" + key] instanceof Symbol) {
        continue;
      } else if ($test.call(/[^\w$]/, key)) {
        xs.push(inspect(key, obj) + ": " + inspect(obj[key], obj));
      } else {
        xs.push(key + ": " + inspect(obj[key], obj));
      }
    }
    if (typeof gOPS === "function") {
      for (var j2 = 0; j2 < syms.length; j2++) {
        if (isEnumerable.call(obj, syms[j2])) {
          xs.push("[" + inspect(syms[j2]) + "]: " + inspect(obj[syms[j2]], obj));
        }
      }
    }
    return xs;
  }
  return objectInspect;
}
var sideChannelList;
var hasRequiredSideChannelList;
function requireSideChannelList() {
  if (hasRequiredSideChannelList) return sideChannelList;
  hasRequiredSideChannelList = 1;
  var inspect = /* @__PURE__ */ requireObjectInspect();
  var $TypeError = /* @__PURE__ */ requireType();
  var listGetNode = function(list2, key, isDelete) {
    var prev = list2;
    var curr;
    for (; (curr = prev.next) != null; prev = curr) {
      if (curr.key === key) {
        prev.next = curr.next;
        if (!isDelete) {
          curr.next = /** @type {NonNullable<typeof list.next>} */
          list2.next;
          list2.next = curr;
        }
        return curr;
      }
    }
  };
  var listGet = function(objects, key) {
    if (!objects) {
      return void 0;
    }
    var node2 = listGetNode(objects, key);
    return node2 && node2.value;
  };
  var listSet = function(objects, key, value) {
    var node2 = listGetNode(objects, key);
    if (node2) {
      node2.value = value;
    } else {
      objects.next = /** @type {import('./list.d.ts').ListNode<typeof value, typeof key>} */
      {
        // eslint-disable-line no-param-reassign, no-extra-parens
        key,
        next: objects.next,
        value
      };
    }
  };
  var listHas = function(objects, key) {
    if (!objects) {
      return false;
    }
    return !!listGetNode(objects, key);
  };
  var listDelete = function(objects, key) {
    if (objects) {
      return listGetNode(objects, key, true);
    }
  };
  sideChannelList = function getSideChannelList() {
    var $o;
    var channel = {
      assert: function(key) {
        if (!channel.has(key)) {
          throw new $TypeError("Side channel does not contain " + inspect(key));
        }
      },
      "delete": function(key) {
        var root2 = $o && $o.next;
        var deletedNode = listDelete($o, key);
        if (deletedNode && root2 && root2 === deletedNode) {
          $o = void 0;
        }
        return !!deletedNode;
      },
      get: function(key) {
        return listGet($o, key);
      },
      has: function(key) {
        return listHas($o, key);
      },
      set: function(key, value) {
        if (!$o) {
          $o = {
            next: void 0
          };
        }
        listSet(
          /** @type {NonNullable<typeof $o>} */
          $o,
          key,
          value
        );
      }
    };
    return channel;
  };
  return sideChannelList;
}
var callBound;
var hasRequiredCallBound;
function requireCallBound() {
  if (hasRequiredCallBound) return callBound;
  hasRequiredCallBound = 1;
  var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic();
  var callBindBasic = requireCallBindApplyHelpers();
  var $indexOf = callBindBasic([GetIntrinsic("%String.prototype.indexOf%")]);
  callBound = function callBoundIntrinsic(name2, allowMissing) {
    var intrinsic = (
      /** @type {(this: unknown, ...args: unknown[]) => unknown} */
      GetIntrinsic(name2, !!allowMissing)
    );
    if (typeof intrinsic === "function" && $indexOf(name2, ".prototype.") > -1) {
      return callBindBasic(
        /** @type {const} */
        [intrinsic]
      );
    }
    return intrinsic;
  };
  return callBound;
}
var sideChannelMap;
var hasRequiredSideChannelMap;
function requireSideChannelMap() {
  if (hasRequiredSideChannelMap) return sideChannelMap;
  hasRequiredSideChannelMap = 1;
  var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic();
  var callBound2 = /* @__PURE__ */ requireCallBound();
  var inspect = /* @__PURE__ */ requireObjectInspect();
  var $TypeError = /* @__PURE__ */ requireType();
  var $Map = GetIntrinsic("%Map%", true);
  var $mapGet = callBound2("Map.prototype.get", true);
  var $mapSet = callBound2("Map.prototype.set", true);
  var $mapHas = callBound2("Map.prototype.has", true);
  var $mapDelete = callBound2("Map.prototype.delete", true);
  var $mapSize = callBound2("Map.prototype.size", true);
  sideChannelMap = !!$Map && /** @type {Exclude<import('.'), false>} */
  function getSideChannelMap() {
    var $m;
    var channel = {
      assert: function(key) {
        if (!channel.has(key)) {
          throw new $TypeError("Side channel does not contain " + inspect(key));
        }
      },
      "delete": function(key) {
        if ($m) {
          var result = $mapDelete($m, key);
          if ($mapSize($m) === 0) {
            $m = void 0;
          }
          return result;
        }
        return false;
      },
      get: function(key) {
        if ($m) {
          return $mapGet($m, key);
        }
      },
      has: function(key) {
        if ($m) {
          return $mapHas($m, key);
        }
        return false;
      },
      set: function(key, value) {
        if (!$m) {
          $m = new $Map();
        }
        $mapSet($m, key, value);
      }
    };
    return channel;
  };
  return sideChannelMap;
}
var sideChannelWeakmap;
var hasRequiredSideChannelWeakmap;
function requireSideChannelWeakmap() {
  if (hasRequiredSideChannelWeakmap) return sideChannelWeakmap;
  hasRequiredSideChannelWeakmap = 1;
  var GetIntrinsic = /* @__PURE__ */ requireGetIntrinsic();
  var callBound2 = /* @__PURE__ */ requireCallBound();
  var inspect = /* @__PURE__ */ requireObjectInspect();
  var getSideChannelMap = requireSideChannelMap();
  var $TypeError = /* @__PURE__ */ requireType();
  var $WeakMap = GetIntrinsic("%WeakMap%", true);
  var $weakMapGet = callBound2("WeakMap.prototype.get", true);
  var $weakMapSet = callBound2("WeakMap.prototype.set", true);
  var $weakMapHas = callBound2("WeakMap.prototype.has", true);
  var $weakMapDelete = callBound2("WeakMap.prototype.delete", true);
  sideChannelWeakmap = $WeakMap ? (
    /** @type {Exclude<import('.'), false>} */
    function getSideChannelWeakMap() {
      var $wm;
      var $m;
      var channel = {
        assert: function(key) {
          if (!channel.has(key)) {
            throw new $TypeError("Side channel does not contain " + inspect(key));
          }
        },
        "delete": function(key) {
          if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
            if ($wm) {
              return $weakMapDelete($wm, key);
            }
          } else if (getSideChannelMap) {
            if ($m) {
              return $m["delete"](key);
            }
          }
          return false;
        },
        get: function(key) {
          if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
            if ($wm) {
              return $weakMapGet($wm, key);
            }
          }
          return $m && $m.get(key);
        },
        has: function(key) {
          if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
            if ($wm) {
              return $weakMapHas($wm, key);
            }
          }
          return !!$m && $m.has(key);
        },
        set: function(key, value) {
          if ($WeakMap && key && (typeof key === "object" || typeof key === "function")) {
            if (!$wm) {
              $wm = new $WeakMap();
            }
            $weakMapSet($wm, key, value);
          } else if (getSideChannelMap) {
            if (!$m) {
              $m = getSideChannelMap();
            }
            $m.set(key, value);
          }
        }
      };
      return channel;
    }
  ) : getSideChannelMap;
  return sideChannelWeakmap;
}
var sideChannel;
var hasRequiredSideChannel;
function requireSideChannel() {
  if (hasRequiredSideChannel) return sideChannel;
  hasRequiredSideChannel = 1;
  var $TypeError = /* @__PURE__ */ requireType();
  var inspect = /* @__PURE__ */ requireObjectInspect();
  var getSideChannelList = requireSideChannelList();
  var getSideChannelMap = requireSideChannelMap();
  var getSideChannelWeakMap = requireSideChannelWeakmap();
  var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList;
  sideChannel = function getSideChannel() {
    var $channelData;
    var channel = {
      assert: function(key) {
        if (!channel.has(key)) {
          throw new $TypeError("Side channel does not contain " + inspect(key));
        }
      },
      "delete": function(key) {
        return !!$channelData && $channelData["delete"](key);
      },
      get: function(key) {
        return $channelData && $channelData.get(key);
      },
      has: function(key) {
        return !!$channelData && $channelData.has(key);
      },
      set: function(key, value) {
        if (!$channelData) {
          $channelData = makeChannel();
        }
        $channelData.set(key, value);
      }
    };
    return channel;
  };
  return sideChannel;
}
var formats;
var hasRequiredFormats;
function requireFormats() {
  if (hasRequiredFormats) return formats;
  hasRequiredFormats = 1;
  var replace = String.prototype.replace;
  var percentTwenties = /%20/g;
  var Format = {
    RFC1738: "RFC1738",
    RFC3986: "RFC3986"
  };
  formats = {
    "default": Format.RFC3986,
    formatters: {
      RFC1738: function(value) {
        return replace.call(value, percentTwenties, "+");
      },
      RFC3986: function(value) {
        return String(value);
      }
    },
    RFC1738: Format.RFC1738,
    RFC3986: Format.RFC3986
  };
  return formats;
}
var utils;
var hasRequiredUtils;
function requireUtils() {
  if (hasRequiredUtils) return utils;
  hasRequiredUtils = 1;
  var formats2 = /* @__PURE__ */ requireFormats();
  var getSideChannel = requireSideChannel();
  var has = Object.prototype.hasOwnProperty;
  var isArray2 = Array.isArray;
  var overflowChannel = getSideChannel();
  var markOverflow = function markOverflow2(obj, maxIndex) {
    overflowChannel.set(obj, maxIndex);
    return obj;
  };
  var isOverflow = function isOverflow2(obj) {
    return overflowChannel.has(obj);
  };
  var getMaxIndex = function getMaxIndex2(obj) {
    return overflowChannel.get(obj);
  };
  var setMaxIndex = function setMaxIndex2(obj, maxIndex) {
    overflowChannel.set(obj, maxIndex);
  };
  var hexTable = (function() {
    var array = [];
    for (var i = 0; i < 256; ++i) {
      array[array.length] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase();
    }
    return array;
  })();
  var compactQueue = function compactQueue2(queue) {
    while (queue.length > 1) {
      var item = queue.pop();
      var obj = item.obj[item.prop];
      if (isArray2(obj)) {
        var compacted = [];
        for (var j2 = 0; j2 < obj.length; ++j2) {
          if (typeof obj[j2] !== "undefined") {
            compacted[compacted.length] = obj[j2];
          }
        }
        item.obj[item.prop] = compacted;
      }
    }
  };
  var arrayToObject2 = function arrayToObject3(source, options) {
    var obj = options && options.plainObjects ? { __proto__: null } : {};
    for (var i = 0; i < source.length; ++i) {
      if (typeof source[i] !== "undefined") {
        obj[i] = source[i];
      }
    }
    return obj;
  };
  var merge2 = function merge3(target, source, options) {
    if (!source) {
      return target;
    }
    if (typeof source !== "object" && typeof source !== "function") {
      if (isArray2(target)) {
        var nextIndex = target.length;
        if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) {
          return markOverflow(arrayToObject2(target.concat(source), options), nextIndex);
        }
        target[nextIndex] = source;
      } else if (target && typeof target === "object") {
        if (isOverflow(target)) {
          var newIndex = getMaxIndex(target) + 1;
          target[newIndex] = source;
          setMaxIndex(target, newIndex);
        } else if (options && options.strictMerge) {
          return [target, source];
        } else if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) {
          target[source] = true;
        }
      } else {
        return [target, source];
      }
      return target;
    }
    if (!target || typeof target !== "object") {
      if (isOverflow(source)) {
        var sourceKeys = Object.keys(source);
        var result = options && options.plainObjects ? { __proto__: null, 0: target } : { 0: target };
        for (var m2 = 0; m2 < sourceKeys.length; m2++) {
          var oldKey = parseInt(sourceKeys[m2], 10);
          result[oldKey + 1] = source[sourceKeys[m2]];
        }
        return markOverflow(result, getMaxIndex(source) + 1);
      }
      var combined = [target].concat(source);
      if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) {
        return markOverflow(arrayToObject2(combined, options), combined.length - 1);
      }
      return combined;
    }
    var mergeTarget = target;
    if (isArray2(target) && !isArray2(source)) {
      mergeTarget = arrayToObject2(target, options);
    }
    if (isArray2(target) && isArray2(source)) {
      source.forEach(function(item, i) {
        if (has.call(target, i)) {
          var targetItem = target[i];
          if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
            target[i] = merge3(targetItem, item, options);
          } else {
            target[target.length] = item;
          }
        } else {
          target[i] = item;
        }
      });
      return target;
    }
    return Object.keys(source).reduce(function(acc, key) {
      var value = source[key];
      if (has.call(acc, key)) {
        acc[key] = merge3(acc[key], value, options);
      } else {
        acc[key] = value;
      }
      if (isOverflow(source) && !isOverflow(acc)) {
        markOverflow(acc, getMaxIndex(source));
      }
      if (isOverflow(acc)) {
        var keyNum = parseInt(key, 10);
        if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) {
          setMaxIndex(acc, keyNum);
        }
      }
      return acc;
    }, mergeTarget);
  };
  var assign = function assignSingleSource(target, source) {
    return Object.keys(source).reduce(function(acc, key) {
      acc[key] = source[key];
      return acc;
    }, target);
  };
  var decode2 = function(str, defaultDecoder, charset) {
    var strWithoutPlus = str.replace(/\+/g, " ");
    if (charset === "iso-8859-1") {
      return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
    }
    try {
      return decodeURIComponent(strWithoutPlus);
    } catch (e) {
      return strWithoutPlus;
    }
  };
  var limit = 1024;
  var encode2 = function encode3(str, defaultEncoder, charset, kind, format) {
    if (str.length === 0) {
      return str;
    }
    var string2 = str;
    if (typeof str === "symbol") {
      string2 = Symbol.prototype.toString.call(str);
    } else if (typeof str !== "string") {
      string2 = String(str);
    }
    if (charset === "iso-8859-1") {
      return escape(string2).replace(/%u[0-9a-f]{4}/gi, function($0) {
        return "%26%23" + parseInt($0.slice(2), 16) + "%3B";
      });
    }
    var out = "";
    for (var j2 = 0; j2 < string2.length; j2 += limit) {
      var segment = string2.length >= limit ? string2.slice(j2, j2 + limit) : string2;
      var arr = [];
      for (var i = 0; i < segment.length; ++i) {
        var c = segment.charCodeAt(i);
        if (c === 45 || c === 46 || c === 95 || c === 126 || c >= 48 && c <= 57 || c >= 65 && c <= 90 || c >= 97 && c <= 122 || format === formats2.RFC1738 && (c === 40 || c === 41)) {
          arr[arr.length] = segment.charAt(i);
          continue;
        }
        if (c < 128) {
          arr[arr.length] = hexTable[c];
          continue;
        }
        if (c < 2048) {
          arr[arr.length] = hexTable[192 | c >> 6] + hexTable[128 | c & 63];
          continue;
        }
        if (c < 55296 || c >= 57344) {
          arr[arr.length] = hexTable[224 | c >> 12] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
          continue;
        }
        i += 1;
        c = 65536 + ((c & 1023) << 10 | segment.charCodeAt(i) & 1023);
        arr[arr.length] = hexTable[240 | c >> 18] + hexTable[128 | c >> 12 & 63] + hexTable[128 | c >> 6 & 63] + hexTable[128 | c & 63];
      }
      out += arr.join("");
    }
    return out;
  };
  var compact = function compact2(value) {
    var queue = [{ obj: { o: value }, prop: "o" }];
    var refs = [];
    for (var i = 0; i < queue.length; ++i) {
      var item = queue[i];
      var obj = item.obj[item.prop];
      var keys2 = Object.keys(obj);
      for (var j2 = 0; j2 < keys2.length; ++j2) {
        var key = keys2[j2];
        var val = obj[key];
        if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) {
          queue[queue.length] = { obj, prop: key };
          refs[refs.length] = val;
        }
      }
    }
    compactQueue(queue);
    return value;
  };
  var isRegExp2 = function isRegExp3(obj) {
    return Object.prototype.toString.call(obj) === "[object RegExp]";
  };
  var isBuffer2 = function isBuffer3(obj) {
    if (!obj || typeof obj !== "object") {
      return false;
    }
    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
  };
  var combine = function combine2(a, b2, arrayLimit, plainObjects) {
    if (isOverflow(a)) {
      var newIndex = getMaxIndex(a) + 1;
      a[newIndex] = b2;
      setMaxIndex(a, newIndex);
      return a;
    }
    var result = [].concat(a, b2);
    if (result.length > arrayLimit) {
      return markOverflow(arrayToObject2(result, { plainObjects }), result.length - 1);
    }
    return result;
  };
  var maybeMap = function maybeMap2(val, fn) {
    if (isArray2(val)) {
      var mapped = [];
      for (var i = 0; i < val.length; i += 1) {
        mapped[mapped.length] = fn(val[i]);
      }
      return mapped;
    }
    return fn(val);
  };
  utils = {
    arrayToObject: arrayToObject2,
    assign,
    combine,
    compact,
    decode: decode2,
    encode: encode2,
    isBuffer: isBuffer2,
    isOverflow,
    isRegExp: isRegExp2,
    markOverflow,
    maybeMap,
    merge: merge2
  };
  return utils;
}
var stringify_1;
var hasRequiredStringify;
function requireStringify() {
  if (hasRequiredStringify) return stringify_1;
  hasRequiredStringify = 1;
  var getSideChannel = requireSideChannel();
  var utils2 = /* @__PURE__ */ requireUtils();
  var formats2 = /* @__PURE__ */ requireFormats();
  var has = Object.prototype.hasOwnProperty;
  var arrayPrefixGenerators = {
    brackets: function brackets(prefix) {
      return prefix + "[]";
    },
    comma: "comma",
    indices: function indices(prefix, key) {
      return prefix + "[" + key + "]";
    },
    repeat: function repeat(prefix) {
      return prefix;
    }
  };
  var isArray2 = Array.isArray;
  var push2 = Array.prototype.push;
  var pushToArray = function(arr, valueOrArray) {
    push2.apply(arr, isArray2(valueOrArray) ? valueOrArray : [valueOrArray]);
  };
  var toISO = Date.prototype.toISOString;
  var defaultFormat = formats2["default"];
  var defaults2 = {
    addQueryPrefix: false,
    allowDots: false,
    allowEmptyArrays: false,
    arrayFormat: "indices",
    charset: "utf-8",
    charsetSentinel: false,
    commaRoundTrip: false,
    delimiter: "&",
    encode: true,
    encodeDotInKeys: false,
    encoder: utils2.encode,
    encodeValuesOnly: false,
    filter: void 0,
    format: defaultFormat,
    formatter: formats2.formatters[defaultFormat],
    // deprecated
    indices: false,
    serializeDate: function serializeDate(date) {
      return toISO.call(date);
    },
    skipNulls: false,
    strictNullHandling: false
  };
  var isNonNullishPrimitive = function isNonNullishPrimitive2(v2) {
    return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean" || typeof v2 === "symbol" || typeof v2 === "bigint";
  };
  var sentinel = {};
  var stringify2 = function stringify3(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter2, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel2) {
    var obj = object;
    var tmpSc = sideChannel2;
    var step = 0;
    var findFlag = false;
    while ((tmpSc = tmpSc.get(sentinel)) !== void 0 && !findFlag) {
      var pos = tmpSc.get(object);
      step += 1;
      if (typeof pos !== "undefined") {
        if (pos === step) {
          throw new RangeError("Cyclic object value");
        } else {
          findFlag = true;
        }
      }
      if (typeof tmpSc.get(sentinel) === "undefined") {
        step = 0;
      }
    }
    if (typeof filter2 === "function") {
      obj = filter2(prefix, obj);
    } else if (obj instanceof Date) {
      obj = serializeDate(obj);
    } else if (generateArrayPrefix === "comma" && isArray2(obj)) {
      obj = utils2.maybeMap(obj, function(value2) {
        if (value2 instanceof Date) {
          return serializeDate(value2);
        }
        return value2;
      });
    }
    if (obj === null) {
      if (strictNullHandling) {
        return encoder && !encodeValuesOnly ? encoder(prefix, defaults2.encoder, charset, "key", format) : prefix;
      }
      obj = "";
    }
    if (isNonNullishPrimitive(obj) || utils2.isBuffer(obj)) {
      if (encoder) {
        var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults2.encoder, charset, "key", format);
        return [formatter(keyValue) + "=" + formatter(encoder(obj, defaults2.encoder, charset, "value", format))];
      }
      return [formatter(prefix) + "=" + formatter(String(obj))];
    }
    var values = [];
    if (typeof obj === "undefined") {
      return values;
    }
    var objKeys;
    if (generateArrayPrefix === "comma" && isArray2(obj)) {
      if (encodeValuesOnly && encoder) {
        obj = utils2.maybeMap(obj, encoder);
      }
      objKeys = [{ value: obj.length > 0 ? obj.join(",") || null : void 0 }];
    } else if (isArray2(filter2)) {
      objKeys = filter2;
    } else {
      var keys2 = Object.keys(obj);
      objKeys = sort ? keys2.sort(sort) : keys2;
    }
    var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, "%2E") : String(prefix);
    var adjustedPrefix = commaRoundTrip && isArray2(obj) && obj.length === 1 ? encodedPrefix + "[]" : encodedPrefix;
    if (allowEmptyArrays && isArray2(obj) && obj.length === 0) {
      return adjustedPrefix + "[]";
    }
    for (var j2 = 0; j2 < objKeys.length; ++j2) {
      var key = objKeys[j2];
      var value = typeof key === "object" && key && typeof key.value !== "undefined" ? key.value : obj[key];
      if (skipNulls && value === null) {
        continue;
      }
      var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, "%2E") : String(key);
      var keyPrefix = isArray2(obj) ? typeof generateArrayPrefix === "function" ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix : adjustedPrefix + (allowDots ? "." + encodedKey : "[" + encodedKey + "]");
      sideChannel2.set(object, step);
      var valueSideChannel = getSideChannel();
      valueSideChannel.set(sentinel, sideChannel2);
      pushToArray(values, stringify3(
        value,
        keyPrefix,
        generateArrayPrefix,
        commaRoundTrip,
        allowEmptyArrays,
        strictNullHandling,
        skipNulls,
        encodeDotInKeys,
        generateArrayPrefix === "comma" && encodeValuesOnly && isArray2(obj) ? null : encoder,
        filter2,
        sort,
        allowDots,
        serializeDate,
        format,
        formatter,
        encodeValuesOnly,
        charset,
        valueSideChannel
      ));
    }
    return values;
  };
  var normalizeStringifyOptions = function normalizeStringifyOptions2(opts) {
    if (!opts) {
      return defaults2;
    }
    if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
      throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
    }
    if (typeof opts.encodeDotInKeys !== "undefined" && typeof opts.encodeDotInKeys !== "boolean") {
      throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");
    }
    if (opts.encoder !== null && typeof opts.encoder !== "undefined" && typeof opts.encoder !== "function") {
      throw new TypeError("Encoder has to be a function.");
    }
    var charset = opts.charset || defaults2.charset;
    if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
      throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
    }
    var format = formats2["default"];
    if (typeof opts.format !== "undefined") {
      if (!has.call(formats2.formatters, opts.format)) {
        throw new TypeError("Unknown format option provided.");
      }
      format = opts.format;
    }
    var formatter = formats2.formatters[format];
    var filter2 = defaults2.filter;
    if (typeof opts.filter === "function" || isArray2(opts.filter)) {
      filter2 = opts.filter;
    }
    var arrayFormat;
    if (opts.arrayFormat in arrayPrefixGenerators) {
      arrayFormat = opts.arrayFormat;
    } else if ("indices" in opts) {
      arrayFormat = opts.indices ? "indices" : "repeat";
    } else {
      arrayFormat = defaults2.arrayFormat;
    }
    if ("commaRoundTrip" in opts && typeof opts.commaRoundTrip !== "boolean") {
      throw new TypeError("`commaRoundTrip` must be a boolean, or absent");
    }
    var allowDots = typeof opts.allowDots === "undefined" ? opts.encodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots;
    return {
      addQueryPrefix: typeof opts.addQueryPrefix === "boolean" ? opts.addQueryPrefix : defaults2.addQueryPrefix,
      allowDots,
      allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays,
      arrayFormat,
      charset,
      charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
      commaRoundTrip: !!opts.commaRoundTrip,
      delimiter: typeof opts.delimiter === "undefined" ? defaults2.delimiter : opts.delimiter,
      encode: typeof opts.encode === "boolean" ? opts.encode : defaults2.encode,
      encodeDotInKeys: typeof opts.encodeDotInKeys === "boolean" ? opts.encodeDotInKeys : defaults2.encodeDotInKeys,
      encoder: typeof opts.encoder === "function" ? opts.encoder : defaults2.encoder,
      encodeValuesOnly: typeof opts.encodeValuesOnly === "boolean" ? opts.encodeValuesOnly : defaults2.encodeValuesOnly,
      filter: filter2,
      format,
      formatter,
      serializeDate: typeof opts.serializeDate === "function" ? opts.serializeDate : defaults2.serializeDate,
      skipNulls: typeof opts.skipNulls === "boolean" ? opts.skipNulls : defaults2.skipNulls,
      sort: typeof opts.sort === "function" ? opts.sort : null,
      strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling
    };
  };
  stringify_1 = function(object, opts) {
    var obj = object;
    var options = normalizeStringifyOptions(opts);
    var objKeys;
    var filter2;
    if (typeof options.filter === "function") {
      filter2 = options.filter;
      obj = filter2("", obj);
    } else if (isArray2(options.filter)) {
      filter2 = options.filter;
      objKeys = filter2;
    }
    var keys2 = [];
    if (typeof obj !== "object" || obj === null) {
      return "";
    }
    var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat];
    var commaRoundTrip = generateArrayPrefix === "comma" && options.commaRoundTrip;
    if (!objKeys) {
      objKeys = Object.keys(obj);
    }
    if (options.sort) {
      objKeys.sort(options.sort);
    }
    var sideChannel2 = getSideChannel();
    for (var i = 0; i < objKeys.length; ++i) {
      var key = objKeys[i];
      var value = obj[key];
      if (options.skipNulls && value === null) {
        continue;
      }
      pushToArray(keys2, stringify2(
        value,
        key,
        generateArrayPrefix,
        commaRoundTrip,
        options.allowEmptyArrays,
        options.strictNullHandling,
        options.skipNulls,
        options.encodeDotInKeys,
        options.encode ? options.encoder : null,
        options.filter,
        options.sort,
        options.allowDots,
        options.serializeDate,
        options.format,
        options.formatter,
        options.encodeValuesOnly,
        options.charset,
        sideChannel2
      ));
    }
    var joined = keys2.join(options.delimiter);
    var prefix = options.addQueryPrefix === true ? "?" : "";
    if (options.charsetSentinel) {
      if (options.charset === "iso-8859-1") {
        prefix += "utf8=%26%2310003%3B&";
      } else {
        prefix += "utf8=%E2%9C%93&";
      }
    }
    return joined.length > 0 ? prefix + joined : "";
  };
  return stringify_1;
}
var parse$1;
var hasRequiredParse;
function requireParse() {
  if (hasRequiredParse) return parse$1;
  hasRequiredParse = 1;
  var utils2 = /* @__PURE__ */ requireUtils();
  var has = Object.prototype.hasOwnProperty;
  var isArray2 = Array.isArray;
  var defaults2 = {
    allowDots: false,
    allowEmptyArrays: false,
    allowPrototypes: false,
    allowSparse: false,
    arrayLimit: 20,
    charset: "utf-8",
    charsetSentinel: false,
    comma: false,
    decodeDotInKeys: false,
    decoder: utils2.decode,
    delimiter: "&",
    depth: 5,
    duplicates: "combine",
    ignoreQueryPrefix: false,
    interpretNumericEntities: false,
    parameterLimit: 1e3,
    parseArrays: true,
    plainObjects: false,
    strictDepth: false,
    strictMerge: true,
    strictNullHandling: false,
    throwOnLimitExceeded: false
  };
  var interpretNumericEntities = function(str) {
    return str.replace(/&#(\d+);/g, function($0, numberStr) {
      return String.fromCharCode(parseInt(numberStr, 10));
    });
  };
  var parseArrayValue = function(val, options, currentArrayLength) {
    if (val && typeof val === "string" && options.comma && val.indexOf(",") > -1) {
      return val.split(",");
    }
    if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) {
      throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
    }
    return val;
  };
  var isoSentinel = "utf8=%26%2310003%3B";
  var charsetSentinel = "utf8=%E2%9C%93";
  var parseValues = function parseQueryStringValues(str, options) {
    var obj = { __proto__: null };
    var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, "") : str;
    cleanStr = cleanStr.replace(/%5B/gi, "[").replace(/%5D/gi, "]");
    var limit = options.parameterLimit === Infinity ? void 0 : options.parameterLimit;
    var parts = cleanStr.split(
      options.delimiter,
      options.throwOnLimitExceeded ? limit + 1 : limit
    );
    if (options.throwOnLimitExceeded && parts.length > limit) {
      throw new RangeError("Parameter limit exceeded. Only " + limit + " parameter" + (limit === 1 ? "" : "s") + " allowed.");
    }
    var skipIndex = -1;
    var i;
    var charset = options.charset;
    if (options.charsetSentinel) {
      for (i = 0; i < parts.length; ++i) {
        if (parts[i].indexOf("utf8=") === 0) {
          if (parts[i] === charsetSentinel) {
            charset = "utf-8";
          } else if (parts[i] === isoSentinel) {
            charset = "iso-8859-1";
          }
          skipIndex = i;
          i = parts.length;
        }
      }
    }
    for (i = 0; i < parts.length; ++i) {
      if (i === skipIndex) {
        continue;
      }
      var part = parts[i];
      var bracketEqualsPos = part.indexOf("]=");
      var pos = bracketEqualsPos === -1 ? part.indexOf("=") : bracketEqualsPos + 1;
      var key;
      var val;
      if (pos === -1) {
        key = options.decoder(part, defaults2.decoder, charset, "key");
        val = options.strictNullHandling ? null : "";
      } else {
        key = options.decoder(part.slice(0, pos), defaults2.decoder, charset, "key");
        if (key !== null) {
          val = utils2.maybeMap(
            parseArrayValue(
              part.slice(pos + 1),
              options,
              isArray2(obj[key]) ? obj[key].length : 0
            ),
            function(encodedVal) {
              return options.decoder(encodedVal, defaults2.decoder, charset, "value");
            }
          );
        }
      }
      if (val && options.interpretNumericEntities && charset === "iso-8859-1") {
        val = interpretNumericEntities(String(val));
      }
      if (part.indexOf("[]=") > -1) {
        val = isArray2(val) ? [val] : val;
      }
      if (options.comma && isArray2(val) && val.length > options.arrayLimit) {
        if (options.throwOnLimitExceeded) {
          throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
        }
        val = utils2.combine([], val, options.arrayLimit, options.plainObjects);
      }
      if (key !== null) {
        var existing = has.call(obj, key);
        if (existing && (options.duplicates === "combine" || part.indexOf("[]=") > -1)) {
          obj[key] = utils2.combine(
            obj[key],
            val,
            options.arrayLimit,
            options.plainObjects
          );
        } else if (!existing || options.duplicates === "last") {
          obj[key] = val;
        }
      }
    }
    return obj;
  };
  var parseObject = function(chain, val, options, valuesParsed) {
    var currentArrayLength = 0;
    if (chain.length > 0 && chain[chain.length - 1] === "[]") {
      var parentKey = chain.slice(0, -1).join("");
      currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0;
    }
    var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength);
    for (var i = chain.length - 1; i >= 0; --i) {
      var obj;
      var root2 = chain[i];
      if (root2 === "[]" && options.parseArrays) {
        if (utils2.isOverflow(leaf)) {
          obj = leaf;
        } else {
          obj = options.allowEmptyArrays && (leaf === "" || options.strictNullHandling && leaf === null) ? [] : utils2.combine(
            [],
            leaf,
            options.arrayLimit,
            options.plainObjects
          );
        }
      } else {
        obj = options.plainObjects ? { __proto__: null } : {};
        var cleanRoot = root2.charAt(0) === "[" && root2.charAt(root2.length - 1) === "]" ? root2.slice(1, -1) : root2;
        var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot;
        var index2 = parseInt(decodedRoot, 10);
        var isValidArrayIndex = !isNaN(index2) && root2 !== decodedRoot && String(index2) === decodedRoot && index2 >= 0 && options.parseArrays;
        if (!options.parseArrays && decodedRoot === "") {
          obj = { 0: leaf };
        } else if (isValidArrayIndex && index2 < options.arrayLimit) {
          obj = [];
          obj[index2] = leaf;
        } else if (isValidArrayIndex && options.throwOnLimitExceeded) {
          throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
        } else if (isValidArrayIndex) {
          obj[index2] = leaf;
          utils2.markOverflow(obj, index2);
        } else if (decodedRoot !== "__proto__") {
          obj[decodedRoot] = leaf;
        }
      }
      leaf = obj;
    }
    return leaf;
  };
  var splitKeyIntoSegments = function splitKeyIntoSegments2(givenKey, options) {
    var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, "[$1]") : givenKey;
    if (options.depth <= 0) {
      if (!options.plainObjects && has.call(Object.prototype, key)) {
        if (!options.allowPrototypes) {
          return;
        }
      }
      return [key];
    }
    var brackets = /(\[[^[\]]*])/;
    var child = /(\[[^[\]]*])/g;
    var segment = brackets.exec(key);
    var parent = segment ? key.slice(0, segment.index) : key;
    var keys2 = [];
    if (parent) {
      if (!options.plainObjects && has.call(Object.prototype, parent)) {
        if (!options.allowPrototypes) {
          return;
        }
      }
      keys2[keys2.length] = parent;
    }
    var i = 0;
    while ((segment = child.exec(key)) !== null && i < options.depth) {
      i += 1;
      var segmentContent = segment[1].slice(1, -1);
      if (!options.plainObjects && has.call(Object.prototype, segmentContent)) {
        if (!options.allowPrototypes) {
          return;
        }
      }
      keys2[keys2.length] = segment[1];
    }
    if (segment) {
      if (options.strictDepth === true) {
        throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true");
      }
      keys2[keys2.length] = "[" + key.slice(segment.index) + "]";
    }
    return keys2;
  };
  var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {
    if (!givenKey) {
      return;
    }
    var keys2 = splitKeyIntoSegments(givenKey, options);
    if (!keys2) {
      return;
    }
    return parseObject(keys2, val, options, valuesParsed);
  };
  var normalizeParseOptions = function normalizeParseOptions2(opts) {
    if (!opts) {
      return defaults2;
    }
    if (typeof opts.allowEmptyArrays !== "undefined" && typeof opts.allowEmptyArrays !== "boolean") {
      throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");
    }
    if (typeof opts.decodeDotInKeys !== "undefined" && typeof opts.decodeDotInKeys !== "boolean") {
      throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");
    }
    if (opts.decoder !== null && typeof opts.decoder !== "undefined" && typeof opts.decoder !== "function") {
      throw new TypeError("Decoder has to be a function.");
    }
    if (typeof opts.charset !== "undefined" && opts.charset !== "utf-8" && opts.charset !== "iso-8859-1") {
      throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");
    }
    if (typeof opts.throwOnLimitExceeded !== "undefined" && typeof opts.throwOnLimitExceeded !== "boolean") {
      throw new TypeError("`throwOnLimitExceeded` option must be a boolean");
    }
    var charset = typeof opts.charset === "undefined" ? defaults2.charset : opts.charset;
    var duplicates = typeof opts.duplicates === "undefined" ? defaults2.duplicates : opts.duplicates;
    if (duplicates !== "combine" && duplicates !== "first" && duplicates !== "last") {
      throw new TypeError("The duplicates option must be either combine, first, or last");
    }
    var allowDots = typeof opts.allowDots === "undefined" ? opts.decodeDotInKeys === true ? true : defaults2.allowDots : !!opts.allowDots;
    return {
      allowDots,
      allowEmptyArrays: typeof opts.allowEmptyArrays === "boolean" ? !!opts.allowEmptyArrays : defaults2.allowEmptyArrays,
      allowPrototypes: typeof opts.allowPrototypes === "boolean" ? opts.allowPrototypes : defaults2.allowPrototypes,
      allowSparse: typeof opts.allowSparse === "boolean" ? opts.allowSparse : defaults2.allowSparse,
      arrayLimit: typeof opts.arrayLimit === "number" ? opts.arrayLimit : defaults2.arrayLimit,
      charset,
      charsetSentinel: typeof opts.charsetSentinel === "boolean" ? opts.charsetSentinel : defaults2.charsetSentinel,
      comma: typeof opts.comma === "boolean" ? opts.comma : defaults2.comma,
      decodeDotInKeys: typeof opts.decodeDotInKeys === "boolean" ? opts.decodeDotInKeys : defaults2.decodeDotInKeys,
      decoder: typeof opts.decoder === "function" ? opts.decoder : defaults2.decoder,
      delimiter: typeof opts.delimiter === "string" || utils2.isRegExp(opts.delimiter) ? opts.delimiter : defaults2.delimiter,
      // eslint-disable-next-line no-implicit-coercion, no-extra-parens
      depth: typeof opts.depth === "number" || opts.depth === false ? +opts.depth : defaults2.depth,
      duplicates,
      ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
      interpretNumericEntities: typeof opts.interpretNumericEntities === "boolean" ? opts.interpretNumericEntities : defaults2.interpretNumericEntities,
      parameterLimit: typeof opts.parameterLimit === "number" ? opts.parameterLimit : defaults2.parameterLimit,
      parseArrays: opts.parseArrays !== false,
      plainObjects: typeof opts.plainObjects === "boolean" ? opts.plainObjects : defaults2.plainObjects,
      strictDepth: typeof opts.strictDepth === "boolean" ? !!opts.strictDepth : defaults2.strictDepth,
      strictMerge: typeof opts.strictMerge === "boolean" ? !!opts.strictMerge : defaults2.strictMerge,
      strictNullHandling: typeof opts.strictNullHandling === "boolean" ? opts.strictNullHandling : defaults2.strictNullHandling,
      throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === "boolean" ? opts.throwOnLimitExceeded : false
    };
  };
  parse$1 = function(str, opts) {
    var options = normalizeParseOptions(opts);
    if (str === "" || str === null || typeof str === "undefined") {
      return options.plainObjects ? { __proto__: null } : {};
    }
    var tempObj = typeof str === "string" ? parseValues(str, options) : str;
    var obj = options.plainObjects ? { __proto__: null } : {};
    var keys2 = Object.keys(tempObj);
    for (var i = 0; i < keys2.length; ++i) {
      var key = keys2[i];
      var newObj = parseKeys(key, tempObj[key], options, typeof str === "string");
      obj = utils2.merge(obj, newObj, options);
    }
    if (options.allowSparse === true) {
      return obj;
    }
    return utils2.compact(obj);
  };
  return parse$1;
}
var lib;
var hasRequiredLib;
function requireLib() {
  if (hasRequiredLib) return lib;
  hasRequiredLib = 1;
  var stringify2 = /* @__PURE__ */ requireStringify();
  var parse2 = /* @__PURE__ */ requireParse();
  var formats2 = /* @__PURE__ */ requireFormats();
  lib = {
    formats: formats2,
    parse: parse2,
    stringify: stringify2
  };
  return lib;
}
var libExports = /* @__PURE__ */ requireLib();
var nprogress$1 = { exports: {} };
var nprogress = nprogress$1.exports;
var hasRequiredNprogress;
function requireNprogress() {
  if (hasRequiredNprogress) return nprogress$1.exports;
  hasRequiredNprogress = 1;
  (function(module, exports$1) {
    (function(root2, factory2) {
      {
        module.exports = factory2();
      }
    })(nprogress, function() {
      var NProgress = {};
      NProgress.version = "0.2.0";
      var Settings = NProgress.settings = {
        minimum: 0.08,
        easing: "ease",
        positionUsing: "",
        speed: 200,
        trickle: true,
        trickleRate: 0.02,
        trickleSpeed: 800,
        showSpinner: true,
        barSelector: '[role="bar"]',
        spinnerSelector: '[role="spinner"]',
        parent: "body",
        template: '<div class="bar" role="bar"><div class="peg"></div></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>'
      };
      NProgress.configure = function(options) {
        var key, value;
        for (key in options) {
          value = options[key];
          if (value !== void 0 && options.hasOwnProperty(key)) Settings[key] = value;
        }
        return this;
      };
      NProgress.status = null;
      NProgress.set = function(n) {
        var started = NProgress.isStarted();
        n = clamp2(n, Settings.minimum, 1);
        NProgress.status = n === 1 ? null : n;
        var progress = NProgress.render(!started), bar = progress.querySelector(Settings.barSelector), speed = Settings.speed, ease = Settings.easing;
        progress.offsetWidth;
        queue(function(next) {
          if (Settings.positionUsing === "") Settings.positionUsing = NProgress.getPositioningCSS();
          css(bar, barPositionCSS(n, speed, ease));
          if (n === 1) {
            css(progress, {
              transition: "none",
              opacity: 1
            });
            progress.offsetWidth;
            setTimeout(function() {
              css(progress, {
                transition: "all " + speed + "ms linear",
                opacity: 0
              });
              setTimeout(function() {
                NProgress.remove();
                next();
              }, speed);
            }, speed);
          } else {
            setTimeout(next, speed);
          }
        });
        return this;
      };
      NProgress.isStarted = function() {
        return typeof NProgress.status === "number";
      };
      NProgress.start = function() {
        if (!NProgress.status) NProgress.set(0);
        var work = function() {
          setTimeout(function() {
            if (!NProgress.status) return;
            NProgress.trickle();
            work();
          }, Settings.trickleSpeed);
        };
        if (Settings.trickle) work();
        return this;
      };
      NProgress.done = function(force) {
        if (!force && !NProgress.status) return this;
        return NProgress.inc(0.3 + 0.5 * Math.random()).set(1);
      };
      NProgress.inc = function(amount) {
        var n = NProgress.status;
        if (!n) {
          return NProgress.start();
        } else {
          if (typeof amount !== "number") {
            amount = (1 - n) * clamp2(Math.random() * n, 0.1, 0.95);
          }
          n = clamp2(n + amount, 0, 0.994);
          return NProgress.set(n);
        }
      };
      NProgress.trickle = function() {
        return NProgress.inc(Math.random() * Settings.trickleRate);
      };
      (function() {
        var initial = 0, current = 0;
        NProgress.promise = function($promise) {
          if (!$promise || $promise.state() === "resolved") {
            return this;
          }
          if (current === 0) {
            NProgress.start();
          }
          initial++;
          current++;
          $promise.always(function() {
            current--;
            if (current === 0) {
              initial = 0;
              NProgress.done();
            } else {
              NProgress.set((initial - current) / initial);
            }
          });
          return this;
        };
      })();
      NProgress.render = function(fromStart) {
        if (NProgress.isRendered()) return document.getElementById("nprogress");
        addClass(document.documentElement, "nprogress-busy");
        var progress = document.createElement("div");
        progress.id = "nprogress";
        progress.innerHTML = Settings.template;
        var bar = progress.querySelector(Settings.barSelector), perc = fromStart ? "-100" : toBarPerc(NProgress.status || 0), parent = document.querySelector(Settings.parent), spinner;
        css(bar, {
          transition: "all 0 linear",
          transform: "translate3d(" + perc + "%,0,0)"
        });
        if (!Settings.showSpinner) {
          spinner = progress.querySelector(Settings.spinnerSelector);
          spinner && removeElement(spinner);
        }
        if (parent != document.body) {
          addClass(parent, "nprogress-custom-parent");
        }
        parent.appendChild(progress);
        return progress;
      };
      NProgress.remove = function() {
        removeClass(document.documentElement, "nprogress-busy");
        removeClass(document.querySelector(Settings.parent), "nprogress-custom-parent");
        var progress = document.getElementById("nprogress");
        progress && removeElement(progress);
      };
      NProgress.isRendered = function() {
        return !!document.getElementById("nprogress");
      };
      NProgress.getPositioningCSS = function() {
        var bodyStyle = document.body.style;
        var vendorPrefix = "WebkitTransform" in bodyStyle ? "Webkit" : "MozTransform" in bodyStyle ? "Moz" : "msTransform" in bodyStyle ? "ms" : "OTransform" in bodyStyle ? "O" : "";
        if (vendorPrefix + "Perspective" in bodyStyle) {
          return "translate3d";
        } else if (vendorPrefix + "Transform" in bodyStyle) {
          return "translate";
        } else {
          return "margin";
        }
      };
      function clamp2(n, min2, max2) {
        if (n < min2) return min2;
        if (n > max2) return max2;
        return n;
      }
      function toBarPerc(n) {
        return (-1 + n) * 100;
      }
      function barPositionCSS(n, speed, ease) {
        var barCSS;
        if (Settings.positionUsing === "translate3d") {
          barCSS = { transform: "translate3d(" + toBarPerc(n) + "%,0,0)" };
        } else if (Settings.positionUsing === "translate") {
          barCSS = { transform: "translate(" + toBarPerc(n) + "%,0)" };
        } else {
          barCSS = { "margin-left": toBarPerc(n) + "%" };
        }
        barCSS.transition = "all " + speed + "ms " + ease;
        return barCSS;
      }
      var queue = /* @__PURE__ */ (function() {
        var pending = [];
        function next() {
          var fn = pending.shift();
          if (fn) {
            fn(next);
          }
        }
        return function(fn) {
          pending.push(fn);
          if (pending.length == 1) next();
        };
      })();
      var css = /* @__PURE__ */ (function() {
        var cssPrefixes = ["Webkit", "O", "Moz", "ms"], cssProps = {};
        function camelCase(string2) {
          return string2.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function(match, letter) {
            return letter.toUpperCase();
          });
        }
        function getVendorProp(name2) {
          var style = document.body.style;
          if (name2 in style) return name2;
          var i = cssPrefixes.length, capName = name2.charAt(0).toUpperCase() + name2.slice(1), vendorName;
          while (i--) {
            vendorName = cssPrefixes[i] + capName;
            if (vendorName in style) return vendorName;
          }
          return name2;
        }
        function getStyleProp(name2) {
          name2 = camelCase(name2);
          return cssProps[name2] || (cssProps[name2] = getVendorProp(name2));
        }
        function applyCss(element2, prop, value) {
          prop = getStyleProp(prop);
          element2.style[prop] = value;
        }
        return function(element2, properties) {
          var args = arguments, prop, value;
          if (args.length == 2) {
            for (prop in properties) {
              value = properties[prop];
              if (value !== void 0 && properties.hasOwnProperty(prop)) applyCss(element2, prop, value);
            }
          } else {
            applyCss(element2, args[1], args[2]);
          }
        };
      })();
      function hasClass(element2, name2) {
        var list2 = typeof element2 == "string" ? element2 : classList(element2);
        return list2.indexOf(" " + name2 + " ") >= 0;
      }
      function addClass(element2, name2) {
        var oldList = classList(element2), newList = oldList + name2;
        if (hasClass(oldList, name2)) return;
        element2.className = newList.substring(1);
      }
      function removeClass(element2, name2) {
        var oldList = classList(element2), newList;
        if (!hasClass(element2, name2)) return;
        newList = oldList.replace(" " + name2 + " ", " ");
        element2.className = newList.substring(1, newList.length - 1);
      }
      function classList(element2) {
        return (" " + (element2.className || "") + " ").replace(/\s+/gi, " ");
      }
      function removeElement(element2) {
        element2 && element2.parentNode && element2.parentNode.removeChild(element2);
      }
      return NProgress;
    });
  })(nprogress$1);
  return nprogress$1.exports;
}
var nprogressExports = requireNprogress();
const u = /* @__PURE__ */ getDefaultExportFromCjs(nprogressExports);
function T$1(t, e) {
  let i;
  return function(...r) {
    clearTimeout(i), i = setTimeout(() => t.apply(this, r), e);
  };
}
function f(t, e) {
  return document.dispatchEvent(new CustomEvent(`inertia:${t}`, e));
}
var H$2 = (t) => f("before", { cancelable: true, detail: { visit: t } }), q$1 = (t) => f("error", { detail: { errors: t } }), $$1 = (t) => f("exception", { cancelable: true, detail: { exception: t } }), N$2 = (t) => f("finish", { detail: { visit: t } }), W$2 = (t) => f("invalid", { cancelable: true, detail: { response: t } }), P$1 = (t) => f("navigate", { detail: { page: t } }), K$2 = (t) => f("progress", { detail: { progress: t } }), X$2 = (t) => f("start", { detail: { visit: t } }), B$1 = (t) => f("success", { detail: { page: t } });
function I$1(t) {
  return t instanceof File || t instanceof Blob || t instanceof FileList && t.length > 0 || t instanceof FormData && Array.from(t.values()).some((e) => I$1(e)) || typeof t == "object" && t !== null && Object.values(t).some((e) => I$1(e));
}
function k(t, e = new FormData(), i = null) {
  t = t || {};
  for (let r in t) Object.prototype.hasOwnProperty.call(t, r) && z$1(e, J$2(i, r), t[r]);
  return e;
}
function J$2(t, e) {
  return t ? t + "[" + e + "]" : e;
}
function z$1(t, e, i) {
  if (Array.isArray(i)) return Array.from(i.keys()).forEach((r) => z$1(t, J$2(e, r.toString()), i[r]));
  if (i instanceof Date) return t.append(e, i.toISOString());
  if (i instanceof File) return t.append(e, i, i.name);
  if (i instanceof Blob) return t.append(e, i);
  if (typeof i == "boolean") return t.append(e, i ? "1" : "0");
  if (typeof i == "string") return t.append(e, i);
  if (typeof i == "number") return t.append(e, `${i}`);
  if (i == null) return t.append(e, "");
  k(i, t, e);
}
var _$1 = { modal: null, listener: null, show(t) {
  typeof t == "object" && (t = `All Inertia requests must receive a valid Inertia response, however a plain JSON response was received.<hr>${JSON.stringify(t)}`);
  let e = document.createElement("html");
  e.innerHTML = t, e.querySelectorAll("a").forEach((r) => r.setAttribute("target", "_top")), this.modal = document.createElement("div"), this.modal.style.position = "fixed", this.modal.style.width = "100vw", this.modal.style.height = "100vh", this.modal.style.padding = "50px", this.modal.style.boxSizing = "border-box", this.modal.style.backgroundColor = "rgba(0, 0, 0, .6)", this.modal.style.zIndex = 2e5, this.modal.addEventListener("click", () => this.hide());
  let i = document.createElement("iframe");
  if (i.style.backgroundColor = "white", i.style.borderRadius = "5px", i.style.width = "100%", i.style.height = "100%", this.modal.appendChild(i), document.body.prepend(this.modal), document.body.style.overflow = "hidden", !i.contentWindow) throw new Error("iframe not yet ready.");
  i.contentWindow.document.open(), i.contentWindow.document.write(e.outerHTML), i.contentWindow.document.close(), this.listener = this.hideOnEscape.bind(this), document.addEventListener("keydown", this.listener);
}, hide() {
  this.modal.outerHTML = "", this.modal = null, document.body.style.overflow = "visible", document.removeEventListener("keydown", this.listener);
}, hideOnEscape(t) {
  t.keyCode === 27 && this.hide();
} };
function b$1(t) {
  return new URL(t.toString(), window.location.toString());
}
function D$1(t, e, i, r = "brackets") {
  let s2 = /^https?:\/\//.test(e.toString()), l3 = s2 || e.toString().startsWith("/"), h = !l3 && !e.toString().startsWith("#") && !e.toString().startsWith("?"), g2 = e.toString().includes("?") || t === "get" && Object.keys(i).length, m2 = e.toString().includes("#"), c = new URL(e.toString(), "http://localhost");
  return t === "get" && Object.keys(i).length && (c.search = libExports.stringify(oe$1(libExports.parse(c.search, { ignoreQueryPrefix: true }), i), { encodeValuesOnly: true, arrayFormat: r }), i = {}), [[s2 ? `${c.protocol}//${c.host}` : "", l3 ? c.pathname : "", h ? c.pathname.substring(1) : "", g2 ? c.search : "", m2 ? c.hash : ""].join(""), i];
}
function E$1(t) {
  return t = new URL(t.href), t.hash = "", t;
}
var C$1 = typeof window > "u", Y$1 = !C$1 && /CriOS/.test(window.navigator.userAgent), Z = (t) => {
  requestAnimationFrame(() => {
    requestAnimationFrame(t);
  });
}, F$1 = class F {
  constructor() {
    this.visitId = null;
  }
  init({ initialPage: e, resolveComponent: i, swapComponent: r }) {
    this.page = e, this.resolveComponent = i, this.swapComponent = r, this.setNavigationType(), this.clearRememberedStateOnReload(), this.isBackForwardVisit() ? this.handleBackForwardVisit(this.page) : this.isLocationVisit() ? this.handleLocationVisit(this.page) : this.handleInitialPageVisit(this.page), this.setupEventListeners();
  }
  setNavigationType() {
    this.navigationType = window.performance && window.performance.getEntriesByType && window.performance.getEntriesByType("navigation").length > 0 ? window.performance.getEntriesByType("navigation")[0].type : "navigate";
  }
  clearRememberedStateOnReload() {
    this.navigationType === "reload" && window.history.state?.rememberedState && delete window.history.state.rememberedState;
  }
  handleInitialPageVisit(e) {
    let i = window.location.hash;
    this.page.url.includes(i) || (this.page.url += i), this.setPage(e, { preserveScroll: true, preserveState: true }).then(() => P$1(e));
  }
  setupEventListeners() {
    window.addEventListener("popstate", this.handlePopstateEvent.bind(this)), document.addEventListener("scroll", T$1(this.handleScrollEvent.bind(this), 100), true);
  }
  scrollRegions() {
    return document.querySelectorAll("[scroll-region]");
  }
  handleScrollEvent(e) {
    typeof e.target.hasAttribute == "function" && e.target.hasAttribute("scroll-region") && this.saveScrollPositions();
  }
  saveScrollPositions() {
    this.replaceState({ ...this.page, scrollRegions: Array.from(this.scrollRegions()).map((e) => ({ top: e.scrollTop, left: e.scrollLeft })) });
  }
  resetScrollPositions() {
    Z(() => {
      window.scrollTo(0, 0), this.scrollRegions().forEach((e) => {
        typeof e.scrollTo == "function" ? e.scrollTo(0, 0) : (e.scrollTop = 0, e.scrollLeft = 0);
      }), this.saveScrollPositions(), window.location.hash && document.getElementById(window.location.hash.slice(1))?.scrollIntoView();
    });
  }
  restoreScrollPositions() {
    Z(() => {
      this.page.scrollRegions && this.scrollRegions().forEach((e, i) => {
        let r = this.page.scrollRegions[i];
        if (r) typeof e.scrollTo == "function" ? e.scrollTo(r.left, r.top) : (e.scrollTop = r.top, e.scrollLeft = r.left);
        else return;
      });
    });
  }
  isBackForwardVisit() {
    return window.history.state && this.navigationType === "back_forward";
  }
  handleBackForwardVisit(e) {
    window.history.state.version = e.version, this.setPage(window.history.state, { preserveScroll: true, preserveState: true }).then(() => {
      this.restoreScrollPositions(), P$1(e);
    });
  }
  locationVisit(e, i) {
    try {
      let r = { preserveScroll: i };
      window.sessionStorage.setItem("inertiaLocationVisit", JSON.stringify(r)), window.location.href = e.href, E$1(window.location).href === E$1(e).href && window.location.reload();
    } catch {
      return false;
    }
  }
  isLocationVisit() {
    try {
      return window.sessionStorage.getItem("inertiaLocationVisit") !== null;
    } catch {
      return false;
    }
  }
  handleLocationVisit(e) {
    let i = JSON.parse(window.sessionStorage.getItem("inertiaLocationVisit") || "");
    window.sessionStorage.removeItem("inertiaLocationVisit"), e.url += window.location.hash, e.rememberedState = window.history.state?.rememberedState ?? {}, e.scrollRegions = window.history.state?.scrollRegions ?? [], this.setPage(e, { preserveScroll: i.preserveScroll, preserveState: true }).then(() => {
      i.preserveScroll && this.restoreScrollPositions(), P$1(e);
    });
  }
  isLocationVisitResponse(e) {
    return !!(e && e.status === 409 && e.headers["x-inertia-location"]);
  }
  isInertiaResponse(e) {
    return !!e?.headers["x-inertia"];
  }
  createVisitId() {
    return this.visitId = {}, this.visitId;
  }
  cancelVisit(e, { cancelled: i = false, interrupted: r = false }) {
    e && !e.completed && !e.cancelled && !e.interrupted && (e.cancelToken.abort(), e.onCancel(), e.completed = false, e.cancelled = i, e.interrupted = r, N$2(e), e.onFinish(e));
  }
  finishVisit(e) {
    !e.cancelled && !e.interrupted && (e.completed = true, e.cancelled = false, e.interrupted = false, N$2(e), e.onFinish(e));
  }
  resolvePreserveOption(e, i) {
    return typeof e == "function" ? e(i) : e === "errors" ? Object.keys(i.props.errors || {}).length > 0 : e;
  }
  cancel() {
    this.activeVisit && this.cancelVisit(this.activeVisit, { cancelled: true });
  }
  visit(e, { method: i = "get", data: r = {}, replace: s2 = false, preserveScroll: l3 = false, preserveState: h = false, only: g2 = [], except: m2 = [], headers: c = {}, errorBag: o = "", forceFormData: v2 = false, onCancelToken: L2 = () => {
  }, onBefore: d2 = () => {
  }, onStart: p = () => {
  }, onProgress: x2 = () => {
  }, onFinish: y2 = () => {
  }, onCancel: ne = () => {
  }, onSuccess: U2 = () => {
  }, onError: G2 = () => {
  }, queryStringArrayFormat: A2 = "brackets" } = {}) {
    let S = typeof e == "string" ? b$1(e) : e;
    if ((I$1(r) || v2) && !(r instanceof FormData) && (r = k(r)), !(r instanceof FormData)) {
      let [n, a] = D$1(i, S, r, A2);
      S = b$1(n), r = a;
    }
    let R = { url: S, method: i, data: r, replace: s2, preserveScroll: l3, preserveState: h, only: g2, except: m2, headers: c, errorBag: o, forceFormData: v2, queryStringArrayFormat: A2, cancelled: false, completed: false, interrupted: false };
    if (d2(R) === false || !H$2(R)) return;
    this.activeVisit && this.cancelVisit(this.activeVisit, { interrupted: true }), this.saveScrollPositions();
    let M2 = this.createVisitId();
    this.activeVisit = { ...R, onCancelToken: L2, onBefore: d2, onStart: p, onProgress: x2, onFinish: y2, onCancel: ne, onSuccess: U2, onError: G2, queryStringArrayFormat: A2, cancelToken: new AbortController() }, L2({ cancel: () => {
      this.activeVisit && this.cancelVisit(this.activeVisit, { cancelled: true });
    } }), X$2(R), p(R);
    let j2 = !!(g2.length || m2.length);
    axios({ method: i, url: E$1(S).href, data: i === "get" ? {} : r, params: i === "get" ? r : {}, signal: this.activeVisit.cancelToken.signal, headers: { ...c, Accept: "text/html, application/xhtml+xml", "X-Requested-With": "XMLHttpRequest", "X-Inertia": true, ...j2 ? { "X-Inertia-Partial-Component": this.page.component } : {}, ...g2.length ? { "X-Inertia-Partial-Data": g2.join(",") } : {}, ...m2.length ? { "X-Inertia-Partial-Except": m2.join(",") } : {}, ...o && o.length ? { "X-Inertia-Error-Bag": o } : {}, ...this.page.version ? { "X-Inertia-Version": this.page.version } : {} }, onUploadProgress: (n) => {
      r instanceof FormData && (n.percentage = n.progress ? Math.round(n.progress * 100) : 0, K$2(n), x2(n));
    } }).then((n) => {
      if (!this.isInertiaResponse(n)) return Promise.reject({ response: n });
      let a = n.data;
      j2 && a.component === this.page.component && (a.props = { ...this.page.props, ...a.props }), l3 = this.resolvePreserveOption(l3, a), h = this.resolvePreserveOption(h, a), h && window.history.state?.rememberedState && a.component === this.page.component && (a.rememberedState = window.history.state.rememberedState);
      let w2 = S, V2 = b$1(a.url);
      return w2.hash && !V2.hash && E$1(w2).href === V2.href && (V2.hash = w2.hash, a.url = V2.href), this.setPage(a, { visitId: M2, replace: s2, preserveScroll: l3, preserveState: h });
    }).then(() => {
      let n = this.page.props.errors || {};
      if (Object.keys(n).length > 0) {
        let a = o ? n[o] ? n[o] : {} : n;
        return q$1(a), G2(a);
      }
      return B$1(this.page), U2(this.page);
    }).catch((n) => {
      if (this.isInertiaResponse(n.response)) return this.setPage(n.response.data, { visitId: M2 });
      if (this.isLocationVisitResponse(n.response)) {
        let a = b$1(n.response.headers["x-inertia-location"]), w2 = S;
        w2.hash && !a.hash && E$1(w2).href === a.href && (a.hash = w2.hash), this.locationVisit(a, l3 === true);
      } else if (n.response) W$2(n.response) && _$1.show(n.response.data);
      else return Promise.reject(n);
    }).then(() => {
      this.activeVisit && this.finishVisit(this.activeVisit);
    }).catch((n) => {
      if (!axios.isCancel(n)) {
        let a = $$1(n);
        if (this.activeVisit && this.finishVisit(this.activeVisit), a) return Promise.reject(n);
      }
    });
  }
  setPage(e, { visitId: i = this.createVisitId(), replace: r = false, preserveScroll: s2 = false, preserveState: l3 = false } = {}) {
    return Promise.resolve(this.resolveComponent(e.component)).then((h) => {
      i === this.visitId && (e.scrollRegions = this.page.scrollRegions || [], e.rememberedState = e.rememberedState || {}, r = r || b$1(e.url).href === window.location.href, r ? this.replaceState(e) : this.pushState(e), this.swapComponent({ component: h, page: e, preserveState: l3 }).then(() => {
        s2 ? this.restoreScrollPositions() : this.resetScrollPositions(), r || P$1(e);
      }));
    });
  }
  pushState(e) {
    this.page = e, Y$1 ? setTimeout(() => window.history.pushState(e, "", e.url)) : window.history.pushState(e, "", e.url);
  }
  replaceState(e) {
    this.page = e, Y$1 ? setTimeout(() => window.history.replaceState(e, "", e.url)) : window.history.replaceState(e, "", e.url);
  }
  handlePopstateEvent(e) {
    if (e.state !== null) {
      let i = e.state, r = this.createVisitId();
      Promise.resolve(this.resolveComponent(i.component)).then((s2) => {
        r === this.visitId && (this.page = i, this.swapComponent({ component: s2, page: i, preserveState: false }).then(() => {
          this.restoreScrollPositions(), P$1(i);
        }));
      });
    } else {
      let i = b$1(this.page.url);
      i.hash = window.location.hash, this.replaceState({ ...this.page, url: i.href }), this.resetScrollPositions();
    }
  }
  get(e, i = {}, r = {}) {
    return this.visit(e, { ...r, method: "get", data: i });
  }
  reload(e = {}) {
    return this.visit(window.location.href, { ...e, preserveScroll: true, preserveState: true });
  }
  replace(e, i = {}) {
    return console.warn(`Inertia.replace() has been deprecated and will be removed in a future release. Please use Inertia.${i.method ?? "get"}() instead.`), this.visit(e, { preserveState: true, ...i, replace: true });
  }
  post(e, i = {}, r = {}) {
    return this.visit(e, { preserveState: true, ...r, method: "post", data: i });
  }
  put(e, i = {}, r = {}) {
    return this.visit(e, { preserveState: true, ...r, method: "put", data: i });
  }
  patch(e, i = {}, r = {}) {
    return this.visit(e, { preserveState: true, ...r, method: "patch", data: i });
  }
  delete(e, i = {}) {
    return this.visit(e, { preserveState: true, ...i, method: "delete" });
  }
  remember(e, i = "default") {
    C$1 || this.replaceState({ ...this.page, rememberedState: { ...this.page?.rememberedState, [i]: e } });
  }
  restore(e = "default") {
    if (!C$1) return window.history.state?.rememberedState?.[e];
  }
  on(e, i) {
    if (C$1) return () => {
    };
    let r = (s2) => {
      let l3 = i(s2);
      s2.cancelable && !s2.defaultPrevented && l3 === false && s2.preventDefault();
    };
    return document.addEventListener(`inertia:${e}`, r), () => document.removeEventListener(`inertia:${e}`, r);
  }
};
var se$1 = { buildDOMElement(t) {
  let e = document.createElement("template");
  e.innerHTML = t;
  let i = e.content.firstChild;
  if (!t.startsWith("<script ")) return i;
  let r = document.createElement("script");
  return r.innerHTML = i.innerHTML, i.getAttributeNames().forEach((s2) => {
    r.setAttribute(s2, i.getAttribute(s2) || "");
  }), r;
}, isInertiaManagedElement(t) {
  return t.nodeType === Node.ELEMENT_NODE && t.getAttribute("inertia") !== null;
}, findMatchingElementIndex(t, e) {
  let i = t.getAttribute("inertia");
  return i !== null ? e.findIndex((r) => r.getAttribute("inertia") === i) : -1;
}, update: T$1(function(t) {
  let e = t.map((r) => this.buildDOMElement(r));
  Array.from(document.head.childNodes).filter((r) => this.isInertiaManagedElement(r)).forEach((r) => {
    let s2 = this.findMatchingElementIndex(r, e);
    if (s2 === -1) {
      r?.parentNode?.removeChild(r);
      return;
    }
    let l3 = e.splice(s2, 1)[0];
    l3 && !r.isEqualNode(l3) && r?.parentNode?.replaceChild(l3, r);
  }), e.forEach((r) => document.head.appendChild(r));
}, 1) };
function ee(t, e, i) {
  let r = {}, s2 = 0;
  function l3() {
    let o = s2 += 1;
    return r[o] = [], o.toString();
  }
  function h(o) {
    o === null || Object.keys(r).indexOf(o) === -1 || (delete r[o], c());
  }
  function g2(o, v2 = []) {
    o !== null && Object.keys(r).indexOf(o) > -1 && (r[o] = v2), c();
  }
  function m2() {
    let o = e(""), v2 = { ...o ? { title: `<title inertia="">${o}</title>` } : {} }, L2 = Object.values(r).reduce((d2, p) => d2.concat(p), []).reduce((d2, p) => {
      if (p.indexOf("<") === -1) return d2;
      if (p.indexOf("<title ") === 0) {
        let y2 = p.match(/(<title [^>]+>)(.*?)(<\/title>)/);
        return d2.title = y2 ? `${y2[1]}${e(y2[2])}${y2[3]}` : p, d2;
      }
      let x2 = p.match(/ inertia="[^"]+"/);
      return x2 ? d2[x2[0]] = p : d2[Object.keys(d2).length] = p, d2;
    }, v2);
    return Object.values(L2);
  }
  function c() {
    t ? i(m2()) : se$1.update(m2());
  }
  return c(), { forceUpdate: c, createProvider: function() {
    let o = l3();
    return { update: (v2) => g2(o, v2), disconnect: () => h(o) };
  } };
}
var te = null;
function ae$1(t) {
  document.addEventListener("inertia:start", le$1.bind(null, t)), document.addEventListener("inertia:progress", ce$1), document.addEventListener("inertia:finish", de$1);
}
function le$1(t) {
  te = setTimeout(() => u.start(), t);
}
function ce$1(t) {
  u.isStarted() && t.detail.progress?.percentage && u.set(Math.max(u.status, t.detail.progress.percentage / 100 * 0.9));
}
function de$1(t) {
  if (clearTimeout(te), u.isStarted()) t.detail.visit.completed ? u.done() : t.detail.visit.interrupted ? u.set(0) : t.detail.visit.cancelled && (u.done(), u.remove());
  else return;
}
function pe$1(t) {
  let e = document.createElement("style");
  e.type = "text/css", e.textContent = `
    #nprogress {
      pointer-events: none;
    }

    #nprogress .bar {
      background: ${t};

      position: fixed;
      z-index: 1031;
      top: 0;
      left: 0;

      width: 100%;
      height: 2px;
    }

    #nprogress .peg {
      display: block;
      position: absolute;
      right: 0px;
      width: 100px;
      height: 100%;
      box-shadow: 0 0 10px ${t}, 0 0 5px ${t};
      opacity: 1.0;

      -webkit-transform: rotate(3deg) translate(0px, -4px);
          -ms-transform: rotate(3deg) translate(0px, -4px);
              transform: rotate(3deg) translate(0px, -4px);
    }

    #nprogress .spinner {
      display: block;
      position: fixed;
      z-index: 1031;
      top: 15px;
      right: 15px;
    }

    #nprogress .spinner-icon {
      width: 18px;
      height: 18px;
      box-sizing: border-box;

      border: solid 2px transparent;
      border-top-color: ${t};
      border-left-color: ${t};
      border-radius: 50%;

      -webkit-animation: nprogress-spinner 400ms linear infinite;
              animation: nprogress-spinner 400ms linear infinite;
    }

    .nprogress-custom-parent {
      overflow: hidden;
      position: relative;
    }

    .nprogress-custom-parent #nprogress .spinner,
    .nprogress-custom-parent #nprogress .bar {
      position: absolute;
    }

    @-webkit-keyframes nprogress-spinner {
      0%   { -webkit-transform: rotate(0deg); }
      100% { -webkit-transform: rotate(360deg); }
    }
    @keyframes nprogress-spinner {
      0%   { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  `, document.head.appendChild(e);
}
function ie$1({ delay: t = 250, color: e = "#29d", includeCSS: i = true, showSpinner: r = false } = {}) {
  ae$1(t), u.configure({ showSpinner: r }), i && pe$1(e);
}
function re$2(t) {
  let e = t.currentTarget.tagName.toLowerCase() === "a";
  return !(t.target && (t?.target).isContentEditable || t.defaultPrevented || e && t.altKey || e && t.ctrlKey || e && t.metaKey || e && t.shiftKey || e && "button" in t && t.button !== 0);
}
var Ne$1 = new F$1();
var lodash_isequal = { exports: {} };
lodash_isequal.exports;
var hasRequiredLodash_isequal;
function requireLodash_isequal() {
  if (hasRequiredLodash_isequal) return lodash_isequal.exports;
  hasRequiredLodash_isequal = 1;
  (function(module, exports$1) {
    var LARGE_ARRAY_SIZE = 200;
    var HASH_UNDEFINED = "__lodash_hash_undefined__";
    var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
    var MAX_SAFE_INTEGER = 9007199254740991;
    var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]";
    var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
    var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
    var reIsHostCtor = /^\[object .+?Constructor\]$/;
    var reIsUint = /^(?:0|[1-9]\d*)$/;
    var typedArrayTags = {};
    typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
    typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
    var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root2 = freeGlobal || freeSelf || Function("return this")();
    var freeExports = exports$1 && !exports$1.nodeType && exports$1;
    var freeModule = freeExports && true && module && !module.nodeType && module;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal.process;
    var nodeUtil = (function() {
      try {
        return freeProcess && freeProcess.binding && freeProcess.binding("util");
      } catch (e) {
      }
    })();
    var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
    function arrayFilter(array, predicate) {
      var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
      while (++index2 < length) {
        var value = array[index2];
        if (predicate(value, index2, array)) {
          result[resIndex++] = value;
        }
      }
      return result;
    }
    function arrayPush(array, values) {
      var index2 = -1, length = values.length, offset = array.length;
      while (++index2 < length) {
        array[offset + index2] = values[index2];
      }
      return array;
    }
    function arraySome(array, predicate) {
      var index2 = -1, length = array == null ? 0 : array.length;
      while (++index2 < length) {
        if (predicate(array[index2], index2, array)) {
          return true;
        }
      }
      return false;
    }
    function baseTimes(n, iteratee) {
      var index2 = -1, result = Array(n);
      while (++index2 < n) {
        result[index2] = iteratee(index2);
      }
      return result;
    }
    function baseUnary(func) {
      return function(value) {
        return func(value);
      };
    }
    function cacheHas(cache, key) {
      return cache.has(key);
    }
    function getValue(object, key) {
      return object == null ? void 0 : object[key];
    }
    function mapToArray(map) {
      var index2 = -1, result = Array(map.size);
      map.forEach(function(value, key) {
        result[++index2] = [key, value];
      });
      return result;
    }
    function overArg(func, transform) {
      return function(arg) {
        return func(transform(arg));
      };
    }
    function setToArray(set) {
      var index2 = -1, result = Array(set.size);
      set.forEach(function(value) {
        result[++index2] = value;
      });
      return result;
    }
    var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype;
    var coreJsData = root2["__core-js_shared__"];
    var funcToString = funcProto.toString;
    var hasOwnProperty2 = objectProto.hasOwnProperty;
    var maskSrcKey = (function() {
      var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
      return uid ? "Symbol(src)_1." + uid : "";
    })();
    var nativeObjectToString = objectProto.toString;
    var reIsNative = RegExp(
      "^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
    );
    var Buffer2 = moduleExports ? root2.Buffer : void 0, Symbol2 = root2.Symbol, Uint8Array2 = root2.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice2 = arrayProto.splice, symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
    var nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0, nativeKeys = overArg(Object.keys, Object);
    var DataView2 = getNative(root2, "DataView"), Map2 = getNative(root2, "Map"), Promise2 = getNative(root2, "Promise"), Set2 = getNative(root2, "Set"), WeakMap2 = getNative(root2, "WeakMap"), nativeCreate = getNative(Object, "create");
    var dataViewCtorString = toSource(DataView2), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap2);
    var symbolProto = Symbol2 ? Symbol2.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
    function Hash(entries) {
      var index2 = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index2 < length) {
        var entry = entries[index2];
        this.set(entry[0], entry[1]);
      }
    }
    function hashClear() {
      this.__data__ = nativeCreate ? nativeCreate(null) : {};
      this.size = 0;
    }
    function hashDelete(key) {
      var result = this.has(key) && delete this.__data__[key];
      this.size -= result ? 1 : 0;
      return result;
    }
    function hashGet(key) {
      var data = this.__data__;
      if (nativeCreate) {
        var result = data[key];
        return result === HASH_UNDEFINED ? void 0 : result;
      }
      return hasOwnProperty2.call(data, key) ? data[key] : void 0;
    }
    function hashHas(key) {
      var data = this.__data__;
      return nativeCreate ? data[key] !== void 0 : hasOwnProperty2.call(data, key);
    }
    function hashSet(key, value) {
      var data = this.__data__;
      this.size += this.has(key) ? 0 : 1;
      data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
      return this;
    }
    Hash.prototype.clear = hashClear;
    Hash.prototype["delete"] = hashDelete;
    Hash.prototype.get = hashGet;
    Hash.prototype.has = hashHas;
    Hash.prototype.set = hashSet;
    function ListCache(entries) {
      var index2 = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index2 < length) {
        var entry = entries[index2];
        this.set(entry[0], entry[1]);
      }
    }
    function listCacheClear() {
      this.__data__ = [];
      this.size = 0;
    }
    function listCacheDelete(key) {
      var data = this.__data__, index2 = assocIndexOf(data, key);
      if (index2 < 0) {
        return false;
      }
      var lastIndex = data.length - 1;
      if (index2 == lastIndex) {
        data.pop();
      } else {
        splice2.call(data, index2, 1);
      }
      --this.size;
      return true;
    }
    function listCacheGet(key) {
      var data = this.__data__, index2 = assocIndexOf(data, key);
      return index2 < 0 ? void 0 : data[index2][1];
    }
    function listCacheHas(key) {
      return assocIndexOf(this.__data__, key) > -1;
    }
    function listCacheSet(key, value) {
      var data = this.__data__, index2 = assocIndexOf(data, key);
      if (index2 < 0) {
        ++this.size;
        data.push([key, value]);
      } else {
        data[index2][1] = value;
      }
      return this;
    }
    ListCache.prototype.clear = listCacheClear;
    ListCache.prototype["delete"] = listCacheDelete;
    ListCache.prototype.get = listCacheGet;
    ListCache.prototype.has = listCacheHas;
    ListCache.prototype.set = listCacheSet;
    function MapCache(entries) {
      var index2 = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index2 < length) {
        var entry = entries[index2];
        this.set(entry[0], entry[1]);
      }
    }
    function mapCacheClear() {
      this.size = 0;
      this.__data__ = {
        "hash": new Hash(),
        "map": new (Map2 || ListCache)(),
        "string": new Hash()
      };
    }
    function mapCacheDelete(key) {
      var result = getMapData(this, key)["delete"](key);
      this.size -= result ? 1 : 0;
      return result;
    }
    function mapCacheGet(key) {
      return getMapData(this, key).get(key);
    }
    function mapCacheHas(key) {
      return getMapData(this, key).has(key);
    }
    function mapCacheSet(key, value) {
      var data = getMapData(this, key), size = data.size;
      data.set(key, value);
      this.size += data.size == size ? 0 : 1;
      return this;
    }
    MapCache.prototype.clear = mapCacheClear;
    MapCache.prototype["delete"] = mapCacheDelete;
    MapCache.prototype.get = mapCacheGet;
    MapCache.prototype.has = mapCacheHas;
    MapCache.prototype.set = mapCacheSet;
    function SetCache(values) {
      var index2 = -1, length = values == null ? 0 : values.length;
      this.__data__ = new MapCache();
      while (++index2 < length) {
        this.add(values[index2]);
      }
    }
    function setCacheAdd(value) {
      this.__data__.set(value, HASH_UNDEFINED);
      return this;
    }
    function setCacheHas(value) {
      return this.__data__.has(value);
    }
    SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
    SetCache.prototype.has = setCacheHas;
    function Stack(entries) {
      var data = this.__data__ = new ListCache(entries);
      this.size = data.size;
    }
    function stackClear() {
      this.__data__ = new ListCache();
      this.size = 0;
    }
    function stackDelete(key) {
      var data = this.__data__, result = data["delete"](key);
      this.size = data.size;
      return result;
    }
    function stackGet(key) {
      return this.__data__.get(key);
    }
    function stackHas(key) {
      return this.__data__.has(key);
    }
    function stackSet(key, value) {
      var data = this.__data__;
      if (data instanceof ListCache) {
        var pairs = data.__data__;
        if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
          pairs.push([key, value]);
          this.size = ++data.size;
          return this;
        }
        data = this.__data__ = new MapCache(pairs);
      }
      data.set(key, value);
      this.size = data.size;
      return this;
    }
    Stack.prototype.clear = stackClear;
    Stack.prototype["delete"] = stackDelete;
    Stack.prototype.get = stackGet;
    Stack.prototype.has = stackHas;
    Stack.prototype.set = stackSet;
    function arrayLikeKeys(value, inherited) {
      var isArr = isArray2(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer2(value), isType = !isArr && !isArg && !isBuff && isTypedArray2(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
      for (var key in value) {
        if (hasOwnProperty2.call(value, key) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
        (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
        isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
        isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
        isIndex(key, length)))) {
          result.push(key);
        }
      }
      return result;
    }
    function assocIndexOf(array, key) {
      var length = array.length;
      while (length--) {
        if (eq(array[length][0], key)) {
          return length;
        }
      }
      return -1;
    }
    function baseGetAllKeys(object, keysFunc, symbolsFunc) {
      var result = keysFunc(object);
      return isArray2(object) ? result : arrayPush(result, symbolsFunc(object));
    }
    function baseGetTag(value) {
      if (value == null) {
        return value === void 0 ? undefinedTag : nullTag;
      }
      return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
    }
    function baseIsArguments(value) {
      return isObjectLike(value) && baseGetTag(value) == argsTag;
    }
    function baseIsEqual(value, other, bitmask, customizer, stack) {
      if (value === other) {
        return true;
      }
      if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
        return value !== value && other !== other;
      }
      return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
    }
    function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
      var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
      objTag = objTag == argsTag ? objectTag : objTag;
      othTag = othTag == argsTag ? objectTag : othTag;
      var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
      if (isSameTag && isBuffer2(object)) {
        if (!isBuffer2(other)) {
          return false;
        }
        objIsArr = true;
        objIsObj = false;
      }
      if (isSameTag && !objIsObj) {
        stack || (stack = new Stack());
        return objIsArr || isTypedArray2(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
      }
      if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
        var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__");
        if (objIsWrapped || othIsWrapped) {
          var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
          stack || (stack = new Stack());
          return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
        }
      }
      if (!isSameTag) {
        return false;
      }
      stack || (stack = new Stack());
      return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
    }
    function baseIsNative(value) {
      if (!isObject2(value) || isMasked(value)) {
        return false;
      }
      var pattern = isFunction2(value) ? reIsNative : reIsHostCtor;
      return pattern.test(toSource(value));
    }
    function baseIsTypedArray(value) {
      return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
    }
    function baseKeys(object) {
      if (!isPrototype(object)) {
        return nativeKeys(object);
      }
      var result = [];
      for (var key in Object(object)) {
        if (hasOwnProperty2.call(object, key) && key != "constructor") {
          result.push(key);
        }
      }
      return result;
    }
    function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
      if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
        return false;
      }
      var stacked = stack.get(array);
      if (stacked && stack.get(other)) {
        return stacked == other;
      }
      var index2 = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0;
      stack.set(array, other);
      stack.set(other, array);
      while (++index2 < arrLength) {
        var arrValue = array[index2], othValue = other[index2];
        if (customizer) {
          var compared = isPartial ? customizer(othValue, arrValue, index2, other, array, stack) : customizer(arrValue, othValue, index2, array, other, stack);
        }
        if (compared !== void 0) {
          if (compared) {
            continue;
          }
          result = false;
          break;
        }
        if (seen) {
          if (!arraySome(other, function(othValue2, othIndex) {
            if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
            result = false;
            break;
          }
        } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          result = false;
          break;
        }
      }
      stack["delete"](array);
      stack["delete"](other);
      return result;
    }
    function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
      switch (tag) {
        case dataViewTag:
          if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
            return false;
          }
          object = object.buffer;
          other = other.buffer;
        case arrayBufferTag:
          if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
            return false;
          }
          return true;
        case boolTag:
        case dateTag:
        case numberTag:
          return eq(+object, +other);
        case errorTag:
          return object.name == other.name && object.message == other.message;
        case regexpTag:
        case stringTag:
          return object == other + "";
        case mapTag:
          var convert2 = mapToArray;
        case setTag:
          var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
          convert2 || (convert2 = setToArray);
          if (object.size != other.size && !isPartial) {
            return false;
          }
          var stacked = stack.get(object);
          if (stacked) {
            return stacked == other;
          }
          bitmask |= COMPARE_UNORDERED_FLAG;
          stack.set(object, other);
          var result = equalArrays(convert2(object), convert2(other), bitmask, customizer, equalFunc, stack);
          stack["delete"](object);
          return result;
        case symbolTag:
          if (symbolValueOf) {
            return symbolValueOf.call(object) == symbolValueOf.call(other);
          }
      }
      return false;
    }
    function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
      if (objLength != othLength && !isPartial) {
        return false;
      }
      var index2 = objLength;
      while (index2--) {
        var key = objProps[index2];
        if (!(isPartial ? key in other : hasOwnProperty2.call(other, key))) {
          return false;
        }
      }
      var stacked = stack.get(object);
      if (stacked && stack.get(other)) {
        return stacked == other;
      }
      var result = true;
      stack.set(object, other);
      stack.set(other, object);
      var skipCtor = isPartial;
      while (++index2 < objLength) {
        key = objProps[index2];
        var objValue = object[key], othValue = other[key];
        if (customizer) {
          var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
        }
        if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
          result = false;
          break;
        }
        skipCtor || (skipCtor = key == "constructor");
      }
      if (result && !skipCtor) {
        var objCtor = object.constructor, othCtor = other.constructor;
        if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
          result = false;
        }
      }
      stack["delete"](object);
      stack["delete"](other);
      return result;
    }
    function getAllKeys(object) {
      return baseGetAllKeys(object, keys2, getSymbols);
    }
    function getMapData(map, key) {
      var data = map.__data__;
      return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
    }
    function getNative(object, key) {
      var value = getValue(object, key);
      return baseIsNative(value) ? value : void 0;
    }
    function getRawTag(value) {
      var isOwn = hasOwnProperty2.call(value, symToStringTag), tag = value[symToStringTag];
      try {
        value[symToStringTag] = void 0;
        var unmasked = true;
      } catch (e) {
      }
      var result = nativeObjectToString.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag] = tag;
        } else {
          delete value[symToStringTag];
        }
      }
      return result;
    }
    var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
      if (object == null) {
        return [];
      }
      object = Object(object);
      return arrayFilter(nativeGetSymbols(object), function(symbol) {
        return propertyIsEnumerable.call(object, symbol);
      });
    };
    var getTag = baseGetTag;
    if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
      getTag = function(value) {
        var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
        if (ctorString) {
          switch (ctorString) {
            case dataViewCtorString:
              return dataViewTag;
            case mapCtorString:
              return mapTag;
            case promiseCtorString:
              return promiseTag;
            case setCtorString:
              return setTag;
            case weakMapCtorString:
              return weakMapTag;
          }
        }
        return result;
      };
    }
    function isIndex(value, length) {
      length = length == null ? MAX_SAFE_INTEGER : length;
      return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
    }
    function isKeyable(value) {
      var type2 = typeof value;
      return type2 == "string" || type2 == "number" || type2 == "symbol" || type2 == "boolean" ? value !== "__proto__" : value === null;
    }
    function isMasked(func) {
      return !!maskSrcKey && maskSrcKey in func;
    }
    function isPrototype(value) {
      var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
      return value === proto;
    }
    function objectToString(value) {
      return nativeObjectToString.call(value);
    }
    function toSource(func) {
      if (func != null) {
        try {
          return funcToString.call(func);
        } catch (e) {
        }
        try {
          return func + "";
        } catch (e) {
        }
      }
      return "";
    }
    function eq(value, other) {
      return value === other || value !== value && other !== other;
    }
    var isArguments = baseIsArguments(/* @__PURE__ */ (function() {
      return arguments;
    })()) ? baseIsArguments : function(value) {
      return isObjectLike(value) && hasOwnProperty2.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
    };
    var isArray2 = Array.isArray;
    function isArrayLike(value) {
      return value != null && isLength(value.length) && !isFunction2(value);
    }
    var isBuffer2 = nativeIsBuffer || stubFalse;
    function isEqual(value, other) {
      return baseIsEqual(value, other);
    }
    function isFunction2(value) {
      if (!isObject2(value)) {
        return false;
      }
      var tag = baseGetTag(value);
      return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
    }
    function isLength(value) {
      return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
    }
    function isObject2(value) {
      var type2 = typeof value;
      return value != null && (type2 == "object" || type2 == "function");
    }
    function isObjectLike(value) {
      return value != null && typeof value == "object";
    }
    var isTypedArray2 = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
    function keys2(object) {
      return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
    }
    function stubArray() {
      return [];
    }
    function stubFalse() {
      return false;
    }
    module.exports = isEqual;
  })(lodash_isequal, lodash_isequal.exports);
  return lodash_isequal.exports;
}
var lodash_isequalExports = requireLodash_isequal();
const Ae$1 = /* @__PURE__ */ getDefaultExportFromCjs(lodash_isequalExports);
var V$1 = reactExports.createContext(void 0);
V$1.displayName = "InertiaHeadContext";
var M$1 = V$1;
var K$1 = reactExports.createContext(void 0);
K$1.displayName = "InertiaPageContext";
var H$1 = K$1;
function N$1({ children: l3, initialPage: p, initialComponent: a, resolveComponent: i, titleCallback: n, onHeadUpdate: F3 }) {
  let [d2, y2] = reactExports.useState({ component: a || null, page: p, key: null }), u2 = reactExports.useMemo(() => ee(typeof window > "u", n || ((c) => c), F3 || (() => {
  })), []);
  if (reactExports.useEffect(() => {
    Ne$1.init({ initialPage: p, resolveComponent: i, swapComponent: async ({ component: c, page: e, preserveState: s2 }) => {
      y2((r) => ({ component: c, page: e, key: s2 ? r.key : Date.now() }));
    } }), Ne$1.on("navigate", () => u2.forceUpdate());
  }, []), !d2.component) return reactExports.createElement(M$1.Provider, { value: u2 }, reactExports.createElement(H$1.Provider, { value: d2.page }, null));
  let f2 = l3 || (({ Component: c, props: e, key: s2 }) => {
    let r = reactExports.createElement(c, { key: s2, ...e });
    return typeof c.layout == "function" ? c.layout(r) : Array.isArray(c.layout) ? c.layout.concat(r).reverse().reduce((g2, T2) => reactExports.createElement(T2, { children: g2, ...e })) : r;
  });
  return reactExports.createElement(M$1.Provider, { value: u2 }, reactExports.createElement(H$1.Provider, { value: d2.page }, f2({ Component: d2.component, key: d2.key, props: d2.page.props })));
}
N$1.displayName = "Inertia";
async function W$1({ id: l3 = "app", resolve: p, setup: a, title: i, progress: n = {}, page: F3, render: d2 }) {
  let y2 = typeof window > "u", u2 = y2 ? null : document.getElementById(l3), f2 = F3 || JSON.parse(u2.dataset.page), c = (r) => Promise.resolve(p(r)).then((g2) => g2.default || g2), e = [], s2 = await c(f2.component).then((r) => a({ el: u2, App: N$1, props: { initialPage: f2, initialComponent: r, resolveComponent: c, titleCallback: i, onHeadUpdate: y2 ? (g2) => e = g2 : null } }));
  if (!y2 && n && ie$1(n), y2) {
    let r = await d2(reactExports.createElement("div", { id: l3, "data-page": JSON.stringify(f2) }, s2));
    return { head: e, body: r };
  }
}
var Te$1 = function({ children: l3, title: p }) {
  let a = reactExports.useContext(M$1), i = reactExports.useMemo(() => a.createProvider(), [a]);
  reactExports.useEffect(() => () => {
    i.disconnect();
  }, [i]);
  function n(e) {
    return ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"].indexOf(e.type) > -1;
  }
  function F3(e) {
    let s2 = Object.keys(e.props).reduce((r, g2) => {
      if (["head-key", "children", "dangerouslySetInnerHTML"].includes(g2)) return r;
      let T2 = e.props[g2];
      return T2 === "" ? r + ` ${g2}` : r + ` ${g2}="${T2}"`;
    }, "");
    return `<${e.type}${s2}>`;
  }
  function d2(e) {
    return typeof e.props.children == "string" ? e.props.children : e.props.children.reduce((s2, r) => s2 + y2(r), "");
  }
  function y2(e) {
    let s2 = F3(e);
    return e.props.children && (s2 += d2(e)), e.props.dangerouslySetInnerHTML && (s2 += e.props.dangerouslySetInnerHTML.__html), n(e) || (s2 += `</${e.type}>`), s2;
  }
  function u2(e) {
    return React.cloneElement(e, { inertia: e.props["head-key"] !== void 0 ? e.props["head-key"] : "" });
  }
  function f2(e) {
    return y2(u2(e));
  }
  function c(e) {
    let s2 = React.Children.toArray(e).filter((r) => r).map((r) => f2(r));
    return p && !s2.find((r) => r.startsWith("<title")) && s2.push(`<title inertia>${p}</title>`), s2;
  }
  return i.update(c(l3)), null;
}, Se$1 = Te$1;
var C = () => {
}, J$1 = reactExports.forwardRef(({ children: l3, as: p = "a", data: a = {}, href: i, method: n = "get", preserveScroll: F3 = false, preserveState: d2 = null, replace: y2 = false, only: u2 = [], except: f2 = [], headers: c = {}, queryStringArrayFormat: e = "brackets", onClick: s2 = C, onCancelToken: r = C, onBefore: g2 = C, onStart: T2 = C, onProgress: O2 = C, onFinish: k2 = C, onCancel: L2 = C, onSuccess: R = C, onError: B2 = C, ...I2 }, A2) => {
  let v2 = reactExports.useCallback((E2) => {
    s2(E2), re$2(E2) && (E2.preventDefault(), Ne$1.visit(i, { data: a, method: n, preserveScroll: F3, preserveState: d2 ?? n !== "get", replace: y2, only: u2, except: f2, headers: c, onCancelToken: r, onBefore: g2, onStart: T2, onProgress: O2, onFinish: k2, onCancel: L2, onSuccess: R, onError: B2 }));
  }, [a, i, n, F3, d2, y2, u2, f2, c, s2, r, g2, T2, O2, k2, L2, R, B2]);
  p = p.toLowerCase(), n = n.toLowerCase();
  let [j2, U2] = D$1(n, i || "", a, e);
  return i = j2, a = U2, p === "a" && n !== "get" && console.warn(`Creating POST/PUT/PATCH/DELETE <a> links is discouraged as it causes "Open Link in New Tab/Window" accessibility issues.

Please specify a more appropriate element using the "as" attribute. For example:

<Link href="${i}" method="${n}" as="button">...</Link>`), reactExports.createElement(p, { ...I2, ...p === "a" ? { href: i } : {}, ref: A2, onClick: v2 }, l3);
});
J$1.displayName = "InertiaLink";
var xe = J$1;
function w$1(l3, p) {
  let [a, i] = reactExports.useState(() => {
    let n = Ne$1.restore(p);
    return n !== void 0 ? n : l3;
  });
  return reactExports.useEffect(() => {
    Ne$1.remember(a, p);
  }, [a, p]), [a, i];
}
function G$1(l3, p) {
  let a = reactExports.useRef(null), i = typeof l3 == "string" ? l3 : null, [n, F3] = reactExports.useState((typeof l3 == "string" ? p : l3) || {}), d2 = reactExports.useRef(null), y2 = reactExports.useRef(null), [u2, f2] = i ? w$1(n, `${i}:data`) : reactExports.useState(n), [c, e] = i ? w$1({}, `${i}:errors`) : reactExports.useState({}), [s2, r] = reactExports.useState(false), [g2, T2] = reactExports.useState(false), [O2, k2] = reactExports.useState(null), [L2, R] = reactExports.useState(false), [B2, I2] = reactExports.useState(false), A2 = reactExports.useRef((o) => o);
  reactExports.useEffect(() => (a.current = true, () => {
    a.current = false;
  }), []);
  let v2 = reactExports.useCallback((o, P2, t = {}) => {
    let h = { ...t, onCancelToken: (m2) => {
      if (d2.current = m2, t.onCancelToken) return t.onCancelToken(m2);
    }, onBefore: (m2) => {
      if (R(false), I2(false), clearTimeout(y2.current), t.onBefore) return t.onBefore(m2);
    }, onStart: (m2) => {
      if (T2(true), t.onStart) return t.onStart(m2);
    }, onProgress: (m2) => {
      if (k2(m2), t.onProgress) return t.onProgress(m2);
    }, onSuccess: (m2) => {
      if (a.current && (T2(false), k2(null), e({}), r(false), R(true), I2(true), y2.current = setTimeout(() => {
        a.current && I2(false);
      }, 2e3)), t.onSuccess) return t.onSuccess(m2);
    }, onError: (m2) => {
      if (a.current && (T2(false), k2(null), e(m2), r(true)), t.onError) return t.onError(m2);
    }, onCancel: () => {
      if (a.current && (T2(false), k2(null)), t.onCancel) return t.onCancel();
    }, onFinish: () => {
      if (a.current && (T2(false), k2(null)), d2.current = null, t.onFinish) return t.onFinish();
    } };
    o === "delete" ? Ne$1.delete(P2, { ...h, data: A2.current(u2) }) : Ne$1[o](P2, A2.current(u2), h);
  }, [u2, e]), j2 = reactExports.useCallback((o, P2) => {
    f2(typeof o == "string" ? (t) => ({ ...t, [o]: P2 }) : typeof o == "function" ? (t) => o(t) : o);
  }, [f2]), U2 = reactExports.useCallback((o, P2) => {
    F3(typeof o > "u" ? () => u2 : (t) => ({ ...t, ...typeof o == "string" ? { [o]: P2 } : o }));
  }, [u2, F3]), E2 = reactExports.useCallback((...o) => {
    o.length === 0 ? f2(n) : f2((P2) => Object.keys(n).filter((t) => o.includes(t)).reduce((t, h) => (t[h] = n[h], t), { ...P2 }));
  }, [f2, n]), Y2 = reactExports.useCallback((o, P2) => {
    e((t) => {
      let h = { ...t, ...typeof o == "string" ? { [o]: P2 } : o };
      return r(Object.keys(h).length > 0), h;
    });
  }, [e, r]), Z2 = reactExports.useCallback((...o) => {
    e((P2) => {
      let t = Object.keys(P2).reduce((h, m2) => ({ ...h, ...o.length > 0 && !o.includes(m2) ? { [m2]: P2[m2] } : {} }), {});
      return r(Object.keys(t).length > 0), t;
    });
  }, [e, r]), D2 = (o) => (P2, t) => {
    v2(o, P2, t);
  }, ee2 = reactExports.useCallback(D2("get"), [v2]), te2 = reactExports.useCallback(D2("post"), [v2]), re2 = reactExports.useCallback(D2("put"), [v2]), oe2 = reactExports.useCallback(D2("patch"), [v2]), ne = reactExports.useCallback(D2("delete"), [v2]), ae2 = reactExports.useCallback(() => {
    d2.current && d2.current.cancel();
  }, []), se2 = reactExports.useCallback((o) => {
    A2.current = o;
  }, []);
  return { data: u2, setData: j2, isDirty: !Ae$1(u2, n), errors: c, hasErrors: s2, processing: g2, progress: O2, wasSuccessful: L2, recentlySuccessful: B2, transform: se2, setDefaults: U2, reset: E2, setError: Y2, clearErrors: Z2, submit: v2, get: ee2, post: te2, put: re2, patch: oe2, delete: ne, cancel: ae2 };
}
function X$1() {
  let l3 = reactExports.useContext(H$1);
  if (!l3) throw new Error("usePage must be used within the Inertia component");
  return l3;
}
var At = Ne$1;
const LABELS$2 = {
  free: "Free",
  creator: "Creator",
  pro: "Pro",
  admin: "Admin"
};
const CLASSES = {
  free: "border-white/12 bg-white/[0.06] text-slate-200",
  creator: "border-amber-300/25 bg-amber-300/12 text-amber-100",
  pro: "border-sky-300/25 bg-sky-300/12 text-sky-100",
  admin: "border-emerald-300/25 bg-emerald-300/12 text-emerald-100"
};
function AccessBadge({ tier = "free", className = "" }) {
  const normalizedTier = typeof tier === "string" ? tier.toLowerCase() : "free";
  const label = LABELS$2[normalizedTier] || "Free";
  const tone = CLASSES[normalizedTier] || CLASSES.free;
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] ${tone} ${className}`.trim() }, label);
}
function formatDate$j(iso) {
  if (!iso) return null;
  try {
    return new Date(iso).toLocaleDateString(void 0, { year: "numeric", month: "long", day: "numeric" });
  } catch {
    return null;
  }
}
function AcademyBillingAccount({ currentTier, isSubscribed, subscription, activePlan = null, links = {} }) {
  const endsAt = formatDate$j(subscription?.endsAt);
  const onGracePeriod = subscription?.onGracePeriod === true;
  const subscriptionActive = subscription?.active === true;
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.14),_transparent_26%),linear-gradient(180deg,_#07111f_0%,_#0f172a_45%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Academy Subscription" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1280px] space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[40px] border border-white/10 bg-[linear-gradient(135deg,rgba(7,17,31,0.95),rgba(12,24,45,0.9),rgba(15,23,42,0.96))] p-8 shadow-[0_32px_100px_rgba(2,6,23,0.42)] md:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-100/85" }, "Skinbase Academy"), /* @__PURE__ */ React.createElement(AccessBadge, { tier: currentTier })), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, isSubscribed ? "Your subscription" : "Academy subscription"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-base leading-8 text-slate-300" }, isSubscribed ? "Your Academy access is active. Manage, upgrade, or cancel your subscription here at any time." : "You are on the free Academy tier. Upgrade to Creator or Pro to unlock premium content.")), onGracePeriod && endsAt ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-amber-300/25 bg-amber-300/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-amber-100" }, "Your subscription was cancelled and will end on ", endsAt, "."), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-100/75" }, "You still have full access until that date. Open the subscription portal to resume your plan if you change your mind."), /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.portal,
      className: "mt-4 inline-flex items-center rounded-full border border-amber-300/30 bg-amber-300/12 px-5 py-2.5 text-sm font-semibold text-amber-100 transition hover:bg-amber-300/20"
    },
    "Resume subscription"
  )) : null, !isSubscribed ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[linear-gradient(135deg,rgba(8,47,73,0.92),rgba(30,41,59,0.94))] p-6 md:p-7" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-100/85" }, "Upgrade"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Choose a plan to get started"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-xl text-sm leading-7 text-slate-200/90" }, "Creator unlocks premium lessons and the full prompt library for €4.99/month. Pro gives you everything — all lessons, the advanced content track, and every new Academy drop — for €9.99/month."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.pricing || "/academy/pricing",
      className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18"
    },
    "See plans and pricing"
  ), /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.academy || "/academy",
      className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]"
    },
    "Back to Academy"
  ))) : null, isSubscribed ? /* @__PURE__ */ React.createElement("section", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-5 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 md:p-7" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Subscription details"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Active plan"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, activePlan?.label || "Academy plan"), activePlan?.price_display ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, activePlan.price_display, " / month") : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold capitalize text-white" }, onGracePeriod ? "Cancelling" : subscriptionActive ? "Active" : subscription?.status || "Active"), onGracePeriod && endsAt ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-amber-300/80" }, "Access ends ", endsAt) : null, !onGracePeriod && subscriptionActive ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-emerald-300/80" }, "Renews automatically") : null)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Your Academy access"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(AccessBadge, { tier: currentTier }), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-300" }, currentTier === "pro" ? "Full access to all Academy lessons and content." : currentTier === "creator" ? "Full access to all Creator lessons and prompts." : "Access to free Academy content.")))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-3 rounded-[32px] border border-white/10 bg-black/20 p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, "Manage"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6 text-slate-400" }, "Use the subscription portal to upgrade, downgrade, or cancel. Changes take effect at your next billing date."), /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.portal,
      className: "mt-2 inline-flex w-full items-center justify-center rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18"
    },
    "Upgrade, downgrade or cancel"
  ), /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.pricing || "/academy/pricing",
      className: "inline-flex w-full items-center justify-center rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]"
    },
    "Compare plans"
  ), /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.academy || "/academy",
      className: "inline-flex w-full items-center justify-center rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]"
    },
    "Go to Academy"
  ))) : null));
}
const __vite_glob_0_0 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyBillingAccount
}, Symbol.toStringTag, { value: "Module" }));
function AcademyBillingCancel({ message, links = {} }) {
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(251,191,36,0.14),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(148,163,184,0.14),_transparent_26%),linear-gradient(180deg,_#07111f_0%,_#0f172a_45%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Academy Billing Canceled" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[920px] space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[40px] border border-white/10 bg-[linear-gradient(135deg,rgba(7,17,31,0.95),rgba(12,24,45,0.9),rgba(67,20,7,0.78))] p-8 shadow-[0_32px_100px_rgba(2,6,23,0.42)] md:p-10" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-amber-100/85" }, "Checkout canceled"), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, "No payment was made."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-base leading-8 text-slate-300" }, message)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: links.pricing || "/academy/pricing", className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Return to pricing"), /* @__PURE__ */ React.createElement(xe, { href: links.academy || "/academy", className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]" }, "Back to Academy"))));
}
const __vite_glob_0_1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyBillingCancel
}, Symbol.toStringTag, { value: "Module" }));
function normalizeJsonLd(input) {
  if (!input) return [];
  return (Array.isArray(input) ? input : [input]).filter((schema) => schema && typeof schema === "object");
}
function SeoHead({ seo = {}, title = null, description = null, jsonLd = null }) {
  const metaTitle = seo?.title || title || "Skinbase";
  const metaDescription = seo?.description || description || "";
  const canonical = seo?.canonical || null;
  const robots = seo?.robots || null;
  const prev = seo?.prev || null;
  const next = seo?.next || null;
  const ogTitle = seo?.og_title || metaTitle;
  const ogDescription = seo?.og_description || metaDescription;
  const ogUrl = seo?.og_url || canonical;
  const ogType = seo?.og_type || "website";
  const ogImage = seo?.og_image || null;
  const keywords = seo?.keywords || null;
  const twitterCard = seo?.twitter_card || (ogImage ? "summary_large_image" : "summary");
  const twitterTitle = seo?.twitter_title || ogTitle;
  const twitterDescription = seo?.twitter_description || ogDescription;
  const twitterImage = seo?.twitter_image || ogImage || null;
  const schemas = [...normalizeJsonLd(seo?.json_ld), ...normalizeJsonLd(jsonLd)];
  return /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, metaTitle), metaDescription ? /* @__PURE__ */ React.createElement("meta", { "head-key": "description", name: "description", content: metaDescription }) : null, keywords ? /* @__PURE__ */ React.createElement("meta", { "head-key": "keywords", name: "keywords", content: keywords }) : null, robots ? /* @__PURE__ */ React.createElement("meta", { "head-key": "robots", name: "robots", content: robots }) : null, canonical ? /* @__PURE__ */ React.createElement("link", { "head-key": "canonical", rel: "canonical", href: canonical }) : null, prev ? /* @__PURE__ */ React.createElement("link", { "head-key": "prev", rel: "prev", href: prev }) : null, next ? /* @__PURE__ */ React.createElement("link", { "head-key": "next", rel: "next", href: next }) : null, /* @__PURE__ */ React.createElement("meta", { "head-key": "og:site_name", property: "og:site_name", content: seo?.og_site_name || "Skinbase" }), /* @__PURE__ */ React.createElement("meta", { "head-key": "og:type", property: "og:type", content: ogType }), /* @__PURE__ */ React.createElement("meta", { "head-key": "og:title", property: "og:title", content: ogTitle }), ogDescription ? /* @__PURE__ */ React.createElement("meta", { "head-key": "og:description", property: "og:description", content: ogDescription }) : null, ogUrl ? /* @__PURE__ */ React.createElement("meta", { "head-key": "og:url", property: "og:url", content: ogUrl }) : null, ogImage ? /* @__PURE__ */ React.createElement("meta", { "head-key": "og:image", property: "og:image", content: ogImage }) : null, seo?.og_image_alt ? /* @__PURE__ */ React.createElement("meta", { "head-key": "og:image:alt", property: "og:image:alt", content: seo.og_image_alt }) : null, seo?.og_image_width ? /* @__PURE__ */ React.createElement("meta", { "head-key": "og:image:width", property: "og:image:width", content: String(seo.og_image_width) }) : null, seo?.og_image_height ? /* @__PURE__ */ React.createElement("meta", { "head-key": "og:image:height", property: "og:image:height", content: String(seo.og_image_height) }) : null, /* @__PURE__ */ React.createElement("meta", { "head-key": "twitter:card", name: "twitter:card", content: twitterCard }), /* @__PURE__ */ React.createElement("meta", { "head-key": "twitter:title", name: "twitter:title", content: twitterTitle }), twitterDescription ? /* @__PURE__ */ React.createElement("meta", { "head-key": "twitter:description", name: "twitter:description", content: twitterDescription }) : null, twitterImage ? /* @__PURE__ */ React.createElement("meta", { "head-key": "twitter:image", name: "twitter:image", content: twitterImage }) : null, schemas.map((schema, index2) => {
    const schemaType = typeof schema?.["@type"] === "string" ? schema["@type"] : "schema";
    return /* @__PURE__ */ React.createElement(
      "script",
      {
        key: `jsonld-${schemaType}-${index2}`,
        "head-key": `jsonld-${schemaType}-${index2}`,
        type: "application/ld+json",
        dangerouslySetInnerHTML: { __html: JSON.stringify(schema) }
      }
    );
  }));
}
function ActionButton$1({ disabled, children, onClick, href, tone = "primary" }) {
  const toneClass = {
    primary: "border-sky-300/25 bg-sky-300/12 text-sky-100 hover:border-sky-300/40 hover:bg-sky-300/18",
    emerald: "border-emerald-300/25 bg-emerald-300/10 text-emerald-100 hover:bg-emerald-300/18",
    default: "border-white/10 bg-white/[0.05] text-white hover:border-white/20 hover:bg-white/[0.08]"
  }[tone] ?? "border-white/10 bg-white/[0.05] text-white hover:border-white/20 hover:bg-white/[0.08]";
  if (href) {
    return /* @__PURE__ */ React.createElement(xe, { href, className: `inline-flex w-full items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition ${toneClass}` }, children);
  }
  return /* @__PURE__ */ React.createElement("button", { type: "button", disabled, onClick, className: `inline-flex w-full items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-60 ${toneClass}` }, children);
}
function PlanCard({ product, selectedPlan, currentTier, isSubscribed, activePlanKey, billingEnabled, loginHref, manageHref, onCheckout }) {
  const activeTier = typeof currentTier === "string" ? currentTier.toLowerCase() : "free";
  const isActivePlan = selectedPlan?.key === activePlanKey;
  const isHigherTierCovered = activeTier === "pro" && product.tier === "creator";
  const isPlanReady = Boolean(selectedPlan?.configured && selectedPlan?.price_id_valid);
  const isSubscribedElsewhere = isSubscribed && !isActivePlan;
  return /* @__PURE__ */ React.createElement("article", { className: `relative overflow-hidden rounded-[32px] border p-6 transition md:p-7 ${isActivePlan ? "border-emerald-300/25 bg-[linear-gradient(180deg,rgba(16,185,129,0.1),rgba(15,23,42,0.96))] shadow-[0_28px_90px_rgba(5,150,105,0.14)]" : product.featured ? "border-sky-300/25 bg-[linear-gradient(180deg,rgba(14,165,233,0.12),rgba(15,23,42,0.96))] shadow-[0_28px_90px_rgba(2,132,199,0.14)]" : "border-white/10 bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-px bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.45),transparent)]" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, product.badge), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, product.name), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, product.description)), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-col items-end gap-2" }, isActivePlan ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/30 bg-emerald-300/14 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-100" }, "Your plan") : /* @__PURE__ */ React.createElement(AccessBadge, { tier: product.tier }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Monthly"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, selectedPlan?.price_display || "—"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Billed monthly · cancel anytime")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3 text-sm text-slate-300" }, product.features.map((feature) => /* @__PURE__ */ React.createElement("div", { key: feature, className: "flex items-start gap-2.5 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-px shrink-0 text-emerald-400" }, "✓"), /* @__PURE__ */ React.createElement("span", null, feature)))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, isActivePlan ? /* @__PURE__ */ React.createElement(ActionButton$1, { href: manageHref, tone: "emerald" }, "Manage subscription") : null, isSubscribedElsewhere && !isHigherTierCovered ? /* @__PURE__ */ React.createElement(ActionButton$1, { href: manageHref, tone: "default" }, "Switch to ", product.name) : null, isHigherTierCovered && !isActivePlan ? /* @__PURE__ */ React.createElement("p", { className: "text-center text-xs text-slate-500" }, "Included in your Pro plan") : null, !isSubscribed && loginHref ? /* @__PURE__ */ React.createElement(ActionButton$1, { href: loginHref, tone: "primary" }, billingEnabled ? `Get ${product.name}` : "Coming soon") : null, !isSubscribed && !loginHref ? /* @__PURE__ */ React.createElement(
    ActionButton$1,
    {
      disabled: !billingEnabled || !isPlanReady,
      onClick: () => onCheckout(selectedPlan),
      tone: "primary"
    },
    !billingEnabled ? "Coming soon" : isPlanReady ? `Get ${product.name} — ${selectedPlan?.price_display || ""}` : "Not available yet"
  ) : null));
}
const VISITOR_STORAGE_KEY$1 = "academy.analytics.visitor-id";
const VISITOR_COOKIE_NAME = "academy_visitor_id";
const ONCE_PREFIX = "academy.analytics.once:";
function getCsrfToken$k() {
  if (typeof document === "undefined") {
    return "";
  }
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function getCookieValue(name2) {
  if (typeof document === "undefined") {
    return "";
  }
  const match = document.cookie.match(new RegExp(`(?:^|; )${name2}=([^;]*)`));
  return match ? decodeURIComponent(match[1]) : "";
}
function generateVisitorId() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return `academy-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function ensureVisitorId() {
  if (typeof window === "undefined") {
    return null;
  }
  let visitorId = "";
  try {
    visitorId = window.localStorage.getItem(VISITOR_STORAGE_KEY$1) || "";
  } catch {
    visitorId = "";
  }
  if (!visitorId) {
    visitorId = getCookieValue(VISITOR_COOKIE_NAME);
  }
  if (!visitorId) {
    visitorId = generateVisitorId();
  }
  try {
    window.localStorage.setItem(VISITOR_STORAGE_KEY$1, visitorId);
  } catch {
  }
  if (typeof document !== "undefined") {
    document.cookie = `${VISITOR_COOKIE_NAME}=${encodeURIComponent(visitorId)}; path=/; max-age=31536000; SameSite=Lax`;
  }
  return visitorId;
}
function buildPayload$1(payload = {}) {
  return {
    ...payload,
    visitor_id: payload.visitor_id || ensureVisitorId(),
    url: payload.url || (typeof window !== "undefined" ? window.location.href : null),
    _token: payload._token || getCsrfToken$k()
  };
}
function markOnce(onceKey) {
  if (!onceKey || typeof window === "undefined") {
    return false;
  }
  const storageKey2 = `${ONCE_PREFIX}${onceKey}`;
  try {
    if (window.sessionStorage.getItem(storageKey2)) {
      return true;
    }
    window.sessionStorage.setItem(storageKey2, "1");
  } catch {
    return false;
  }
  return false;
}
async function postAcademyAction(url, payload = {}) {
  if (!url || typeof window === "undefined") {
    return null;
  }
  const response = await fetch(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest",
      "X-CSRF-TOKEN": getCsrfToken$k()
    },
    credentials: "same-origin",
    body: JSON.stringify(buildPayload$1(payload))
  }).catch(() => null);
  if (!response?.ok) {
    return null;
  }
  const responseContentType = response.headers.get("content-type") || "";
  if (!responseContentType.includes("application/json")) {
    return null;
  }
  return response.json().catch(() => null);
}
function trackAcademyEvent(eventType, contentType, contentId, metadata = {}, options = {}) {
  if (!eventType || !options?.url || typeof window === "undefined") {
    return Promise.resolve(false);
  }
  if (options.onceKey && markOnce(options.onceKey)) {
    return Promise.resolve(false);
  }
  const payload = buildPayload$1({
    event_type: eventType,
    content_type: contentType || null,
    content_id: contentId || null,
    metadata,
    route_name: options.pageName || null
  });
  const body2 = JSON.stringify(payload);
  if (options.useBeacon !== false && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
    try {
      const blob = new Blob([body2], { type: "application/json" });
      const queued = navigator.sendBeacon(options.url, blob);
      if (queued) {
        return Promise.resolve(true);
      }
    } catch {
    }
  }
  return fetch(options.url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest",
      "X-CSRF-TOKEN": getCsrfToken$k()
    },
    credentials: "same-origin",
    keepalive: options.keepalive === true,
    body: body2
  }).then(() => true).catch(() => false);
}
function normalizeAcademySearchQuery(query = "") {
  const normalizedWhitespace = String(query).trim().toLowerCase().replace(/\s+/g, " ");
  return normalizedWhitespace.replace(/[^a-z0-9\s\-_]+/g, "").trim();
}
function trackAcademySearchResultClick(analytics, search2, result) {
  if (!analytics?.eventUrl || !search2?.query || !result?.contentType || !result?.contentId) {
    return;
  }
  void trackAcademyEvent("academy_search_result_click", result.contentType, result.contentId, {
    query: search2.query,
    normalized_query: search2.normalizedQuery || normalizeAcademySearchQuery(search2.query),
    results_count: Number(search2.resultsCount || 0),
    position: result.position || null,
    source: result.source || "academy_search_results",
    filters: search2.filters || {}
  }, {
    url: analytics.eventUrl,
    pageName: analytics.pageName,
    keepalive: true
  });
}
function contentViewEventType(contentType) {
  if (contentType === "academy_lesson") return "academy_lesson_view";
  if (contentType === "academy_course") return "academy_course_view";
  if (contentType === "academy_prompt_pack") return "academy_prompt_pack_view";
  if (contentType === "academy_challenge") return "academy_challenge_view";
  return "academy_content_view";
}
function analyticsMetadata(analytics, extra = {}) {
  const metadata = analytics?.metadata && typeof analytics.metadata === "object" ? analytics.metadata : {};
  return {
    page_name: analytics?.pageName,
    ...metadata,
    ...extra
  };
}
function analyticsTrackingKey(analytics) {
  if (analytics?.trackingKey) {
    return String(analytics.trackingKey);
  }
  const metadata = analytics?.metadata && typeof analytics.metadata === "object" ? analytics.metadata : {};
  const pairs = Object.entries(metadata).filter(([, value]) => value !== void 0 && value !== null && value !== "").sort(([left], [right]) => left.localeCompare(right)).map(([key, value]) => `${key}:${String(value)}`);
  return pairs.join("|");
}
function trackUpgradeClick(analytics, metadata = {}) {
  if (!analytics?.eventUrl) {
    return;
  }
  void trackAcademyEvent("academy_upgrade_click", analytics?.contentType || "academy_upgrade", analytics?.contentId || null, metadata, {
    url: analytics.eventUrl,
    pageName: analytics.pageName,
    useBeacon: false
  });
}
function useAcademyPageAnalytics(analytics) {
  reactExports.useEffect(() => {
    if (!analytics?.enabled || !analytics?.eventUrl || typeof window === "undefined") {
      return void 0;
    }
    const trackingKey = analyticsTrackingKey(analytics);
    const baseKey = `${analytics.pageName || window.location.pathname}:${analytics.contentType || "page"}:${analytics.contentId || "none"}:${trackingKey || "default"}`;
    void trackAcademyEvent("academy_page_view", analytics.contentType || null, analytics.contentId || null, analyticsMetadata(analytics), {
      url: analytics.eventUrl,
      pageName: analytics.pageName,
      onceKey: `${baseKey}:page-view`
    });
    if (analytics.contentType || analytics.contentId) {
      void trackAcademyEvent(contentViewEventType(analytics.contentType), analytics.contentType || null, analytics.contentId || null, analyticsMetadata(analytics), {
        url: analytics.eventUrl,
        pageName: analytics.pageName,
        onceKey: `${baseKey}:content-view`
      });
    }
    if (analytics.isPremium && analytics.isLocked) {
      void trackAcademyEvent("academy_premium_preview_view", analytics.contentType || null, analytics.contentId || null, analyticsMetadata(analytics), {
        url: analytics.eventUrl,
        pageName: analytics.pageName,
        onceKey: `${baseKey}:premium-preview`
      });
    }
    const engagedTimer = window.setTimeout(() => {
      void trackAcademyEvent("academy_engaged_view", analytics.contentType || null, analytics.contentId || null, analyticsMetadata(analytics, {
        engaged_seconds: 15
      }), {
        url: analytics.eventUrl,
        pageName: analytics.pageName,
        onceKey: `${baseKey}:engaged`
      });
    }, 15e3);
    const sentMilestones = /* @__PURE__ */ new Set();
    const onScroll = () => {
      const doc = document.documentElement;
      const scrollable = Math.max(1, doc.scrollHeight - window.innerHeight);
      const percent = Math.min(100, Math.round(window.scrollY / scrollable * 100));
      [
        { threshold: 50, eventType: "academy_scroll_50" },
        { threshold: 75, eventType: "academy_scroll_75" },
        { threshold: 100, eventType: "academy_scroll_100" }
      ].forEach((milestone) => {
        if (percent < milestone.threshold || sentMilestones.has(milestone.threshold)) {
          return;
        }
        sentMilestones.add(milestone.threshold);
        void trackAcademyEvent(milestone.eventType, analytics.contentType || null, analytics.contentId || null, analyticsMetadata(analytics, {
          scroll_percent: milestone.threshold
        }), {
          url: analytics.eventUrl,
          pageName: analytics.pageName,
          onceKey: `${baseKey}:scroll-${milestone.threshold}`
        });
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      window.clearTimeout(engagedTimer);
      window.removeEventListener("scroll", onScroll);
    };
  }, [analytics?.contentId, analytics?.contentType, analytics?.enabled, analytics?.eventUrl, analytics?.isLocked, analytics?.isPremium, analytics?.pageName, analytics?.trackingKey, JSON.stringify(analytics?.metadata || {})]);
}
function getCsrfToken$j() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function heroText(currentTier, isSubscribed) {
  if (isSubscribed && currentTier === "pro") {
    return {
      heading: "You have full Academy access.",
      body: "All lessons, prompts, and Academy content are unlocked on your Pro plan. To upgrade, downgrade, or cancel, use the subscription manager below."
    };
  }
  if (isSubscribed && currentTier === "creator") {
    return {
      heading: "You're on the Creator plan.",
      body: "Creator content is fully unlocked. Upgrade to Pro anytime to access the advanced lesson track and everything new that launches at the Pro tier."
    };
  }
  if (currentTier === "admin") {
    return {
      heading: "Academy plans.",
      body: "Your admin account already has full Academy access. Browse the plans below."
    };
  }
  if (isSubscribed) {
    return {
      heading: "Manage your Academy subscription.",
      body: "Your plan is active. Review your options below or use the subscription manager to make changes."
    };
  }
  return {
    heading: "Unlock everything in Academy.",
    body: "Start free and upgrade when you're ready. Creator unlocks premium lessons and the full prompt library. Pro adds the advanced lesson track and is the highest Academy tier."
  };
}
function SidePanel({ currentTier, isSubscribed, activePlanLabel, activePlanPrice, manageHref }) {
  if (isSubscribed) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-emerald-300/20 bg-emerald-300/[0.06] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-emerald-200/80" }, "Your subscription"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] uppercase tracking-[0.16em] text-slate-500" }, "Active plan"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, activePlanLabel || "Academy plan")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] uppercase tracking-[0.16em] text-slate-500" }, "Billed monthly"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, activePlanPrice || "—"))), manageHref ? /* @__PURE__ */ React.createElement(xe, { href: manageHref, className: "mt-5 inline-flex w-full items-center justify-center rounded-full border border-emerald-300/30 bg-emerald-300/10 px-5 py-3 text-sm font-semibold text-emerald-100 transition hover:bg-emerald-300/18" }, "Manage subscription") : null);
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-black/20 p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Why upgrade?"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, [
    { title: "Instant access", body: "Subscription activates the moment payment is confirmed." },
    { title: "Cancel anytime", body: "No lock-in. Keep access until the end of the billing period." },
    { title: "Switch freely", body: "Move between Creator and Pro from your subscription manager." }
  ].map(({ title, body: body2 }) => /* @__PURE__ */ React.createElement("div", { key: title, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs leading-5 text-slate-400" }, body2)))));
}
function AcademyBillingPricing({ seo, billingEnabled, currentTier, isSubscribed, activePlanKey = null, activePlanLabel = null, catalog = [], links = {}, analytics }) {
  const { auth, errors, flash } = X$1().props;
  useAcademyPageAnalytics(analytics);
  const loginHref = auth?.user ? null : `${links.login || "/login"}?intended=${encodeURIComponent(links.pricing || "/academy/pricing")}`;
  const products = catalog.map((product) => ({
    ...product,
    selectedPlan: product.plans[0] || null
  }));
  const activePlanPrice = products.flatMap((p) => p.plans).find((p) => p?.key === activePlanKey)?.price_display || null;
  const handleCheckout = (plan) => {
    if (!plan?.key || !links.checkout) return;
    trackUpgradeClick(analytics, {
      source: "academy_billing_pricing",
      academy_plan: plan.key,
      academy_interval: plan.interval
    });
    const form = document.createElement("form");
    form.method = "POST";
    form.action = links.checkout;
    form.style.display = "none";
    const csrfInput = document.createElement("input");
    csrfInput.type = "hidden";
    csrfInput.name = "_token";
    csrfInput.value = getCsrfToken$j();
    const planInput = document.createElement("input");
    planInput.type = "hidden";
    planInput.name = "plan";
    planInput.value = plan.key;
    form.appendChild(csrfInput);
    form.appendChild(planInput);
    document.body.appendChild(form);
    form.submit();
  };
  const hero = heroText(currentTier, isSubscribed);
  const showFreeBadgeAsCurrentPlan = currentTier === "free" && !isSubscribed && auth?.user;
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(251,191,36,0.16),_transparent_22%),radial-gradient(circle_at_bottom_right,_rgba(56,189,248,0.18),_transparent_26%),linear-gradient(180deg,_#07111f_0%,_#0f172a_45%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: "Skinbase Academy — Plans & Pricing", description: seo?.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1380px] space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[40px] border border-white/10 bg-[linear-gradient(135deg,rgba(7,17,31,0.95),rgba(12,24,45,0.9),rgba(67,20,7,0.82))] p-8 shadow-[0_32px_100px_rgba(2,6,23,0.42)] md:p-10 lg:p-12" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_320px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-amber-200/85" }, "Skinbase Academy"), currentTier !== "free" ? /* @__PURE__ */ React.createElement(AccessBadge, { tier: currentTier }) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 max-w-3xl text-4xl font-semibold tracking-[-0.055em] text-white md:text-5xl xl:text-6xl" }, hero.heading), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-2xl text-base leading-8 text-slate-300 md:text-lg" }, hero.body), errors?.plan ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm font-medium text-rose-200" }, errors.plan) : null, flash?.error ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm font-medium text-rose-100" }, flash.error) : null, flash?.success ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm font-medium text-emerald-100" }, flash.success) : null), /* @__PURE__ */ React.createElement(
    SidePanel,
    {
      currentTier,
      isSubscribed,
      activePlanLabel,
      activePlanPrice,
      manageHref: links.billingAccount
    }
  ))), /* @__PURE__ */ React.createElement("section", { className: "grid gap-5 xl:grid-cols-[minmax(0,0.9fr)_1fr_1fr]" }, /* @__PURE__ */ React.createElement("article", { className: `rounded-[32px] border p-6 md:p-7 ${showFreeBadgeAsCurrentPlan ? "border-white/20 bg-white/[0.06]" : "border-white/10 bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Free"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, "Explorer")), showFreeBadgeAsCurrentPlan ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/20 bg-white/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, "Your plan") : /* @__PURE__ */ React.createElement(AccessBadge, { tier: "free" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-3xl font-semibold tracking-[-0.04em] text-white" }, "Free"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "No payment needed")), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, "Everything you need to explore Academy, follow public lessons, and see a preview of what the paid tiers include."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3 text-sm text-slate-300" }, [
    "Public lessons and Academy listings",
    "Prompt previews and public documentation",
    "Community access and updates",
    "Upgrade to Creator or Pro anytime"
  ].map((feature) => /* @__PURE__ */ React.createElement("div", { key: feature, className: "flex items-start gap-2.5 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-px shrink-0 text-slate-500" }, "✓"), /* @__PURE__ */ React.createElement("span", null, feature))))), products.map((product) => /* @__PURE__ */ React.createElement(
    PlanCard,
    {
      key: product.tier,
      product,
      selectedPlan: product.selectedPlan,
      currentTier,
      isSubscribed,
      activePlanKey,
      billingEnabled,
      loginHref,
      manageHref: links.billingAccount,
      onCheckout: handleCheckout
    }
  )))));
}
const __vite_glob_0_2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyBillingPricing
}, Symbol.toStringTag, { value: "Module" }));
function AcademyBillingSuccess({ currentTier, isSubscribed, links = {} }) {
  return /* @__PURE__ */ React.createElement("main", { className: "flex min-h-screen items-center bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(16,185,129,0.14),_transparent_24%),linear-gradient(180deg,_#07111f_0%,_#0f172a_45%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Subscription Confirmed" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto w-full max-w-[640px] space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[40px] border border-emerald-300/20 bg-[linear-gradient(135deg,rgba(7,17,31,0.95),rgba(12,24,45,0.92),rgba(6,78,59,0.82))] p-8 shadow-[0_32px_100px_rgba(2,6,23,0.42)] md:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-3xl leading-none" }, "🎉"), isSubscribed ? /* @__PURE__ */ React.createElement(AccessBadge, { tier: currentTier }) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, isSubscribed ? "Welcome to Academy." : "You're all set."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-lg text-base leading-8 text-slate-300" }, isSubscribed ? "Your subscription is active and all premium content for your plan is now unlocked. Head to Academy and start exploring." : "Your payment was confirmed and your subscription is activating now. This usually takes just a moment. If you don't see your access right away, refresh the Academy page in a few seconds.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.academy || "/academy",
      className: "rounded-full border border-emerald-300/25 bg-emerald-300/12 px-5 py-3 text-sm font-semibold text-emerald-100 transition hover:bg-emerald-300/18"
    },
    "Go to Academy"
  ), links.account ? /* @__PURE__ */ React.createElement(
    xe,
    {
      href: links.account,
      className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]"
    },
    "View my subscription"
  ) : null)));
}
const __vite_glob_0_3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyBillingSuccess
}, Symbol.toStringTag, { value: "Module" }));
function NovaSelect({
  options = [],
  value,
  onChange,
  multi = false,
  placeholder = "Select…",
  searchable = true,
  clearable = false,
  label,
  error,
  hint,
  required = false,
  disabled = false,
  renderOption,
  renderValue,
  id,
  className = "",
  searchPlaceholder = "Search…"
}) {
  const [open, setOpen] = reactExports.useState(false);
  const [search2, setSearch] = reactExports.useState("");
  const [highlighted, setHigh] = reactExports.useState(-1);
  const [dropPos, setDropPos] = reactExports.useState({ top: 0, left: 0, width: 300, openUp: false });
  const triggerRef = reactExports.useRef(null);
  const searchRef = reactExports.useRef(null);
  const listRef = reactExports.useRef(null);
  const inputId = id ?? (label ? `nova-select-${label.toLowerCase().replace(/\s+/g, "-")}` : "nova-select");
  const selected = reactExports.useMemo(() => {
    if (multi) return Array.isArray(value) ? value : value != null ? [value] : [];
    return value != null ? [value] : [];
  }, [value, multi]);
  const selectedSet = reactExports.useMemo(() => new Set(selected.map(String)), [selected]);
  const filtered = reactExports.useMemo(() => {
    const q2 = search2.toLowerCase();
    return options.filter((o) => !q2 || o.label.toLowerCase().includes(q2));
  }, [options, search2]);
  const measurePosition = reactExports.useCallback(() => {
    if (!triggerRef.current) return;
    const rect = triggerRef.current.getBoundingClientRect();
    const spaceBelow = window.innerHeight - rect.bottom;
    const spaceAbove = rect.top;
    const dropH = Math.min(280, filtered.length * 38 + 52);
    const openUp = spaceBelow < dropH + 8 && spaceAbove > spaceBelow;
    const padding = 8;
    const leftClamped = Math.max(padding, Math.min(rect.left, window.innerWidth - rect.width - padding));
    setDropPos({
      top: openUp ? rect.top - dropH - 4 : rect.bottom + 4,
      left: leftClamped,
      width: rect.width,
      openUp
    });
  }, [filtered.length]);
  const openDropdown = reactExports.useCallback(() => {
    if (disabled) return;
    measurePosition();
    setOpen(true);
    setHigh(-1);
  }, [disabled, measurePosition]);
  const closeDropdown = reactExports.useCallback(() => {
    setOpen(false);
    setSearch("");
    setHigh(-1);
  }, []);
  reactExports.useLayoutEffect(() => {
    if (open && searchable) {
      setTimeout(() => searchRef.current?.focus(), 0);
    }
  }, [open, searchable]);
  reactExports.useEffect(() => {
    if (!open) return;
    const onScroll = (e) => {
      const dropdown = document.getElementById(`nova-select-dropdown-${inputId}`);
      if (dropdown && dropdown.contains(e.target)) return;
      closeDropdown();
    };
    const onResize = () => closeDropdown();
    window.addEventListener("scroll", onScroll, true);
    window.addEventListener("resize", onResize);
    return () => {
      window.removeEventListener("scroll", onScroll, true);
      window.removeEventListener("resize", onResize);
    };
  }, [open, closeDropdown, inputId]);
  reactExports.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (!triggerRef.current?.contains(e.target) && !document.getElementById(`nova-select-dropdown-${inputId}`)?.contains(e.target)) {
        closeDropdown();
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open, closeDropdown, inputId]);
  reactExports.useEffect(() => {
    if (highlighted < 0 || !listRef.current) return;
    const item = listRef.current.querySelectorAll("[data-option]")[highlighted];
    item?.scrollIntoView({ block: "nearest" });
  }, [highlighted]);
  const selectOption = reactExports.useCallback((opt) => {
    if (opt.disabled) return;
    if (multi) {
      const exists = selectedSet.has(String(opt.value));
      onChange(exists ? selected.filter((v2) => String(v2) !== String(opt.value)) : [...selected, opt.value]);
      setSearch("");
      searchRef.current?.focus();
    } else {
      onChange(opt.value);
      closeDropdown();
      triggerRef.current?.focus();
    }
  }, [multi, selected, selectedSet, onChange, closeDropdown]);
  const clearValue = reactExports.useCallback((e) => {
    e.stopPropagation();
    onChange(multi ? [] : null);
  }, [multi, onChange]);
  const removeTag = reactExports.useCallback((val, e) => {
    e.stopPropagation();
    onChange(selected.filter((v2) => String(v2) !== String(val)));
  }, [selected, onChange]);
  const handleKeyDown2 = reactExports.useCallback((e) => {
    if (!open) {
      if (["ArrowDown", "ArrowUp", "Enter", " "].includes(e.key)) {
        e.preventDefault();
        openDropdown();
      }
      return;
    }
    switch (e.key) {
      case "ArrowDown":
        e.preventDefault();
        setHigh((h) => Math.min(h + 1, filtered.length - 1));
        break;
      case "ArrowUp":
        e.preventDefault();
        setHigh((h) => Math.max(h - 1, 0));
        break;
      case "Enter":
        e.preventDefault();
        if (highlighted >= 0 && filtered[highlighted]) selectOption(filtered[highlighted]);
        break;
      case "Escape":
        e.preventDefault();
        closeDropdown();
        triggerRef.current?.focus();
        break;
      case "Backspace":
        if (multi && !search2 && selected.length > 0) {
          onChange(selected.slice(0, -1));
        }
        break;
    }
  }, [open, filtered, highlighted, search2, multi, selected, selectOption, closeDropdown, openDropdown, onChange]);
  const optionMap = reactExports.useMemo(() => Object.fromEntries(options.map((o) => [String(o.value), o])), [options]);
  const labelMap = reactExports.useMemo(() => Object.fromEntries(options.map((o) => [String(o.value), o.label])), [options]);
  const hasValue = selected.length > 0;
  const selectedOption = !multi && hasValue ? optionMap[String(selected[0])] ?? null : null;
  const triggerClass = [
    "relative w-full flex items-center min-h-[42px] rounded-xl border px-3 py-1.5 gap-2 cursor-pointer",
    "bg-white/[0.06] text-sm text-white transition-all duration-150",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-0",
    error ? "border-red-500/60 focus-visible:ring-red-500/40" : open ? "border-accent/50 ring-2 ring-accent/40" : "border-white/12 hover:border-white/22",
    disabled ? "opacity-50 cursor-not-allowed pointer-events-none" : "",
    className
  ].join(" ");
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1.5" }, label && /* @__PURE__ */ React.createElement("label", { htmlFor: inputId, className: "text-sm font-medium text-white/85 select-none" }, label, required && /* @__PURE__ */ React.createElement("span", { className: "text-red-400 ml-1" }, "*")), /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: triggerRef,
      id: inputId,
      role: "combobox",
      "aria-expanded": open,
      "aria-haspopup": "listbox",
      "aria-label": label ?? placeholder,
      tabIndex: disabled ? -1 : 0,
      className: triggerClass,
      onClick: open ? closeDropdown : openDropdown,
      onKeyDown: handleKeyDown2
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-1 flex-1 min-w-0" }, multi && selected.map((v2) => /* @__PURE__ */ React.createElement(
      "span",
      {
        key: v2,
        className: "inline-flex items-center gap-1 h-6 px-2 rounded-md bg-accent/20 text-accent text-xs font-medium"
      },
      labelMap[String(v2)] ?? v2,
      /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          tabIndex: -1,
          onClick: (e) => removeTag(v2, e),
          className: "hover:text-white transition-colors",
          "aria-label": `Remove ${labelMap[String(v2)] ?? v2}`
        },
        /* @__PURE__ */ React.createElement("svg", { width: "8", height: "8", viewBox: "0 0 8 8", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M1 1l6 6M7 1L1 7", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }))
      )
    )), !multi && hasValue && (renderValue && selectedOption ? renderValue(selectedOption) : /* @__PURE__ */ React.createElement("span", { className: "truncate text-white" }, labelMap[String(selected[0])] ?? selected[0])), !hasValue && /* @__PURE__ */ React.createElement("span", { className: "text-slate-500 truncate" }, placeholder)),
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 shrink-0" }, clearable && hasValue && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        tabIndex: -1,
        onClick: clearValue,
        className: "w-5 h-5 flex items-center justify-center rounded text-slate-500 hover:text-white transition-colors",
        "aria-label": "Clear"
      },
      /* @__PURE__ */ React.createElement("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M1 1l8 8M9 1L1 9", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }))
    ), /* @__PURE__ */ React.createElement(
      "svg",
      {
        width: "12",
        height: "12",
        viewBox: "0 0 12 12",
        fill: "none",
        "aria-hidden": "true",
        className: `text-slate-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`
      },
      /* @__PURE__ */ React.createElement("path", { d: "M2 4l4 4 4-4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" })
    ))
  ), error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error), !error && hint && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, hint), open && reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        id: `nova-select-dropdown-${inputId}`,
        role: "listbox",
        "aria-multiselectable": multi,
        className: "fixed z-[500] flex flex-col rounded-xl border border-white/12 bg-nova-900/80 backdrop-blur-xl shadow-2xl shadow-black/50 overflow-hidden",
        style: { top: dropPos.top, left: dropPos.left, width: dropPos.width, maxHeight: 280 }
      },
      searchable && /* @__PURE__ */ React.createElement("div", { className: "px-2 pt-2 pb-1 border-b border-white/8" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
        "svg",
        {
          width: "12",
          height: "12",
          viewBox: "0 0 12 12",
          fill: "none",
          className: "absolute right-2.5 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none",
          "aria-hidden": "true"
        },
        /* @__PURE__ */ React.createElement("circle", { cx: "5", cy: "5", r: "3.5", stroke: "currentColor", strokeWidth: "1.5" }),
        /* @__PURE__ */ React.createElement("path", { d: "M8 8l2.5 2.5", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" })
      ), /* @__PURE__ */ React.createElement(
        "input",
        {
          ref: searchRef,
          type: "text",
          value: search2,
          onChange: (e) => {
            setSearch(e.target.value);
            setHigh(0);
          },
          onKeyDown: handleKeyDown2,
          placeholder: searchPlaceholder,
          className: "w-full pl-3 pr-7 py-1.5 rounded-lg bg-white/5 border border-white/8 text-white text-xs placeholder:text-slate-500 focus:outline-none focus:ring-1 focus:ring-accent/50",
          autoComplete: "off"
        }
      ))),
      /* @__PURE__ */ React.createElement("div", { ref: listRef, className: "overflow-y-auto flex-1 nova-scrollbar", style: { maxHeight: 220 } }, filtered.length === 0 ? /* @__PURE__ */ React.createElement("p", { className: "px-3 py-6 text-center text-xs text-slate-500" }, "No options found") : filtered.map((opt, idx) => {
        const isSelected = selectedSet.has(String(opt.value));
        const isHighlighted = idx === highlighted;
        const prevGroup = idx > 0 ? filtered[idx - 1].group : void 0;
        const showGroupHeader = opt.group != null && opt.group !== prevGroup;
        return /* @__PURE__ */ React.createElement(React.Fragment, { key: String(opt.value) }, showGroupHeader && /* @__PURE__ */ React.createElement("div", { className: `px-3 pt-2 pb-0.5 text-[10px] font-semibold text-slate-500 uppercase tracking-widest select-none${idx > 0 ? " border-t border-white/5" : ""}` }, opt.group), /* @__PURE__ */ React.createElement(
          "div",
          {
            "data-option": true,
            role: "option",
            "aria-selected": isSelected,
            "aria-disabled": opt.disabled,
            onClick: () => selectOption(opt),
            onMouseEnter: () => setHigh(idx),
            className: [
              "flex items-center gap-2.5 px-3 py-2 text-sm cursor-pointer transition-colors duration-75",
              opt.disabled ? "opacity-40 cursor-not-allowed" : "",
              isHighlighted ? "bg-white/[0.13]" : "hover:bg-white/[0.07]",
              isSelected ? "text-accent" : "text-white/85"
            ].join(" ")
          },
          multi && /* @__PURE__ */ React.createElement("span", { className: [
            "w-4 h-4 shrink-0 rounded border flex items-center justify-center transition-colors",
            isSelected ? "bg-accent border-accent" : "border-white/25 bg-white/5"
          ].join(" ") }, isSelected && /* @__PURE__ */ React.createElement("svg", { width: "9", height: "9", viewBox: "0 0 9 9", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M1.5 4.5l2 2 4-4", stroke: "white", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))),
          opt.icon && /* @__PURE__ */ React.createElement("span", { className: "shrink-0" }, opt.icon),
          renderOption ? renderOption(opt) : /* @__PURE__ */ React.createElement("span", { className: "flex-1 truncate" }, opt.label),
          !multi && isSelected && /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 12 12", fill: "none", className: "text-accent shrink-0", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M2 6l3 3 5-5", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))
        ));
      }))
    ),
    document.body
  ));
}
function AcademyChallengeSubmit({ seo, challenge, artworks, submitUrl }) {
  const form = G$1({
    artwork_id: artworks[0]?.id || "",
    prompt_used: "",
    workflow_notes: "",
    ai_tool_used: "",
    is_ai_generated: false,
    is_ai_assisted: true
  });
  const artworkOptions = artworks.map((artwork) => ({ value: artwork.id, label: artwork.title }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.15),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.16),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: `Submit to ${challenge.title}` }), /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: `Submit to ${challenge.title}`, description: challenge.excerpt || challenge.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[960px] space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[38px] border border-white/10 bg-black/20 p-8 md:p-10" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Academy challenge"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, "Submit to ", challenge.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-base leading-8 text-slate-300" }, "Attach one of your public artworks and optionally include the prompt or workflow notes used to create it.")), /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    form.post(submitUrl);
  }, className: "space-y-5 rounded-[30px] border border-white/10 bg-white/[0.04] p-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, "Artwork"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: form.data.artwork_id,
      onChange: (nextValue) => form.setData("artwork_id", nextValue || ""),
      options: artworkOptions,
      placeholder: "Select artwork",
      className: "mt-2 rounded-2xl bg-black/20"
    }
  ), form.errors.artwork_id ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-rose-300" }, form.errors.artwork_id) : null), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, "Prompt used"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.prompt_used, onChange: (event) => form.setData("prompt_used", event.target.value), rows: 5, className: "mt-2 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, "Workflow notes"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.workflow_notes, onChange: (event) => form.setData("workflow_notes", event.target.value), rows: 4, className: "mt-2 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, "AI tool used"), /* @__PURE__ */ React.createElement("input", { value: form.data.ai_tool_used, onChange: (event) => form.setData("ai_tool_used", event.target.value), className: "mt-2 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: form.data.is_ai_generated, onChange: (event) => form.setData("is_ai_generated", event.target.checked) }), " AI-generated"), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: form.data.is_ai_assisted, onChange: (event) => form.setData("is_ai_assisted", event.target.checked) }), " AI-assisted")), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Submitting..." : "Submit artwork"))));
}
const __vite_glob_0_4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyChallengeSubmit
}, Symbol.toStringTag, { value: "Module" }));
function Breadcrumbs$2({ items = [] }) {
  if (!items.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("nav", { "aria-label": "Breadcrumb", className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, items.map((item, index2) => {
    const isLast = index2 === items.length - 1;
    return /* @__PURE__ */ React.createElement(React.Fragment, { key: `${item.label}-${index2}` }, isLast ? /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, item.label) : /* @__PURE__ */ React.createElement(xe, { href: item.href, className: "transition hover:text-white" }, item.label), !isLast ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-600" }, "/") : null);
  }));
}
function formatAccessDate$2(value) {
  if (!value) {
    return null;
  }
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }
  return new Intl.DateTimeFormat(void 0, {
    year: "numeric",
    month: "short",
    day: "numeric"
  }).format(parsed);
}
function academyAccessHeading$2(access) {
  switch (access?.status) {
    case "staff_access":
      return "You currently have full staff access to the Academy.";
    case "grace_period":
      return `${access.tierLabel} access is still active.`;
    case "trialing":
      return `${access.tierLabel} trial is active right now.`;
    case "active":
      return access?.hasPaidAccess ? `${access.tierLabel} access is active.` : "Your Academy access is active.";
    case "free":
      return "You currently have Free access to the Academy.";
    default:
      return null;
  }
}
function academyAccessMeta$2(access) {
  if (!access?.signedIn) {
    return [];
  }
  const items = [
    { label: "Current tier", value: access?.tierLabel || "Free" },
    { label: "Status", value: access?.statusLabel || "Free access" }
  ];
  const formattedDate = formatAccessDate$2(access?.expiresAt);
  if (formattedDate && access?.dateLabel) {
    items.push({ label: access.dateLabel, value: formattedDate });
  } else if (access?.renewsAutomatically) {
    items.push({ label: "Billing", value: "Renews automatically" });
  } else if (!access?.hasPaidAccess) {
    items.push({ label: "Upgrade", value: "Creator and Pro unlock premium lessons and courses" });
  }
  return items;
}
function CourseCard({ course, analytics = null, searchContext = null, position: position2 = null }) {
  const progress = course?.progress || null;
  const cover = course?.cover_image_url || course?.teaser_image_url || course?.cover_image || course?.teaser_image || "";
  const trackSearchClick = () => {
    if (!searchContext?.query) {
      return;
    }
    trackAcademySearchResultClick(analytics, searchContext, {
      contentType: "academy_course",
      contentId: course?.id,
      position: position2
    });
  };
  return /* @__PURE__ */ React.createElement(
    xe,
    {
      href: course.public_url,
      onClick: trackSearchClick,
      "data-academy-content-type": searchContext?.query ? "academy_course" : void 0,
      "data-academy-content-id": searchContext?.query ? course?.id : void 0,
      "data-academy-search-query": searchContext?.query || void 0,
      "data-academy-search-results-count": searchContext?.resultsCount || void 0,
      "data-academy-search-position": position2 || void 0,
      className: "group overflow-hidden rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(7,11,18,0.96))] shadow-[0_20px_50px_rgba(2,6,23,0.18)] transition hover:border-amber-200/24 hover:bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(10,15,26,0.98))]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/10] overflow-hidden bg-[linear-gradient(135deg,rgba(251,191,36,0.18),rgba(17,24,39,0.94))]" }, cover ? /* @__PURE__ */ React.createElement("img", { src: cover, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.72))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, course?.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, course.difficulty) : null, course?.access_level ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, course.access_level) : null, course.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/15 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-4 left-4 right-4 flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, course?.lessons_count || 0, " lessons"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, course?.estimated_minutes ? `${course.estimated_minutes} min` : "Flexible pace")))),
    /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, "Academy course"), course?.subtitle ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, course.subtitle) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white transition group-hover:text-amber-50" }, course.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, course.excerpt || course.description || "Structured Academy course."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, progress ? `${progress.percent}% complete` : "Start fresh", course?.access_level ? ` · ${course.access_level}` : ""))
  );
}
function AcademyCoursesIndex({ seo, title, description, items, featuredCourses = [], filters = {}, pricingUrl, lessonsUrl, promptLibraryUrl, academyAccess = null, analytics }) {
  const flash = X$1().props.flash || {};
  useAcademyPageAnalytics(analytics);
  const breadcrumbs = [
    { label: "Academy", href: "/academy" },
    { label: "Courses", href: "/academy/courses" }
  ];
  const visibleItems = Array.isArray(items?.data) ? items.data : [];
  const totalCourses = Number(items?.total || items?.data?.length || 0);
  featuredCourses.length;
  const featuredCourse = featuredCourses.find((course) => course?.cover_image_url || course?.teaser_image_url || course?.cover_image || course?.teaser_image) || featuredCourses[0] || visibleItems[0] || null;
  const featuredCover = featuredCourse?.cover_image_url || featuredCourse?.teaser_image_url || featuredCourse?.cover_image || featuredCourse?.teaser_image || "";
  const showSignedInAccess = Boolean(academyAccess?.signedIn);
  const accessHeading = academyAccessHeading$2(academyAccess);
  const accessMeta = academyAccessMeta$2(academyAccess);
  const useBillingAction = showSignedInAccess && academyAccess?.hasPaidAccess && academyAccess?.billingUrl;
  const primaryActionLabel = useBillingAction ? academyAccess?.status === "grace_period" ? "Renew now" : "Manage billing" : "See plans";
  const primaryActionIcon = useBillingAction ? academyAccess?.status === "grace_period" ? "fa-solid fa-rotate-right" : "fa-solid fa-sliders" : "fa-solid fa-arrow-up-right-from-square";
  const primaryActionHref = useBillingAction ? academyAccess.billingUrl : pricingUrl;
  const searchContext = analytics?.search ? {
    query: analytics.search.query,
    normalizedQuery: analytics.search.normalizedQuery,
    resultsCount: analytics.search.resultsCount,
    filters
  } : null;
  const difficultyOptions = [
    { value: "", label: "All levels" },
    { value: "beginner", label: "Beginner" },
    { value: "intermediate", label: "Intermediate" },
    { value: "advanced", label: "Advanced" }
  ];
  const accessOptions = [
    { value: "", label: "All access" },
    { value: "free", label: "Free" },
    { value: "premium", label: "Premium" },
    { value: "mixed", label: "Mixed" }
  ];
  const handlePrimaryAction = () => {
    if (!useBillingAction) {
      trackUpgradeClick(analytics, { source: "academy_courses_index_hero_primary" });
    }
  };
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.16),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title, description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1400px] space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[40px] border border-amber-200/12 bg-[linear-gradient(155deg,rgba(251,191,36,0.14),rgba(15,23,42,0.96)_36%,rgba(14,165,233,0.14))] p-5 shadow-[0_32px_96px_rgba(2,6,23,0.32)] md:p-6 xl:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_14%,rgba(253,230,138,0.14),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,24px_24px,24px_24px] opacity-75" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -left-8 top-12 h-36 w-36 rounded-full bg-amber-300/18 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -right-10 bottom-0 h-40 w-40 rounded-full bg-sky-300/14 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement(Breadcrumbs$2, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-200/18 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-amber-50/90" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-200" }, "Courses"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, totalCourses, " guided paths")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, /* @__PURE__ */ React.createElement("h1", { className: "max-w-[13ch] text-4xl font-semibold tracking-[-0.05em] text-white md:max-w-[14ch] md:text-[4.2rem] xl:max-w-[15ch] xl:text-[4.5rem]" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-200/95" }, description)), /* @__PURE__ */ React.createElement("span", { className: "hidden h-20 w-20 shrink-0 items-center justify-center rounded-[26px] border border-white/10 bg-white/[0.04] text-2xl text-amber-50 shadow-[0_18px_40px_rgba(2,6,23,0.22)] md:flex" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-route" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100/75" }, "Library"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, totalCourses, " guided courses")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100/75" }, "Focus"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, "Sequenced learning + tracked completion"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-amber-50/90" }, "Structured progression"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-amber-50/90" }, "Tracked completion"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-amber-50/90" }, "Reusable lesson paths")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: lessonsUrl || "/academy/lessons", className: "inline-flex items-center gap-2 rounded-full border border-amber-200/26 bg-amber-300/12 px-5 py-3 text-sm font-semibold text-amber-50 transition hover:border-amber-200/36 hover:bg-amber-300/18" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open-reader text-xs" }), "Browse lessons"), /* @__PURE__ */ React.createElement(xe, { href: promptLibraryUrl || "/academy/prompts", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white/90 transition hover:bg-white/[0.1]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles text-xs" }), "Prompt library"), /* @__PURE__ */ React.createElement(xe, { href: primaryActionHref, onClick: handlePrimaryAction, className: "inline-flex items-center gap-2 rounded-full border border-sky-200/20 bg-sky-300/10 px-5 py-3 text-sm font-semibold text-sky-50 transition hover:border-sky-200/30 hover:bg-sky-300/16" }, /* @__PURE__ */ React.createElement("i", { className: `${primaryActionIcon} text-xs` }), primaryActionLabel))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-4 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Featured course"), featuredCourse?.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white/80" }, featuredCourse.difficulty) : null), /* @__PURE__ */ React.createElement(xe, { href: featuredCourse?.public_url || "#academy-courses-grid", className: "group mt-4 block overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04] transition hover:border-amber-200/24 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/10] overflow-hidden bg-[linear-gradient(135deg,rgba(251,191,36,0.18),rgba(17,24,39,0.94))]" }, featuredCover ? /* @__PURE__ */ React.createElement("img", { src: featuredCover, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.78))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, featuredCourse?.access_level ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, featuredCourse.access_level) : null, featuredCourse?.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, "Spotlight") : null)), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, featuredCourse?.subtitle || "Guided learning path"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold tracking-[-0.03em] text-white transition group-hover:text-amber-50" }, featuredCourse?.title || "Explore courses"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, featuredCourse?.excerpt || featuredCourse?.description || "Open a structured Academy course built from reusable lessons."))))), /* @__PURE__ */ React.createElement("div", { className: "xl:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-sky-300/20 bg-[linear-gradient(135deg,rgba(56,189,248,0.16),rgba(15,23,42,0.82))] p-4 shadow-[0_18px_45px_rgba(2,6,23,0.2)] md:p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-300/25 bg-sky-300/12 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-crown text-sm" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/80" }, showSignedInAccess ? "Your Academy access" : "Upgrade for full access"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-4xl text-lg font-semibold text-white md:text-[1.85rem] md:leading-[1.45]" }, showSignedInAccess ? accessHeading : "Unlock the full course library, premium lesson paths, and the broader Academy learning track."))), showSignedInAccess ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, accessMeta.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 md:px-5 md:py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/70" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white md:text-base" }, item.value)))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: primaryActionHref, onClick: handlePrimaryAction, className: "inline-flex items-center gap-2 rounded-full border border-sky-200/30 bg-sky-200/15 px-5 py-2.5 text-sm font-semibold text-sky-50 transition hover:bg-sky-200/22" }, /* @__PURE__ */ React.createElement("i", { className: `${primaryActionIcon} text-xs` }), primaryActionLabel), /* @__PURE__ */ React.createElement(xe, { href: lessonsUrl || "/academy/lessons", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-5 py-2.5 text-sm font-semibold text-white/90 transition hover:bg-white/[0.1]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open-reader text-xs" }), "Browse lessons")), academyAccess?.status === "grace_period" ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-sky-100/75" }, "Opens billing account to restore renewal before access ends.") : null)))), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, /* @__PURE__ */ React.createElement("section", { className: "grid gap-3 rounded-[30px] border border-white/10 bg-black/20 p-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Difficulty",
      value: filters?.difficulty || "",
      onChange: (nextValue) => At.get(window.location.pathname, { ...filters, difficulty: nextValue || void 0 }, { preserveScroll: true, preserveState: true }),
      options: difficultyOptions,
      searchable: false,
      className: "rounded-2xl bg-white/[0.04]"
    }
  ), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Access",
      value: filters?.access || "",
      onChange: (nextValue) => At.get(window.location.pathname, { ...filters, access: nextValue || void 0 }, { preserveScroll: true, preserveState: true }),
      options: accessOptions,
      searchable: false,
      className: "rounded-2xl bg-white/[0.04]"
    }
  )), visibleItems.length === 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-400" }, "No published Academy courses matched these filters.") : /* @__PURE__ */ React.createElement("section", { id: "academy-courses-grid", className: "grid gap-5 md:grid-cols-2 xl:grid-cols-3" }, visibleItems.map((course, index2) => /* @__PURE__ */ React.createElement(CourseCard, { key: course.id, course, analytics, searchContext, position: index2 + 1 })))));
}
const __vite_glob_0_5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyCoursesIndex
}, Symbol.toStringTag, { value: "Module" }));
function CourseBreadcrumbs({ items = [] }) {
  if (!items.length) return null;
  return /* @__PURE__ */ React.createElement("nav", { "aria-label": "Breadcrumb", className: "flex flex-wrap items-center gap-2 text-sm text-slate-400" }, items.map((item, index2) => {
    const isLast = index2 === items.length - 1;
    return /* @__PURE__ */ React.createElement(React.Fragment, { key: `${item.label}-${index2}` }, index2 > 0 ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-600" }, "/") : null, isLast ? /* @__PURE__ */ React.createElement("span", { className: "font-medium text-slate-200" }, item.label) : /* @__PURE__ */ React.createElement(xe, { href: item.href, className: "transition hover:text-white" }, item.label));
  }));
}
function ProgressMeter({ progress }) {
  const percent = Math.max(0, Math.min(100, Number(progress?.percent || 0)));
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72))] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Progress"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-3xl font-semibold tracking-[-0.04em] text-white" }, percent, "%")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, progress ? "In progress" : "Not started")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-2.5 overflow-hidden rounded-full bg-white/[0.06]" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "h-full rounded-full bg-[linear-gradient(90deg,rgba(125,211,252,0.95),rgba(251,191,36,0.9))] transition-[width] duration-500",
      style: { width: `${percent}%` }
    }
  )), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, progress ? `${progress.completedRequired}/${progress.totalRequired} required lessons completed` : "Start the course to begin tracking progress through required lessons."));
}
function LessonChip({ lesson }) {
  const thumbnail = lesson?.cover_image_url || lesson?.article_cover_image_url || lesson?.cover_image || lesson?.article_cover_image || "";
  const stepLabel = lesson?.course_step_label || null;
  const stepNumber = Number(lesson?.course_step_number || 0);
  const isCompleted = Boolean(lesson?.completed);
  const readingMinutes = Number(lesson?.reading_minutes || 0);
  const ctaLabel = isCompleted ? "Review lesson" : "Open lesson";
  const difficultyLabel = lesson?.difficulty || "lesson";
  const accessLabel = lesson?.access_level || "free";
  const lessonTypeLabel = lesson?.lesson_type || "article";
  const statusLabel2 = isCompleted ? "Completed" : lesson?.is_required ? "Required next" : "Optional read";
  const supportCopy = isCompleted ? "You already finished this lesson." : lesson?.is_required ? "Recommended as the next required step in this course." : "Optional depth you can take at your own pace.";
  return /* @__PURE__ */ React.createElement(
    xe,
    {
      href: lesson.course_url || `/academy/lessons/${lesson.slug}`,
      className: [
        "group relative overflow-hidden rounded-[34px] border bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(15,23,42,0.78))] shadow-[0_24px_54px_rgba(2,6,23,0.22)] transition duration-200 hover:-translate-y-1 hover:border-sky-300/30 hover:shadow-[0_28px_74px_rgba(14,165,233,0.16)]",
        isCompleted ? "border-emerald-300/25" : "border-white/10"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(125,211,252,0.12),transparent_24%),radial-gradient(circle_at_bottom_left,rgba(251,191,36,0.08),transparent_28%),linear-gradient(135deg,transparent,rgba(255,255,255,0.02))] opacity-80 transition duration-200 group-hover:opacity-100" }),
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-px bg-[linear-gradient(90deg,transparent,rgba(125,211,252,0.42),transparent)]" }),
    /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-0 lg:grid-cols-[188px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative border-b border-white/10 bg-slate-950/90 lg:border-b-0 lg:border-r lg:border-white/10" }, thumbnail ? /* @__PURE__ */ React.createElement("img", { src: thumbnail, alt: "", "aria-hidden": "true", className: "h-44 w-full object-cover lg:h-full" }) : /* @__PURE__ */ React.createElement("div", { className: "h-44 w-full bg-[linear-gradient(135deg,rgba(56,189,248,0.2),rgba(15,23,42,0.96))] lg:h-full" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.08),rgba(2,6,23,0.42)_42%,rgba(2,6,23,0.9))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-4 top-4 flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] backdrop-blur ${lesson.is_required ? "border-white/10 bg-black/40 text-white/82" : "border-white/10 bg-black/30 text-white/62"}` }, lesson.is_required ? "Required" : "Optional"), isCompleted ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-emerald-300/25 bg-emerald-300/12 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100 backdrop-blur" }, /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", className: "h-3.5 w-3.5" }, /* @__PURE__ */ React.createElement("circle", { cx: "8", cy: "8", r: "7", stroke: "currentColor", strokeWidth: "1.2" }), /* @__PURE__ */ React.createElement("path", { d: "M4.75 8.2 7 10.4l4.25-4.8", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" })), "Done") : null), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-4 bottom-4 flex items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/30 px-3 py-2 backdrop-blur-sm" }, stepLabel ? /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.24em] text-sky-100/80" }, stepLabel) : null, stepNumber > 0 ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-5xl font-semibold tracking-[-0.1em] text-white" }, String(stepNumber).padStart(2, "0")) : null, !stepNumber && lesson.formatted_lesson_number ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold uppercase tracking-[0.16em] text-white/80" }, lesson.formatted_lesson_number) : null))), /* @__PURE__ */ React.createElement("div", { className: "p-5 md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_240px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2.5" }, stepLabel ? /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-sky-100" }, stepLabel) : null, lesson.formatted_lesson_number ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, lesson.formatted_lesson_number) : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, difficultyLabel), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, accessLabel), readingMinutes > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, readingMinutes, " min") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 max-w-3xl text-[1.65rem] font-semibold tracking-[-0.05em] text-white transition group-hover:text-sky-100" }, lesson.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, supportCopy), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[26px] border border-white/10 bg-[linear-gradient(180deg,rgba(2,6,23,0.36),rgba(2,6,23,0.18))] px-4 py-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-7 text-slate-300" }, lesson.excerpt || lesson.content_preview || "Open this lesson inside the course.")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap items-center gap-2.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5" }, lessonTypeLabel), lesson.category_name ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5" }, lesson.category_name) : null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Course flow"))), /* @__PURE__ */ React.createElement("div", { className: "flex h-full flex-col justify-between gap-4 xl:border-l xl:border-white/10 xl:pl-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Lesson path"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-[18px] border border-white/10 bg-black/20 px-3 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement("span", { className: `text-sm font-semibold ${isCompleted ? "text-emerald-100" : "text-white"}` }, statusLabel2)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-[18px] border border-white/10 bg-black/20 px-3 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Access"), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, accessLabel)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-[18px] border border-white/10 bg-black/20 px-3 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Read time"), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, readingMinutes > 0 ? `${readingMinutes} min` : "Quick read")))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 xl:justify-end" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, "Continue path"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition group-hover:border-sky-300/35 group-hover:bg-sky-300/14 group-hover:text-white" }, ctaLabel, /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M3.5 8h9m0 0-3.5-3.5M12.5 8l-3.5 3.5", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round" }))))))))
  );
}
function SectionBlock({ section, isActive = false }) {
  if (!section?.is_visible) return null;
  const lessonCount = section.lessons?.length || 0;
  const requiredCount = (section.lessons || []).filter((lesson) => lesson?.is_required).length;
  return /* @__PURE__ */ React.createElement("section", { className: `relative overflow-hidden rounded-[34px] border p-6 transition md:p-7 ${isActive ? "border-sky-300/25 bg-[linear-gradient(180deg,rgba(14,165,233,0.08),rgba(255,255,255,0.04))] shadow-[0_24px_56px_rgba(14,165,233,0.08)]" : "border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.02))]"}` }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(125,211,252,0.08),transparent_28%),linear-gradient(135deg,transparent,rgba(255,255,255,0.015))] opacity-80" }), /* @__PURE__ */ React.createElement("div", { className: "relative flex flex-wrap items-start justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2.5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Course section"), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${isActive ? "border-sky-300/20 bg-sky-300/12 text-sky-100" : "border-white/10 bg-black/20 text-slate-300"}` }, section.order_num + 1), requiredCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, requiredCount, " required") : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.05em] text-white md:text-[2rem]" }, section.title), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, section.description) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, lessonCount, " lessons mapped in this section")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-300" }, lessonCount, " lessons"), isActive ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Reading now") : null)), /* @__PURE__ */ React.createElement("div", { className: "relative mt-6 space-y-6" }, (section.lessons || []).map((lesson) => /* @__PURE__ */ React.createElement(LessonChip, { key: lesson.course_lesson_id || lesson.id, lesson }))));
}
function AcademyCoursesShow({ seo, course, sections = [], unsectionedLessons = [], pricingUrl, startUrl = null, interaction = null, interactionRoutes = null, loginUrl = null, analytics = null }) {
  const flash = X$1().props.flash || {};
  useAcademyPageAnalytics(analytics);
  const cover = course?.cover_image_url || course?.cover_image || course?.teaser_image_url || course?.teaser_image || "";
  const heroBackground = course?.teaser_image_url || course?.teaser_image || course?.cover_image_url || course?.cover_image || "";
  const progress = course?.progress || null;
  const [liked, setLiked] = reactExports.useState(Boolean(interaction?.liked));
  const [saved, setSaved] = reactExports.useState(Boolean(interaction?.saved));
  const [likesCount, setLikesCount] = reactExports.useState(Number(interaction?.likes_count || 0));
  const [savesCount, setSavesCount] = reactExports.useState(Number(interaction?.saves_count || 0));
  const visibleSections = sections.filter((section) => section?.is_visible);
  const totalLessons = Number(course?.lessons_count || unsectionedLessons.length + visibleSections.reduce((sum, section) => sum + (section.lessons || []).length, 0));
  const totalSections = visibleSections.length + (unsectionedLessons.length ? 1 : 0);
  const estimatedMinutes = course?.estimated_minutes ? `${course.estimated_minutes} min` : "Flexible pace";
  const sectionJumpItems = reactExports.useMemo(
    () => [
      ...unsectionedLessons.length ? [{ id: "course-outline-core", label: "Core lessons", count: unsectionedLessons.length }] : [],
      ...visibleSections.map((section) => ({ id: `section-${section.id}`, label: section.title, count: (section.lessons || []).length }))
    ],
    [unsectionedLessons, visibleSections]
  );
  const [activeJumpId, setActiveJumpId] = reactExports.useState(sectionJumpItems[0]?.id || null);
  const breadcrumbs = [
    { label: "Academy", href: "/academy" },
    { label: "Courses", href: "/academy/courses" },
    { label: course?.title || "Course", href: course?.public_url || "#" }
  ];
  reactExports.useEffect(() => {
    if (!sectionJumpItems.length || typeof window === "undefined" || typeof IntersectionObserver === "undefined") {
      return void 0;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        const visibleEntries = entries.filter((entry) => entry.isIntersecting).sort((left, right) => right.intersectionRatio - left.intersectionRatio);
        if (!visibleEntries.length) return;
        setActiveJumpId(visibleEntries[0].target.id);
      },
      {
        rootMargin: "-20% 0px -55% 0px",
        threshold: [0.2, 0.45, 0.7]
      }
    );
    const elements = sectionJumpItems.map((item) => document.getElementById(item.id)).filter(Boolean);
    elements.forEach((element2) => observer.observe(element2));
    return () => observer.disconnect();
  }, [sectionJumpItems]);
  const requireLogin = () => {
    if (loginUrl && typeof window !== "undefined") {
      window.location.href = loginUrl;
    }
  };
  const startCourse = () => {
    if (!startUrl) {
      requireLogin();
      return;
    }
    At.post(startUrl);
  };
  const toggleLike = async () => {
    if (!interactionRoutes?.like || !analytics?.contentType || !analytics?.contentId) {
      return;
    }
    if (analytics?.isGuest) {
      requireLogin();
      return;
    }
    const payload = await postAcademyAction(interactionRoutes.like, {
      content_type: analytics.contentType,
      content_id: analytics.contentId
    });
    if (payload?.liked !== void 0) {
      setLiked(Boolean(payload.liked));
      setLikesCount(Number(payload.likes_count || 0));
    }
  };
  const toggleSave = async () => {
    if (!interactionRoutes?.save || !analytics?.contentType || !analytics?.contentId) {
      return;
    }
    if (analytics?.isGuest) {
      requireLogin();
      return;
    }
    const payload = await postAcademyAction(interactionRoutes.save, {
      content_type: analytics.contentType,
      content_id: analytics.contentId
    });
    if (payload?.saved !== void 0) {
      setSaved(Boolean(payload.saved));
      setSavesCount(Number(payload.saves_count || 0));
    }
  };
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.16),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: course?.title, description: course?.excerpt || course?.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1400px] space-y-6" }, flash.success ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[40px] border border-sky-200/12 bg-[linear-gradient(145deg,rgba(14,165,233,0.16),rgba(15,23,42,0.95)_38%,rgba(251,191,36,0.14))] shadow-[0_24px_90px_rgba(2,6,23,0.34)]" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_14%,rgba(125,211,252,0.14),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,24px_24px,24px_24px] opacity-70" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -left-8 top-10 h-36 w-36 rounded-full bg-sky-300/18 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -right-10 bottom-0 h-40 w-40 rounded-full bg-amber-300/14 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-6 p-5 md:p-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, heroBackground ? /* @__PURE__ */ React.createElement("img", { src: heroBackground, alt: "", "aria-hidden": "true", className: "absolute inset-0 h-full w-full object-cover opacity-[0.08]" }) : null, /* @__PURE__ */ React.createElement("div", { className: "relative z-10 max-w-5xl" }, /* @__PURE__ */ React.createElement(CourseBreadcrumbs, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap items-center gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-200/18 bg-sky-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-50/90" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-200" }, "Course path"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, course?.difficulty), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, course?.access_level), progress?.percent ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-300/12 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-emerald-100" }, progress.percent, "% complete") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, course?.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold uppercase tracking-[0.24em] text-amber-100/90" }, course.subtitle) : null, /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold tracking-[-0.06em] text-white md:text-5xl lg:text-[3.9rem]" }, course?.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-200/95 md:text-lg" }, course?.excerpt || course?.description)), /* @__PURE__ */ React.createElement("span", { className: "hidden h-20 w-20 shrink-0 items-center justify-center rounded-[26px] border border-white/10 bg-white/[0.04] text-2xl text-sky-50 shadow-[0_18px_40px_rgba(2,6,23,0.22)] md:flex" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-route" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: startCourse, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, progress?.percent ? "Continue course" : "Start course"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleLike, className: "rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]" }, liked ? `Liked · ${likesCount}` : `Like · ${likesCount}`), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleSave, className: "rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]" }, saved ? `Saved · ${savesCount}` : `Save · ${savesCount}`), /* @__PURE__ */ React.createElement(xe, { href: pricingUrl, onClick: () => trackUpgradeClick(analytics, { source: "academy_course_header" }), className: "rounded-full border border-amber-300/25 bg-amber-300/12 px-5 py-3 text-sm font-semibold text-amber-100" }, "See plans")), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-4 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/75" }, "Library"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, totalLessons, " lessons")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-4 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/75" }, "Structure"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, totalSections, " sections")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-4 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/75" }, "Pace"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, estimatedMinutes)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-4 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/75" }, "Status"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, progress?.percent ? `${progress.percent}% complete` : "Ready to start"))))), /* @__PURE__ */ React.createElement("aside", { className: "grid gap-4 self-start xl:pt-2" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/10 bg-black/20 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm" }, cover ? /* @__PURE__ */ React.createElement("img", { src: cover, alt: course?.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center bg-[linear-gradient(135deg,rgba(56,189,248,0.18),rgba(15,23,42,0.92))] px-6 text-center text-sm text-slate-400" }, "No course cover image yet")), /* @__PURE__ */ React.createElement(ProgressMeter, { progress }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-black/20 p-5 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Jump through the course"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, sectionJumpItems.length ? sectionJumpItems.map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.id,
      href: `#${item.id}`,
      onClick: () => setActiveJumpId(item.id),
      className: `flex items-center justify-between rounded-2xl border px-4 py-3 text-sm transition ${activeJumpId === item.id ? "border-sky-300/25 bg-sky-300/12 text-white" : "border-white/10 bg-white/[0.03] text-slate-300 hover:border-white/20 hover:bg-white/[0.06]"}`
    },
    /* @__PURE__ */ React.createElement("span", { className: "font-medium" }, item.label),
    /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, item.count)
  )) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-400" }, "No course outline items are available yet.")))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, unsectionedLessons.length ? /* @__PURE__ */ React.createElement(
    SectionBlock,
    {
      section: {
        order_num: -1,
        title: "Core lessons",
        description: "Lessons shown before the course branches into sections.",
        is_visible: true,
        lessons: unsectionedLessons
      },
      isActive: activeJumpId === "course-outline-core"
    }
  ) : null, sections.filter((section) => section?.is_visible).map((section) => /* @__PURE__ */ React.createElement(SectionBlock, { key: section.id, section, isActive: activeJumpId === `section-${section.id}` })))));
}
const __vite_glob_0_6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyCoursesShow
}, Symbol.toStringTag, { value: "Module" }));
function academyHref$1(section, slug) {
  return `/academy/${section}/${encodeURIComponent(slug)}`;
}
function formatStatValue(value, singular, plural = `${singular}s`) {
  const numericValue = Number(value || 0);
  return `${numericValue.toLocaleString()} ${numericValue === 1 ? singular : plural}`;
}
function FeatureCard({ title, description, href, cta: cta2, icon, eyebrow, highlights = [], tags = [], meta, theme }) {
  return /* @__PURE__ */ React.createElement(xe, { href, className: `group relative overflow-hidden rounded-[32px] border p-6 shadow-[0_24px_80px_rgba(2,6,23,0.22)] transition hover:-translate-y-1 hover:shadow-[0_30px_95px_rgba(2,6,23,0.32)] ${theme.shell}` }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-0 ${theme.backdrop}` }), /* @__PURE__ */ React.createElement("div", { className: `absolute inset-0 opacity-60 ${theme.pattern}` }), /* @__PURE__ */ React.createElement("div", { className: `absolute -right-14 top-6 h-32 w-32 rounded-full blur-3xl ${theme.glow}` }), /* @__PURE__ */ React.createElement("div", { className: "relative flex min-h-[290px] flex-col" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: `text-[11px] font-semibold uppercase tracking-[0.24em] ${theme.eyebrow}` }, eyebrow), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-[2rem] font-semibold tracking-[-0.05em] text-white" }, title)), /* @__PURE__ */ React.createElement("span", { className: `flex h-14 w-14 shrink-0 items-center justify-center rounded-[18px] border text-lg shadow-[0_14px_34px_rgba(2,6,23,0.28)] transition group-hover:scale-105 ${theme.iconWrap}` }, /* @__PURE__ */ React.createElement("i", { className: icon }))), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-[34ch] text-sm leading-7 text-slate-200/95" }, description), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3 sm:grid-cols-2" }, highlights.map((item) => /* @__PURE__ */ React.createElement("div", { key: `${title}-${item.label}`, className: `rounded-[22px] border px-4 py-3 backdrop-blur-sm ${theme.highlightCard}` }, /* @__PURE__ */ React.createElement("p", { className: `text-[10px] font-semibold uppercase tracking-[0.18em] ${theme.highlightLabel}` }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, item.value)))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, tags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: `${title}-${tag}`, className: `rounded-full border px-3 py-1 text-[11px] font-semibold tracking-[0.12em] ${theme.tag}` }, tag))), /* @__PURE__ */ React.createElement("div", { className: "mt-auto flex items-center justify-between gap-4 pt-6" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-4 py-2 text-sm font-semibold transition group-hover:translate-x-1 ${theme.cta}` }, cta2), /* @__PURE__ */ React.createElement("span", { className: `text-right text-[11px] font-semibold uppercase tracking-[0.2em] ${theme.meta}` }, meta))));
}
function FeatureRailCard({ eyebrow, title, description, icon, items = [], emptyText, actionHref = null, actionLabel = null, theme, renderItem }) {
  return /* @__PURE__ */ React.createElement("section", { className: `relative overflow-hidden rounded-[30px] border p-6 shadow-[0_22px_70px_rgba(2,6,23,0.26)] ${theme.shell}` }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-0 ${theme.backdrop}` }), /* @__PURE__ */ React.createElement("div", { className: `absolute inset-0 opacity-60 ${theme.pattern}` }), /* @__PURE__ */ React.createElement("div", { className: `absolute right-0 top-0 h-28 w-28 translate-x-8 -translate-y-6 rounded-full blur-3xl ${theme.glow}` }), /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-[30ch]" }, /* @__PURE__ */ React.createElement("p", { className: `text-[11px] font-semibold uppercase tracking-[0.24em] ${theme.eyebrow}` }, eyebrow), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `flex h-11 w-11 items-center justify-center rounded-[16px] border text-sm ${theme.iconWrap}` }, /* @__PURE__ */ React.createElement("i", { className: icon })), /* @__PURE__ */ React.createElement("h3", { className: "text-2xl font-semibold tracking-[-0.04em] text-white" }, title)), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-200/92" }, description)), actionHref && actionLabel ? /* @__PURE__ */ React.createElement(xe, { href: actionHref, className: `inline-flex shrink-0 rounded-full border px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] transition ${theme.action}` }, actionLabel) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, items.length > 0 ? items.map((item, index2) => renderItem(item, index2)) : /* @__PURE__ */ React.createElement("div", { className: `rounded-[22px] border px-4 py-4 text-sm ${theme.empty}` }, emptyText))));
}
function MetricCard$2({ label, value, accent }) {
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[24px] border px-5 py-5 backdrop-blur-sm ${accent.shell}` }, /* @__PURE__ */ React.createElement("p", { className: `text-[10px] font-semibold uppercase tracking-[0.2em] ${accent.label}` }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white md:text-[2.4rem]" }, value));
}
function FeaturedCourseCard({ course }) {
  const cover = course?.cover_image_url || course?.teaser_image_url || course?.cover_image || course?.teaser_image || "";
  return /* @__PURE__ */ React.createElement(xe, { href: course.public_url, className: "group relative overflow-hidden rounded-[28px] border border-sky-200/12 bg-[linear-gradient(180deg,rgba(15,23,42,0.9),rgba(15,23,42,0.72))] transition hover:-translate-y-1 hover:border-sky-300/24 hover:shadow-[0_24px_72px_rgba(2,6,23,0.3)]" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(125,211,252,0.14),transparent_24%),linear-gradient(135deg,transparent_0%,transparent_48%,rgba(125,211,252,0.05)_48%,rgba(125,211,252,0.05)_52%,transparent_52%,transparent_100%)] opacity-80" }), /* @__PURE__ */ React.createElement("div", { className: "relative h-44 overflow-hidden bg-[linear-gradient(135deg,rgba(14,165,233,0.24),rgba(15,23,42,0.92))]" }, cover ? /* @__PURE__ */ React.createElement("img", { src: cover, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.82))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, course.difficulty), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, course.access_level))), /* @__PURE__ */ React.createElement("div", { className: "relative p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-sky-100/75" }, "Guided course"), /* @__PURE__ */ React.createElement("h3", { className: "text-2xl font-semibold tracking-[-0.04em] text-white transition group-hover:text-sky-100" }, course.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, course.excerpt || course.description || "Guided Academy course."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, course.lessons_count || 0, " lessons · ", course.estimated_minutes ? `${course.estimated_minutes} min` : "Flexible duration"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100 transition group-hover:translate-x-1" }, "Open path"))));
}
function formatAccessDate$1(value) {
  if (!value) {
    return null;
  }
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }
  return new Intl.DateTimeFormat(void 0, {
    year: "numeric",
    month: "short",
    day: "numeric"
  }).format(parsed);
}
function academyAccessHeading$1(access) {
  switch (access?.status) {
    case "staff_access":
      return "You currently have full staff access to the Academy.";
    case "grace_period":
      return `${access.tierLabel} access is still active.`;
    case "trialing":
      return `${access.tierLabel} trial is active right now.`;
    case "active":
      return access?.hasPaidAccess ? `${access.tierLabel} access is active.` : "Your Academy access is active.";
    case "free":
      return "You currently have Free access to the Academy.";
    default:
      return "Preview the Academy before you upgrade.";
  }
}
function academyAccessMeta$1(access) {
  const items = [
    { label: "Current tier", value: access?.tierLabel || "Guest" },
    { label: "Status", value: access?.statusLabel || "Preview access only" }
  ];
  const formattedDate = formatAccessDate$1(access?.expiresAt);
  if (formattedDate && access?.dateLabel) {
    items.push({ label: access.dateLabel, value: formattedDate });
  } else if (access?.renewsAutomatically) {
    items.push({ label: "Billing", value: "Renews automatically" });
  } else if (access?.signedIn && !access?.hasPaidAccess) {
    items.push({ label: "Upgrade", value: "Creator and Pro unlock premium workflows" });
  } else if (!access?.signedIn) {
    items.push({ label: "Upgrade", value: "Sign in to track access and unlock premium content" });
  }
  return items;
}
function AcademyIndex({ seo, pricingUrl, academyAccess = null, links, featureFlags, stats, featuredCourses, featuredLessons, featuredPrompts, featuredChallenges, analytics }) {
  useAcademyPageAnalytics(analytics);
  const accessHeading = academyAccessHeading$1(academyAccess);
  const accessMeta = academyAccessMeta$1(academyAccess);
  const useBillingAction = academyAccess?.signedIn && academyAccess?.hasPaidAccess && academyAccess?.billingUrl;
  const accessActionLabel = useBillingAction ? academyAccess?.status === "grace_period" ? "Renew now" : "Manage billing" : "See plans";
  const accessActionHref = useBillingAction ? academyAccess.billingUrl : pricingUrl;
  const academySections = [
    {
      title: "Courses",
      description: "Follow guided learning paths that stitch reusable Academy lessons into a clean progression with completion tracking.",
      href: links.courses,
      cta: "Browse courses",
      icon: "fa-solid fa-route",
      eyebrow: "Academy paths",
      highlights: [
        { label: "Library", value: formatStatValue(stats?.courseCount, "course") },
        { label: "Includes", value: formatStatValue(stats?.lessonCount, "lesson") }
      ],
      tags: ["Progress tracked", "Learning paths", "Skill ladders"],
      meta: "Structured progression",
      theme: {
        shell: "border-sky-300/18 bg-slate-950/40 hover:border-sky-300/30",
        backdrop: "bg-[linear-gradient(145deg,rgba(14,165,233,0.16),rgba(15,23,42,0.95)_42%,rgba(16,185,129,0.18))]",
        pattern: "bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.16),transparent_30%),linear-gradient(125deg,transparent_0%,transparent_45%,rgba(125,211,252,0.08)_45%,rgba(125,211,252,0.08)_52%,transparent_52%,transparent_100%)]",
        glow: "bg-sky-300/25",
        eyebrow: "text-sky-100/80",
        iconWrap: "border-sky-200/20 bg-sky-300/12 text-sky-100",
        highlightCard: "border-sky-200/12 bg-slate-950/40",
        highlightLabel: "text-sky-100/75",
        tag: "border-sky-200/12 bg-sky-300/10 text-sky-100",
        cta: "border-sky-300/25 bg-sky-300/12 text-sky-100",
        meta: "text-sky-100/75"
      }
    },
    {
      title: "Lessons",
      description: "Structured tutorials for prompt writing, cleanup workflows, AI ethics, and Skinbase-native publishing habits.",
      href: links.lessons,
      cta: "Open lessons",
      icon: "fa-solid fa-book-open-reader",
      eyebrow: "Focused tutorials",
      highlights: [
        { label: "Depth", value: formatStatValue(stats?.lessonCount, "lesson") },
        { label: "Coverage", value: "Prompt craft + workflow cleanup" }
      ],
      tags: ["Short wins", "Creative habits", "Practical steps"],
      meta: "Skill-by-skill learning",
      theme: {
        shell: "border-amber-300/18 bg-slate-950/40 hover:border-amber-300/30",
        backdrop: "bg-[linear-gradient(160deg,rgba(251,191,36,0.18),rgba(15,23,42,0.95)_40%,rgba(249,115,22,0.14))]",
        pattern: "bg-[radial-gradient(circle_at_top_right,rgba(253,230,138,0.14),transparent_28%),linear-gradient(180deg,transparent_0%,transparent_54%,rgba(251,191,36,0.08)_54%,rgba(251,191,36,0.08)_58%,transparent_58%,transparent_100%)]",
        glow: "bg-amber-300/20",
        eyebrow: "text-amber-100/85",
        iconWrap: "border-amber-200/20 bg-amber-300/12 text-amber-100",
        highlightCard: "border-amber-200/12 bg-slate-950/42",
        highlightLabel: "text-amber-100/75",
        tag: "border-amber-200/12 bg-amber-300/10 text-amber-100",
        cta: "border-amber-300/25 bg-amber-300/12 text-amber-100",
        meta: "text-amber-100/75"
      }
    },
    {
      title: "Prompt Library",
      description: "Discover reusable prompt templates, locked premium previews, and creator-focused visual workflows.",
      href: links.prompts,
      cta: "Explore prompts",
      icon: "fa-solid fa-wand-magic-sparkles",
      eyebrow: "Reusable prompt kits",
      highlights: [
        { label: "Templates", value: formatStatValue(stats?.promptCount, "prompt") },
        { label: "Use case", value: "Reusable systems + premium previews" }
      ],
      tags: ["Fast starts", "Visual workflows", "Copy + adapt"],
      meta: "High-speed ideation",
      theme: {
        shell: "border-rose-300/18 bg-slate-950/40 hover:border-rose-300/30",
        backdrop: "bg-[linear-gradient(150deg,rgba(244,63,94,0.16),rgba(15,23,42,0.95)_38%,rgba(45,212,191,0.16))]",
        pattern: "bg-[radial-gradient(circle_at_20%_15%,rgba(251,113,133,0.16),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,22px_22px,22px_22px]",
        glow: "bg-rose-300/20",
        eyebrow: "text-rose-100/85",
        iconWrap: "border-rose-200/20 bg-rose-300/12 text-rose-100",
        highlightCard: "border-rose-200/12 bg-slate-950/42",
        highlightLabel: "text-rose-100/75",
        tag: "border-rose-200/12 bg-rose-300/10 text-rose-100",
        cta: "border-rose-300/25 bg-rose-300/12 text-rose-100",
        meta: "text-rose-100/75"
      }
    }
  ];
  const academyFeatureRails = [
    {
      key: "lessons",
      eyebrow: "Featured lessons",
      title: "Jump-in tutorials",
      description: "Shorter Academy pieces for specific prompt problems, cleanup workflows, and publishing habits.",
      icon: "fa-solid fa-book-open-reader",
      actionHref: links.lessons,
      actionLabel: "All lessons",
      items: (featuredLessons || []).slice(0, 3),
      emptyText: "Featured lessons will appear here when the Academy team highlights a new tutorial.",
      theme: {
        shell: "border-amber-300/16 bg-slate-950/45",
        backdrop: "bg-[linear-gradient(160deg,rgba(251,191,36,0.15),rgba(15,23,42,0.96)_42%,rgba(249,115,22,0.14))]",
        pattern: "bg-[radial-gradient(circle_at_top_right,rgba(253,230,138,0.12),transparent_24%),linear-gradient(180deg,transparent_0%,transparent_52%,rgba(251,191,36,0.08)_52%,rgba(251,191,36,0.08)_56%,transparent_56%,transparent_100%)]",
        glow: "bg-amber-300/18",
        eyebrow: "text-amber-100/82",
        iconWrap: "border-amber-200/20 bg-amber-300/12 text-amber-100",
        action: "border-amber-300/22 bg-amber-300/10 text-amber-100 hover:border-amber-300/34 hover:bg-amber-300/16",
        item: "border-amber-200/10 bg-slate-950/38 hover:border-amber-200/18 hover:bg-slate-950/52",
        itemEyebrow: "text-amber-100/75",
        itemMeta: "text-amber-100/70",
        empty: "border-amber-200/10 bg-slate-950/30 text-amber-50/80"
      },
      renderItem: (item, index2, theme) => /* @__PURE__ */ React.createElement(xe, { key: item.id, href: academyHref$1("lessons", item.slug), className: `group block rounded-[22px] border px-4 py-4 transition ${theme.item}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-[10px] font-semibold ${theme.iconWrap}` }, index2 + 1), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: `block text-[10px] font-semibold uppercase tracking-[0.18em] ${theme.itemEyebrow}` }, item.lesson_label || "Featured lesson"), /* @__PURE__ */ React.createElement("span", { className: "mt-2 block text-sm font-semibold text-white transition group-hover:text-amber-50" }, item.title), /* @__PURE__ */ React.createElement("span", { className: `mt-2 block text-[11px] font-semibold uppercase tracking-[0.16em] ${theme.itemMeta}` }, "Practical tutorial"))))
    },
    {
      key: "prompts",
      eyebrow: "Featured prompts",
      title: "Reusable prompt packs",
      description: "Template-driven prompt entries designed for fast reuse, remixing, and premium workflow previews.",
      icon: "fa-solid fa-wand-magic-sparkles",
      actionHref: links.promptPopular,
      actionLabel: "Top prompts",
      items: (featuredPrompts || []).slice(0, 3),
      emptyText: "Featured prompts will appear here when reusable prompt templates are promoted on the homepage.",
      theme: {
        shell: "border-rose-300/16 bg-slate-950/45",
        backdrop: "bg-[linear-gradient(155deg,rgba(244,63,94,0.14),rgba(15,23,42,0.96)_40%,rgba(45,212,191,0.14))]",
        pattern: "bg-[radial-gradient(circle_at_20%_18%,rgba(251,113,133,0.14),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,22px_22px,22px_22px]",
        glow: "bg-rose-300/18",
        eyebrow: "text-rose-100/82",
        iconWrap: "border-rose-200/20 bg-rose-300/12 text-rose-100",
        action: "border-rose-300/22 bg-rose-300/10 text-rose-100 hover:border-rose-300/34 hover:bg-rose-300/16",
        item: "border-rose-200/10 bg-slate-950/38 hover:border-rose-200/18 hover:bg-slate-950/52",
        itemEyebrow: "text-rose-100/75",
        itemMeta: "text-rose-100/70",
        empty: "border-rose-200/10 bg-slate-950/30 text-rose-50/80"
      },
      renderItem: (item, index2, theme) => /* @__PURE__ */ React.createElement(xe, { key: item.id, href: academyHref$1("prompts", item.slug), className: `group block rounded-[22px] border px-4 py-4 transition ${theme.item}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: `block text-[10px] font-semibold uppercase tracking-[0.18em] ${theme.itemEyebrow}` }, "Prompt template #", index2 + 1), /* @__PURE__ */ React.createElement("span", { className: "mt-2 block text-sm font-semibold text-white transition group-hover:text-rose-50" }, item.title)), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${theme.iconWrap}` }, "Template")), /* @__PURE__ */ React.createElement("span", { className: `mt-3 block text-[11px] font-semibold uppercase tracking-[0.16em] ${theme.itemMeta}` }, "Reusable workflow"))
    },
    {
      key: "challenges",
      eyebrow: "Current challenges",
      title: "Build around a brief",
      description: "Academy challenges turn lessons and prompt systems into practical output with a clear creative objective.",
      icon: "fa-solid fa-trophy",
      items: (featuredChallenges || []).slice(0, 3),
      emptyText: "Current challenges will appear here when the Academy team launches a new guided brief.",
      theme: {
        shell: "border-emerald-300/16 bg-slate-950/45",
        backdrop: "bg-[linear-gradient(155deg,rgba(16,185,129,0.14),rgba(15,23,42,0.96)_42%,rgba(56,189,248,0.12))]",
        pattern: "bg-[radial-gradient(circle_at_top_left,rgba(110,231,183,0.14),transparent_24%),linear-gradient(135deg,transparent_0%,transparent_48%,rgba(16,185,129,0.08)_48%,rgba(16,185,129,0.08)_56%,transparent_56%,transparent_100%)]",
        glow: "bg-emerald-300/18",
        eyebrow: "text-emerald-100/82",
        iconWrap: "border-emerald-200/20 bg-emerald-300/12 text-emerald-100",
        action: "border-emerald-300/22 bg-emerald-300/10 text-emerald-100 hover:border-emerald-300/34 hover:bg-emerald-300/16",
        item: "border-emerald-200/10 bg-slate-950/38 hover:border-emerald-200/18 hover:bg-slate-950/52",
        itemEyebrow: "text-emerald-100/75",
        itemMeta: "text-emerald-100/70",
        empty: "border-emerald-200/10 bg-slate-950/30 text-emerald-50/80"
      },
      renderItem: (item, index2, theme) => /* @__PURE__ */ React.createElement(xe, { key: item.id, href: academyHref$1("challenges", item.slug), className: `group block rounded-[22px] border px-4 py-4 transition ${theme.item}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 min-w-8 items-center justify-center rounded-full border px-2 text-[10px] font-semibold ${theme.iconWrap}` }, "#", index2 + 1), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: `block text-[10px] font-semibold uppercase tracking-[0.18em] ${theme.itemEyebrow}` }, "Active brief"), /* @__PURE__ */ React.createElement("span", { className: "mt-2 block text-sm font-semibold text-white transition group-hover:text-emerald-50" }, item.title), /* @__PURE__ */ React.createElement("span", { className: `mt-2 block text-[11px] font-semibold uppercase tracking-[0.16em] ${theme.itemMeta}` }, "Apply what you learned"))))
    }
  ];
  const handleAccessAction = () => {
    if (!useBillingAction) {
      trackUpgradeClick(analytics, { source: "academy_home_hero" });
    }
  };
  const academyMetrics = [
    {
      key: "courses",
      label: "Courses",
      value: stats?.courseCount || 0,
      accent: {
        shell: "border-sky-300/14 bg-sky-300/[0.08]",
        label: "text-sky-100/78"
      }
    },
    {
      key: "lessons",
      label: "Lessons",
      value: stats?.lessonCount || 0,
      accent: {
        shell: "border-amber-300/14 bg-amber-300/[0.08]",
        label: "text-amber-100/78"
      }
    },
    {
      key: "prompts",
      label: "Prompts",
      value: stats?.promptCount || 0,
      accent: {
        shell: "border-rose-300/14 bg-rose-300/[0.08]",
        label: "text-rose-100/78"
      }
    },
    {
      key: "challenges",
      label: "Challenges",
      value: stats?.challengeCount || 0,
      accent: {
        shell: "border-emerald-300/14 bg-emerald-300/[0.08]",
        label: "text-emerald-100/78"
      }
    }
  ];
  const jsonLd = [{
    "@context": "https://schema.org",
    "@type": "WebPage",
    name: "Skinbase AI Academy",
    description: seo?.description,
    url: seo?.canonical
  }];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(251,191,36,0.18),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(56,189,248,0.18),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-6 sm:px-6 sm:py-8 lg:px-8 lg:py-10" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: "Skinbase AI Academy", description: seo?.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1440px] space-y-6 md:space-y-8 xl:space-y-10" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[40px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.94),rgba(28,25,23,0.88)),radial-gradient(circle_at_top_right,rgba(251,191,36,0.2),transparent_26%)] p-6 shadow-[0_32px_100px_rgba(2,6,23,0.38)] md:p-7 lg:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_300px] xl:items-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-amber-200/80" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-[15ch] text-4xl font-semibold tracking-[-0.05em] text-white md:max-w-[16ch] md:text-5xl xl:max-w-[19ch] xl:text-[3.2rem]" }, "Learn how to turn prompts into wallpapers, digital art, skins, covers, and visual worlds."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-7 text-slate-300 md:text-lg md:leading-8" }, "Skinbase AI Academy is the creative learning hub for AI-assisted art on Skinbase. Start with free lessons, explore prompt templates, and unlock premium workflows later."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2.5" }, /* @__PURE__ */ React.createElement(xe, { href: links.courses, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Browse courses"), /* @__PURE__ */ React.createElement(xe, { href: links.lessons, className: "rounded-full border border-amber-300/25 bg-amber-300/12 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:border-amber-300/40 hover:bg-amber-300/18" }, "Browse lessons"), /* @__PURE__ */ React.createElement(xe, { href: links.prompts, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open prompt library"), /* @__PURE__ */ React.createElement(xe, { href: links.promptPopular, className: "rounded-full border border-rose-300/25 bg-rose-300/12 px-5 py-3 text-sm font-semibold text-rose-100 transition hover:border-rose-300/40 hover:bg-rose-300/18" }, "Top prompts"), /* @__PURE__ */ React.createElement(xe, { href: pricingUrl, onClick: () => trackUpgradeClick(analytics, { source: "academy_home_hero" }), className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "See plans"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-sky-300/20 bg-[linear-gradient(135deg,rgba(56,189,248,0.16),rgba(15,23,42,0.82))] p-4 md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-sky-300/25 bg-sky-300/12 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-crown text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-100/80" }, "Your Academy access"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-lg font-semibold text-white" }, accessHeading))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, accessMeta.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, item.label), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.value)))), /* @__PURE__ */ React.createElement(xe, { href: accessActionHref, onClick: handleAccessAction, className: "mt-4 inline-flex rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, accessActionLabel), academyAccess?.status === "grace_period" ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-sky-100/75" }, "Opens billing account to restore renewal before access ends.") : null))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4 md:space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 rounded-[30px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.6),rgba(15,23,42,0.22))] px-5 py-4 shadow-[0_16px_48px_rgba(2,6,23,0.18)] md:flex-row md:items-end md:justify-between md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-100/75" }, "Choose your Academy lane"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.045em] text-white md:text-[2rem]" }, "Start with the format that matches how you learn.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "h-px flex-1 bg-gradient-to-r from-transparent via-sky-300/35 to-transparent md:min-w-24" }), /* @__PURE__ */ React.createElement("span", null, "Courses, lessons, prompts"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-3" }, academySections.map((section) => /* @__PURE__ */ React.createElement(FeatureCard, { key: section.title, ...section })))), /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[34px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.82),rgba(15,23,42,0.58)),radial-gradient(circle_at_top_left,rgba(56,189,248,0.12),transparent_30%),radial-gradient(circle_at_bottom_right,rgba(251,191,36,0.12),transparent_28%)] p-3 shadow-[0_18px_56px_rgba(2,6,23,0.24)] sm:p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-4" }, academyMetrics.map((metric) => /* @__PURE__ */ React.createElement(MetricCard$2, { key: metric.key, label: metric.label, value: metric.value, accent: metric.accent })))), featuredCourses?.length ? /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[36px] border border-sky-200/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.82),rgba(3,7,18,0.94)),radial-gradient(circle_at_top_left,rgba(14,165,233,0.14),transparent_28%),radial-gradient(circle_at_bottom_right,rgba(16,185,129,0.1),transparent_30%)] p-5 shadow-[0_24px_70px_rgba(2,6,23,0.26)] md:p-6 lg:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(90deg,rgba(255,255,255,0.03)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.03)_1px,transparent_1px)] bg-[length:28px_28px] opacity-25" }), /* @__PURE__ */ React.createElement("div", { className: "relative space-y-4 md:space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4 rounded-[28px] border border-white/10 bg-black/15 px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-100/78" }, "Featured courses"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-3xl font-semibold tracking-[-0.045em] text-white" }, "Guided Academy paths"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-[54ch] text-sm leading-7 text-slate-300" }, "Longer learning paths for people who want a clearer start-to-finish route instead of individual tutorials or standalone prompt templates.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-sky-300/18 bg-sky-300/10 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/85" }, formatStatValue(featuredCourses.length, "featured path")), /* @__PURE__ */ React.createElement(xe, { href: links.courses, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]" }, "All courses"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-3" }, featuredCourses.slice(0, 3).map((course) => /* @__PURE__ */ React.createElement(FeaturedCourseCard, { key: course.id, course }))))) : null, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 xl:grid-cols-3 xl:gap-5" }, academyFeatureRails.map((rail) => /* @__PURE__ */ React.createElement(
    FeatureRailCard,
    {
      key: rail.key,
      eyebrow: rail.eyebrow,
      title: rail.title,
      description: rail.description,
      icon: rail.icon,
      items: rail.items,
      emptyText: rail.emptyText,
      actionHref: rail.actionHref,
      actionLabel: rail.actionLabel,
      theme: rail.theme,
      renderItem: (item, index2) => rail.renderItem(item, index2, rail.theme)
    }
  )))));
}
const __vite_glob_0_7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyIndex
}, Symbol.toStringTag, { value: "Module" }));
function academyHref(section, slug) {
  return `/academy/${section}/${encodeURIComponent(slug)}`;
}
function Breadcrumbs$1({ items = [] }) {
  if (!items.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("nav", { "aria-label": "Breadcrumb", className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, items.map((item, index2) => {
    const isLast = index2 === items.length - 1;
    return /* @__PURE__ */ React.createElement(React.Fragment, { key: `${item.label}-${index2}` }, isLast ? /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, item.label) : /* @__PURE__ */ React.createElement(xe, { href: item.href, className: "transition hover:text-white" }, item.label), !isLast ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-600" }, "/") : null);
  }));
}
function QueryFilters({ pageType, filters, categories }) {
  if (pageType !== "lessons" && pageType !== "prompts") {
    return null;
  }
  const categoryOptions = [{ value: "", label: "All categories" }, ...(categories || []).map((category) => ({ value: category.slug, label: category.name }))];
  const difficultyOptions = [
    { value: "", label: "All levels" },
    { value: "beginner", label: "Beginner" },
    { value: "intermediate", label: "Intermediate" },
    { value: "advanced", label: "Advanced" },
    { value: "pro", label: "Pro" }
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[28px] border border-white/10 bg-black/20 p-5 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      defaultValue: filters?.q || "",
      placeholder: `Search ${pageType}`,
      className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500",
      onKeyDown: (event) => {
        if (event.key !== "Enter") return;
        At.get(window.location.pathname, { ...filters, q: event.currentTarget.value }, { preserveState: true, preserveScroll: true });
      }
    }
  ), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters?.category || "",
      onChange: (nextValue) => At.get(window.location.pathname, { ...filters, category: nextValue || void 0 }, { preserveState: true, preserveScroll: true }),
      options: categoryOptions,
      searchable: false,
      className: "rounded-2xl bg-white/[0.04]",
      placeholder: "All categories"
    }
  ), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters?.difficulty || "",
      onChange: (nextValue) => At.get(window.location.pathname, { ...filters, difficulty: nextValue || void 0 }, { preserveState: true, preserveScroll: true }),
      options: difficultyOptions,
      searchable: false,
      className: "rounded-2xl bg-white/[0.04]",
      placeholder: "All levels"
    }
  ));
}
function LockBadge({ item }) {
  if (!item?.locked) return /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/25 bg-emerald-300/12 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-emerald-100" }, item.access_level);
  return /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/25 bg-amber-300/12 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-amber-100" }, "Locked · ", item.access_level);
}
function itemHref$1(pageType, item) {
  if (pageType === "lessons") return academyHref("lessons", item.slug);
  if (pageType === "prompts") return academyHref("prompts", item.slug);
  if (pageType === "packs") return academyHref("packs", item.slug);
  return academyHref("challenges", item.slug);
}
function searchResultContentType(pageType) {
  if (pageType === "prompts") return "academy_prompt";
  if (pageType === "lessons") return "academy_lesson";
  if (pageType === "packs") return "academy_prompt_pack";
  if (pageType === "challenges") return "academy_challenge";
  return null;
}
function promptPreviewAsset(item) {
  const full = item?.preview_image || "";
  const thumb = item?.preview_image_thumb || full;
  if (!thumb) {
    return null;
  }
  return {
    src: thumb,
    srcSet: item?.preview_image_srcset || ""
  };
}
function lessonPreviewAsset(item) {
  const src2 = item?.cover_image_url || item?.article_cover_image_url || item?.cover_image || item?.article_cover_image || "";
  if (!src2) {
    return null;
  }
  return { src: src2 };
}
function PromptSpotlightCard({ item }) {
  const preview = promptPreviewAsset(item);
  return /* @__PURE__ */ React.createElement(xe, { href: academyHref("prompts", item.slug), className: "group rounded-[28px] border border-white/10 bg-white/[0.04] p-4 transition hover:border-sky-300/25 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-[104px_minmax(0,1fr)] sm:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[22px] border border-white/10 bg-[linear-gradient(135deg,rgba(56,189,248,0.18),rgba(17,24,39,0.94))] aspect-square" }, preview ? /* @__PURE__ */ React.createElement("img", { src: preview.src, srcSet: preview.srcSet || void 0, sizes: "104px", alt: "", "aria-hidden": "true", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, item?.spotlight?.eyebrow || "Prompt pick"), item?.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, item.difficulty) : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-lg font-semibold tracking-[-0.03em] text-white transition group-hover:text-sky-100" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 line-clamp-2 text-sm leading-6 text-slate-300" }, item.excerpt || item.prompt_preview || item.description || "Reusable prompt template."), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, item?.category?.name || "Academy"), item?.tags?.[0] ? /* @__PURE__ */ React.createElement("span", null, item.tags[0]) : null))));
}
function PromptDiscoverySection({ id, title, description, items = [], href, ctaLabel }) {
  if (!items.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { id, className: "rounded-[34px] border border-white/10 bg-black/20 p-6 md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-200/80" }, "Prompt discovery"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white md:text-3xl" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-7 text-slate-300" }, description)), href && ctaLabel ? /* @__PURE__ */ React.createElement(xe, { href, className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.09]" }, ctaLabel) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement(PromptSpotlightCard, { key: `spotlight-${item.id}`, item }))));
}
function PopularPromptPeriodTabs({ currentPeriod, periods = [] }) {
  if (!periods.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, periods.map((period) => /* @__PURE__ */ React.createElement(
    xe,
    {
      key: period.value,
      href: period.href,
      className: `rounded-2xl border px-4 py-3 text-left transition ${period.active ? "border-sky-200/35 bg-sky-200/15 text-sky-50" : "border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em]" }, period.label),
    /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-inherit/80" }, period.description)
  )), currentPeriod?.description ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs text-slate-300" }, currentPeriod.description) : null);
}
function formatAccessDate(value) {
  if (!value) {
    return null;
  }
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }
  return new Intl.DateTimeFormat(void 0, {
    year: "numeric",
    month: "short",
    day: "numeric"
  }).format(parsed);
}
function academyAccessHeading(access) {
  switch (access?.status) {
    case "staff_access":
      return "You currently have full staff access to the Academy.";
    case "grace_period":
      return `${access.tierLabel} access is still active.`;
    case "trialing":
      return `${access.tierLabel} trial is active right now.`;
    case "active":
      return access?.hasPaidAccess ? `${access.tierLabel} access is active.` : "Your Academy access is active.";
    case "free":
      return "You currently have Free access to the Academy.";
    default:
      return null;
  }
}
function academyAccessMeta(access) {
  if (!access?.signedIn) {
    return [];
  }
  const items = [
    { label: "Current tier", value: access?.tierLabel || "Free" },
    { label: "Status", value: access?.statusLabel || "Free access" }
  ];
  const formattedDate = formatAccessDate(access?.expiresAt);
  if (formattedDate && access?.dateLabel) {
    items.push({ label: access.dateLabel, value: formattedDate });
  } else if (access?.renewsAutomatically) {
    items.push({ label: "Billing", value: "Renews automatically" });
  } else if (!access?.hasPaidAccess) {
    items.push({ label: "Upgrade", value: "Creator and Pro unlock premium prompts" });
  }
  return items;
}
function PromptLibraryHero({ promptView = "library", title, description, items, pricingUrl, coursesUrl, packsUrl, promptPopularUrl, promptLibraryUrl, popularPeriod, popularPeriods = [], totalCount, analytics, hasPopularSection, academyAccess = null }) {
  const isPopularView = promptView === "popular";
  const statLabel = isPopularView ? `ranked prompts ${currentPeriodStatSuffix(popularPeriod)}` : "prompts available";
  const showSignedInAccess = Boolean(academyAccess?.signedIn);
  const accessHeading = academyAccessHeading(academyAccess);
  const accessMeta = academyAccessMeta(academyAccess);
  const useBillingAction = showSignedInAccess && academyAccess?.hasPaidAccess && academyAccess?.billingUrl;
  const primaryActionLabel = useBillingAction ? academyAccess?.status === "grace_period" ? "Renew now" : "Manage billing" : "Upgrade now";
  const primaryActionIcon = useBillingAction ? academyAccess?.status === "grace_period" ? "fa-solid fa-rotate-right" : "fa-solid fa-sliders" : "fa-solid fa-arrow-up-right-from-square";
  const primaryActionHref = useBillingAction ? academyAccess.billingUrl : pricingUrl;
  const secondaryAction = isPopularView ? { href: promptLibraryUrl, label: "Browse full library", icon: "fa-solid fa-grid-2" } : hasPopularSection ? { href: promptPopularUrl, label: "Top prompts", icon: "fa-solid fa-fire" } : { href: coursesUrl, label: "Explore courses", icon: "fa-solid fa-graduation-cap" };
  const heroHighlights = [
    {
      label: isPopularView ? "Ranking window" : "Templates",
      value: isPopularView ? `${totalCount || 0} ranked prompts` : `${totalCount || 0} prompts`
    },
    {
      label: "Use case",
      value: isPopularView ? "High-performing systems + trend tracking" : "Reusable systems + premium previews"
    }
  ];
  const heroTags = isPopularView ? ["Momentum picks", "Copy trends", "Compare windows"] : ["Fast starts", "Visual workflows", "Copy + adapt"];
  const handlePrimaryAction = () => {
    if (!useBillingAction) {
      trackUpgradeClick(analytics, { source: "prompts_library_hero_primary" });
    }
  };
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[40px] border border-rose-200/12 bg-[linear-gradient(150deg,rgba(244,63,94,0.14),rgba(15,23,42,0.96)_36%,rgba(45,212,191,0.14))] p-5 shadow-[0_32px_96px_rgba(2,6,23,0.32)] md:p-6 xl:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_14%,rgba(251,113,133,0.15),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,24px_24px,24px_24px] opacity-75" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -left-8 top-12 h-36 w-36 rounded-full bg-rose-300/18 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -right-10 bottom-0 h-40 w-40 rounded-full bg-cyan-300/14 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-200/18 bg-rose-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-rose-50/90" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-200" }, isPopularView ? "Popular prompts" : "Prompt Library"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, totalCount || 0, " ", statLabel)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, /* @__PURE__ */ React.createElement("h1", { className: "max-w-[13ch] text-4xl font-semibold tracking-[-0.05em] text-white md:max-w-[14ch] md:text-[4.2rem] xl:max-w-[15ch] xl:text-[4.5rem]" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-200/95" }, description)), /* @__PURE__ */ React.createElement("span", { className: "hidden h-20 w-20 shrink-0 items-center justify-center rounded-[26px] border border-white/10 bg-white/[0.04] text-2xl text-rose-50 shadow-[0_18px_40px_rgba(2,6,23,0.22)] md:flex" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles" }))), isPopularView ? /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement(PopularPromptPeriodTabs, { currentPeriod: popularPeriod, periods: popularPeriods })) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3 sm:grid-cols-2" }, heroHighlights.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-rose-100/75" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold leading-8 text-white" }, item.value)))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2.5" }, heroTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-rose-50/90" }, tag))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: primaryActionHref, onClick: handlePrimaryAction, className: "inline-flex items-center gap-2 rounded-full border border-rose-200/26 bg-rose-300/12 px-5 py-3 text-sm font-semibold text-rose-50 transition hover:border-rose-200/36 hover:bg-rose-300/18" }, /* @__PURE__ */ React.createElement("i", { className: `${primaryActionIcon} text-xs` }), primaryActionLabel), /* @__PURE__ */ React.createElement(xe, { href: secondaryAction.href, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white/90 transition hover:bg-white/[0.1]" }, /* @__PURE__ */ React.createElement("i", { className: `${secondaryAction.icon} text-xs` }), secondaryAction.label), /* @__PURE__ */ React.createElement(xe, { href: packsUrl, className: "inline-flex items-center gap-2 rounded-full border border-cyan-200/20 bg-cyan-300/10 px-5 py-3 text-sm font-semibold text-cyan-50 transition hover:border-cyan-200/30 hover:bg-cyan-300/16" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-box-open text-xs" }), "See prompt packs"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-4 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Quick routes"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white/80" }, totalCount || 0, " total")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: isPopularView ? promptLibraryUrl : coursesUrl, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-[0.9rem] text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, isPopularView ? "Browse full prompt library" : "Browse Academy courses"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-xs text-slate-400" })), /* @__PURE__ */ React.createElement(xe, { href: packsUrl, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-[0.9rem] text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, "See prompt packs"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-box-open text-xs text-slate-400" })), isPopularView ? /* @__PURE__ */ React.createElement(xe, { href: coursesUrl, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-[0.9rem] text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, "Explore Academy courses"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-graduation-cap text-xs text-slate-400" })) : hasPopularSection ? /* @__PURE__ */ React.createElement(xe, { href: promptPopularUrl, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-[0.9rem] text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, "Open top prompts page"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-fire text-xs text-slate-400" })) : null, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.03] px-4 py-[0.9rem] text-sm font-semibold text-white/85" }, isPopularView ? "Use the period tabs to compare momentum windows." : "Jump straight into packs, courses, or ranked prompts.")))), /* @__PURE__ */ React.createElement("div", { className: "xl:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-sky-300/20 bg-[linear-gradient(135deg,rgba(56,189,248,0.16),rgba(15,23,42,0.82))] p-4 shadow-[0_18px_45px_rgba(2,6,23,0.2)] md:p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-300/25 bg-sky-300/12 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-crown text-sm" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/80" }, showSignedInAccess ? "Your Academy access" : isPopularView ? "Turn rankings into results" : "Upgrade for full access"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-4xl text-lg font-semibold text-white md:text-[1.85rem] md:leading-[1.45]" }, showSignedInAccess ? accessHeading : isPopularView ? "Open the highest-performing prompts, then unlock the full text, helper prompts, variants, and premium workflows." : "Unlock full prompt text, helper prompts, variants, and premium workflows."))), showSignedInAccess ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, accessMeta.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 md:px-5 md:py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/70" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white md:text-base" }, item.value)))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: primaryActionHref, onClick: handlePrimaryAction, className: "inline-flex items-center gap-2 rounded-full border border-sky-200/30 bg-sky-200/15 px-5 py-2.5 text-sm font-semibold text-sky-50 transition hover:bg-sky-200/22" }, /* @__PURE__ */ React.createElement("i", { className: `${primaryActionIcon} text-xs` }), primaryActionLabel), /* @__PURE__ */ React.createElement(xe, { href: secondaryAction.href, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-5 py-2.5 text-sm font-semibold text-white/90 transition hover:bg-white/[0.1]" }, /* @__PURE__ */ React.createElement("i", { className: `${secondaryAction.icon} text-xs` }), secondaryAction.label)), academyAccess?.status === "grace_period" ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-sky-100/75" }, "Opens billing account to restore renewal before access ends.") : null))));
}
function LessonsLibraryHero({ title, description, items = [], totalCount, pricingUrl, coursesUrl, promptLibraryUrl, academyAccess = null, analytics }) {
  const featuredLesson = items.find((item) => lessonPreviewAsset(item)) || items[0] || null;
  const featuredPreview = lessonPreviewAsset(featuredLesson);
  const showSignedInAccess = Boolean(academyAccess?.signedIn);
  const accessHeading = academyAccessHeading(academyAccess);
  const accessMeta = academyAccessMeta(academyAccess);
  const useBillingAction = showSignedInAccess && academyAccess?.hasPaidAccess && academyAccess?.billingUrl;
  const primaryActionLabel = useBillingAction ? academyAccess?.status === "grace_period" ? "Renew now" : "Manage billing" : "See plans";
  const primaryActionIcon = useBillingAction ? academyAccess?.status === "grace_period" ? "fa-solid fa-rotate-right" : "fa-solid fa-sliders" : "fa-solid fa-arrow-up-right-from-square";
  const primaryActionHref = useBillingAction ? academyAccess.billingUrl : pricingUrl;
  const handlePrimaryAction = () => {
    if (!useBillingAction) {
      trackUpgradeClick(analytics, { source: "lessons_library_hero_primary" });
    }
  };
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[40px] border border-amber-200/12 bg-[linear-gradient(155deg,rgba(251,191,36,0.14),rgba(15,23,42,0.96)_36%,rgba(14,165,233,0.14))] p-5 shadow-[0_32px_96px_rgba(2,6,23,0.32)] md:p-6 xl:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_14%,rgba(253,230,138,0.14),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,24px_24px,24px_24px] opacity-75" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -left-8 top-12 h-36 w-36 rounded-full bg-amber-300/18 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -right-10 bottom-0 h-40 w-40 rounded-full bg-sky-300/14 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-5 xl:grid-cols-[minmax(0,1.1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-200/18 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-amber-50/90" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-200" }, "Lessons"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, totalCount || 0, " tutorials")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, /* @__PURE__ */ React.createElement("h1", { className: "max-w-[13ch] text-4xl font-semibold tracking-[-0.05em] text-white md:max-w-[14ch] md:text-[4.2rem] xl:max-w-[15ch] xl:text-[4.5rem]" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-200/95" }, description)), /* @__PURE__ */ React.createElement("span", { className: "hidden h-20 w-20 shrink-0 items-center justify-center rounded-[26px] border border-white/10 bg-white/[0.04] text-2xl text-amber-50 shadow-[0_18px_40px_rgba(2,6,23,0.22)] md:flex" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open-reader" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100/75" }, "Library"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold leading-8 text-white" }, totalCount || 0, " structured lessons")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/35 px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100/75" }, "Focus"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold leading-8 text-white" }, "Prompt craft + workflow cleanup"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-amber-50/90" }, "Short wins"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-amber-50/90" }, "Creative habits"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-amber-50/90" }, "Practical steps")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: coursesUrl, className: "inline-flex items-center gap-2 rounded-full border border-amber-200/26 bg-amber-300/12 px-5 py-3 text-sm font-semibold text-amber-50 transition hover:border-amber-200/36 hover:bg-amber-300/18" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-route text-xs" }), "Browse courses"), /* @__PURE__ */ React.createElement(xe, { href: promptLibraryUrl || "/academy/prompts", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white/90 transition hover:bg-white/[0.1]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles text-xs" }), "Prompt library"), /* @__PURE__ */ React.createElement(xe, { href: primaryActionHref, onClick: handlePrimaryAction, className: "inline-flex items-center gap-2 rounded-full border border-sky-200/20 bg-sky-300/10 px-5 py-3 text-sm font-semibold text-sky-50 transition hover:border-sky-200/30 hover:bg-sky-300/16" }, /* @__PURE__ */ React.createElement("i", { className: `${primaryActionIcon} text-xs` }), primaryActionLabel))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-4 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Latest lesson"), featuredLesson?.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white/80" }, featuredLesson.difficulty) : null), /* @__PURE__ */ React.createElement(xe, { href: featuredLesson ? academyHref("lessons", featuredLesson.slug) : coursesUrl, className: "group mt-4 block overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04] transition hover:border-amber-200/24 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/10] overflow-hidden bg-[linear-gradient(135deg,rgba(251,191,36,0.18),rgba(17,24,39,0.94))]" }, featuredPreview ? /* @__PURE__ */ React.createElement("img", { src: featuredPreview.src, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.78))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, featuredLesson?.formatted_lesson_number ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, featuredLesson.formatted_lesson_number) : null, featuredLesson ? /* @__PURE__ */ React.createElement(LockBadge, { item: featuredLesson }) : null)), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, String(featuredLesson?.series_name || featuredLesson?.category?.name || "Academy lesson").trim()), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold tracking-[-0.03em] text-white transition group-hover:text-amber-50" }, featuredLesson?.title || "Explore lessons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, featuredLesson?.excerpt || featuredLesson?.content_preview || featuredLesson?.description || "Open a practical Academy lesson."))))), /* @__PURE__ */ React.createElement("div", { className: "xl:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-sky-300/20 bg-[linear-gradient(135deg,rgba(56,189,248,0.16),rgba(15,23,42,0.82))] p-4 shadow-[0_18px_45px_rgba(2,6,23,0.2)] md:p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-300/25 bg-sky-300/12 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-crown text-sm" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/80" }, showSignedInAccess ? "Your Academy access" : "Upgrade for full access"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-4xl text-lg font-semibold text-white md:text-[1.85rem] md:leading-[1.45]" }, showSignedInAccess ? accessHeading : "Unlock the full lesson library, premium workflows, and the broader Academy learning track."))), showSignedInAccess ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, accessMeta.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 md:px-5 md:py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/70" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white md:text-base" }, item.value)))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: primaryActionHref, onClick: handlePrimaryAction, className: "inline-flex items-center gap-2 rounded-full border border-sky-200/30 bg-sky-200/15 px-5 py-2.5 text-sm font-semibold text-sky-50 transition hover:bg-sky-200/22" }, /* @__PURE__ */ React.createElement("i", { className: `${primaryActionIcon} text-xs` }), primaryActionLabel), /* @__PURE__ */ React.createElement(xe, { href: coursesUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-5 py-2.5 text-sm font-semibold text-white/90 transition hover:bg-white/[0.1]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-route text-xs" }), "Browse courses")), academyAccess?.status === "grace_period" ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-sky-100/75" }, "Opens billing account to restore renewal before access ends.") : null))));
}
function currentPeriodStatSuffix(popularPeriod) {
  if (!popularPeriod?.label) {
    return "this month";
  }
  return popularPeriod.label === "30 days" ? "this month" : `for ${popularPeriod.label.toLowerCase()}`;
}
function AcademyCard({ pageType, item, analytics, searchContext, position: position2 }) {
  const lessonSeries = String(item?.series_name || "").trim();
  const promptPreviewImage = item?.preview_image_thumb || item?.preview_image || "";
  const promptPreviewSrcSet = item?.preview_image_srcset || "";
  const lessonPreview = lessonPreviewAsset(item);
  const contentType = searchResultContentType(pageType);
  const href = itemHref$1(pageType, item);
  const trackSearchClick = () => {
    if (!searchContext?.query || !contentType) {
      return;
    }
    trackAcademySearchResultClick(analytics, searchContext, {
      contentType,
      contentId: item?.id,
      position: position2
    });
  };
  if (pageType === "prompts") {
    return /* @__PURE__ */ React.createElement(
      xe,
      {
        href,
        onClick: trackSearchClick,
        "data-academy-content-type": contentType || void 0,
        "data-academy-content-id": item?.id || void 0,
        "data-academy-search-query": searchContext?.query || void 0,
        "data-academy-search-results-count": searchContext?.resultsCount || void 0,
        "data-academy-search-position": position2 || void 0,
        className: "group overflow-hidden rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(7,11,18,0.96))] shadow-[0_20px_50px_rgba(2,6,23,0.18)] transition hover:border-sky-300/25 hover:bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(10,15,26,0.98))]"
      },
      /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/11] overflow-hidden bg-[linear-gradient(135deg,rgba(56,189,248,0.18),rgba(17,24,39,0.94))]" }, promptPreviewImage ? /* @__PURE__ */ React.createElement("img", { src: promptPreviewImage, srcSet: promptPreviewSrcSet || void 0, sizes: "(max-width: 767px) calc(100vw - 2rem), (max-width: 1279px) calc(50vw - 2rem), 420px", alt: "", "aria-hidden": "true", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.72))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-[#fff0ea]" }, item?.ranking?.rank ? `#${item.ranking.rank} this month` : "Prompt template"), /* @__PURE__ */ React.createElement(LockBadge, { item })), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-4 left-4 right-4 flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, item?.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, item.difficulty) : null, item?.aspect_ratio ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, item.aspect_ratio) : null))),
      /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, item?.category?.name || "Academy"), Array.isArray(item?.tool_notes) && item.tool_notes.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#ffcfbf]/15 bg-[#ffcfbf]/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-[#fff0ea]" }, item.tool_notes.length, " comparisons") : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white transition group-hover:text-sky-100" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.excerpt || item.description || item.prompt_preview || "No description yet."), item?.ranking ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-400" }, item.ranking.prompt_copies > 0 ? `${item.ranking.prompt_copies} copies` : `${item.ranking.views} views`, " · popularity ", item.ranking.popularity_score) : null, item.tags?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.tags.slice(0, 4).join(" · ")) : null)
    );
  }
  if (pageType === "lessons") {
    return /* @__PURE__ */ React.createElement(
      xe,
      {
        href,
        onClick: trackSearchClick,
        "data-academy-content-type": contentType || void 0,
        "data-academy-content-id": item?.id || void 0,
        "data-academy-search-query": searchContext?.query || void 0,
        "data-academy-search-results-count": searchContext?.resultsCount || void 0,
        "data-academy-search-position": position2 || void 0,
        className: "group overflow-hidden rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(7,11,18,0.96))] shadow-[0_20px_50px_rgba(2,6,23,0.18)] transition hover:border-amber-200/24 hover:bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(10,15,26,0.98))]"
      },
      /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/10] overflow-hidden bg-[linear-gradient(135deg,rgba(251,191,36,0.18),rgba(17,24,39,0.94))]" }, lessonPreview ? /* @__PURE__ */ React.createElement("img", { src: lessonPreview.src, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.72))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, item?.formatted_lesson_number ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, item.formatted_lesson_number) : null, /* @__PURE__ */ React.createElement(LockBadge, { item })), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-4 left-4 right-4 flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, item?.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, item.difficulty) : null, item?.reading_minutes ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/30 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white" }, item.reading_minutes, " min") : null))),
      /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, item?.category?.name || "Academy lesson"), lessonSeries ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, lessonSeries) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white transition group-hover:text-amber-50" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.excerpt || item.description || item.content_preview || "No description yet."), item.tags?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.tags.slice(0, 4).join(" · ")) : null)
    );
  }
  return /* @__PURE__ */ React.createElement(
    xe,
    {
      href,
      onClick: trackSearchClick,
      "data-academy-content-type": contentType || void 0,
      "data-academy-content-id": item?.id || void 0,
      "data-academy-search-query": searchContext?.query || void 0,
      "data-academy-search-results-count": searchContext?.resultsCount || void 0,
      "data-academy-search-position": position2 || void 0,
      className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 transition hover:border-white/20 hover:bg-white/[0.06]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, pageType.slice(0, -1)), /* @__PURE__ */ React.createElement(LockBadge, { item })),
    pageType === "lessons" && item?.formatted_lesson_number ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-amber-100" }, item.formatted_lesson_number), lessonSeries ? /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium uppercase tracking-[0.18em] text-slate-500" }, lessonSeries) : null) : null,
    /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-2xl font-semibold tracking-[-0.04em] text-white" }, item.title),
    /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.excerpt || item.description || item.prompt_preview || item.content_preview || "No description yet."),
    pageType === "lessons" && item.tags?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.tags.slice(0, 4).join(" · ")) : null,
    pageType === "prompts" && item.tags?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.tags.slice(0, 4).join(" · ")) : null,
    pageType === "challenges" ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.status, " · ", item.submission_count ?? 0, " submissions") : null
  );
}
async function fetchAcademyPage(url) {
  const response = await fetch(url, {
    headers: {
      Accept: "application/json",
      "X-Requested-With": "XMLHttpRequest"
    },
    credentials: "same-origin"
  });
  if (!response.ok) {
    throw new Error("Failed to load the next page.");
  }
  return response.json();
}
function AcademyList({ pageType, promptView = "library", title, description, seo, breadcrumbs = [], items, filters, categories, pricingUrl, coursesUrl, packsUrl, promptPopularUrl, promptLibraryUrl, popularPeriod = null, popularPeriods = [], featuredPrompts = [], popularPrompts = [], academyAccess = null, analytics }) {
  const flash = X$1().props.flash || {};
  useAcademyPageAnalytics(analytics);
  const searchContext = analytics?.search ? {
    query: analytics.search.query,
    normalizedQuery: analytics.search.normalizedQuery,
    resultsCount: analytics.search.resultsCount,
    filters
  } : null;
  const initialItems = React.useMemo(() => Array.isArray(items?.data) ? items.data : [], [items]);
  const [visibleItems, setVisibleItems] = React.useState(initialItems);
  const [pagination, setPagination] = React.useState({
    currentPage: Number(items?.current_page || 1),
    lastPage: Number(items?.last_page || 1),
    prevPageUrl: items?.prev_page_url || null,
    nextPageUrl: items?.next_page_url || null
  });
  const [loadingMore, setLoadingMore] = React.useState(false);
  const sentinelRef = React.useRef(null);
  const hasActivePromptFilters = pageType === "prompts" && promptView === "library" && Boolean(filters?.q || filters?.category || filters?.difficulty || filters?.tag);
  const showPromptDiscovery = pageType === "prompts" && promptView === "library" && !hasActivePromptFilters;
  const showPopularFeatured = pageType === "prompts" && promptView === "popular" && featuredPrompts.length > 0;
  const infiniteLoadLabel = pageType === "lessons" ? "lessons" : "prompts";
  const usesInfiniteLoad = pageType === "prompts" && promptView === "library" || pageType === "lessons";
  React.useEffect(() => {
    setVisibleItems(initialItems);
    setPagination({
      currentPage: Number(items?.current_page || 1),
      lastPage: Number(items?.last_page || 1),
      prevPageUrl: items?.prev_page_url || null,
      nextPageUrl: items?.next_page_url || null
    });
    setLoadingMore(false);
  }, [initialItems, items?.current_page, items?.last_page, items?.next_page_url, items?.prev_page_url, pageType]);
  const hasMorePages = usesInfiniteLoad && pagination.currentPage < pagination.lastPage && Boolean(pagination.nextPageUrl);
  const hasFallbackPagination = usesInfiniteLoad && pagination.lastPage > 1;
  const loadMore = React.useCallback(async () => {
    if (!usesInfiniteLoad || loadingMore || !pagination.nextPageUrl) {
      return;
    }
    setLoadingMore(true);
    try {
      const payload = await fetchAcademyPage(pagination.nextPageUrl);
      const nextItems = Array.isArray(payload?.data) ? payload.data : [];
      setVisibleItems((current) => [...current, ...nextItems.filter((item) => !current.some((existing) => String(existing.id) === String(item.id)))]);
      setPagination({
        currentPage: Number(payload?.current_page || pagination.currentPage),
        lastPage: Number(payload?.last_page || pagination.lastPage),
        prevPageUrl: payload?.prev_page_url || pagination.prevPageUrl,
        nextPageUrl: payload?.next_page_url || null
      });
    } catch {
      setPagination((current) => ({ ...current, nextPageUrl: null }));
    } finally {
      setLoadingMore(false);
    }
  }, [loadingMore, pagination.currentPage, pagination.lastPage, pagination.nextPageUrl, pagination.prevPageUrl, usesInfiniteLoad]);
  React.useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || !hasMorePages || loadingMore || typeof window === "undefined" || typeof window.IntersectionObserver !== "function") {
      return void 0;
    }
    const observer = new window.IntersectionObserver((entries) => {
      if (entries[0]?.isIntersecting) {
        void loadMore();
      }
    }, { rootMargin: "360px 0px" });
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [hasMorePages, loadMore, loadingMore]);
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.15),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.16),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title, description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1360px] space-y-6" }, pageType === "prompts" || pageType === "lessons" ? /* @__PURE__ */ React.createElement(Breadcrumbs$1, { items: breadcrumbs }) : null, pageType === "prompts" ? /* @__PURE__ */ React.createElement(PromptLibraryHero, { promptView, title, description, items: visibleItems, pricingUrl, coursesUrl, packsUrl, promptPopularUrl, promptLibraryUrl, popularPeriod, popularPeriods, totalCount: Number(items?.total || visibleItems.length || 0), analytics, hasPopularSection: popularPrompts.length > 0, academyAccess }) : pageType === "lessons" ? /* @__PURE__ */ React.createElement(LessonsLibraryHero, { title, description, items: visibleItems, totalCount: Number(items?.total || visibleItems.length || 0), pricingUrl, coursesUrl, promptLibraryUrl, academyAccess, analytics }) : /* @__PURE__ */ React.createElement("section", { className: "rounded-[38px] border border-white/10 bg-black/20 p-8 md:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-300" }, description)), /* @__PURE__ */ React.createElement(xe, { href: pricingUrl, onClick: () => trackUpgradeClick(analytics, { source: `${pageType}_list_hero` }), className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Upgrade preview"))), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, promptView === "library" ? /* @__PURE__ */ React.createElement(QueryFilters, { pageType, filters, categories }) : null, showPromptDiscovery ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PromptDiscoverySection, { id: "popular-prompts", title: "Popular prompts right now", description: "See which prompt templates are getting the most momentum from views and copies this month.", items: popularPrompts, href: promptPopularUrl, ctaLabel: "Open rankings" }), /* @__PURE__ */ React.createElement(PromptDiscoverySection, { id: "featured-prompts", title: "Featured prompt picks", description: "Hand-picked templates worth starting from if you want quick wins for wallpapers, worlds, portraits, and creator-style visuals.", items: featuredPrompts, href: coursesUrl, ctaLabel: "Browse courses" })) : null, showPopularFeatured ? /* @__PURE__ */ React.createElement(PromptDiscoverySection, { id: "featured-prompts", title: "Featured picks to try next", description: "Once you have reviewed the top-performing prompts, jump into a few curated templates that are worth adapting into your own workflow.", items: featuredPrompts, href: promptLibraryUrl, ctaLabel: "Browse full library" }) : null, visibleItems.length === 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-400" }, "Nothing matched this Academy view yet.") : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("section", { className: "grid gap-5 md:grid-cols-2 xl:grid-cols-3" }, visibleItems.map((item, index2) => /* @__PURE__ */ React.createElement(AcademyCard, { key: `${pageType}-${item.id}`, pageType, item, analytics, searchContext, position: index2 + 1 }))), usesInfiniteLoad ? /* @__PURE__ */ React.createElement("div", { className: "pt-2" }, /* @__PURE__ */ React.createElement("div", { ref: sentinelRef, className: "h-10 w-full", "aria-hidden": "true" }), loadingMore ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-5 py-4 text-center text-sm text-slate-300" }, "Loading more ", infiniteLoadLabel, "...") : null, !hasMorePages && visibleItems.length > initialItems.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-5 py-4 text-center text-sm text-slate-400" }, "You have reached the end of the ", pageType === "lessons" ? "lesson library" : "prompt library", ".") : null, hasFallbackPagination ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center justify-between gap-3 rounded-[22px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Auto-load is primary. Pagination is available as a backup."), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, pagination.prevPageUrl ? /* @__PURE__ */ React.createElement(xe, { href: pagination.prevPageUrl, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Previous") : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-slate-300" }, "Page ", pagination.currentPage || 1, " of ", pagination.lastPage || 1), pagination.nextPageUrl ? /* @__PURE__ */ React.createElement(xe, { href: pagination.nextPageUrl, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-[10px]" })) : null)) : null) : null)));
}
const __vite_glob_0_8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyList
}, Symbol.toStringTag, { value: "Module" }));
function AcademyBreadcrumbs({ items = [] }) {
  if (!items.length) return null;
  return /* @__PURE__ */ React.createElement("nav", { "aria-label": "Breadcrumb", className: "flex flex-wrap items-center gap-2 text-sm text-slate-400" }, items.map((item, index2) => {
    const isLast = index2 === items.length - 1;
    return /* @__PURE__ */ React.createElement(React.Fragment, { key: `${item.label}-${index2}` }, index2 > 0 ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-600" }, "/") : null, isLast ? /* @__PURE__ */ React.createElement("span", { className: "font-medium text-slate-200" }, item.label) : /* @__PURE__ */ React.createElement(xe, { href: item.href, className: "transition hover:text-white" }, item.label));
  }));
}
function slugifyHeading(value, fallback = "section") {
  const normalized = String(value || "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
  return normalized || fallback;
}
function formatLessonDate(value) {
  if (!value) return "Recently updated";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Recently updated";
  return new Intl.DateTimeFormat("en", { month: "short", day: "numeric", year: "numeric" }).format(date);
}
function formatLessonMinutes(minutes) {
  const value = Number(minutes || 0);
  return value > 0 ? `${value} min read` : "Quick read";
}
function normalizePromptAccessLevel(accessLevel) {
  const value = String(accessLevel || "free").trim().toLowerCase();
  return value === "creator" || value === "pro" ? value : "free";
}
function promptRequirementText(accessLevel) {
  const level = normalizePromptAccessLevel(accessLevel);
  if (level === "pro") return "Requires Pro access.";
  if (level === "creator") return "Requires Creator or Pro access.";
  return null;
}
function promptUnlockHeading(accessLevel) {
  const level = normalizePromptAccessLevel(accessLevel);
  if (level === "pro") return "Unlock the full Pro prompt.";
  if (level === "creator") return "Unlock the full Creator prompt.";
  return "Unlock the full prompt.";
}
function promptUnlockDescription(accessLevel) {
  const level = normalizePromptAccessLevel(accessLevel);
  if (level === "pro") {
    return "Get the complete reusable prompt, negative prompt, workflow notes, model settings, and variation strategy.";
  }
  if (level === "creator") {
    return "Get the complete reusable prompt, negative prompt, workflow notes, and creative workflow.";
  }
  return "Get the complete reusable prompt and workflow notes.";
}
function promptInlineImage(url, thumbUrl) {
  return thumbUrl || url || "";
}
function formatMetaDisplay(value) {
  const normalized = String(value || "").trim();
  if (!normalized) return "";
  return normalized.replace(/[_-]+/g, " ").replace(/\b\w/g, (character) => character.toUpperCase());
}
function StatPill$2({ label, value, icon, accentClassName = "border-white/10 bg-white/[0.04] text-slate-300", valueClassName = "text-white" }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.18))] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("p", { className: `mt-3 text-[clamp(1.35rem,2.2vw,2rem)] font-semibold tracking-[-0.04em] ${valueClassName}` }, value)), icon ? /* @__PURE__ */ React.createElement("span", { className: `mt-1 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[18px] border ${accentClassName}`, "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-xs` })) : null));
}
function PromptHeaderStat({ label, value, icon, accentClassName = "border-white/10 bg-white/[0.04] text-slate-300", valueClassName = "text-white" }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.16))] px-4 py-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.03)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-[9px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("p", { className: `mt-2 break-words text-[clamp(0.75rem,0.95vw,0.95rem)] font-semibold leading-[1.25] tracking-[-0.03em] ${valueClassName}` }, value)), icon ? /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-[14px] border ${accentClassName}`, "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-[10px]` })) : null));
}
function LessonInfoRow({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, value));
}
function LessonNavCard({ direction, lesson }) {
  if (!lesson) return null;
  const eyebrow = direction === "previous" ? "Previous lesson" : "Next lesson";
  const alignClass = direction === "previous" ? "items-start text-left" : "items-end text-right";
  const href = lesson.course_url || `/academy/lessons/${lesson.slug}`;
  return /* @__PURE__ */ React.createElement(
    xe,
    {
      href,
      "aria-label": `${eyebrow}: ${lesson.title}`,
      className: `group flex min-h-full flex-col justify-between rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-sky-300/25 hover:bg-white/[0.06] ${alignClass}`
    },
    /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, eyebrow), lesson.lesson_label ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs font-semibold uppercase tracking-[0.2em] text-amber-100" }, lesson.lesson_label) : null, /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white transition group-hover:text-sky-100" }, lesson.title)),
    /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, lesson.excerpt || lesson.content_preview || "Open the next step in this Academy sequence.")
  );
}
function LockedPanel({ pricingUrl, label, accessLevel, onUpgrade }) {
  const isPrompt = label === "prompt";
  const requirement = promptRequirementText(accessLevel);
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-amber-300/20 bg-amber-300/10 p-6 text-amber-50" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, "Premium content"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em]" }, isPrompt ? promptUnlockHeading(accessLevel) : `Unlock the full ${label}.`), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-amber-50/90" }, isPrompt ? promptUnlockDescription(accessLevel) : "This preview is visible, but the full Academy content stays server-side until your account has the required access."), requirement ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs font-semibold uppercase tracking-[0.18em] text-amber-100" }, requirement) : null, /* @__PURE__ */ React.createElement(xe, { href: pricingUrl, onClick: onUpgrade, className: "mt-5 inline-flex rounded-full border border-amber-200/25 bg-white/10 px-5 py-3 text-sm font-semibold text-white" }, "See Academy plans"));
}
function copyTextToClipboard$1(text2) {
  const source = String(text2 || "");
  if (!source) return Promise.reject(new Error("Nothing to copy"));
  if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
    return navigator.clipboard.writeText(source);
  }
  const textarea = document.createElement("textarea");
  textarea.value = source;
  textarea.setAttribute("readonly", "true");
  textarea.style.position = "fixed";
  textarea.style.top = "-1000px";
  textarea.style.left = "-1000px";
  document.body.appendChild(textarea);
  textarea.select();
  try {
    if (document.execCommand("copy")) {
      return Promise.resolve();
    }
  } finally {
    document.body.removeChild(textarea);
  }
  return Promise.reject(new Error("Clipboard unavailable"));
}
function PromptCopyButton({ prompt, label = "Copy prompt", analytics = null, contentId = null, eventType = "academy_prompt_copy", metadata = {} }) {
  const [status2, setStatus] = reactExports.useState("idle");
  const resetTimerRef = reactExports.useRef(0);
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        copyTextToClipboard$1(prompt).then(() => {
          setStatus("copied");
          void trackAcademyEvent(eventType, analytics?.contentType || null, contentId || analytics?.contentId || null, metadata, {
            url: analytics?.eventUrl,
            pageName: analytics?.pageName,
            useBeacon: false
          });
        }).catch(() => setStatus("failed")).finally(() => {
          window.clearTimeout(resetTimerRef.current);
          resetTimerRef.current = window.setTimeout(() => setStatus("idle"), 1800);
        });
      },
      className: "inline-flex items-center gap-2 rounded-full border border-[#ffb9ab]/20 bg-[#ffb9ab]/10 px-4 py-2 text-sm font-semibold text-[#ffe2dc] transition hover:border-[#ffb9ab]/35 hover:bg-[#ffb9ab]/16",
      "aria-label": "Copy prompt"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${status2 === "copied" ? "fa-check" : status2 === "failed" ? "fa-triangle-exclamation" : "fa-copy"}` }),
    /* @__PURE__ */ React.createElement("span", null, status2 === "copied" ? "Copied" : status2 === "failed" ? "Copy failed" : label)
  );
}
function ImageLightbox({ gallery, onClose, onNavigate }) {
  reactExports.useEffect(() => {
    if (!gallery?.images?.length) return void 0;
    const handleEscape = (event) => {
      if (event.key === "Escape") {
        onClose();
        return;
      }
      if (event.key === "ArrowLeft") {
        onNavigate(-1);
        return;
      }
      if (event.key === "ArrowRight") {
        onNavigate(1);
      }
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", handleEscape);
    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", handleEscape);
    };
  }, [gallery, onClose, onNavigate]);
  const images = Array.isArray(gallery?.images) ? gallery.images : [];
  const currentIndex = Math.max(0, Math.min(images.length - 1, Number(gallery?.index || 0)));
  const currentImage = images[currentIndex];
  if (!currentImage?.src) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-[120] flex items-center justify-center bg-[#020611e6] p-4 backdrop-blur-md", onClick: onClose, role: "dialog", "aria-modal": "true", "aria-label": currentImage.alt || "Image preview" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "absolute right-4 top-4 inline-flex h-11 w-11 items-center justify-center rounded-full border border-white/10 bg-black/35 text-white transition hover:border-white/25 hover:bg-white/10", "aria-label": "Close image preview" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark text-lg" })), images.length > 1 ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: (event) => {
    event.stopPropagation();
    onNavigate(-1);
  }, className: "absolute left-4 top-1/2 inline-flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/35 text-white transition hover:border-white/25 hover:bg-white/10", "aria-label": "Previous image" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-left" })) : null, images.length > 1 ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: (event) => {
    event.stopPropagation();
    onNavigate(1);
  }, className: "absolute right-4 top-1/2 inline-flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full border border-white/10 bg-black/35 text-white transition hover:border-white/25 hover:bg-white/10", "aria-label": "Next image" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-right" })) : null, /* @__PURE__ */ React.createElement("div", { className: "max-h-[92vh] max-w-[min(1400px,96vw)] overflow-hidden rounded-[30px] border border-white/10 bg-black/30 shadow-[0_30px_120px_rgba(0,0,0,0.5)]", onClick: (event) => event.stopPropagation() }, /* @__PURE__ */ React.createElement("img", { src: currentImage.src, alt: currentImage.alt || "", className: "max-h-[92vh] w-full object-contain" }), images.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4 border-t border-white/10 bg-black/35 px-5 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, currentImage.alt || `Image ${currentIndex + 1}`), /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-400" }, `Image ${currentIndex + 1} of ${images.length}`)), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, images.map((image2, index2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${image2.src}-${index2}`,
      type: "button",
      onClick: () => onNavigate(index2 - currentIndex),
      className: `h-2.5 w-2.5 rounded-full transition ${index2 === currentIndex ? "bg-white" : "bg-white/25 hover:bg-white/45"}`,
      "aria-label": `Go to image ${index2 + 1}`
    }
  )))) : null));
}
function PromptToolNoteCard({ note, index: index2, galleryIndex, onOpenImage }) {
  if (!note || typeof note !== "object") return null;
  const displayType = String(note.display_type || "").trim();
  const eyebrowLabel = displayType || "AI comparison";
  const title = note.model_name || note.provider || `${displayType || "Comparison"} ${String(index2 + 1).padStart(2, "0")}`;
  const subtitle = [note.provider, note.model_name].filter(Boolean).join(" · ");
  const previewUrl = promptInlineImage(note.image_url, note.thumb_url);
  const hasContent = Boolean(displayType || note.notes || note.strengths || note.weaknesses || note.best_for || note.settings || previewUrl || note.score || subtitle);
  if (!hasContent) return null;
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(15,23,42,0.22))] p-5 shadow-[0_16px_40px_rgba(2,6,23,0.16)]" }, previewUrl ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onOpenImage?.(galleryIndex),
      className: "group mb-5 block w-full overflow-hidden rounded-[24px] border border-white/10 bg-slate-950 text-left transition hover:border-sky-300/25 focus:outline-none focus:ring-2 focus:ring-sky-300/35",
      "aria-label": `Open comparison image for ${title}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("img", { src: previewUrl, srcSet: note.image_srcset || void 0, sizes: "(max-width: 767px) calc(100vw - 4rem), (max-width: 1535px) calc(50vw - 3rem), 560px", alt: title, loading: "lazy", className: "aspect-[4/3] w-full object-cover transition duration-500 group-hover:scale-[1.03]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 flex items-center justify-between gap-3 bg-[linear-gradient(180deg,transparent,rgba(2,6,23,0.72))] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-100/90" }, "Click to zoom"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-9 w-9 items-center justify-center rounded-full border border-white/10 bg-black/25 text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-expand" }))))
  ) : null, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-[#ffcfbf]" }, eyebrowLabel), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, title), subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-end gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, String(index2 + 1).padStart(2, "0")), note.score ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-3 py-1 text-xs font-semibold text-[#fff0ea]" }, `Score ${note.score}/10`) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, note.settings ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/25 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Generated in"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, note.settings)) : null, note.notes ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Overall notes"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, note.notes)) : null, note.best_for ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-sky-300/15 bg-sky-300/10 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Best for"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-100" }, note.best_for)) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, note.strengths ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-emerald-300/15 bg-emerald-300/10 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-100" }, "Strengths"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-100" }, note.strengths)) : null, note.weaknesses ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-amber-300/15 bg-amber-300/10 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Weaknesses"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-100" }, note.weaknesses)) : null)));
}
function normalizePromptDocumentation(documentation) {
  const source = documentation && typeof documentation === "object" && !Array.isArray(documentation) ? documentation : {};
  const list2 = (key) => (Array.isArray(source[key]) ? source[key] : []).map((item) => String(item || "").trim()).filter(Boolean);
  return {
    summary: String(source.summary || "").trim(),
    best_for: list2("best_for"),
    how_to_use: list2("how_to_use"),
    required_inputs: list2("required_inputs"),
    workflow: list2("workflow"),
    tips: list2("tips"),
    common_mistakes: list2("common_mistakes"),
    data_accuracy_notes: list2("data_accuracy_notes"),
    display_notes: String(source.display_notes || "").trim()
  };
}
function PromptDocumentationPanel({ documentation }) {
  const hasContent = Boolean(
    documentation.summary || documentation.display_notes || documentation.best_for.length || documentation.how_to_use.length || documentation.required_inputs.length || documentation.workflow.length || documentation.tips.length || documentation.common_mistakes.length || documentation.data_accuracy_notes.length
  );
  if (!hasContent) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "How to use"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Prompt documentation"), documentation.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300 md:text-base" }, documentation.summary) : null), documentation.best_for.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Best for"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, documentation.best_for.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, item)))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 xl:grid-cols-2" }, documentation.how_to_use.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-[#ffd8cd]" }, "How to use"), /* @__PURE__ */ React.createElement("ol", { className: "mt-3 space-y-3 text-sm leading-7 text-slate-200" }, documentation.how_to_use.map((step, index2) => /* @__PURE__ */ React.createElement("li", { key: `${step}-${index2}`, className: "flex gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-[11px] font-semibold text-white" }, index2 + 1), /* @__PURE__ */ React.createElement("span", null, step))))) : null, documentation.workflow.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-emerald-200/75" }, "Workflow"), /* @__PURE__ */ React.createElement("ol", { className: "mt-3 space-y-3 text-sm leading-7 text-slate-200" }, documentation.workflow.map((step, index2) => /* @__PURE__ */ React.createElement("li", { key: `${step}-${index2}`, className: "flex gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-emerald-300/15 bg-emerald-300/10 text-[11px] font-semibold text-emerald-100" }, index2 + 1), /* @__PURE__ */ React.createElement("span", null, step))))) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-5 xl:grid-cols-3" }, documentation.required_inputs.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Required inputs"), /* @__PURE__ */ React.createElement("ul", { className: "mt-3 space-y-2 text-sm leading-7 text-slate-200" }, documentation.required_inputs.map((item) => /* @__PURE__ */ React.createElement("li", { key: item }, item)))) : null, documentation.tips.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-emerald-300/15 bg-emerald-300/10 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-emerald-100" }, "Tips"), /* @__PURE__ */ React.createElement("ul", { className: "mt-3 space-y-2 text-sm leading-7 text-slate-100" }, documentation.tips.map((item) => /* @__PURE__ */ React.createElement("li", { key: item }, item)))) : null, documentation.common_mistakes.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-amber-300/15 bg-amber-300/10 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-amber-100" }, "Common mistakes"), /* @__PURE__ */ React.createElement("ul", { className: "mt-3 space-y-2 text-sm leading-7 text-slate-100" }, documentation.common_mistakes.map((item) => /* @__PURE__ */ React.createElement("li", { key: item }, item)))) : null), documentation.data_accuracy_notes.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[26px] border border-sky-300/15 bg-sky-300/10 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100" }, "Data accuracy notes"), /* @__PURE__ */ React.createElement("ul", { className: "mt-3 space-y-2 text-sm leading-7 text-slate-100" }, documentation.data_accuracy_notes.map((item) => /* @__PURE__ */ React.createElement("li", { key: item }, item)))) : null, documentation.display_notes ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[26px] border border-[#ffcfbf]/18 bg-[#ffcfbf]/10 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-[#fff0ea]" }, "Display note"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-100" }, documentation.display_notes)) : null);
}
function PromptPlaceholderCard({ placeholder }) {
  if (!placeholder || typeof placeholder !== "object") return null;
  const example = placeholder.example;
  const defaultValue = placeholder.default;
  const renderValue = (value) => {
    if (value == null || value === "") return null;
    if (typeof value === "object") {
      return /* @__PURE__ */ React.createElement("pre", { className: "mt-2 overflow-x-auto rounded-[20px] border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-200" }, JSON.stringify(value, null, 2));
    }
    return /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-200" }, String(value));
  };
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.2))] p-5 shadow-[0_16px_40px_rgba(2,6,23,0.16)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Placeholder"), /* @__PURE__ */ React.createElement("code", { className: "mt-3 inline-flex rounded-full border border-white/10 bg-black/25 px-3 py-1.5 font-mono text-sm text-white" }, "[", placeholder.key || "VALUE", "]"), placeholder.label ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-lg font-semibold tracking-[-0.03em] text-white" }, placeholder.label) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, placeholder.type ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, placeholder.type) : null, placeholder.required ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Required") : null)), placeholder.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, placeholder.description) : null, example != null && example !== "" ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Example"), renderValue(example)) : null, defaultValue != null && defaultValue !== "" ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Default"), renderValue(defaultValue)) : null);
}
function PromptVariantCard({ variant, analytics, contentId }) {
  if (!variant || typeof variant !== "object") return null;
  return /* @__PURE__ */ React.createElement("article", { className: `rounded-[28px] border p-5 shadow-[0_16px_40px_rgba(2,6,23,0.16)] ${variant.recommended ? "border-[#ffcfbf]/22 bg-[linear-gradient(180deg,rgba(255,207,191,0.08),rgba(15,23,42,0.24))]" : "border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.2))]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Prompt variant"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, variant.title || "Variant"), variant.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-7 text-slate-300" }, variant.description) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, variant.recommended ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#ffcfbf]/22 bg-[#ffcfbf]/12 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-[#fff0ea]" }, "Recommended") : null, variant.slug ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 font-mono text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, variant.slug) : null)), variant.recommended_for?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, variant.recommended_for.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, item))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-white/10 bg-black/25 p-4 md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Variant prompt"), /* @__PURE__ */ React.createElement(PromptCopyButton, { prompt: variant.prompt, label: "Copy variant", analytics, contentId, eventType: "academy_prompt_variant_copy", metadata: { copy_type: "prompt_variant", variant_title: variant.title || "", source: "prompt_variant" } })), /* @__PURE__ */ React.createElement("pre", { className: "mt-4 whitespace-pre-wrap rounded-[22px] border border-white/10 bg-slate-950/70 p-4 text-sm leading-7 text-slate-100" }, variant.prompt)), variant.negative_prompt ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4 md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Negative prompt"), /* @__PURE__ */ React.createElement(PromptCopyButton, { prompt: variant.negative_prompt, label: "Copy negative", analytics, contentId, eventType: "academy_prompt_variant_negative_copy", metadata: { copy_type: "prompt_variant_negative", variant_title: variant.title || "", source: "prompt_variant" } })), /* @__PURE__ */ React.createElement("pre", { className: "mt-4 whitespace-pre-wrap rounded-[22px] border border-white/10 bg-slate-950/70 p-4 text-sm leading-7 text-slate-200" }, variant.negative_prompt)) : null, variant.risk_notes?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-amber-300/15 bg-amber-300/10 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Risk notes"), /* @__PURE__ */ React.createElement("ul", { className: "mt-3 space-y-2 text-sm leading-7 text-slate-100" }, variant.risk_notes.map((item) => /* @__PURE__ */ React.createElement("li", { key: item }, item)))) : null);
}
function PromptVariantsSection({ variants, analytics, contentId }) {
  const visibleVariants = Array.isArray(variants) ? variants.filter((variant) => variant && typeof variant === "object") : [];
  const [activeVariantKey, setActiveVariantKey] = reactExports.useState("");
  const variantsScrollRef = reactExports.useRef(null);
  const [canScrollVariantsLeft, setCanScrollVariantsLeft] = reactExports.useState(false);
  const [canScrollVariantsRight, setCanScrollVariantsRight] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") {
      return void 0;
    }
    const updateVariantScrollState = () => {
      const element22 = variantsScrollRef.current;
      if (!element22) {
        setCanScrollVariantsLeft(false);
        setCanScrollVariantsRight(false);
        return;
      }
      const maxScrollLeft = Math.max(0, element22.scrollWidth - element22.clientWidth);
      setCanScrollVariantsLeft(element22.scrollLeft > 6);
      setCanScrollVariantsRight(element22.scrollLeft < maxScrollLeft - 6);
    };
    updateVariantScrollState();
    const element2 = variantsScrollRef.current;
    if (!element2) {
      return void 0;
    }
    element2.addEventListener("scroll", updateVariantScrollState, { passive: true });
    window.addEventListener("resize", updateVariantScrollState, { passive: true });
    return () => {
      element2.removeEventListener("scroll", updateVariantScrollState);
      window.removeEventListener("resize", updateVariantScrollState);
    };
  }, [visibleVariants.length]);
  const scrollVariants = (direction) => {
    const element2 = variantsScrollRef.current;
    if (!element2) return;
    const amount = Math.max(260, Math.floor(element2.clientWidth * 0.7));
    element2.scrollBy({
      left: direction === "left" ? -amount : amount,
      behavior: "smooth"
    });
  };
  reactExports.useEffect(() => {
    if (!visibleVariants.length) {
      setActiveVariantKey("");
      return;
    }
    const recommendedVariant = visibleVariants.find((variant) => variant?.recommended);
    const nextDefaultKey = String(recommendedVariant?.slug || recommendedVariant?.title || visibleVariants[0]?.slug || visibleVariants[0]?.title || "variant-0");
    setActiveVariantKey((current) => {
      if (visibleVariants.some((variant, index2) => String(variant?.slug || variant?.title || `variant-${index2}`) === current)) {
        return current;
      }
      return nextDefaultKey;
    });
  }, [visibleVariants]);
  if (!visibleVariants.length) return null;
  const activeVariant = visibleVariants.find((variant, index2) => String(variant?.slug || variant?.title || `variant-${index2}`) === activeVariantKey) || visibleVariants[0];
  return /* @__PURE__ */ React.createElement("section", { className: "academy-paywalled-content rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(148,163,184,0.03))] p-6 text-slate-200 shadow-[0_24px_70px_rgba(2,6,23,0.2)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Variants"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Alternative prompt versions"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Switch between safer, shorter, or more specialized prompt variants without losing the core creative direction.")), /* @__PURE__ */ React.createElement("div", { className: "relative mt-6" }, /* @__PURE__ */ React.createElement("div", { className: `pointer-events-none absolute inset-y-0 left-0 z-10 w-14 bg-gradient-to-r from-[#182233] via-[#182233]/85 to-transparent transition ${canScrollVariantsLeft ? "opacity-100" : "opacity-0"}`, "aria-hidden": "true" }), /* @__PURE__ */ React.createElement("div", { className: `pointer-events-none absolute inset-y-0 right-0 z-10 w-14 bg-gradient-to-l from-[#182233] via-[#182233]/85 to-transparent transition ${canScrollVariantsRight ? "opacity-100" : "opacity-0"}`, "aria-hidden": "true" }), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Scroll prompt variants left",
      onClick: () => scrollVariants("left"),
      className: `absolute left-2 top-1/2 z-20 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-white/12 bg-slate-950/80 text-white/80 shadow-[0_16px_36px_rgba(2,6,23,0.28)] backdrop-blur transition ${canScrollVariantsLeft ? "opacity-100 hover:scale-105 hover:bg-slate-900/95" : "pointer-events-none opacity-0"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-left text-sm" })
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Scroll prompt variants right",
      onClick: () => scrollVariants("right"),
      className: `absolute right-2 top-1/2 z-20 flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-white/12 bg-slate-950/80 text-white/80 shadow-[0_16px_36px_rgba(2,6,23,0.28)] backdrop-blur transition ${canScrollVariantsRight ? "opacity-100 hover:scale-105 hover:bg-slate-900/95" : "pointer-events-none opacity-0"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-right text-sm" })
  ), /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: variantsScrollRef,
      className: "flex gap-3 overflow-x-auto px-1 pb-3 pt-1 snap-x snap-mandatory scroll-smooth scrollbar-hide [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden",
      role: "tablist",
      "aria-label": "Prompt variants"
    },
    visibleVariants.map((variant, index2) => {
      const variantKey = String(variant?.slug || variant?.title || `variant-${index2}`);
      const isActive = activeVariant === variant;
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          key: variantKey,
          type: "button",
          role: "tab",
          "aria-selected": isActive,
          onClick: () => setActiveVariantKey(variantKey),
          className: [
            "w-[min(360px,calc(100vw-4.5rem))] shrink-0 snap-start rounded-[24px] border px-4 py-3 text-left transition sm:w-[320px]",
            isActive ? "border-sky-300/30 bg-sky-300/12 shadow-[0_16px_40px_rgba(2,6,23,0.18)]" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.05]"
          ].join(" ")
        },
        /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-semibold text-white" }, variant.title || `Variant ${index2 + 1}`), variant.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 line-clamp-2 text-xs leading-5 text-slate-300" }, variant.description) : null), variant.recommended ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-[#ffcfbf]/22 bg-[#ffcfbf]/12 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-[#fff0ea]" }, "Top pick") : null),
        /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, variant.slug ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 font-mono text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, variant.slug) : null, variant.recommended_for?.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, variant.recommended_for.length, " use case", variant.recommended_for.length === 1 ? "" : "s") : null)
      );
    })
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(PromptVariantCard, { variant: activeVariant, analytics, contentId })));
}
function PromptPublicExampleCard({ example, index: index2, galleryIndex, onOpenImage, className = "", frameClassName }) {
  if (!example || typeof example !== "object") return null;
  const previewUrl = promptInlineImage(example.image_url, example.thumb_url);
  if (!previewUrl) return null;
  const title = example.title || `Prompt Example ${index2 + 1}`;
  const subtitle = [example.provider, example.model_name].filter(Boolean).join(" · ");
  const resolvedFrameClassName = frameClassName || (index2 === 0 ? "aspect-[6/5]" : "aspect-[4/5]");
  return /* @__PURE__ */ React.createElement("article", { className: `group overflow-hidden rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.3))] shadow-[0_16px_40px_rgba(2,6,23,0.18)] transition hover:-translate-y-0.5 hover:border-sky-300/20 hover:shadow-[0_22px_50px_rgba(2,6,23,0.28)] ${className}` }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onOpenImage?.(galleryIndex),
      className: "group block w-full text-left",
      "aria-label": `Open example image for ${title}`
    },
    /* @__PURE__ */ React.createElement("div", { className: `relative ${resolvedFrameClassName} overflow-hidden bg-slate-950/80` }, /* @__PURE__ */ React.createElement("img", { src: previewUrl, srcSet: example.image_srcset || void 0, sizes: "(max-width: 767px) calc(100vw - 4rem), (max-width: 1279px) calc(50vw - 2rem), 420px", alt: example.alt || title, loading: "lazy", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.04]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.02),rgba(2,6,23,0.14)_52%,rgba(2,6,23,0.9))] opacity-0 transition duration-300 group-hover:opacity-100" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 flex items-start justify-between gap-3 p-3 opacity-0 transition duration-300 group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/35 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-100 backdrop-blur-sm" }, example.type_label || "Variation"), example.score ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/15 px-2.5 py-1 text-[10px] font-semibold text-[#fff0ea] backdrop-blur-sm" }, `${example.score}/10`) : null), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 translate-y-2 px-3 py-3 opacity-0 transition duration-300 group-hover:translate-y-0 group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, title), subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-300" }, subtitle) : null, example.caption ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 line-clamp-2 text-xs leading-5 text-slate-300/95" }, example.caption) : null))
  ));
}
function AiComparisonSection({ block }) {
  const payload = block?.payload || {};
  const criteria = Array.isArray(payload.criteria) ? payload.criteria.filter(Boolean) : [];
  const results = Array.isArray(block?.comparison_results) ? block.comparison_results.filter((result) => result?.active !== false) : [];
  const hasPrompt = Boolean(payload.prompt);
  const hasNegativePrompt = Boolean(payload.negative_prompt);
  const hasUsefulData = Boolean(block?.title || payload.title || payload.intro || hasPrompt || hasNegativePrompt || payload.aspect_ratio || criteria.length || results.length);
  if (!hasUsefulData) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(255,151,132,0.14),transparent_30%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.28)] md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-[#ffb8aa]" }, "AI Model Comparison"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white md:text-3xl" }, payload.title || block.title || "Same Prompt, Different AI Models"), payload.intro ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300 md:text-base" }, payload.intro) : null), payload.aspect_ratio ? /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-200" }, "Aspect ratio ", payload.aspect_ratio) : null), hasPrompt ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-[#ffb8aa]/15 bg-black/25 p-4 md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-[#ffd0c6]" }, "Prompt used"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Shared source prompt across all compared models")), /* @__PURE__ */ React.createElement(PromptCopyButton, { prompt: payload.prompt })), /* @__PURE__ */ React.createElement("pre", { className: "mt-4 whitespace-pre-wrap rounded-[22px] border border-white/10 bg-slate-950/70 p-4 text-sm leading-7 text-slate-100" }, payload.prompt), hasNegativePrompt ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Negative prompt"), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, payload.negative_prompt)) : null) : null, criteria.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "What we compare"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, criteria.map((criterion) => /* @__PURE__ */ React.createElement("span", { key: criterion, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-medium text-slate-100" }, criterion)))) : null, results.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 md:grid-cols-2 2xl:grid-cols-4" }, results.map((result) => {
    const imageUrl = result.thumb_url || result.image_url || result.thumb_path || result.image_path || "";
    const score = Number(result.score || 0);
    const hasScore = Number.isFinite(score) && score > 0;
    const altText = `${result.model_name || "AI model"} by ${result.provider || "unknown provider"} result for ${payload.prompt || "comparison prompt"}`;
    return /* @__PURE__ */ React.createElement("article", { key: result.id || `${result.provider}-${result.model_name}-${result.sort_order || 0}`, className: "overflow-hidden rounded-[28px] border border-white/10 bg-white/[0.04] shadow-[0_16px_40px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-video overflow-hidden bg-slate-950/80" }, imageUrl ? /* @__PURE__ */ React.createElement("img", { src: imageUrl, alt: altText, loading: "lazy", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center px-6 text-center text-sm text-slate-500" }, "No comparison image provided.")), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, result.model_name || result.provider || "AI model"), result.provider ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, result.provider) : null), hasScore ? /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-[#ffb8aa]/20 bg-[#ffb8aa]/10 px-3 py-1 text-sm font-semibold text-[#ffe3dd]" }, `Skinbase score ${score}/10`) : null), result.settings ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Settings"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, result.settings)) : null, result.strengths ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-200/75" }, "Strengths"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, result.strengths)) : null, result.weaknesses ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-200/75" }, "Weaknesses"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, result.weaknesses)) : null, result.best_for ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/75" }, "Best for"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, result.best_for)) : null));
  })) : null);
}
function AcademyShow({ pageType, item, relatedLessons = [], relatedCourses = [], previousLesson = null, nextLesson = null, seo, pricingUrl, completeUrl, completed: initialCompleted, saveUrl, unsaveUrl, saved: initialSaved, submitUrl, courseContext = null, interaction = null, interactionRoutes = null, loginUrl = null, analytics = null, progressRoutes = null }) {
  const flash = X$1().props.flash || {};
  useAcademyPageAnalytics(analytics);
  const [completed, setCompleted] = reactExports.useState(Boolean(initialCompleted));
  const [saved, setSaved] = reactExports.useState(Boolean(initialSaved));
  const [liked, setLiked] = reactExports.useState(Boolean(interaction?.liked));
  const [likesCount, setLikesCount] = reactExports.useState(Number(interaction?.likes_count || 0));
  const [savesCount, setSavesCount] = reactExports.useState(Number(interaction?.saves_count || 0));
  const [tableOfContents, setTableOfContents] = reactExports.useState([]);
  const [activeHeadingId, setActiveHeadingId] = reactExports.useState("");
  const [lightboxGallery, setLightboxGallery] = reactExports.useState(null);
  const articleContentRef = reactExports.useRef(null);
  const handledInitialHashRef = reactExports.useRef(false);
  const lessonCover = item?.cover_image_url || item?.cover_image || "";
  const articleCover = item?.article_cover_image_url || item?.article_cover_image || "";
  const lessonCategory = item?.category?.name || "Academy";
  const lessonSeries = String(item?.series_name || "").trim() || lessonCategory;
  const lessonDifficulty = item?.difficulty || "Intermediate";
  const lessonMinutes = formatLessonMinutes(item?.reading_minutes);
  const lessonUpdated = formatLessonDate(item?.published_at);
  const lessonBlocks = Array.isArray(item?.blocks) ? item.blocks : [];
  const relatedLessonList = Array.isArray(relatedLessons) ? relatedLessons : [];
  const relatedCourseList = Array.isArray(relatedCourses) ? relatedCourses : [];
  const courseOutline = Array.isArray(courseContext?.outline) ? courseContext.outline : [];
  const lessonSummary = item.excerpt || item.description || item.prompt_preview || item.content_preview || "A focused Academy lesson with practical guidance and examples.";
  const lessonTags = Array.isArray(item?.tags) ? item.tags.filter(Boolean) : [];
  const promptPreviewImage = item?.preview_image || "";
  const promptPreviewThumbImage = item?.preview_image_thumb || promptPreviewImage;
  const promptPreviewSrcSet = item?.preview_image_srcset || "";
  const promptBody = item?.prompt || item?.prompt_preview || "";
  const promptDocumentation = normalizePromptDocumentation(item?.documentation);
  const promptPlaceholders = Array.isArray(item?.placeholders) ? item.placeholders.filter((placeholder) => placeholder && typeof placeholder === "object" && [
    placeholder.key,
    placeholder.label,
    placeholder.description,
    placeholder.example,
    placeholder.default,
    placeholder.type
  ].some((value) => value != null && value !== "" && value !== false)) : [];
  const promptHelperPrompts = Array.isArray(item?.helper_prompts) ? item.helper_prompts.filter((helperPrompt) => helperPrompt && typeof helperPrompt === "object" && [
    helperPrompt.title,
    helperPrompt.description,
    helperPrompt.prompt,
    helperPrompt.expected_output,
    helperPrompt.type
  ].some(Boolean)) : [];
  const promptVariants = Array.isArray(item?.prompt_variants) ? item.prompt_variants.filter((variant) => variant && typeof variant === "object" && [
    variant.title,
    variant.description,
    variant.prompt,
    variant.negative_prompt,
    variant.slug,
    variant.recommended,
    ...Array.isArray(variant.recommended_for) ? variant.recommended_for : [],
    ...Array.isArray(variant.risk_notes) ? variant.risk_notes : []
  ].some((value) => value != null && value !== "" && value !== false)) : [];
  const promptPublicExamples = Array.isArray(item?.public_examples) ? item.public_examples.filter((example) => example && typeof example === "object" && [
    example.title,
    example.caption,
    example.image_path,
    example.image_url,
    example.thumb_path,
    example.thumb_url,
    example.provider,
    example.model_name,
    example.score
  ].some(Boolean)) : [];
  const promptComparisons = Array.isArray(item?.tool_notes) ? item.tool_notes.filter((note) => note && typeof note === "object" && note.active !== false && [
    note.display_type,
    note.provider,
    note.model_name,
    note.notes,
    note.strengths,
    note.weaknesses,
    note.best_for,
    note.image_path,
    note.image_url,
    note.thumb_path,
    note.thumb_url,
    note.settings,
    note.score
  ].some(Boolean)) : [];
  const promptUsageNotes = String(item?.usage_notes || "").trim();
  const promptWorkflowNotes = String(item?.workflow_notes || "").trim();
  const promptHasFullAccess = Boolean(item?.prompt);
  const hasPromptDocumentation = Boolean(
    promptDocumentation.summary || promptDocumentation.display_notes || promptDocumentation.best_for.length || promptDocumentation.how_to_use.length || promptDocumentation.required_inputs.length || promptDocumentation.workflow.length || promptDocumentation.tips.length || promptDocumentation.common_mistakes.length || promptDocumentation.data_accuracy_notes.length
  );
  const hasPromptPlaceholders = Boolean(item?.has_placeholder_inputs) && promptPlaceholders.length > 0;
  Boolean(item?.has_helper_prompts) && !promptHasFullAccess;
  const promptHasLockedVariants = Boolean(item?.has_prompt_variants) && !promptHasFullAccess;
  promptHelperPrompts.length > 0;
  const hasPromptVariants = promptVariants.length > 0;
  const promptAccessRequirement = item?.access_requirement || promptRequirementText(item?.access_level);
  const promptUnlockTitle = item?.unlock_heading || promptUnlockHeading(item?.access_level);
  const promptUnlockDetails = item?.unlock_description || promptUnlockDescription(item?.access_level);
  const promptFeaturedExamples = promptPreviewImage ? promptPublicExamples.slice(0, 2) : promptPublicExamples.slice(0, 4);
  const promptOverflowExamples = promptPublicExamples.slice(promptFeaturedExamples.length);
  const promptComparisonGalleryImages = promptComparisons.map((note, index2) => {
    const src2 = note.image_url || note.thumb_url || "";
    if (!src2) return null;
    return {
      src: src2,
      alt: note.model_name || note.provider || `Comparison ${index2 + 1}`
    };
  }).filter(Boolean);
  const promptPublicExampleGalleryImages = [
    ...promptPreviewImage ? [{ src: promptPreviewImage, alt: item?.title || "Prompt preview" }] : [],
    ...promptPublicExamples.map((example, index2) => {
      const src2 = example.image_url || example.thumb_url || "";
      if (!src2) return null;
      return {
        src: src2,
        alt: example.alt || example.title || `Prompt example ${index2 + 1}`
      };
    }).filter(Boolean)
  ];
  const promptBestUseCase = promptComparisons[0]?.best_for || promptDocumentation.best_for[0] || promptUsageNotes || lessonSummary;
  const academyBreadcrumbs = pageType === "prompt" ? [
    { label: "Academy", href: "/academy" },
    { label: "Prompt Library", href: "/academy/prompts" },
    { label: item?.title || "Prompt" }
  ] : [];
  const fontScaleStorageKey = "academy.lesson.font-scale";
  const fontScaleMin = 0.95;
  const fontScaleMax = 1.12;
  const fontScaleStep = 0.04;
  const [lessonFontScale, setLessonFontScale] = reactExports.useState(1.04);
  const findArticleHeading = (headingId) => {
    if (!headingId || typeof document === "undefined") {
      return null;
    }
    const escapedHeadingId = typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(headingId) : String(headingId).replace(/[^a-zA-Z0-9_-]/g, "");
    return articleContentRef.current?.querySelector(`#${escapedHeadingId}`) || document.getElementById(headingId);
  };
  const markComplete = () => {
    if (!completeUrl || completed) return;
    At.post(completeUrl, courseContext?.completePayload || {}, {
      preserveScroll: true,
      onSuccess: () => setCompleted(true)
    });
  };
  const requireLogin = () => {
    if (loginUrl && typeof window !== "undefined") {
      window.location.href = loginUrl;
    }
  };
  const toggleLike = async () => {
    if (!interactionRoutes?.like || !analytics?.contentType || !analytics?.contentId) {
      return;
    }
    if (analytics?.isGuest) {
      requireLogin();
      return;
    }
    const payload = await postAcademyAction(interactionRoutes.like, {
      content_type: analytics.contentType,
      content_id: analytics.contentId
    });
    if (payload?.liked !== void 0) {
      setLiked(Boolean(payload.liked));
      setLikesCount(Number(payload.likes_count || 0));
    }
  };
  const toggleSave = async () => {
    if (interactionRoutes?.save && analytics?.contentType && analytics?.contentId) {
      if (analytics?.isGuest) {
        requireLogin();
        return;
      }
      const payload = await postAcademyAction(interactionRoutes.save, {
        content_type: analytics.contentType,
        content_id: analytics.contentId
      });
      if (payload?.saved !== void 0) {
        setSaved(Boolean(payload.saved));
        setSavesCount(Number(payload.saves_count || 0));
      }
      return;
    }
    const url = saved ? unsaveUrl : saveUrl;
    if (!url) return;
    const method = saved ? At.delete : At.post;
    method(url, {}, {
      preserveScroll: true,
      onSuccess: () => setSaved(!saved)
    });
  };
  reactExports.useEffect(() => {
    if (pageType !== "lesson" || !progressRoutes?.startLesson || !item?.id || analytics?.isGuest || completed || typeof window === "undefined") {
      return;
    }
    const onceKey = `academy-start-lesson:${item.id}:${courseContext?.id || "solo"}`;
    if (window.sessionStorage.getItem(onceKey)) {
      return;
    }
    window.sessionStorage.setItem(onceKey, "1");
    void postAcademyAction(progressRoutes.startLesson, {
      lesson_id: item.id,
      course_id: courseContext?.id || null
    });
  }, [analytics?.isGuest, completed, courseContext?.id, item?.id, pageType, progressRoutes?.startLesson]);
  const decreaseFontSize = () => {
    setLessonFontScale((current) => Math.max(fontScaleMin, Number((current - fontScaleStep).toFixed(2))));
  };
  const increaseFontSize = () => {
    setLessonFontScale((current) => Math.min(fontScaleMax, Number((current + fontScaleStep).toFixed(2))));
  };
  const openPromptPreviewImage = () => {
    if (!promptPreviewImage) return;
    setLightboxGallery({
      images: [{ src: promptPreviewImage, alt: item?.title || "Prompt preview" }],
      index: 0
    });
  };
  const openPromptComparisonGallery = (index2) => {
    if (!promptComparisonGalleryImages.length) return;
    setLightboxGallery({
      images: promptComparisonGalleryImages,
      index: Math.max(0, Math.min(promptComparisonGalleryImages.length - 1, Number(index2 || 0)))
    });
  };
  const openPromptExampleGallery = (index2) => {
    if (!promptPublicExampleGalleryImages.length) return;
    setLightboxGallery({
      images: promptPublicExampleGalleryImages,
      index: Math.max(0, Math.min(promptPublicExampleGalleryImages.length - 1, Number(index2 || 0)))
    });
  };
  const navigateLightboxGallery = (direction) => {
    setLightboxGallery((current) => {
      if (!current?.images?.length) return current;
      const total = current.images.length;
      const nextIndex = typeof direction === "number" && Math.abs(direction) > 1 ? Math.max(0, Math.min(total - 1, current.index + direction)) : (current.index + direction + total) % total;
      return {
        ...current,
        index: nextIndex
      };
    });
  };
  const scrollToHeading = (headingId, behavior = "smooth") => {
    if (typeof window === "undefined") {
      return;
    }
    const heading2 = findArticleHeading(headingId);
    if (!heading2) {
      return;
    }
    const top = Math.max(0, window.scrollY + heading2.getBoundingClientRect().top - 112);
    window.scrollTo({ top, behavior });
    setActiveHeadingId(headingId);
    if (window.history?.replaceState) {
      window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}#${headingId}`);
    }
  };
  reactExports.useEffect(() => {
    handledInitialHashRef.current = false;
  }, [item?.slug]);
  reactExports.useEffect(() => {
    if (pageType !== "lesson" || !item?.content || !articleContentRef.current) {
      setTableOfContents([]);
      setActiveHeadingId("");
      return;
    }
    const headings = Array.from(articleContentRef.current.querySelectorAll("h2, h3"));
    const seenIds = /* @__PURE__ */ new Map();
    const nextTableOfContents = headings.map((heading2, index2) => {
      const baseId = slugifyHeading(heading2.textContent, `section-${index2 + 1}`);
      const seenCount = seenIds.get(baseId) ?? 0;
      const nextId = seenCount > 0 ? `${baseId}-${seenCount + 1}` : baseId;
      seenIds.set(baseId, seenCount + 1);
      heading2.id = nextId;
      heading2.style.scrollMarginTop = "128px";
      return {
        id: nextId,
        title: heading2.textContent?.trim() || `Section ${index2 + 1}`,
        level: heading2.tagName.toLowerCase()
      };
    });
    setTableOfContents(nextTableOfContents);
  }, [item?.content, pageType]);
  reactExports.useEffect(() => {
    if (pageType !== "lesson" || tableOfContents.length === 0 || handledInitialHashRef.current || typeof window === "undefined") {
      return;
    }
    const hash = window.location.hash.replace(/^#/, "").trim();
    if (!hash) {
      handledInitialHashRef.current = true;
      return;
    }
    const matchingEntry = tableOfContents.find((entry) => entry.id === hash);
    if (!matchingEntry) {
      handledInitialHashRef.current = true;
      return;
    }
    handledInitialHashRef.current = true;
    window.requestAnimationFrame(() => scrollToHeading(matchingEntry.id, "auto"));
  }, [pageType, tableOfContents]);
  reactExports.useEffect(() => {
    if (pageType !== "lesson" || tableOfContents.length === 0 || typeof window === "undefined") {
      return void 0;
    }
    const handleHashChange = () => {
      const hash = window.location.hash.replace(/^#/, "").trim();
      if (!hash) {
        return;
      }
      const matchingEntry = tableOfContents.find((entry) => entry.id === hash);
      if (!matchingEntry) {
        return;
      }
      window.requestAnimationFrame(() => scrollToHeading(matchingEntry.id, "auto"));
    };
    window.addEventListener("hashchange", handleHashChange);
    return () => window.removeEventListener("hashchange", handleHashChange);
  }, [pageType, tableOfContents]);
  reactExports.useEffect(() => {
    if (pageType !== "lesson" || tableOfContents.length === 0 || !articleContentRef.current) {
      setActiveHeadingId("");
      return;
    }
    const getActiveId = () => {
      const headings = Array.from(articleContentRef.current.querySelectorAll("h2[id], h3[id]"));
      if (!headings.length) return "";
      const offset = 140;
      let activeId = headings[0].id;
      for (const heading2 of headings) {
        if (heading2.getBoundingClientRect().top <= offset) {
          activeId = heading2.id;
        }
      }
      return activeId;
    };
    setActiveHeadingId(getActiveId());
    const onScroll = () => setActiveHeadingId(getActiveId());
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [pageType, tableOfContents, lessonFontScale]);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }
    const storedValue = Number(window.localStorage.getItem(fontScaleStorageKey));
    if (!Number.isFinite(storedValue)) {
      return;
    }
    setLessonFontScale(Math.min(fontScaleMax, Math.max(fontScaleMin, storedValue)));
  }, [fontScaleMax, fontScaleMin, fontScaleStorageKey]);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }
    window.localStorage.setItem(fontScaleStorageKey, String(lessonFontScale));
  }, [lessonFontScale]);
  reactExports.useEffect(() => {
    if (pageType !== "lesson" || !item?.content || !articleContentRef.current) {
      return;
    }
    const codeBlocks = Array.from(articleContentRef.current.querySelectorAll("pre code"));
    if (!codeBlocks.length) {
      return;
    }
    const fallbackCopyText = (text2) => {
      const textarea = document.createElement("textarea");
      textarea.value = text2;
      textarea.setAttribute("readonly", "true");
      textarea.style.position = "fixed";
      textarea.style.top = "-1000px";
      textarea.style.left = "-1000px";
      document.body.appendChild(textarea);
      textarea.select();
      try {
        return document.execCommand("copy");
      } catch (_error) {
        return false;
      } finally {
        document.body.removeChild(textarea);
      }
    };
    const copyText = (text2) => {
      if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
        return navigator.clipboard.writeText(text2);
      }
      return fallbackCopyText(text2) ? Promise.resolve() : Promise.reject(new Error("Clipboard unavailable"));
    };
    codeBlocks.forEach((block) => {
      const pre = block.parentElement;
      if (!pre || pre.dataset.academyCopyButtonMounted === "true") {
        return;
      }
      const button = document.createElement("button");
      const icon = document.createElement("span");
      const label = document.createElement("span");
      button.type = "button";
      button.className = "story-code-copy-button academy-code-copy-button";
      icon.className = "story-code-copy-icon";
      icon.setAttribute("aria-hidden", "true");
      icon.textContent = "⧉";
      label.className = "story-code-copy-label";
      label.textContent = "Copy";
      button.appendChild(icon);
      button.appendChild(label);
      button.dataset.copied = "idle";
      button.setAttribute("aria-label", "Copy code block");
      let resetTimer = 0;
      button.addEventListener("click", () => {
        const source = block.innerText || block.textContent || "";
        copyText(source).then(() => {
          icon.textContent = "✓";
          label.textContent = "Copied";
          button.dataset.copied = "true";
        }).catch(() => {
          icon.textContent = "!";
          label.textContent = "Failed";
          button.dataset.copied = "false";
        }).finally(() => {
          window.clearTimeout(resetTimer);
          resetTimer = window.setTimeout(() => {
            icon.textContent = "⧉";
            label.textContent = "Copy";
            button.dataset.copied = "idle";
          }, 1800);
        });
      });
      pre.appendChild(button);
      pre.dataset.academyCopyButtonMounted = "true";
    });
  }, [item?.content, lessonFontScale, pageType]);
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(59,130,246,0.14),_transparent_26%),linear-gradient(180deg,_#0b1220_0%,_#111827_46%,_#0f172a_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: item?.title, description: item?.excerpt || item?.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1320px] space-y-6" }, flash.success ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, item.locked ? /* @__PURE__ */ React.createElement(LockedPanel, { pricingUrl, label: pageType, accessLevel: item?.access_level, onUpgrade: () => trackUpgradeClick(analytics, { source: `${pageType}_locked_panel` }) }) : null, pageType === "lesson" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[40px] border border-sky-200/12 bg-[linear-gradient(145deg,rgba(14,165,233,0.16),rgba(15,23,42,0.95)_38%,rgba(251,191,36,0.14))] shadow-[0_24px_90px_rgba(15,23,42,0.34)]" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_14%,rgba(125,211,252,0.14),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,24px_24px,24px_24px] opacity-70" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -left-8 top-10 h-36 w-36 rounded-full bg-sky-300/18 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -right-10 bottom-0 h-40 w-40 rounded-full bg-amber-300/14 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-6 p-5 md:p-6 lg:grid-cols-[minmax(0,1fr)_360px] lg:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[34px] border border-white/10 bg-[linear-gradient(135deg,rgba(2,6,23,0.86),rgba(15,23,42,0.62))] p-5 shadow-[0_20px_46px_rgba(2,6,23,0.18)] md:p-6 lg:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(135deg,rgba(2,6,23,0.86),rgba(15,23,42,0.62))]" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 max-w-4xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-200/18 bg-sky-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-50/90" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-200" }, "Lesson"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-300" }, lessonCategory), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-300" }, lessonDifficulty)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, item.lesson_label ? /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold uppercase tracking-[0.24em] text-amber-100" }, item.lesson_label) : null, /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold tracking-[-0.055em] text-white md:text-5xl lg:text-[3.8rem]" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-200/95 md:text-lg" }, lessonSummary)), /* @__PURE__ */ React.createElement("span", { className: "hidden h-20 w-20 shrink-0 items-center justify-center rounded-[26px] border border-white/10 bg-white/[0.04] text-2xl text-sky-50 shadow-[0_18px_40px_rgba(2,6,23,0.22)] md:flex" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open-reader" }))), lessonTags.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2.5" }, lessonTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-[11px] font-semibold tracking-[0.16em] text-sky-50/90" }, tag))) : null, courseContext?.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 max-w-2xl rounded-[24px] border border-white/10 bg-slate-950/35 p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Part of course"), /* @__PURE__ */ React.createElement(xe, { href: courseContext.showUrl, className: "mt-2 inline-flex text-lg font-semibold text-sky-100 transition hover:text-white" }, courseContext.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, courseContext.subtitle || "This lesson is being viewed inside a structured Academy course path.")) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-7 flex flex-wrap gap-3" }, completeUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: markComplete, className: "rounded-full border border-emerald-300/25 bg-emerald-300/12 px-5 py-3 text-sm font-semibold text-emerald-100" }, completed ? "Completed" : "Mark complete") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleLike, className: "rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]" }, liked ? `Liked · ${likesCount}` : `Like · ${likesCount}`), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleSave, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, saved ? `Saved · ${savesCount}` : `Save · ${savesCount}`), submitUrl ? /* @__PURE__ */ React.createElement(xe, { href: submitUrl, className: "rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white transition hover:border-sky-300/25 hover:bg-sky-300/12 hover:text-sky-100" }, "Submit artwork") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatPill$2, { label: "Category", value: lessonCategory }), /* @__PURE__ */ React.createElement(StatPill$2, { label: "Reading", value: lessonMinutes }), /* @__PURE__ */ React.createElement(StatPill$2, { label: "Updated", value: lessonUpdated }), /* @__PURE__ */ React.createElement(StatPill$2, { label: courseContext?.title ? "Course progress" : "Access", value: courseContext?.progress ? `${courseContext.progress.percent}%` : item.access_level || "free" })))), /* @__PURE__ */ React.createElement("aside", { className: "grid gap-4 self-start" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[32px] border border-white/10 bg-slate-950 shadow-[0_24px_56px_rgba(2,6,23,0.24)]" }, lessonCover ? /* @__PURE__ */ React.createElement("img", { src: lessonCover, alt: item.title, className: "h-[260px] w-full object-cover sm:h-[300px] lg:h-[320px]" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-[260px] items-center justify-center bg-[linear-gradient(135deg,_rgba(14,165,233,0.22),_rgba(17,24,39,0.96))] text-sm font-semibold uppercase tracking-[0.24em] text-slate-300 sm:h-[300px] lg:h-[320px]" }, "Lesson cover"), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.02),rgba(2,6,23,0.2)_48%,rgba(2,6,23,0.88))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/30 px-4 py-3 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-sky-100/80" }, "Lesson cover"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, item.lesson_label || item.title)))), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 rounded-[30px] border border-white/10 bg-black/20 p-5 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Series", value: lessonSeries }), item.formatted_lesson_number ? /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Lesson", value: item.formatted_lesson_number }) : null, /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Difficulty", value: lessonDifficulty }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Reading time", value: lessonMinutes }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Published", value: lessonUpdated })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-slate-950/35 p-5 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Lesson status"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.locked ? "This lesson is partially locked for your account level." : courseContext?.title ? "This lesson is being tracked inside a course. Completion updates your course progress." : "Full lesson content is available below."))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 lg:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("article", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(148,163,184,0.03))] p-6 text-slate-200 shadow-[0_24px_70px_rgba(2,6,23,0.2)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4 border-b border-white/10 pb-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Article"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Lesson content")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-slate-300" }, lessonMinutes), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 rounded-full border border-white/10 bg-black/20 p-1" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: decreaseFontSize,
      disabled: lessonFontScale <= fontScaleMin,
      "aria-label": "Decrease article text size",
      className: "inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-sm font-semibold text-slate-200 transition hover:border-sky-300/30 hover:bg-sky-300/12 hover:text-sky-100 disabled:cursor-not-allowed disabled:opacity-40"
    },
    "-"
  ), /* @__PURE__ */ React.createElement("span", { className: "min-w-12 px-1 text-center text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, Math.round(lessonFontScale * 100), "%"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: increaseFontSize,
      disabled: lessonFontScale >= fontScaleMax,
      "aria-label": "Increase article text size",
      className: "inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-sm font-semibold text-slate-200 transition hover:border-sky-300/30 hover:bg-sky-300/12 hover:text-sky-100 disabled:cursor-not-allowed disabled:opacity-40"
    },
    "+"
  )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, articleCover ? /* @__PURE__ */ React.createElement("div", { className: "mb-8 overflow-hidden rounded-[28px] border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("img", { src: articleCover, alt: `${item.title} article cover`, className: "w-full object-cover" })) : null, item.content ? /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: articleContentRef,
      className: "story-prose academy-lesson-prose prose prose-invert max-w-none",
      style: { "--academy-lesson-font-scale": lessonFontScale },
      dangerouslySetInnerHTML: { __html: item.content }
    }
  ), lessonBlocks.map((block) => /* @__PURE__ */ React.createElement(AiComparisonSection, { key: block.id || `${block.type}-${block.sort_order || 0}`, block }))) : /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("div", { className: "whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.content_preview), lessonBlocks.map((block) => /* @__PURE__ */ React.createElement(AiComparisonSection, { key: block.id || `${block.type}-${block.sort_order || 0}`, block })))), previousLesson || nextLesson ? /* @__PURE__ */ React.createElement("section", { className: "mt-10 border-t border-white/10 pt-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, courseContext?.title ? "Course navigation" : "Lesson navigation"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, courseContext?.title ? "Continue this course" : "Continue in order"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(LessonNavCard, { direction: "previous", lesson: previousLesson }), /* @__PURE__ */ React.createElement(LessonNavCard, { direction: "next", lesson: nextLesson }))) : null), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6 lg:sticky lg:top-6 lg:self-start" }, tableOfContents.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "On this page"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Table of contents"), /* @__PURE__ */ React.createElement("nav", { "aria-label": "Lesson table of contents", className: "mt-5 space-y-1.5" }, tableOfContents.map((entry) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: entry.id,
      href: `#${entry.id}`,
      onClick: (event) => {
        event.preventDefault();
        scrollToHeading(entry.id);
      },
      "aria-current": activeHeadingId === entry.id ? "location" : void 0,
      className: `academy-lesson-toc-link ${entry.level === "h3" ? "academy-lesson-toc-link-subtle" : ""} ${activeHeadingId === entry.id ? "academy-lesson-toc-link-active" : ""}`
    },
    /* @__PURE__ */ React.createElement("span", { className: "academy-lesson-toc-link-indicator", "aria-hidden": "true" }),
    /* @__PURE__ */ React.createElement("span", null, entry.title)
  )))) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, courseContext?.title ? "Course progress" : "Series info"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, courseContext?.title ? courseContext.title : lessonSeries), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Category", value: lessonCategory }), item.formatted_lesson_number ? /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Lesson", value: item.formatted_lesson_number }) : null, /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Difficulty", value: lessonDifficulty }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Reading", value: lessonMinutes }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: courseContext?.title ? "Progress" : "Updated", value: courseContext?.progress ? `${courseContext.progress.completedRequired}/${courseContext.progress.totalRequired} completed` : lessonUpdated }))), courseOutline.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Course outline"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, courseOutline.map((outlineLesson, index2) => /* @__PURE__ */ React.createElement(xe, { key: outlineLesson.course_lesson_id || outlineLesson.id || index2, href: outlineLesson.course_url || `/academy/lessons/${outlineLesson.slug}`, className: `flex items-start gap-3 rounded-[20px] border px-4 py-3 text-sm transition ${outlineLesson.slug === item.slug ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 bg-black/20 text-slate-300 hover:border-sky-300/25 hover:bg-white/[0.06]"}` }, /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.05] text-[10px] font-semibold" }, String(index2 + 1).padStart(2, "0")), /* @__PURE__ */ React.createElement("span", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold" }, outlineLesson.title), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs uppercase tracking-[0.16em] text-slate-500" }, outlineLesson.is_required ? "Required" : "Optional")))))) : null, lessonTags.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Microtags"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, lessonTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, tag)))) : null, relatedLessonList.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Continue learning"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "More in ", lessonSeries), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, relatedLessonList.map((relatedLesson, index2) => /* @__PURE__ */ React.createElement(
    xe,
    {
      key: relatedLesson.id,
      href: relatedLesson.course_url || `/academy/lessons/${relatedLesson.slug}`,
      className: "group flex gap-4 rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-sky-300/25 hover:bg-white/[0.06]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/15 bg-sky-300/10 text-sm font-semibold text-sky-100" }, String(index2 + 1).padStart(2, "0")),
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, relatedLesson.formatted_lesson_number ? /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, relatedLesson.formatted_lesson_number) : null, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white transition group-hover:text-sky-100" }, relatedLesson.title)), /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, formatLessonMinutes(relatedLesson.reading_minutes))), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6 text-slate-400" }, relatedLesson.excerpt || relatedLesson.content_preview || "Continue the series with the next lesson."))
  )))) : null, relatedCourseList.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Related courses"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, relatedCourseList.map((course) => /* @__PURE__ */ React.createElement(xe, { key: course.id, href: course.public_url, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-sky-300/25 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, course.difficulty, " · ", course.access_level), /* @__PURE__ */ React.createElement("h4", { className: "mt-2 text-sm font-semibold text-white" }, course.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6 text-slate-400" }, course.excerpt || course.description || "Open this course to continue with a guided path."))))) : null))) : pageType === "prompt" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[40px] border border-rose-200/12 bg-[linear-gradient(150deg,rgba(244,63,94,0.14),rgba(15,23,42,0.96)_36%,rgba(45,212,191,0.14))] shadow-[0_24px_90px_rgba(15,23,42,0.34)]" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_14%,rgba(251,113,133,0.15),transparent_24%),linear-gradient(90deg,rgba(255,255,255,0.04)_1px,transparent_1px),linear-gradient(180deg,rgba(255,255,255,0.04)_1px,transparent_1px)] bg-[length:auto,24px_24px,24px_24px] opacity-75" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -left-8 top-10 h-36 w-36 rounded-full bg-rose-300/16 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "absolute -right-10 bottom-0 h-40 w-40 rounded-full bg-cyan-300/14 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-6 p-5 md:p-6 lg:grid-cols-[minmax(0,1fr)_minmax(320px,0.72fr)] lg:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, academyBreadcrumbs.length ? /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement(AcademyBreadcrumbs, { items: academyBreadcrumbs })) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-200/18 bg-rose-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-rose-50/90" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-200" }, "Prompt Library"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, lessonCategory), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, lessonDifficulty), item.aspect_ratio ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-300" }, item.aspect_ratio) : null, item.prompt_of_week ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/25 bg-amber-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-100" }, "Prompt of the week") : null, item.featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-sky-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-rose-100/80" }, "Prompt template"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-[13ch] text-[clamp(2.6rem,5vw,4.8rem)] font-semibold leading-[0.95] tracking-[-0.05em] text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-base leading-8 text-slate-200/95" }, lessonSummary)), /* @__PURE__ */ React.createElement("span", { className: "hidden h-20 w-20 shrink-0 items-center justify-center rounded-[26px] border border-white/10 bg-white/[0.04] text-2xl text-rose-50 shadow-[0_18px_40px_rgba(2,6,23,0.22)] md:flex" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleLike, className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2.5 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]" }, liked ? `Liked · ${likesCount}` : `Like · ${likesCount}`), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleSave, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-sm font-semibold text-sky-100" }, saved ? `Saved · ${savesCount}` : `Save · ${savesCount}`), promptHasFullAccess ? /* @__PURE__ */ React.createElement(PromptCopyButton, { prompt: item.prompt, analytics, contentId: item.id, eventType: "academy_prompt_copy", metadata: { copy_type: "main_prompt", source: "prompt_detail" } }) : null, promptHasFullAccess && item.negative_prompt ? /* @__PURE__ */ React.createElement(PromptCopyButton, { prompt: item.negative_prompt, label: "Copy negative", analytics, contentId: item.id, eventType: "academy_prompt_negative_copy", metadata: { copy_type: "negative_prompt", source: "prompt_detail" } }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-7 grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(
    PromptHeaderStat,
    {
      label: "Category",
      value: lessonCategory,
      icon: "fa-layer-group",
      accentClassName: "border-sky-300/15 bg-sky-300/10 text-sky-100",
      valueClassName: "text-white"
    }
  ), /* @__PURE__ */ React.createElement(
    PromptHeaderStat,
    {
      label: "Access",
      value: formatMetaDisplay(item.access_level || "free"),
      icon: normalizePromptAccessLevel(item.access_level) === "pro" ? "fa-crown" : normalizePromptAccessLevel(item.access_level) === "creator" ? "fa-key" : "fa-lock-open",
      accentClassName: normalizePromptAccessLevel(item.access_level) === "pro" ? "border-amber-300/20 bg-amber-300/10 text-amber-100" : normalizePromptAccessLevel(item.access_level) === "creator" ? "border-violet-300/20 bg-violet-300/10 text-violet-100" : "border-emerald-300/20 bg-emerald-300/10 text-emerald-100",
      valueClassName: normalizePromptAccessLevel(item.access_level) === "pro" ? "text-amber-50" : normalizePromptAccessLevel(item.access_level) === "creator" ? "text-violet-50" : "text-emerald-50"
    }
  ), /* @__PURE__ */ React.createElement(
    PromptHeaderStat,
    {
      label: "Difficulty",
      value: formatMetaDisplay(lessonDifficulty),
      icon: String(lessonDifficulty || "").toLowerCase() === "advanced" ? "fa-bolt" : String(lessonDifficulty || "").toLowerCase() === "beginner" ? "fa-seedling" : "fa-compass-drafting",
      accentClassName: String(lessonDifficulty || "").toLowerCase() === "advanced" ? "border-rose-300/20 bg-rose-300/10 text-rose-100" : String(lessonDifficulty || "").toLowerCase() === "beginner" ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border-sky-300/20 bg-sky-300/10 text-sky-100",
      valueClassName: String(lessonDifficulty || "").toLowerCase() === "advanced" ? "text-rose-50" : String(lessonDifficulty || "").toLowerCase() === "beginner" ? "text-emerald-50" : "text-sky-50"
    }
  ), /* @__PURE__ */ React.createElement(
    PromptHeaderStat,
    {
      label: "Updated",
      value: lessonUpdated,
      icon: "fa-calendar-days",
      accentClassName: "border-white/10 bg-white/[0.05] text-slate-200",
      valueClassName: "text-white"
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:pt-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-full flex-col rounded-[30px] border border-white/10 bg-black/20 p-4 shadow-[0_18px_42px_rgba(2,6,23,0.18)] backdrop-blur-sm md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-rose-100/80" }, "Preview artwork"), promptPreviewImage ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "Click to zoom") : null), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: openPromptPreviewImage,
      className: "group mt-4 flex min-h-[420px] flex-1 flex-col overflow-hidden rounded-[28px] border border-white/10 bg-black/30 text-left shadow-[0_24px_80px_rgba(2,6,23,0.26)] transition hover:border-sky-300/25 focus:outline-none focus:ring-2 focus:ring-sky-300/35 lg:min-h-[640px]",
      disabled: !promptPreviewImage,
      "aria-label": promptPreviewImage ? `Open preview image for ${item.title}` : "Preview image unavailable"
    },
    promptPreviewImage ? /* @__PURE__ */ React.createElement("div", { className: "relative min-h-0 flex-1 overflow-hidden" }, /* @__PURE__ */ React.createElement("img", { src: promptPreviewImage || promptPreviewThumbImage, srcSet: promptPreviewSrcSet || void 0, sizes: "(max-width: 1023px) calc(100vw - 3rem), 34vw", alt: item.title, className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.03]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.02),rgba(2,6,23,0.36))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-4 left-4 right-4 flex items-end justify-between gap-4 rounded-[24px] border border-white/10 bg-black/30 px-4 py-3 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-sky-100/80" }, "Prompt visual"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, "Open full-size preview")), /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-full border border-white/10 bg-white/10 text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-expand" })))) : /* @__PURE__ */ React.createElement("div", { className: "flex min-h-0 flex-1 items-center justify-center bg-[linear-gradient(135deg,rgba(251,146,60,0.14),rgba(17,24,39,0.96))] px-8 text-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Visual placeholder"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-lg font-semibold text-white" }, "Preview image coming soon"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "This prompt page will feel much better once the generated cover image is attached.")))
  ))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 lg:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, !promptHasFullAccess && (promptPreviewImage || promptPublicExamples.length) ? /* @__PURE__ */ React.createElement("section", { className: "academy-public-examples rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(148,163,184,0.03))] p-6 text-slate-200 shadow-[0_24px_70px_rgba(2,6,23,0.2)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-[#ffd8cd]" }, "Public examples"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Example results from this prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Preview the visual direction before unlocking the full prompt.")), item.locked && promptAccessRequirement ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, promptAccessRequirement) : null), /* @__PURE__ */ React.createElement("div", { className: `mt-6 grid gap-4 ${promptPreviewImage ? "xl:grid-cols-[minmax(0,0.98fr)_minmax(0,1.02fr)] xl:items-start" : ""}` }, promptPreviewImage ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => openPromptExampleGallery(0),
      className: "group overflow-hidden rounded-[28px] border border-white/10 bg-slate-950 text-left shadow-[0_18px_50px_rgba(2,6,23,0.22)] transition hover:border-sky-300/25",
      "aria-label": "Open main prompt preview"
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[4/5] overflow-hidden xl:aspect-[6/5]" }, /* @__PURE__ */ React.createElement("img", { src: promptPreviewThumbImage, srcSet: promptPreviewSrcSet || void 0, sizes: "(max-width: 767px) calc(100vw - 4rem), (max-width: 1279px) calc(100vw - 4rem), 640px", alt: item?.title || "Prompt preview", className: "h-full w-full object-cover transition duration-500 group-hover:scale-[1.03]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.04),rgba(2,6,23,0.42))]" })),
    /* @__PURE__ */ React.createElement("div", { className: "space-y-2 border-t border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.94),rgba(2,6,23,0.88))] p-4 md:p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-[#ffcfbf]" }, "Preview artwork"), /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, "Prompt visual"), /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-300" }, item?.excerpt || "Studio-ready packaging, pose, and finish."))
  ) : null, promptFeaturedExamples.length ? /* @__PURE__ */ React.createElement("div", { className: `grid gap-3 ${promptPreviewImage ? "sm:grid-cols-2 xl:grid-cols-1" : "sm:grid-cols-2 xl:grid-cols-3"}` }, promptFeaturedExamples.map((example, index2) => /* @__PURE__ */ React.createElement(
    PromptPublicExampleCard,
    {
      key: `${example.image_path || example.image_url || "example"}-${index2}`,
      example,
      index: index2,
      galleryIndex: index2 + (promptPreviewImage ? 1 : 0),
      onOpenImage: openPromptExampleGallery,
      className: !promptPreviewImage && index2 === 0 ? "sm:col-span-2 xl:col-span-2" : "",
      frameClassName: promptPreviewImage ? "aspect-[16/10]" : index2 === 0 ? "aspect-[16/10]" : "aspect-[6/7]"
    }
  ))) : null), promptOverflowExamples.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-3" }, promptOverflowExamples.map((example, index2) => /* @__PURE__ */ React.createElement(
    PromptPublicExampleCard,
    {
      key: `${example.image_path || example.image_url || "overflow-example"}-${index2}`,
      example,
      index: index2 + promptFeaturedExamples.length,
      galleryIndex: index2 + promptFeaturedExamples.length + (promptPreviewImage ? 1 : 0),
      onOpenImage: openPromptExampleGallery,
      frameClassName: index2 % 3 === 0 ? "aspect-[6/7]" : index2 % 3 === 1 ? "aspect-square" : "aspect-[5/6]"
    }
  ))) : null) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(148,163,184,0.03))] p-6 text-slate-200 shadow-[0_24px_70px_rgba(2,6,23,0.2)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4 border-b border-white/10 pb-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-[#ffd8cd]" }, "Prompt body"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Prompt text and exclusions"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "academy-paywalled-content rounded-[28px] border border-[#ffcfbf]/15 bg-[linear-gradient(180deg,rgba(255,207,191,0.08),rgba(255,255,255,0.03))] p-5 md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-[#fff0ea]" }, promptHasFullAccess ? "Full prompt" : "Preview prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.16em] text-slate-500" }, promptHasFullAccess ? "Ready to paste into your generation workflow." : "Upgrade your Academy access to reveal the complete prompt text.")), promptBody ? /* @__PURE__ */ React.createElement(
    PromptCopyButton,
    {
      prompt: promptBody,
      label: promptHasFullAccess ? "Copy prompt" : "Copy preview",
      analytics,
      contentId: item.id,
      eventType: "academy_prompt_copy",
      metadata: { copy_type: promptHasFullAccess ? "main_prompt" : "preview_prompt", source: "prompt_body" }
    }
  ) : null), /* @__PURE__ */ React.createElement("pre", { className: "mt-4 whitespace-pre-wrap rounded-[24px] border border-white/10 bg-slate-950/80 p-4 text-sm leading-7 text-slate-100 md:p-5" }, promptBody || "Prompt text is not available yet."), !promptHasFullAccess ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-amber-300/20 bg-amber-300/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-amber-100/80" }, promptUnlockTitle || "Unlock the full prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-amber-50/90" }, promptUnlockDetails), promptAccessRequirement ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs font-semibold uppercase tracking-[0.18em] text-amber-100" }, promptAccessRequirement) : null) : null), item.negative_prompt ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5 md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Negative prompt"), /* @__PURE__ */ React.createElement(
    PromptCopyButton,
    {
      prompt: item.negative_prompt,
      label: "Copy negative",
      analytics,
      contentId: item.id,
      eventType: "academy_prompt_negative_copy",
      metadata: { copy_type: "negative_prompt", source: "prompt_body" }
    }
  )), /* @__PURE__ */ React.createElement("pre", { className: "mt-4 whitespace-pre-wrap rounded-[24px] border border-white/10 bg-slate-950/70 p-4 text-sm leading-7 text-slate-200 md:p-5" }, item.negative_prompt)) : null)), promptUsageNotes || promptWorkflowNotes ? /* @__PURE__ */ React.createElement("section", { className: "academy-paywalled-content rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.82))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Prompt guidance"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "How to use this prompt")), !promptHasFullAccess ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Full notes visible with access") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 md:grid-cols-2" }, promptUsageNotes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-200/75" }, "Usage notes"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, promptUsageNotes)) : null, promptWorkflowNotes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-emerald-200/75" }, "Workflow notes"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, promptWorkflowNotes)) : null)) : null, hasPromptDocumentation ? /* @__PURE__ */ React.createElement(PromptDocumentationPanel, { documentation: promptDocumentation }) : null, hasPromptPlaceholders ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(148,163,184,0.03))] p-6 text-slate-200 shadow-[0_24px_70px_rgba(2,6,23,0.2)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Data"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Placeholders and required inputs"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Prepare these variables before using the final prompt so the output stays consistent and reusable.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 xl:grid-cols-2" }, promptPlaceholders.map((placeholder, index2) => /* @__PURE__ */ React.createElement(PromptPlaceholderCard, { key: `${placeholder.key || "placeholder"}-${index2}`, placeholder })))) : null, null, null, hasPromptVariants ? /* @__PURE__ */ React.createElement(PromptVariantsSection, { variants: promptVariants, analytics, contentId: item.id }) : null, promptHasLockedVariants ? /* @__PURE__ */ React.createElement("section", { className: "academy-paywalled-content rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.045),rgba(148,163,184,0.03))] p-6 text-slate-200 shadow-[0_24px_70px_rgba(2,6,23,0.2)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Variants"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Alternative prompt versions are included"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "This prompt includes recommended or model-specific variants, but they stay locked until your Academy access level matches the template.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(LockedPanel, { pricingUrl, label: "prompt", accessLevel: item?.access_level, onUpgrade: () => trackUpgradeClick(analytics, { source: "prompt_variant_locked_panel" }) }))) : null, promptComparisons.length ? /* @__PURE__ */ React.createElement("section", { className: "academy-paywalled-content rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(255,183,139,0.12),transparent_30%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 text-slate-200 shadow-[0_24px_80px_rgba(2,6,23,0.28)] md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-[#ffcfbf]" }, "AI model comparisons"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white md:text-3xl" }, "How different models respond to the same prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300 md:text-base" }, "Use these notes to decide which provider fits the result you want before you start tuning or post-processing.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 xl:grid-cols-2" }, promptComparisons.map((note, index2) => /* @__PURE__ */ React.createElement(PromptToolNoteCard, { key: `${note.provider || "provider"}-${note.model_name || "model"}-${index2}`, note, index: index2, galleryIndex: index2, onOpenImage: openPromptComparisonGallery })))) : null), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6 lg:sticky lg:top-6 lg:self-start" }, lessonTags.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Microtags"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, lessonTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, tag)))) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(15,23,42,0.84))] p-6 text-slate-200 shadow-[0_18px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Best use case"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, promptBestUseCase))))) : /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 text-slate-200" }, pageType === "pack" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-8 text-slate-200" }, item.description), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, (item.prompts || []).map((prompt) => /* @__PURE__ */ React.createElement("div", { key: prompt.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, prompt.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, prompt.excerpt || prompt.prompt_preview))))) : null, pageType === "challenge" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Brief"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.brief || item.description)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Rules"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.rules || "No special rules posted yet."))), (item.submissions || []).length ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Approved submissions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, item.submissions.map((submission) => /* @__PURE__ */ React.createElement("div", { key: submission.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, submission.artwork?.title || "Submission"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, submission.user?.name || "Unknown creator"))))) : null) : null)), /* @__PURE__ */ React.createElement(ImageLightbox, { gallery: lightboxGallery, onClose: () => setLightboxGallery(null), onNavigate: navigateLightboxGallery }));
}
const __vite_glob_0_9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyShow
}, Symbol.toStringTag, { value: "Module" }));
const buildAdminNavGroups = (isAdmin) => [
  {
    label: "Overview",
    items: [
      { label: "Dashboard", href: "/moderation", icon: "fa-solid fa-gauge-high", exact: true },
      { label: "Daily Activity", href: "/moderation/activity", icon: "fa-solid fa-calendar-day" },
      { label: "Online Users", href: "/moderation/traffic/online", icon: "fa-solid fa-user-check" }
    ]
  },
  {
    label: "People",
    items: [
      { label: "All Users", href: "/moderation/users", icon: "fa-solid fa-users" },
      { label: "Staff", href: "/moderation/users?role=admin", icon: "fa-solid fa-shield-halved" },
      { label: "Moderators", href: "/moderation/users?role=moderator", icon: "fa-solid fa-user-shield" }
    ]
  },
  {
    label: "Content",
    items: [
      { label: "Stories", href: "/moderation/stories", icon: "fa-solid fa-feather-pointed" },
      { label: "Artworks", href: "/moderation/artworks", icon: "fa-solid fa-images" },
      { label: "Enhance Jobs", href: "/moderation/enhance", icon: "fa-solid fa-up-right-and-down-left-from-center" },
      { label: "Featured Artworks", href: "/moderation/artworks/featured", icon: "fa-solid fa-star" },
      { label: "Web Stories", href: "/moderation/web-stories", icon: "fa-solid fa-book-open-reader" },
      { label: "Homepage Announcements", href: "/moderation/homepage/announcements", icon: "fa-solid fa-bullhorn" },
      { label: "Upload Queue", href: "/moderation/uploads", icon: "fa-solid fa-cloud-arrow-up" },
      { label: "Username Queue", href: "/moderation/usernames/moderation", icon: "fa-solid fa-id-badge" },
      { label: "AI Biography", href: "/moderation/ai-biography", icon: "fa-solid fa-wand-magic-sparkles" }
    ]
  },
  {
    label: "Academy",
    items: [
      { label: "Academy Dashboard", href: "/moderation/academy/dashboard", icon: "fa-solid fa-graduation-cap" },
      { label: "Academy Billing", href: "/moderation/academy/billing", icon: "fa-solid fa-credit-card" },
      { label: "Academy Analytics", href: "/moderation/academy/analytics", icon: "fa-solid fa-chart-line" },
      { label: "Academy Courses", href: "/moderation/academy/courses", icon: "fa-solid fa-road" },
      { label: "Academy Lessons", href: "/moderation/academy/lessons", icon: "fa-solid fa-book-open" },
      { label: "Academy Prompts", href: "/moderation/academy/prompts", icon: "fa-solid fa-wand-magic-sparkles" },
      { label: "Academy Challenges", href: "/moderation/academy/challenges", icon: "fa-solid fa-trophy" }
    ]
  },
  {
    label: "System",
    items: [
      ...isAdmin ? [{ label: "Auth Audit", href: "/moderation/auth-audit", icon: "fa-solid fa-user-shield" }] : [],
      { label: "Settings", href: "/moderation/settings", icon: "fa-solid fa-gear" }
    ]
  }
];
function NavLink$2({ item, active }) {
  const cls = `flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${active ? "bg-rose-500/20 text-rose-300 shadow-sm shadow-rose-500/10" : "text-slate-400 hover:text-white hover:bg-white/5"}`;
  if (item.href === "/moderation/traffic/online") {
    return /* @__PURE__ */ React.createElement("a", { href: item.href, className: cls }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }), /* @__PURE__ */ React.createElement("span", null, item.label));
  }
  return /* @__PURE__ */ React.createElement(xe, { href: item.href, className: cls }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }), /* @__PURE__ */ React.createElement("span", null, item.label));
}
function Sidebar({ pathname, isAdmin }) {
  const adminNavGroups = buildAdminNavGroups(isAdmin);
  const isActive = (item) => {
    if (item.exact) return pathname === item.href;
    return pathname.startsWith(item.href.split("?")[0]);
  };
  return /* @__PURE__ */ React.createElement("aside", { className: "nova-scrollbar flex h-full w-64 flex-col overflow-y-auto border-r border-white/[0.07] bg-[rgba(10,14,22,0.98)] px-3 py-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-8 px-3" }, /* @__PURE__ */ React.createElement(xe, { href: "/moderation", className: "flex items-center gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 items-center justify-center rounded-lg bg-rose-500/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-halved text-sm text-rose-400" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-400/80" }, "Skinbase"), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-bold text-white" }, "Admin Panel")))), /* @__PURE__ */ React.createElement("nav", { className: "flex-1 space-y-6" }, adminNavGroups.map((group) => /* @__PURE__ */ React.createElement("div", { key: group.label }, /* @__PURE__ */ React.createElement("p", { className: "mb-1.5 px-4 text-[10px] font-bold uppercase tracking-[0.2em] text-slate-600" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "space-y-0.5" }, group.items.map((item) => /* @__PURE__ */ React.createElement(NavLink$2, { key: item.href, item, active: isActive(item) })))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-0.5 border-t border-white/[0.06] pt-4" }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: "/studio",
      className: "flex items-center gap-3 rounded-xl px-4 py-2.5 text-sm text-slate-500 transition hover:bg-white/5 hover:text-slate-300"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left w-5 text-center text-base" }),
    /* @__PURE__ */ React.createElement("span", null, "Back to Studio")
  )));
}
function AdminLayout({ children, title, subtitle }) {
  const { url, props } = X$1();
  const [mobileOpen, setMobileOpen] = reactExports.useState(false);
  const pathname = url.split("?")[0];
  const currentUserIsAdmin = Boolean(props.auth?.user?.is_admin);
  return /* @__PURE__ */ React.createElement("div", { className: "flex min-h-screen bg-[radial-gradient(ellipse_at_top,_rgba(239,68,68,0.08),_transparent_40%),linear-gradient(180deg,#060a12_0%,#020409_100%)]" }, /* @__PURE__ */ React.createElement("div", { className: "hidden lg:flex lg:w-64 lg:flex-shrink-0" }, /* @__PURE__ */ React.createElement("div", { className: "fixed inset-y-0 left-0 w-64" }, /* @__PURE__ */ React.createElement(Sidebar, { pathname, isAdmin: currentUserIsAdmin }))), /* @__PURE__ */ React.createElement("div", { className: "fixed inset-x-0 top-0 z-40 flex items-center justify-between border-b border-white/10 bg-[rgba(10,14,22,0.97)] px-4 py-3 backdrop-blur-xl lg:hidden" }, /* @__PURE__ */ React.createElement(xe, { href: "/moderation", className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-halved text-rose-400" }), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-bold text-white" }, "Admin Panel")), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setMobileOpen(!mobileOpen),
      className: "rounded-full border border-white/10 p-2 text-slate-400 hover:text-white",
      "aria-label": "Toggle navigation"
    },
    /* @__PURE__ */ React.createElement("i", { className: mobileOpen ? "fa-solid fa-xmark" : "fa-solid fa-bars" })
  )), mobileOpen && /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-30 lg:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-black/60 backdrop-blur-sm", onClick: () => setMobileOpen(false) }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-0 top-0 h-full w-72 pt-14" }, /* @__PURE__ */ React.createElement(Sidebar, { pathname, isAdmin: currentUserIsAdmin }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-1 flex-col lg:pl-8" }, /* @__PURE__ */ React.createElement("main", { className: "flex-1 px-6 py-8 pt-20 lg:pt-8" }, (title || subtitle) && /* @__PURE__ */ React.createElement("div", { className: "mb-8" }, title && /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white" }, title), subtitle && /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle)), children)));
}
function AnalyticsNav({ items = [] }) {
  if (!items.length) return null;
  const pathname = typeof window !== "undefined" ? window.location.pathname : "";
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, items.map((item) => {
    const active = pathname === item.href;
    return /* @__PURE__ */ React.createElement(
      xe,
      {
        key: item.href,
        href: item.href,
        className: `rounded-full border px-4 py-2 text-sm font-semibold transition ${active ? "border-sky-300/25 bg-sky-300/12 text-sky-100" : "border-white/[0.08] bg-white/[0.04] text-slate-300 hover:border-white/15 hover:bg-white/[0.06] hover:text-white"}`
      },
      item.label
    );
  }));
}
const __vite_glob_0_13 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AnalyticsNav
}, Symbol.toStringTag, { value: "Module" }));
function MetricCell({ value, suffix = "" }) {
  return /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, value, suffix);
}
function StatCard$g({ label, value, suffix = "" }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, value, suffix));
}
function AcademyAnalyticsContent({ nav = [], range: range2, title, subtitle, summary = null, rows = [] }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(AnalyticsNav, { items: nav }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Range"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, range2?.from, " to ", range2?.to)), summary ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$g, { label: "Views", value: Number(summary.views || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Unique Visitors", value: Number(summary.uniqueVisitors || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Engaged Views", value: Number(summary.engagedViews || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Engagement Rate", value: Number(summary.engagementRate || 0).toLocaleString(), suffix: "%" }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Avg Engaged Seconds", value: Number(summary.avgEngagedSeconds || 0).toLocaleString(), suffix: "s" }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Scroll 50%", value: Number(summary.scroll50 || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Scroll 100%", value: Number(summary.scroll100 || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$g, { label: "Deep Scroll Rate", value: Number(summary.deepScrollRate || 0).toLocaleString(), suffix: "%" })) : null, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/[0.08] bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full text-left text-sm" }, /* @__PURE__ */ React.createElement("thead", { className: "border-b border-white/[0.08] bg-black/20 text-[11px] uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Title"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Type"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Access"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Views"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Unique"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Engaged"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Likes"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Saves"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Copies"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Starts"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Completions"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Upgrade Clicks"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Popularity"), /* @__PURE__ */ React.createElement("th", { className: "px-4 py-3" }, "Trend"))), /* @__PURE__ */ React.createElement("tbody", null, rows.length ? rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: `${row.content_type}-${row.content_id || "none"}`, className: "border-b border-white/[0.06] align-top text-slate-300" }, /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, "ID ", row.content_id || "n/a")), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, row.content_type_label), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, row.access_level || "n/a"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.views })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.unique_visitors })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.engaged_views })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.likes })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.saves })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.prompt_copies })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.starts })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.completions })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.upgrade_clicks })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(MetricCell, { value: row.popularity_score })), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, row.trend))) : /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 14, className: "px-4 py-10 text-center text-slate-400" }, "No rollup data available yet for this view."))))))));
}
const __vite_glob_0_10 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyAnalyticsContent
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$f({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(value || 0).toLocaleString()));
}
function AcademyAnalyticsFunnel({ nav = [], range: range2, summary = {}, bestConverters = [] }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Funnel", subtitle: "Early conversion signals from premium previews, upgrade clicks, and learning starts." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Funnel" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(AnalyticsNav, { items: nav }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Range"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, range2?.from, " to ", range2?.to)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$f, { label: "Academy Visitors", value: summary.academyVisitors }), /* @__PURE__ */ React.createElement(StatCard$f, { label: "Premium Preview Views", value: summary.premiumPreviewViews }), /* @__PURE__ */ React.createElement(StatCard$f, { label: "Upgrade Clicks", value: summary.upgradeClicks }), /* @__PURE__ */ React.createElement(StatCard$f, { label: "Learning Starts", value: summary.starts }), /* @__PURE__ */ React.createElement(StatCard$f, { label: "Completions", value: summary.completions }), /* @__PURE__ */ React.createElement(StatCard$f, { label: "Checkout Starts", value: summary.checkoutStarts }), /* @__PURE__ */ React.createElement(StatCard$f, { label: "Subscriptions", value: summary.subscriptions })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Best Converting Content"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, bestConverters.length ? bestConverters.map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.content_type}-${item.content_id || "none"}`, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.content_type_label)), /* @__PURE__ */ React.createElement("div", { className: "text-right" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, item.conversion_score), /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "conversion"))))) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-6 text-sm text-slate-400" }, "No conversion signals have been rolled up yet.")))));
}
const __vite_glob_0_11 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyAnalyticsFunnel
}, Symbol.toStringTag, { value: "Module" }));
function SummaryCard$6({ label, value, description }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(value || 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, description));
}
function RangeControls({ range: range2 }) {
  const pathname = typeof window !== "undefined" ? window.location.pathname : "";
  const [from, setFrom] = reactExports.useState(range2?.from || "");
  const [to, setTo] = reactExports.useState(range2?.to || "");
  const visit2 = (nextRange, nextFrom = from, nextTo = to) => {
    At.get(pathname, {
      range: nextRange,
      ...nextRange === "custom" ? { from: nextFrom, to: nextTo } : {}
    }, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Date Range"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, range2?.from, " to ", range2?.to)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (range2?.options || []).map((option) => {
    const active = option.value === range2?.active;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => visit2(option.value),
        className: `rounded-full border px-4 py-2 text-sm font-semibold transition ${active ? "border-sky-300/30 bg-sky-300/12 text-sky-100" : "border-white/[0.08] bg-white/[0.04] text-slate-300 hover:border-white/15 hover:bg-white/[0.06] hover:text-white"}`
      },
      option.label
    );
  }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap items-end gap-3 border-t border-white/[0.08] pt-5" }, /* @__PURE__ */ React.createElement("label", { className: "flex flex-col gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, "From"), /* @__PURE__ */ React.createElement("input", { type: "date", value: from, onChange: (event) => setFrom(event.target.value), className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-3 text-white outline-none transition focus:border-sky-300/30" })), /* @__PURE__ */ React.createElement("label", { className: "flex flex-col gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, "To"), /* @__PURE__ */ React.createElement("input", { type: "date", value: to, onChange: (event) => setTo(event.target.value), className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-3 text-white outline-none transition focus:border-sky-300/30" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => visit2("custom", from, to), className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/15 hover:bg-white/[0.06]" }, "Apply Custom Range")));
}
function Section$2({ title, description, children }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-slate-300" }, description))), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children));
}
function EmptyState$7({ text: text2 }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-8 text-sm text-slate-400" }, text2);
}
function Badge$4({ children, tone = "default" }) {
  const tones2 = {
    default: "border-white/[0.08] bg-white/[0.04] text-slate-200",
    high: "border-rose-300/25 bg-rose-300/10 text-rose-100",
    medium: "border-amber-300/25 bg-amber-300/10 text-amber-100",
    low: "border-emerald-300/25 bg-emerald-300/10 text-emerald-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${tones2[tone] || tones2.default}` }, children);
}
function Table({ columns, children }) {
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto rounded-[24px] border border-white/[0.08] bg-black/20" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/[0.08] text-left" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", null, columns.map((column) => /* @__PURE__ */ React.createElement("th", { key: column, className: "px-4 py-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, column)))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.06]" }, children)));
}
function OpportunityHighlights({ items = [] }) {
  if (!items.length) {
    return /* @__PURE__ */ React.createElement(EmptyState$7, { text: "Recommendations will appear here once Academy analytics has enough activity in the selected range." });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, items.map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: `${item.title}-${index2}`, className: "rounded-[24px] border border-white/[0.08] bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement(Badge$4, { tone: item.priority }, item.priority)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.reason), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm font-semibold text-sky-100" }, item.suggested_action))));
}
function AcademyAnalyticsIntelligence({
  nav = [],
  range: range2,
  contentOpportunities = {},
  searchGaps = {},
  promptInsights = {},
  lessonDropoffs = {},
  courseHealth = {},
  premiumInterest = {},
  editorialRecommendations = {}
}) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Content Intelligence", subtitle: "Editorial and business signals from Academy rollups, search demand, engagement, and premium intent." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Content Intelligence" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(AnalyticsNav, { items: nav }), /* @__PURE__ */ React.createElement(RangeControls, { range: range2 }), /* @__PURE__ */ React.createElement(Section$2, { title: "Content Opportunities", description: "A fast view of where Academy demand is strongest, where content is underperforming, and which changes should be prioritized next." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4 2xl:grid-cols-7" }, (contentOpportunities?.cards || []).map((card) => /* @__PURE__ */ React.createElement(SummaryCard$6, { key: card.label, label: card.label, value: card.value, description: card.description }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(OpportunityHighlights, { items: contentOpportunities?.highlights || [] }))), /* @__PURE__ */ React.createElement(Section$2, { title: "Search Gaps", description: "Queries that suggest missing content, weak relevance, or topics worth expanding because users are clearly engaging with them." }, searchGaps?.rows?.length ? /* @__PURE__ */ React.createElement(Table, { columns: ["Query", "Searches", "Results", "Clicks", "CTR", "Suggested Action"] }, searchGaps.rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: row.normalized_query }, /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 align-top" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, row.query), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Badge$4, { tone: row.priority }, row.issue), row.logged_in_searches > 1 ? /* @__PURE__ */ React.createElement(Badge$4, null, "Logged-in x", row.logged_in_searches) : null, row.subscriber_searches > 0 ? /* @__PURE__ */ React.createElement(Badge$4, null, "Subscribers x", row.subscriber_searches) : null)), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.searches), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.results_count), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.clicks), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.ctr, "%"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm leading-6 text-slate-300" }, row.suggested_action)))) : /* @__PURE__ */ React.createElement(EmptyState$7, { text: "No Academy search gaps were detected in this range." })), /* @__PURE__ */ React.createElement(Section$2, { title: "Prompt Insights", description: "Signals that show whether prompts need better quality, stronger discoverability, more examples, or a premium follow-up." }, promptInsights?.rows?.length ? /* @__PURE__ */ React.createElement(Table, { columns: ["Prompt", "Views", "Copies", "Copy Rate", "Saves", "Likes", "Issue", "Suggested Action"] }, promptInsights.rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: row.content_id }, /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 align-top" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.18em] text-slate-500" }, row.content_type_label)), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.views), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.prompt_copies), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.copy_rate, "%"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.saves), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.likes), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(Badge$4, { tone: row.priority }, row.issue)), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm leading-6 text-slate-300" }, row.suggested_action)))) : /* @__PURE__ */ React.createElement(EmptyState$7, { text: "No prompt intelligence signals were detected in this range." })), /* @__PURE__ */ React.createElement(Section$2, { title: "Lesson Drop-offs", description: "Lessons where users hesitate to start, fail to finish, or unexpectedly show strong premium interest." }, lessonDropoffs?.rows?.length ? /* @__PURE__ */ React.createElement(Table, { columns: ["Lesson", "Views", "Starts", "Completions", "Completion Rate", "Issue", "Suggested Action"] }, lessonDropoffs.rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: row.content_id }, /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 align-top" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Start rate ", row.start_rate, "%")), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.views), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.starts), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.completions), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.completion_rate, "%"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(Badge$4, { tone: row.priority }, row.issue)), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm leading-6 text-slate-300" }, row.suggested_action)))) : /* @__PURE__ */ React.createElement(EmptyState$7, { text: "No lesson drop-off signals were detected in this range." })), /* @__PURE__ */ React.createElement(Section$2, { title: "Course Health", description: "Courses that need better positioning or restructuring, plus courses that have enough momentum to justify expansion." }, courseHealth?.rows?.length ? /* @__PURE__ */ React.createElement(Table, { columns: ["Course", "Views", "Starts", "Completions", "Completion Rate", "Avg Progress", "Suggested Action"] }, courseHealth.rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: row.content_id }, /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 align-top" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Badge$4, { tone: row.priority }, row.issue), row.learners > 0 ? /* @__PURE__ */ React.createElement(Badge$4, null, "Learners ", row.learners) : null)), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.views), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.starts), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.completions), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.completion_rate, "%"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.avg_progress, "%"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm leading-6 text-slate-300" }, row.suggested_action)))) : /* @__PURE__ */ React.createElement(EmptyState$7, { text: "No course health signals were detected in this range." })), /* @__PURE__ */ React.createElement(Section$2, { title: "Premium Interest", description: "Free and premium Academy content that either converts well into upgrade intent or needs stronger teaser positioning." }, premiumInterest?.rows?.length ? /* @__PURE__ */ React.createElement(Table, { columns: ["Content", "Type", "Premium Views", "Upgrade Clicks", "Upgrade Rate", "Suggested Action"] }, premiumInterest.rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: `${row.content_type}-${row.content_id}` }, /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 align-top" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Badge$4, { tone: row.priority }, row.issue), /* @__PURE__ */ React.createElement(Badge$4, null, "Interest score ", row.premium_interest_score))), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.content_type_label), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.premium_preview_views), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.upgrade_clicks), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-200" }, row.upgrade_rate, "%"), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm leading-6 text-slate-300" }, row.suggested_action)))) : /* @__PURE__ */ React.createElement(EmptyState$7, { text: "No premium interest signals were detected in this range." })), /* @__PURE__ */ React.createElement(Section$2, { title: "Editorial Recommendations", description: "Prioritized recommendations that combine content demand, user behavior, and premium intent into concrete next actions." }, editorialRecommendations?.rows?.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, editorialRecommendations.rows.map((row, index2) => /* @__PURE__ */ React.createElement("div", { key: `${row.title}-${index2}`, className: "rounded-[24px] border border-white/[0.08] bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-base font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement(Badge$4, { tone: row.priority }, row.priority)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, row.description), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Reason"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, row.reason), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Suggested Action"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold leading-6 text-sky-100" }, row.suggested_action)))) : /* @__PURE__ */ React.createElement(EmptyState$7, { text: "No editorial recommendations were generated for this range yet." }))));
}
const __vite_glob_0_12 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyAnalyticsIntelligence
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$e({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(value || 0).toLocaleString()));
}
function formatDelta(delta) {
  if (delta === null || delta === void 0) {
    return "new";
  }
  if (Number(delta) === 0) {
    return "0%";
  }
  return `${Number(delta) > 0 ? "+" : ""}${Number(delta).toLocaleString()}%`;
}
function PromptLibraryTrend({ trend }) {
  const current = trend?.current || {};
  const deltas = trend?.deltas || {};
  const items = [
    { label: "Views", value: Number(current.views || 0).toLocaleString(), delta: deltas.views },
    { label: "Unique Visitors", value: Number(current.uniqueVisitors || 0).toLocaleString(), delta: deltas.uniqueVisitors },
    { label: "Engaged Views", value: Number(current.engagedViews || 0).toLocaleString(), delta: deltas.engagedViews },
    { label: "Engagement Rate", value: `${Number(current.engagementRate || 0).toLocaleString()}%`, delta: deltas.engagementRate }
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Prompt Library Trend"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, trend?.range?.current?.from, " to ", trend?.range?.current?.to, " compared with ", trend?.range?.previous?.from, " to ", trend?.range?.previous?.to)), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/[0.08] bg-black/20 px-4 py-2 text-xs uppercase tracking-[0.18em] text-slate-400" }, "Popularity ", Number(current.popularityScore || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-2xl border border-white/[0.08] bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-2xl font-bold text-white" }, item.value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.18em] text-sky-200" }, formatDelta(item.delta), " vs previous")))));
}
function PopularPromptPeriodUsage({ usage }) {
  const periods = usage?.periods || [];
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Popular Prompt Period Usage"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Which ranking window people actually open on the public popular-prompts page.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/[0.08] bg-black/20 px-4 py-2 text-xs uppercase tracking-[0.18em] text-slate-400" }, Number(usage?.totalViews || 0).toLocaleString(), " views · ", Number(usage?.totalVisitors || 0).toLocaleString(), " visitors")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, periods.length ? periods.map((period) => /* @__PURE__ */ React.createElement("div", { key: period.period, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, period.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, period.period)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-right sm:grid-cols-3 sm:gap-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, Number(period.views || 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Views")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, Number(period.uniqueVisitors || 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Visitors")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, Number(period.share || 0).toLocaleString(), "%"), /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Share")))))) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-6 text-sm text-slate-400" }, "No popular prompt period events have been tracked in this range yet.")));
}
function ContentList({ title, items = [] }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, items.length ? items.map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.content_type}-${item.content_id || "none"}`, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.content_type_label)), /* @__PURE__ */ React.createElement("div", { className: "text-right" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, item.popularity_score), /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "popularity"))))) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-6 text-sm text-slate-400" }, "No rollup data yet for this range.")));
}
function AcademyAnalyticsOverview({ nav = [], range: range2, stats, promptLibraryTrend = null, popularPromptPeriodUsage = null, topContent = [], topWeek = [] }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Analytics", subtitle: "Daily rollup overview for Academy traffic, engagement, and subscription intent." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Analytics" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(AnalyticsNav, { items: nav }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Range"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, range2?.from, " to ", range2?.to)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$e, { label: "Views", value: stats.views }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Unique Visitors", value: stats.uniqueVisitors }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Logged-in Views", value: stats.userViews }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Guest Views", value: stats.guestViews }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Subscriber Views", value: stats.subscriberViews }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Prompt Copies", value: stats.promptCopies }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Likes", value: stats.likes }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Saves", value: stats.saves }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Lesson Completions", value: stats.lessonCompletions }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Course Starts", value: stats.courseStarts }), /* @__PURE__ */ React.createElement(StatCard$e, { label: "Upgrade Clicks", value: stats.upgradeClicks })), promptLibraryTrend ? /* @__PURE__ */ React.createElement(PromptLibraryTrend, { trend: promptLibraryTrend }) : null, popularPromptPeriodUsage ? /* @__PURE__ */ React.createElement(PopularPromptPeriodUsage, { usage: popularPromptPeriodUsage }) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(ContentList, { title: "Top Content In Range", items: topContent }), /* @__PURE__ */ React.createElement(ContentList, { title: "Top Content This Week", items: topWeek }))));
}
const __vite_glob_0_14 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyAnalyticsOverview
}, Symbol.toStringTag, { value: "Module" }));
function SearchList({ title, items = [], emptyText }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, items.length ? items.map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: `${item.query}-${index2}`, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, item.query), "searches" in item ? /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, item.searches) : null), "avg_results" in item ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Average results: ", item.avg_results) : null, "clicks" in item ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Clicks: ", item.clicks) : null, "click_through_rate" in item ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "CTR: ", item.click_through_rate, "%") : null, "results_count" in item ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Results: ", item.results_count) : null)) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-6 text-sm text-slate-400" }, emptyText)));
}
function FilterUsageList({ items = [] }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Filter Usage"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, items.length ? items.map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.filter}-${item.value}`, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, item.filter, ": ", item.value), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, item.uses)))) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-6 text-sm text-slate-400" }, "No Academy search filters were used in this range.")));
}
function ClickedResultsList({ items = [] }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Top Clicked Results"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, items.length ? items.map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.content_type}-${item.content_id}`, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-sky-100" }, item.clicks)), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, item.content_type))) : /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-dashed border-white/[0.08] bg-black/20 px-4 py-6 text-sm text-slate-400" }, "No clicked Academy search results were logged in this range.")));
}
function AcademyAnalyticsSearch({ nav = [], range: range2, summary = {}, topSearches = [], zeroResults = [], lowClickThroughSearches = [], highestClickThroughSearches = [], searchesWithResultsNoClicks = [], topClickedResults = [], filterUsage = [], recentSearches = [] }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Search Analytics", subtitle: "Search demand, zero-result gaps, and recent Academy query activity." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Search Analytics" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(AnalyticsNav, { items: nav }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Searches"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(summary.searches || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Zero Result Searches"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(summary.zeroResultSearches || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Logged-in Searches"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(summary.loggedInSearches || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Subscriber Searches"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(summary.subscriberSearches || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Searches With Clicks"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, Number(summary.searchesWithClicks || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Needs CTR Tracking"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Low-click sections use stored search click attribution when present. Queries without clicked-result updates will stay at 0% CTR until that interaction is sent."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Range"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, range2?.from, " to ", range2?.to)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(SearchList, { title: "Top Searches", items: topSearches, emptyText: "No Academy searches were logged in this range." }), /* @__PURE__ */ React.createElement(SearchList, { title: "Highest CTR Searches", items: highestClickThroughSearches, emptyText: "No clicked Academy searches were logged in this range." }), /* @__PURE__ */ React.createElement(SearchList, { title: "Zero-result Searches", items: zeroResults, emptyText: "No zero-result searches were logged in this range." })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(SearchList, { title: "Low Click-through Searches", items: lowClickThroughSearches, emptyText: "No low click-through Academy searches were logged in this range." }), /* @__PURE__ */ React.createElement(SearchList, { title: "Results With No Clicks", items: searchesWithResultsNoClicks, emptyText: "No Academy searches with results but no clicks were logged in this range." }), /* @__PURE__ */ React.createElement(ClickedResultsList, { items: topClickedResults })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(FilterUsageList, { items: filterUsage }), /* @__PURE__ */ React.createElement(SearchList, { title: "Recent Searches", items: recentSearches, emptyText: "No recent Academy searches were logged in this range." }))));
}
const __vite_glob_0_15 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyAnalyticsSearch
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$d({ label, value, hint = null }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, value.toLocaleString()), hint ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, hint) : null);
}
function formatTimestamp$1(value) {
  if (!value) return "No webhook processed yet";
  try {
    return new Intl.DateTimeFormat(void 0, {
      dateStyle: "medium",
      timeStyle: "short"
    }).format(new Date(value));
  } catch {
    return value;
  }
}
function formatEventSummary(summary) {
  const payload = summary && typeof summary === "object" ? summary : {};
  const preferredKeys = [
    "action",
    "outcome",
    "local_subscription_status",
    "status",
    "tracked",
    "user_resolved"
  ];
  const prioritized = preferredKeys.filter((key) => Object.prototype.hasOwnProperty.call(payload, key)).map((key) => [key, payload[key]]);
  const priceIds = Array.isArray(payload.price_ids) && payload.price_ids.length ? [["price_ids", payload.price_ids.join(", ")]] : [];
  const cacheCleared = typeof payload.cache_cleared === "boolean" ? [["cache_cleared", payload.cache_cleared ? "yes" : "no"]] : [];
  const lines = [...prioritized, ...priceIds, ...cacheCleared].filter(([, value]) => value !== null && value !== void 0 && value !== "").slice(0, 4);
  return lines.length ? lines.map(([key, value]) => `${key}: ${String(value)}`).join(" · ") : "No summary fields captured";
}
function AcademyBilling({ summary, planBreakdown, recentEvents, links }) {
  const missingPlans = Array.isArray(summary.missing_plan_keys) ? summary.missing_plan_keys : [];
  const noData = summary.enabled && (summary.active_subscribers || 0) === 0 && (summary.ended_subscriptions || 0) === 0 && (summary.recent_webhook_count || 0) === 0;
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Billing", subtitle: "Moderation overview of Academy subscriptions, Stripe webhook sync activity, and plan readiness." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Billing" }), noData ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-sky-300/20 bg-sky-300/[0.06] px-5 py-4 text-sm text-sky-100" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold" }, "No subscriber data in the database yet."), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sky-100/70" }, "Subscription records are created when Stripe sends webhook events to this server after a completed checkout. In local development, use", " ", /* @__PURE__ */ React.createElement("code", { className: "rounded bg-black/30 px-1.5 py-0.5 font-mono text-xs" }, "stripe listen --forward-to ", window.location.origin, "/stripe/webhook"), " ", "to forward events. On production, confirm the Stripe webhook is configured and active.")) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$d, { label: "Active Subscribers", value: summary.active_subscribers || 0 }), /* @__PURE__ */ React.createElement(StatCard$d, { label: "Creator Subscribers", value: summary.creator_subscribers || 0 }), /* @__PURE__ */ React.createElement(StatCard$d, { label: "Pro Subscribers", value: summary.pro_subscribers || 0 }), /* @__PURE__ */ React.createElement(StatCard$d, { label: "Grace Period", value: summary.grace_period_subscribers || 0, hint: "Canceled subscriptions that still keep access until the billing period ends." })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[1.2fr_0.8fr]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Plan Health"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Configured Academy plans")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: links.dashboard, className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-semibold text-slate-200 transition hover:border-white/15 hover:bg-white/[0.06] hover:text-white" }, "Dashboard"), /* @__PURE__ */ React.createElement(xe, { href: links.pricing, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/30 hover:bg-sky-300/15" }, "Public pricing"), /* @__PURE__ */ React.createElement(xe, { href: links.account, className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-4 py-2 text-sm font-semibold text-emerald-100 transition hover:border-emerald-300/30 hover:bg-emerald-300/15" }, "My billing account"))), missingPlans.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-amber-300/25 bg-amber-300/10 px-4 py-3 text-sm text-amber-100" }, "Missing Stripe price IDs for: ", missingPlans.join(", ")) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, "All configured Academy plans have Stripe price IDs."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, planBreakdown.map((plan) => /* @__PURE__ */ React.createElement("div", { key: plan.key, className: "rounded-2xl border border-white/[0.08] bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-base font-semibold text-white" }, plan.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, plan.tier, " · ", plan.interval)), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-1 text-xs font-semibold uppercase tracking-[0.18em] ${plan.configured ? "bg-emerald-300/12 text-emerald-100" : "bg-amber-300/12 text-amber-100"}` }, plan.configured ? "configured" : "missing")), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-3xl font-bold text-white" }, (plan.subscribers || 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "active subscriptions on this plan"))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Webhook Sync"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Recent Stripe activity"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Billing enabled"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-lg font-semibold text-white" }, summary.enabled ? "Yes" : "No")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Webhook audits stored"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-lg font-semibold text-white" }, (summary.recent_webhook_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Last processed webhook"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-lg font-semibold text-white" }, formatTimestamp$1(summary.last_webhook_at))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Ended subscriptions"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-lg font-semibold text-white" }, (summary.ended_subscriptions || 0).toLocaleString()))))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Audit Trail"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Latest academy billing events")), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Only the safe local summary is stored, not the raw Stripe payload.")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/[0.08] text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "text-left text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "px-3 py-3" }, "Event"), /* @__PURE__ */ React.createElement("th", { className: "px-3 py-3" }, "Plan"), /* @__PURE__ */ React.createElement("th", { className: "px-3 py-3" }, "Tier"), /* @__PURE__ */ React.createElement("th", { className: "px-3 py-3" }, "User"), /* @__PURE__ */ React.createElement("th", { className: "px-3 py-3" }, "Processed"), /* @__PURE__ */ React.createElement("th", { className: "px-3 py-3" }, "Summary"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.06]" }, recentEvents.length ? recentEvents.map((event) => /* @__PURE__ */ React.createElement("tr", { key: event.id }, /* @__PURE__ */ React.createElement("td", { className: "px-3 py-3 font-medium text-white" }, event.event_type), /* @__PURE__ */ React.createElement("td", { className: "px-3 py-3" }, event.academy_plan || "n/a"), /* @__PURE__ */ React.createElement("td", { className: "px-3 py-3" }, event.academy_tier || "n/a"), /* @__PURE__ */ React.createElement("td", { className: "px-3 py-3" }, event.user_id || "guest/unresolved"), /* @__PURE__ */ React.createElement("td", { className: "px-3 py-3" }, formatTimestamp$1(event.processed_at || event.created_at)), /* @__PURE__ */ React.createElement("td", { className: "px-3 py-3 text-slate-400" }, formatEventSummary(event.payload_summary)))) : /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: "6", className: "px-3 py-6 text-center text-slate-400" }, "No Academy billing webhook audits have been stored yet.")))))));
}
const __vite_glob_0_16 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyBilling
}, Symbol.toStringTag, { value: "Module" }));
const MONTH_NAMES = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];
const YEAR_MIN = 1900;
const YEAR_MAX = 2105;
const DAY_ABBR = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
function pad(value) {
  return String(value).padStart(2, "0");
}
function daysInMonth(year, month) {
  return new Date(year, month + 1, 0).getDate();
}
function firstWeekday(year, month) {
  const day = new Date(year, month, 1).getDay();
  return (day + 6) % 7;
}
function toISODate(date) {
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
function parseDatePart(value) {
  if (!value) return null;
  const [year, month, day] = value.split("-").map(Number);
  if (!year || !month || !day) return null;
  return new Date(year, month - 1, day);
}
function normalizeDateTimeInput(value) {
  const raw = String(value || "").trim();
  if (!raw) return { date: "", time: "" };
  const match = raw.match(/^(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2})(?::\d{2})?)?(?:Z|[+-]\d{2}:?\d{2})?$/);
  if (match) {
    return {
      date: match[1],
      time: match[2] || ""
    };
  }
  const parsed = new Date(raw);
  if (Number.isNaN(parsed.getTime())) {
    return { date: raw, time: "" };
  }
  return {
    date: toISODate(parsed),
    time: `${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`
  };
}
function splitDateTime(value) {
  const normalized = normalizeDateTimeInput(value);
  return {
    date: normalized.date,
    time: normalized.time.slice(0, 5)
  };
}
function mergeDateTime(date, time) {
  if (!date) return "";
  return `${date}T${time || "00:00"}`;
}
function maxDateValue(a, b2) {
  if (!a) return b2 || "";
  if (!b2) return a || "";
  return a > b2 ? a : b2;
}
function minDateValue(a, b2) {
  if (!a) return b2 || "";
  if (!b2) return a || "";
  return a < b2 ? a : b2;
}
function clampTimeToBounds(date, time, minDateTime, maxDateTime) {
  const nextTime = time || "00:00";
  const minParts = splitDateTime(minDateTime);
  const maxParts = splitDateTime(maxDateTime);
  if (date && minParts.date === date && minParts.time && nextTime < minParts.time) {
    return minParts.time;
  }
  if (date && maxParts.date === date && maxParts.time && nextTime > maxParts.time) {
    return maxParts.time;
  }
  return nextTime;
}
function formatDisplay(value) {
  if (!value) return "";
  const { date, time } = splitDateTime(value);
  const parsed = parseDatePart(date);
  if (!parsed) return "";
  return `${MONTH_NAMES[parsed.getMonth()].slice(0, 3)} ${parsed.getDate()}, ${parsed.getFullYear()}${time ? ` at ${time}` : ""}`;
}
function isSameDay(a, b2) {
  return a?.getFullYear() === b2?.getFullYear() && a?.getMonth() === b2?.getMonth() && a?.getDate() === b2?.getDate();
}
function CalendarGrid({ year, month, selectedDate, onSelect, minDate, maxDate }) {
  const count = daysInMonth(year, month);
  const start = firstWeekday(year, month);
  const prevMonth = month - 1 < 0 ? 11 : month - 1;
  const prevYear = month - 1 < 0 ? year - 1 : year;
  const prevCount = daysInMonth(prevYear, prevMonth);
  const cells = [];
  for (let index2 = start - 1; index2 >= 0; index2 -= 1) {
    cells.push({
      day: prevCount - index2,
      current: false,
      date: new Date(prevYear, prevMonth, prevCount - index2)
    });
  }
  for (let day = 1; day <= count; day += 1) {
    cells.push({ day, current: true, date: new Date(year, month, day) });
  }
  let nextDay = 1;
  while (cells.length % 7 !== 0) {
    cells.push({ day: nextDay, current: false, date: new Date(year, month + 1, nextDay) });
    nextDay += 1;
  }
  const today = /* @__PURE__ */ new Date();
  today.setHours(0, 0, 0, 0);
  return /* @__PURE__ */ React.createElement("div", { className: "p-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-1 grid grid-cols-7" }, DAY_ABBR.map((day) => /* @__PURE__ */ React.createElement("div", { key: day, className: "py-1 text-center text-[10px] font-semibold text-slate-500" }, day))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-7 gap-y-0.5" }, cells.map((cell, index2) => {
    const iso = toISODate(cell.date);
    const selected = isSameDay(cell.date, selectedDate);
    const todayCell = isSameDay(cell.date, today);
    const disabled = minDate && iso < minDate || maxDate && iso > maxDate;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: `${iso}-${index2}`,
        type: "button",
        disabled,
        onClick: () => onSelect(iso),
        className: [
          "relative mx-auto flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-all",
          !cell.current ? "text-slate-600" : "",
          cell.current && !selected && !disabled ? "text-white hover:bg-white/10" : "",
          selected ? "bg-accent font-semibold text-white shadow shadow-accent/30" : "",
          todayCell && !selected ? "text-accent ring-1 ring-accent/50" : "",
          disabled ? "cursor-not-allowed opacity-30" : "cursor-pointer"
        ].join(" ")
      },
      cell.day
    );
  })));
}
function DateTimePicker({
  value = "",
  onChange,
  label,
  placeholder,
  error,
  hint,
  required = false,
  clearable = false,
  id,
  disabled = false,
  mode = "datetime",
  minDate,
  maxDate,
  minDateTime,
  maxDateTime,
  className = ""
}) {
  const today = /* @__PURE__ */ new Date();
  const initial = splitDateTime(value);
  const initialDate = parseDatePart(initial.date) || today;
  const [open, setOpen] = reactExports.useState(false);
  const [dropPos, setDropPos] = reactExports.useState({ top: 0, left: 0, width: 320 });
  const [viewYear, setViewYear] = reactExports.useState(initialDate.getFullYear());
  const [viewMonth, setViewMonth] = reactExports.useState(initialDate.getMonth());
  const [draftDate, setDraftDate] = reactExports.useState(initial.date);
  const nowTime = `${pad(today.getHours())}:${pad(today.getMinutes())}`;
  const defaultDraftTime = (function() {
    const baseDate = initial.date || toISODate(initialDate);
    const candidate = initial.time || nowTime;
    return clampTimeToBounds(baseDate, candidate, minDateTime, maxDateTime);
  })();
  const [draftTime, setDraftTime] = reactExports.useState(defaultDraftTime);
  const effectivePlaceholder = placeholder || (mode === "date" ? "Pick a date" : "Pick a date and time");
  const triggerRef = reactExports.useRef(null);
  const inputId = id ?? (label ? `dtp-${label.toLowerCase().replace(/\s+/g, "-")}` : "date-time-picker");
  const panelId = `dtp-panel-${inputId}`;
  reactExports.useEffect(() => {
    const next = splitDateTime(value);
    setDraftDate(next.date);
    const fallbackTime = (() => {
      const candidate = next.time || `${pad((/* @__PURE__ */ new Date()).getHours())}:${pad((/* @__PURE__ */ new Date()).getMinutes())}`;
      const dateForClamp = next.date || toISODate(initialDate);
      return clampTimeToBounds(dateForClamp, candidate, minDateTime, maxDateTime);
    })();
    setDraftTime(next.time || fallbackTime);
    const nextDate = parseDatePart(next.date);
    if (nextDate) {
      setViewYear(nextDate.getFullYear());
      setViewMonth(nextDate.getMonth());
    }
  }, [value]);
  const measure = reactExports.useCallback(() => {
    if (!triggerRef.current) return;
    const rect = triggerRef.current.getBoundingClientRect();
    const panelWidth = Math.max(rect.width, 320);
    const panelHeight = 420;
    const openUp = window.innerHeight - rect.bottom < panelHeight + 8 && rect.top > panelHeight + 8;
    setDropPos({
      top: openUp ? rect.top - panelHeight - 4 : rect.bottom + 4,
      left: Math.min(rect.left, window.innerWidth - panelWidth - 8),
      width: panelWidth
    });
  }, []);
  const openPicker = reactExports.useCallback(() => {
    if (disabled) return;
    measure();
    setOpen(true);
  }, [disabled, measure]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleMouseDown = (event) => {
      if (!triggerRef.current?.contains(event.target) && !document.getElementById(panelId)?.contains(event.target)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleMouseDown);
    return () => document.removeEventListener("mousedown", handleMouseDown);
  }, [open, panelId]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleScroll = (event) => {
      if (document.getElementById(panelId)?.contains(event.target)) return;
      setOpen(false);
    };
    const handleResize = () => setOpen(false);
    window.addEventListener("scroll", handleScroll, true);
    window.addEventListener("resize", handleResize);
    return () => {
      window.removeEventListener("scroll", handleScroll, true);
      window.removeEventListener("resize", handleResize);
    };
  }, [open, panelId]);
  const applyValue = reactExports.useCallback((date, time) => {
    if (!date) {
      onChange?.("");
      return;
    }
    onChange?.(mode === "date" ? date : mergeDateTime(date, time));
  }, [mode, onChange]);
  const handleDateSelect = (nextDate) => {
    const nextTime = clampTimeToBounds(nextDate, draftTime, minDateTime, maxDateTime);
    setDraftDate(nextDate);
    setDraftTime(nextTime);
    applyValue(nextDate, nextTime);
  };
  const handleTimeChange = (event) => {
    const nextTime = clampTimeToBounds(draftDate, event.target.value, minDateTime, maxDateTime);
    setDraftTime(nextTime);
    applyValue(draftDate, nextTime);
  };
  const clearValue = (event) => {
    event.stopPropagation();
    const now = `${pad((/* @__PURE__ */ new Date()).getHours())}:${pad((/* @__PURE__ */ new Date()).getMinutes())}`;
    setDraftDate("");
    setDraftTime(now);
    onChange?.("");
  };
  const prevMonth = () => {
    if (viewMonth === 0) {
      setViewMonth(11);
      setViewYear((current) => current - 1);
      return;
    }
    setViewMonth((current) => current - 1);
  };
  const nextMonth = () => {
    if (viewMonth === 11) {
      setViewMonth(0);
      setViewYear((current) => current + 1);
      return;
    }
    setViewMonth((current) => current + 1);
  };
  const triggerClass = [
    "relative flex h-[42px] w-full cursor-pointer items-center gap-2 rounded-xl border px-3.5 text-sm transition-all duration-150",
    "bg-white/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-0",
    error ? "border-red-500/60 focus-visible:ring-red-500/40" : open ? "border-accent/50 ring-2 ring-accent/40" : "border-white/12 hover:border-white/22",
    disabled ? "pointer-events-none cursor-not-allowed opacity-50" : "",
    className
  ].join(" ");
  const selectedDate = parseDatePart(draftDate);
  const minDateTimeParts = splitDateTime(minDateTime);
  const maxDateTimeParts = splitDateTime(maxDateTime);
  const effectiveMinDate = maxDateValue(minDate, minDateTimeParts.date);
  const effectiveMaxDate = minDateValue(maxDate, maxDateTimeParts.date);
  const minTime = draftDate && draftDate === minDateTimeParts.date ? minDateTimeParts.time || void 0 : void 0;
  const maxTime = draftDate && draftDate === maxDateTimeParts.date ? maxDateTimeParts.time || void 0 : void 0;
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1.5" }, label && /* @__PURE__ */ React.createElement("label", { htmlFor: inputId, className: "text-sm font-medium text-white/85 select-none" }, label, required && /* @__PURE__ */ React.createElement("span", { className: "ml-1 text-red-400" }, "*")), /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: triggerRef,
      id: inputId,
      role: "button",
      tabIndex: disabled ? -1 : 0,
      "aria-label": label ?? effectivePlaceholder,
      className: triggerClass,
      onClick: openPicker,
      onKeyDown: (event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          openPicker();
        }
      }
    },
    /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", className: "shrink-0 text-slate-500", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("rect", { x: "1", y: "2.5", width: "12", height: "10.5", rx: "1.5", stroke: "currentColor", strokeWidth: "1.3" }), /* @__PURE__ */ React.createElement("path", { d: "M1 6h12", stroke: "currentColor", strokeWidth: "1.3" }), /* @__PURE__ */ React.createElement("path", { d: "M4 1v3M10 1v3", stroke: "currentColor", strokeWidth: "1.3", strokeLinecap: "round" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "9", r: "0.75", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "7", cy: "9", r: "0.75", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "9.5", cy: "9", r: "0.75", fill: "currentColor" })),
    /* @__PURE__ */ React.createElement("span", { className: `flex-1 truncate ${value ? "text-white" : "text-slate-500"}` }, value ? formatDisplay(value) : effectivePlaceholder),
    clearable && value && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        tabIndex: -1,
        onClick: clearValue,
        className: "flex h-5 w-5 items-center justify-center rounded text-slate-500 transition-colors hover:text-white",
        "aria-label": "Clear date and time"
      },
      /* @__PURE__ */ React.createElement("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M1 1l8 8M9 1L1 9", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round" }))
    )
  ), error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error), !error && hint && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, hint), open && reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        id: panelId,
        className: "fixed z-[500] overflow-hidden rounded-2xl border border-white/12 bg-nova-900 shadow-2xl shadow-black/50",
        style: { top: dropPos.top, left: dropPos.left, width: dropPos.width }
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-2 px-3 pt-3" }, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: prevMonth,
          className: "flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-all hover:bg-white/8 hover:text-white",
          "aria-label": "Previous month"
        },
        /* @__PURE__ */ React.createElement("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M7 1L3 5l4 4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))
      ), /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 flex-1 items-center justify-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "whitespace-nowrap text-sm font-semibold text-white" }, MONTH_NAMES[viewMonth]), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 rounded-xl border border-white/10 bg-white/[0.04] px-1 py-1" }, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => setViewYear((current) => Math.max(YEAR_MIN, current - 1)),
          disabled: viewYear <= YEAR_MIN,
          className: "flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-all hover:bg-white/8 hover:text-white disabled:cursor-not-allowed disabled:opacity-30",
          "aria-label": "Previous year"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-minus text-[11px]", "aria-hidden": "true" })
      ), /* @__PURE__ */ React.createElement("span", { className: "min-w-[72px] px-2 text-center text-sm font-semibold text-white" }, viewYear), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => setViewYear((current) => Math.min(YEAR_MAX, current + 1)),
          disabled: viewYear >= YEAR_MAX,
          className: "flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-all hover:bg-white/8 hover:text-white disabled:cursor-not-allowed disabled:opacity-30",
          "aria-label": "Next year"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-[11px]", "aria-hidden": "true" })
      ))), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: nextMonth,
          className: "flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-all hover:bg-white/8 hover:text-white",
          "aria-label": "Next month"
        },
        /* @__PURE__ */ React.createElement("svg", { width: "10", height: "10", viewBox: "0 0 10 10", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M3 1l4 4-4 4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))
      )),
      /* @__PURE__ */ React.createElement(
        CalendarGrid,
        {
          year: viewYear,
          month: viewMonth,
          selectedDate,
          onSelect: handleDateSelect,
          minDate: effectiveMinDate,
          maxDate: effectiveMaxDate
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/8 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: `grid gap-3 ${mode === "date" ? "" : "sm:grid-cols-[minmax(0,1fr)_7rem] sm:items-end"}` }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Selected date"), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white" }, draftDate ? formatDisplay(draftDate) : "Pick a day")), mode !== "date" ? /* @__PURE__ */ React.createElement("label", { className: "grid gap-1.5 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Time"), /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "time",
          value: draftTime,
          onChange: handleTimeChange,
          min: minTime,
          max: maxTime,
          className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-white outline-none transition focus:border-accent/50 focus:ring-2 focus:ring-accent/40"
        }
      )) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-between" }, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => handleDateSelect(toISODate(/* @__PURE__ */ new Date())),
          className: "text-xs font-medium text-accent transition-colors hover:text-accent/80"
        },
        "Today"
      ), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => setOpen(false),
          className: "rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-medium text-white transition hover:bg-white/[0.08]"
        },
        "Done"
      )))
    ),
    document.body
  ));
}
function ShareToast({ message = "Link copied!", visible = false, onHide, duration = 2e3, variant = "success" }) {
  const [show, setShow] = reactExports.useState(false);
  const config = variant === "error" ? {
    border: "border-rose-300/25",
    background: "bg-rose-950/90",
    text: "text-rose-50",
    icon: "text-rose-300",
    role: "alert",
    live: "assertive",
    iconPath: "M12 9v3.75m0 3.75h.007v.008H12v-.008ZM10.29 3.86 1.82 18a1.875 1.875 0 0 0 1.606 2.813h16.148A1.875 1.875 0 0 0 21.18 18L12.71 3.86a1.875 1.875 0 0 0-3.42 0Z"
  } : {
    border: "border-white/[0.10]",
    background: "bg-nova-800/90",
    text: "text-white",
    icon: "text-emerald-400",
    role: "status",
    live: "polite",
    iconPath: "M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z"
  };
  reactExports.useEffect(() => {
    if (visible) {
      const enterTimer = requestAnimationFrame(() => setShow(true));
      const hideTimer = setTimeout(() => {
        setShow(false);
        setTimeout(() => onHide?.(), 200);
      }, duration);
      return () => {
        cancelAnimationFrame(enterTimer);
        clearTimeout(hideTimer);
      };
    } else {
      setShow(false);
    }
  }, [visible, duration, onHide]);
  if (!visible) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        role: config.role,
        "aria-live": config.live,
        className: [
          "fixed bottom-24 left-1/2 z-[10001] -translate-x-1/2 rounded-full border px-5 py-2.5 text-sm font-medium shadow-xl backdrop-blur-md transition-all duration-200",
          config.border,
          config.background,
          config.text,
          show ? "translate-y-0 opacity-100" : "translate-y-3 opacity-0"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: `h-4 w-4 ${config.icon}` }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: config.iconPath, clipRule: "evenodd" })), message)
    ),
    document.body
  );
}
function formatBytes$2(bytes) {
  const value = Number(bytes || 0);
  if (!Number.isFinite(value) || value <= 0) return null;
  if (value < 1024 * 1024) return `${Math.round(value / 1024)} KB`;
  return `${(value / (1024 * 1024)).toFixed(1)} MB`;
}
function WorldMediaUploadField({
  label,
  slot,
  value,
  previewUrl,
  emptyLabel,
  helperText,
  uploadUrl,
  deleteUrl,
  worldId = null,
  onChange,
  isTemporaryValue = false,
  accept = "image/jpeg,image/png,image/webp",
  maxFileSizeMb = 6
}) {
  const inputRef = reactExports.useRef(null);
  const [dragging, setDragging] = reactExports.useState(false);
  const [uploading, setUploading] = reactExports.useState(false);
  const [error, setError] = reactExports.useState("");
  const [meta, setMeta] = reactExports.useState(null);
  const csrfToken2 = reactExports.useMemo(() => {
    if (typeof document === "undefined") {
      return "";
    }
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
  }, []);
  const deleteTemporaryUpload = async (path) => {
    if (!deleteUrl || !path) return;
    const response = await fetch(deleteUrl, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken2,
        Accept: "application/json"
      },
      credentials: "same-origin",
      body: JSON.stringify({
        path,
        world_id: worldId || void 0
      })
    });
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(payload?.message || payload?.error || "Could not remove uploaded image.");
    }
  };
  const handleFile = async (file) => {
    if (!file || uploading) return;
    const allowed = ["image/jpeg", "image/png", "image/webp"];
    if (!allowed.includes(String(file.type || "").toLowerCase())) {
      setError("Use a JPG, PNG, or WEBP image.");
      return;
    }
    if (file.size > maxFileSizeMb * 1024 * 1024) {
      setError(`Image is too large. Maximum allowed size is ${maxFileSizeMb} MB.`);
      return;
    }
    setUploading(true);
    setError("");
    try {
      if (value && isTemporaryValue) {
        await deleteTemporaryUpload(value);
      }
      const body2 = new FormData();
      body2.append("slot", slot);
      body2.append("image", file);
      if (worldId) {
        body2.append("world_id", String(worldId));
      }
      const response = await fetch(uploadUrl, {
        method: "POST",
        headers: {
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        },
        credentials: "same-origin",
        body: body2
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || payload?.error || "Upload failed.");
      }
      setMeta({
        width: payload?.width || null,
        height: payload?.height || null,
        size: formatBytes$2(payload?.size_bytes)
      });
      onChange?.({ path: payload?.path || "", url: payload?.url || "" });
    } catch (uploadError) {
      setError(uploadError?.message || "Upload failed.");
    } finally {
      setUploading(false);
      if (inputRef.current) {
        inputRef.current.value = "";
      }
    }
  };
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), value ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: async (event) => {
        event.stopPropagation();
        setError("");
        setMeta(null);
        try {
          if (value && isTemporaryValue) {
            setUploading(true);
            await deleteTemporaryUpload(value);
          }
          onChange?.({ path: "", url: "" });
        } catch (deleteError) {
          setError(deleteError?.message || "Could not remove uploaded image.");
        } finally {
          setUploading(false);
        }
      },
      disabled: uploading,
      className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-white"
    },
    "Clear"
  ) : null), /* @__PURE__ */ React.createElement(
    "div",
    {
      role: "button",
      tabIndex: 0,
      onClick: () => !uploading && inputRef.current?.click(),
      onKeyDown: (event) => {
        if (uploading) return;
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          inputRef.current?.click();
        }
      },
      onDragOver: (event) => {
        event.preventDefault();
        if (!uploading) setDragging(true);
      },
      onDragEnter: (event) => {
        event.preventDefault();
        if (!uploading) setDragging(true);
      },
      onDragLeave: (event) => {
        event.preventDefault();
        setDragging(false);
      },
      onDrop: (event) => {
        event.preventDefault();
        setDragging(false);
        void handleFile(event.dataTransfer?.files?.[0]);
      },
      className: [
        "rounded-[24px] border border-dashed px-5 py-5 transition outline-none",
        uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : dragging ? "cursor-pointer border-sky-300/50 bg-sky-400/12" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-cloud-arrow-up"}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, uploading ? "Uploading image…" : "Drop image here or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, helperText), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "JPG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "PNG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "Max ", maxFileSizeMb, " MB")))), /* @__PURE__ */ React.createElement("div", { className: "h-28 w-full overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 lg:w-44" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center px-4 text-center text-sm text-slate-500" }, emptyLabel))),
    value ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 truncate rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs text-slate-400" }, "Stored path: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, value)) : null,
    meta ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "Optimized to ", meta.width, "×", meta.height, meta.size ? ` • ${meta.size}` : "") : null,
    error ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null,
    /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: inputRef,
        type: "file",
        accept,
        className: "hidden",
        disabled: uploading,
        onChange: (event) => {
          void handleFile(event.target.files?.[0]);
        }
      }
    )
  ));
}
const CHALLENGE_EDITOR_TABS = [
  {
    id: "overview",
    label: "Overview",
    description: "Title, slug, access, and the compact summary shown in academy challenge lists.",
    icon: "fa-compass-drafting",
    sections: ["challenge-identity"]
  },
  {
    id: "brief",
    label: "Brief",
    description: "Write the creative objective, rules, prizes, required tags, and eligible categories.",
    icon: "fa-bullseye",
    sections: ["challenge-brief", "challenge-rules"]
  },
  {
    id: "media",
    label: "Media",
    description: "Upload the hero cover and tune the visual used on challenge cards.",
    icon: "fa-image",
    sections: ["challenge-media"]
  },
  {
    id: "timeline",
    label: "Timeline",
    description: "Manage submission and voting windows without mixing them into editorial copy.",
    icon: "fa-calendar-days",
    sections: ["challenge-timeline"]
  },
  {
    id: "publish",
    label: "Publish",
    description: "Control status, visibility, featured placement, and the final public preview.",
    icon: "fa-rocket-launch",
    sections: ["challenge-publishing", "challenge-preview"]
  }
];
const CHALLENGE_FIELD_TAB_MAP = {
  title: "overview",
  slug: "overview",
  excerpt: "overview",
  access_level: "overview",
  description: "brief",
  brief: "brief",
  rules: "brief",
  prize_text: "brief",
  required_tags: "brief",
  allowed_categories: "brief",
  cover_image: "media",
  starts_at: "timeline",
  ends_at: "timeline",
  voting_starts_at: "timeline",
  voting_ends_at: "timeline",
  status: "publish",
  featured: "publish",
  active: "publish"
};
function getField$3(fields, name2) {
  return fields.find((field) => field.name === name2) || null;
}
function FieldError$4({ message }) {
  if (!message) return null;
  return /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, message);
}
function SectionCard$7({ id, eyebrow, title, description, actions, children, tone = "default", className = "" }) {
  const toneClass = tone === "feature" ? "bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.15),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] shadow-[0_24px_70px_rgba(2,6,23,0.28)]" : "bg-white/[0.03]";
  return /* @__PURE__ */ React.createElement("section", { id, className: `min-w-0 scroll-mt-24 rounded-[28px] border border-white/10 p-5 ${toneClass} ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/75" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, description) : null), actions ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, actions) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children));
}
function EditorWorkspaceTabs$2({ activeTab, onChange, errorCounts }) {
  const activeMeta = CHALLENGE_EDITOR_TABS.find((tab2) => tab2.id === activeTab) || CHALLENGE_EDITOR_TABS[0];
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-4 z-20 rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(7,11,18,0.92),rgba(5,8,14,0.88))] px-3 py-3 shadow-[0_18px_50px_rgba(2,6,23,0.18)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2", role: "tablist", "aria-label": "Challenge editor sections" }, CHALLENGE_EDITOR_TABS.map((tab2) => {
    const isActive = tab2.id === activeTab;
    const errorCount = Number(errorCounts?.[tab2.id] || 0);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.id,
        type: "button",
        role: "tab",
        "aria-selected": isActive,
        "aria-controls": `challenge-editor-panel-${tab2.id}`,
        id: `challenge-editor-tab-${tab2.id}`,
        onClick: () => onChange(tab2.id),
        className: [
          "inline-flex items-center gap-2 rounded-2xl border px-4 py-2.5 text-sm font-semibold transition",
          isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-white/80 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} text-xs` }),
      /* @__PURE__ */ React.createElement("span", null, tab2.label),
      errorCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-rose-100" }, errorCount) : null
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center justify-between gap-3 px-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-400" }, activeMeta.description), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, activeMeta.sections.map((section) => /* @__PURE__ */ React.createElement("span", { key: section, className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, section.replace("challenge-", "").replace(/-/g, " "))))));
}
function TextField$4({ label, value, onChange, error, hint, ...rest }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("input", { value: value ?? "", onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", ...rest }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$4, { message: error }));
}
function TextAreaField$3({ label, value, onChange, error, rows = 4, hint, placeholder }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("textarea", { value: value ?? "", onChange, rows, placeholder, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 leading-7 text-white outline-none placeholder:text-slate-600" }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$4, { message: error }));
}
function ToggleField$3({ label, checked, onChange, help, error }) {
  return /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer items-start gap-4 rounded-[28px] border px-5 py-4 transition ${checked ? "border-[#f39a24]/35 bg-[#f39a24]/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "sr-only" }), /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border text-sm transition ${checked ? "border-[#f39a24] bg-[#f39a24] text-white" : "border-white/10 bg-[#151a29] text-transparent"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check" })), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block text-base font-semibold tracking-[-0.02em] text-white" }, label), help ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-sm leading-6 text-slate-300" }, help) : null, /* @__PURE__ */ React.createElement(FieldError$4, { message: error })));
}
function PlainTextPreview({ title, value, fallback }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, String(value || "").trim() || fallback));
}
function statusMeta(status2) {
  const normalized = String(status2 || "draft");
  const labels = {
    draft: "Draft",
    scheduled: "Scheduled",
    active: "Active",
    voting: "Voting",
    completed: "Completed",
    archived: "Archived"
  };
  const classes = {
    draft: "border-white/10 bg-white/[0.04] text-slate-300",
    scheduled: "border-fuchsia-300/20 bg-fuchsia-300/10 text-fuchsia-100",
    active: "border-emerald-300/20 bg-emerald-300/10 text-emerald-100",
    voting: "border-sky-300/20 bg-sky-300/10 text-sky-100",
    completed: "border-amber-300/20 bg-amber-300/10 text-amber-100",
    archived: "border-slate-300/15 bg-slate-300/8 text-slate-300"
  };
  return {
    label: labels[normalized] || normalized,
    className: classes[normalized] || classes.draft
  };
}
function slugifyChallengeTitle(value) {
  return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 180);
}
function normalizeList(value) {
  return String(value || "").split(/[,\n]/).map((item) => item.trim()).filter(Boolean);
}
function normalizeAssetPreview$1(value, cdnBaseUrl) {
  const trimmed = String(value || "").trim();
  if (!trimmed) return "";
  if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) return trimmed;
  return `${String(cdnBaseUrl || "").replace(/\/$/, "")}/${trimmed.replace(/^\//, "")}`;
}
function stripPlainText$1(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}
function countWords$2(value) {
  const text2 = stripPlainText$1(value);
  return text2 ? text2.split(/\s+/).length : 0;
}
function formatDateLabel$2(value, fallback = "Not set") {
  if (!value) return fallback;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return fallback;
  return new Intl.DateTimeFormat("en", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  }).format(date);
}
function daysBetween(start, end) {
  const startDate = start ? new Date(start) : null;
  const endDate = end ? new Date(end) : null;
  if (!startDate || !endDate || Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
    return null;
  }
  const diff = endDate.getTime() - startDate.getTime();
  if (diff < 0) return "Dates need review";
  const days = Math.max(1, Math.ceil(diff / (1e3 * 60 * 60 * 24)));
  return `${days} day${days === 1 ? "" : "s"}`;
}
function firstErrorMessage$4(errors, fallback = "Please correct the highlighted fields and try again.") {
  const queue = [errors];
  while (queue.length > 0) {
    const current = queue.shift();
    if (typeof current === "string") {
      const message = current.trim();
      if (message) return message;
      continue;
    }
    if (Array.isArray(current)) {
      queue.push(...current);
      continue;
    }
    if (current && typeof current === "object") {
      queue.push(...Object.values(current));
    }
  }
  return fallback;
}
function firstChallengeErrorTab(errors) {
  const firstKey = Object.keys(errors || {})[0];
  if (!firstKey) return null;
  const baseKey = firstKey.split(".")[0];
  return CHALLENGE_FIELD_TAB_MAP[baseKey] || null;
}
function challengeTabErrorCounts(errors) {
  const counts = {};
  Object.keys(errors || {}).forEach((key) => {
    const tabId = CHALLENGE_FIELD_TAB_MAP[key.split(".")[0]];
    if (!tabId) return;
    counts[tabId] = Number(counts[tabId] || 0) + 1;
  });
  return counts;
}
function buildChallengePayload(data) {
  return {
    ...data,
    required_tags: normalizeList(data.required_tags),
    allowed_categories: normalizeList(data.allowed_categories)
  };
}
function ChallengeEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext = {} }) {
  const form = G$1(record);
  const slugTouchedRef = reactExports.useRef(String(record?.slug || "").trim() !== "");
  const [activeTab, setActiveTab] = reactExports.useState("overview");
  const [coverPreviewUrl, setCoverPreviewUrl] = reactExports.useState(record?.cover_image_url || normalizeAssetPreview$1(record?.cover_image, editorContext.coverCdnBaseUrl));
  const [stagedCoverPath, setStagedCoverPath] = reactExports.useState("");
  const [toast, setToast] = reactExports.useState({ id: 0, visible: false, message: "", variant: "success" });
  const accessField = getField$3(fields, "access_level");
  const statusField = getField$3(fields, "status");
  const status2 = statusMeta(form.data.status);
  const requiredTags = reactExports.useMemo(() => normalizeList(form.data.required_tags), [form.data.required_tags]);
  const allowedCategories = reactExports.useMemo(() => normalizeList(form.data.allowed_categories), [form.data.allowed_categories]);
  const briefWordCount = countWords$2(`${form.data.description || ""} ${form.data.brief || ""} ${form.data.rules || ""}`);
  const submissionWindow = daysBetween(form.data.starts_at, form.data.ends_at);
  const votingWindow = daysBetween(form.data.voting_starts_at, form.data.voting_ends_at);
  const publicPathPreview = `/academy/challenges/${form.data.slug || "challenge-slug"}`;
  const errorCounts = challengeTabErrorCounts(form.errors);
  const sectionClassName = (sectionId) => {
    const tab2 = CHALLENGE_EDITOR_TABS.find((item) => item.sections.includes(sectionId));
    return tab2 && tab2.id !== activeTab ? "hidden" : "";
  };
  const showToast = (message, variant = "error") => {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant
    });
  };
  const setTitle = (nextTitle) => {
    form.setData("title", nextTitle);
    if (!slugTouchedRef.current) {
      form.setData("slug", slugifyChallengeTitle(nextTitle));
    }
  };
  const handleManualCoverChange = (nextValue) => {
    setStagedCoverPath("");
    form.setData("cover_image", nextValue);
    setCoverPreviewUrl(normalizeAssetPreview$1(nextValue, editorContext.coverCdnBaseUrl));
  };
  const submit = (event) => {
    event.preventDefault();
    const payload = buildChallengePayload(form.data);
    form.transform(() => payload);
    const submitOptions = {
      preserveScroll: true,
      onError: (errors) => {
        const nextTab = firstChallengeErrorTab(errors);
        if (nextTab) {
          setActiveTab(nextTab);
        }
        showToast(firstErrorMessage$4(errors), "error");
      },
      onFinish: () => form.transform((data) => data)
    };
    if (method === "patch") {
      form.patch(submitUrl, submitOptions);
      return;
    }
    form.post(submitUrl, submitOptions);
  };
  const deleteChallenge = () => {
    if (!destroyUrl) return;
    if (!window.confirm("Delete this challenge?")) return;
    At.delete(destroyUrl);
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin - ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-6 pb-16" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] shadow-[0_24px_70px_rgba(2,6,23,0.34)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white transition hover:bg-white/[0.08]" }, "Back to challenges"), /* @__PURE__ */ React.createElement("span", null, destroyUrl ? "Edit challenge" : "New challenge")), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy challenge"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, form.data.excerpt || "Shape a guided creative brief with clear rules, dates, tags, and a public-ready preview.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] ${status2.className}` }, status2.label), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, form.data.access_level || "free"), editorContext?.links?.preview ? /* @__PURE__ */ React.createElement("a", { href: editorContext.links.preview, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100" }, "Preview public page") : null)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 px-5 py-5 md:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Submission window"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, submissionWindow || "Not scheduled")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Voting window"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, votingWindow || "Not scheduled")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Required tags"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, requiredTags.length)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Brief copy"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, briefWordCount.toLocaleString(), " words")))), /* @__PURE__ */ React.createElement(EditorWorkspaceTabs$2, { activeTab, onChange: setActiveTab, errorCounts }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-identity", eyebrow: "Challenge identity", title: "Name and positioning", description: "Keep the title clear, the slug readable, and the card summary useful for academy discovery.", className: sectionClassName("challenge-identity") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$4, { label: "Title", value: form.data.title || "", onChange: (event) => setTitle(event.target.value), error: form.errors.title, maxLength: 180, placeholder: "Creator brief: cinematic wallpaper challenge" }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Slug"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    slugTouchedRef.current = false;
    form.setData("slug", slugifyChallengeTitle(form.data.title));
  }, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Sync")), /* @__PURE__ */ React.createElement("input", { value: form.data.slug || "", onChange: (event) => {
    slugTouchedRef.current = String(event.target.value).trim() !== "";
    form.setData("slug", event.target.value);
  }, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", maxLength: 180, placeholder: "cinematic-wallpaper-challenge" }), /* @__PURE__ */ React.createElement(FieldError$4, { message: form.errors.slug }))), /* @__PURE__ */ React.createElement(TextAreaField$3, { label: "Excerpt", value: form.data.excerpt || "", onChange: (event) => form.setData("excerpt", event.target.value), error: form.errors.excerpt, rows: 4, hint: "Short public summary used on challenge cards and academy home rails." }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: accessField?.label || "Access", value: form.data.access_level || "", onChange: (nextValue) => form.setData("access_level", String(nextValue || "")), options: accessField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.access_level }), /* @__PURE__ */ React.createElement(TextField$4, { label: "Public path", value: publicPathPreview, readOnly: true, hint: "Generated from the slug. Published challenge pages use this path." }))), /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-brief", eyebrow: "Creative brief", title: "Brief and creator direction", description: "Write the task in a way creators can execute without needing extra staff notes.", tone: "feature", className: sectionClassName("challenge-brief") }, /* @__PURE__ */ React.createElement(TextAreaField$3, { label: "Description", value: form.data.description || "", onChange: (event) => form.setData("description", event.target.value), error: form.errors.description, rows: 6, hint: "Overview copy for the challenge page. Plain text is safest here because public challenge pages preserve line breaks.", placeholder: "Introduce the creative goal, theme, and expected output." }), /* @__PURE__ */ React.createElement(TextAreaField$3, { label: "Brief", value: form.data.brief || "", onChange: (event) => form.setData("brief", event.target.value), error: form.errors.brief, rows: 10, hint: "The main actionable brief. Use line breaks for steps, constraints, or judging criteria.", placeholder: "Objective, deliverable, style direction, and acceptance notes." })), /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-rules", eyebrow: "Rules and eligibility", title: "Requirements and rewards", description: "Keep challenge operations close to the brief so staff can audit everything before launch.", className: sectionClassName("challenge-rules") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(260px,0.72fr)]" }, /* @__PURE__ */ React.createElement(TextAreaField$3, { label: "Rules", value: form.data.rules || "", onChange: (event) => form.setData("rules", event.target.value), error: form.errors.rules, rows: 10, hint: "Submission rules, judging notes, restrictions, and moderation expectations." }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement(TextField$4, { label: "Prize text", value: form.data.prize_text || "", onChange: (event) => form.setData("prize_text", event.target.value), error: form.errors.prize_text, maxLength: 180, placeholder: "Featured placement plus Academy badge" }), /* @__PURE__ */ React.createElement(TextAreaField$3, { label: "Required tags", value: form.data.required_tags || "", onChange: (event) => form.setData("required_tags", event.target.value), error: form.errors.required_tags, rows: 4, hint: "Comma-separated or one per line. Saved as an array.", placeholder: "academy-challenge, cinematic, wallpaper" }), /* @__PURE__ */ React.createElement(TextAreaField$3, { label: "Allowed categories", value: form.data.allowed_categories || "", onChange: (event) => form.setData("allowed_categories", event.target.value), error: form.errors.allowed_categories, rows: 4, hint: "Comma-separated or one per line. Saved as an array.", placeholder: "Wallpapers, Skins, Worlds" })))), /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-media", eyebrow: "Visual system", title: "Cover media", description: "Upload clean landscape imagery that works in public challenge cards and the challenge detail hero.", className: sectionClassName("challenge-media") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 lg:grid-cols-2 lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Cover image",
      slot: "cover",
      value: form.data.cover_image,
      previewUrl: coverPreviewUrl,
      emptyLabel: "Challenge cover",
      helperText: "Use a landscape JPG, PNG, or WEBP. Minimum upload is 600x315; a 16:9 cover will crop best across academy surfaces.",
      uploadUrl: editorContext.coverUploadUrl,
      deleteUrl: editorContext.coverDeleteUrl,
      isTemporaryValue: Boolean(stagedCoverPath) && stagedCoverPath === form.data.cover_image,
      onChange: ({ path, url }) => {
        setStagedCoverPath(path || "");
        form.setData("cover_image", path || "");
        setCoverPreviewUrl(url || normalizeAssetPreview$1(path || "", editorContext.coverCdnBaseUrl));
      }
    }
  ), /* @__PURE__ */ React.createElement(FieldError$4, { message: form.errors.cover_image }), /* @__PURE__ */ React.createElement(TextField$4, { label: "Advanced cover path or URL", value: form.data.cover_image || "", onChange: (event) => handleManualCoverChange(event.target.value), error: form.errors.cover_image, placeholder: "Optional external URL or stored object path" })), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-slate-950" }, coverPreviewUrl ? /* @__PURE__ */ React.createElement("img", { src: coverPreviewUrl, alt: "Challenge cover preview", className: "h-72 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-72 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No challenge cover selected yet.")))), /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-timeline", eyebrow: "Timeline", title: "Submission and voting windows", description: "Set the dates that move the challenge from scheduled, to active, to voting, then completed.", className: sectionClassName("challenge-timeline") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Starts at", value: form.data.starts_at || "", onChange: (nextValue) => form.setData("starts_at", nextValue || ""), error: form.errors.starts_at, clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Ends at", value: form.data.ends_at || "", onChange: (nextValue) => form.setData("ends_at", nextValue || ""), error: form.errors.ends_at, clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Voting starts at", value: form.data.voting_starts_at || "", onChange: (nextValue) => form.setData("voting_starts_at", nextValue || ""), error: form.errors.voting_starts_at, clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Voting ends at", value: form.data.voting_ends_at || "", onChange: (nextValue) => form.setData("voting_ends_at", nextValue || ""), error: form.errors.voting_ends_at, clearable: true, className: "bg-black/20" }))), /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-publishing", eyebrow: "Publishing", title: "Status and visibility", description: "Choose how this challenge behaves in academy discovery and whether it appears in featured placements.", className: sectionClassName("challenge-publishing") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: statusField?.label || "Status", value: form.data.status || "", onChange: (nextValue) => form.setData("status", String(nextValue || "")), options: statusField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.status }), /* @__PURE__ */ React.createElement(ToggleField$3, { label: "Featured", checked: Boolean(form.data.featured), onChange: (event) => form.setData("featured", event.target.checked), help: "Promote this challenge on academy rails.", error: form.errors.featured }), /* @__PURE__ */ React.createElement(ToggleField$3, { label: "Active", checked: Boolean(form.data.active), onChange: (event) => form.setData("active", event.target.checked), help: "Inactive challenges stay hidden even when their status is public.", error: form.errors.active }))), /* @__PURE__ */ React.createElement(SectionCard$7, { id: "challenge-preview", eyebrow: "Preview", title: "Public-facing snapshot", description: "Scan the challenge card, brief, rules, tags, and timeline before saving.", tone: "feature", className: sectionClassName("challenge-preview") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-slate-950" }, coverPreviewUrl ? /* @__PURE__ */ React.createElement("img", { src: coverPreviewUrl, alt: "Challenge preview", className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-64 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No cover image selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${status2.className}` }, status2.label), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, form.data.access_level || "free"), form.data.featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/15 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy challenge"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, form.data.excerpt || "Add a short challenge summary to explain what creators are building."), form.data.prize_text ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 rounded-2xl border border-[#f39a24]/20 bg-[#f39a24]/10 px-4 py-3 text-sm font-semibold text-[#ffd5cd]" }, form.data.prize_text) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(PlainTextPreview, { title: "Brief preview", value: form.data.brief || form.data.description, fallback: "The challenge brief is still empty." }), /* @__PURE__ */ React.createElement(PlainTextPreview, { title: "Rules preview", value: form.data.rules, fallback: "No special rules posted yet." })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6 xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement(SectionCard$7, { eyebrow: "At a glance", title: "Challenge summary", description: "A compact view of the details editors usually check before launch." }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/18 bg-sky-300/8 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Public path"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 break-all text-sm font-semibold text-white" }, publicPathPreview)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, status2.label)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Cover"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, coverPreviewUrl ? "Ready" : "Missing")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Submissions"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, formatDateLabel$2(form.data.starts_at), " to ", formatDateLabel$2(form.data.ends_at))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Voting"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, formatDateLabel$2(form.data.voting_starts_at), " to ", formatDateLabel$2(form.data.voting_ends_at))))), /* @__PURE__ */ React.createElement(SectionCard$7, { eyebrow: "Requirements", title: "Tags and categories", description: "A quick scan of the saved arrays before the challenge opens." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Required tags"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, requiredTags.length ? requiredTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs font-semibold text-sky-100" }, tag)) : /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, "No required tags yet."))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Allowed categories"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, allowedCategories.length ? allowedCategories.map((category) => /* @__PURE__ */ React.createElement("span", { key: category, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-slate-200" }, category)) : /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, "All categories are allowed unless you add limits."))))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save challenge"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteChallenge, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null)), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ));
}
const __vite_glob_0_17 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ChallengeEditor
}, Symbol.toStringTag, { value: "Module" }));
function laneKey(sectionId) {
  return sectionId == null ? "unsectioned" : `section:${sectionId}`;
}
function sortSections(items = []) {
  return [...items].sort((left, right) => {
    const orderDiff = Number(left?.order_num || 0) - Number(right?.order_num || 0);
    if (orderDiff !== 0) return orderDiff;
    return Number(left?.id || 0) - Number(right?.id || 0);
  });
}
function sortLessons(items = []) {
  return [...items].sort((left, right) => {
    const leftSection = left?.section_id == null ? -1 : Number(left.section_id);
    const rightSection = right?.section_id == null ? -1 : Number(right.section_id);
    if (leftSection !== rightSection) return leftSection - rightSection;
    const orderDiff = Number(left?.order_num || 0) - Number(right?.order_num || 0);
    if (orderDiff !== 0) return orderDiff;
    return Number(left?.id || 0) - Number(right?.id || 0);
  });
}
function buildLessonLanes(sections = [], lessons = []) {
  const orderedSections = sortSections(sections);
  const orderedLessons = sortLessons(lessons);
  return [
    {
      key: "unsectioned",
      sectionId: null,
      title: "Core lessons",
      description: "Lessons shown before the course branches into sections.",
      isVisible: true,
      lessons: orderedLessons.filter((lesson) => lesson.section_id == null)
    },
    ...orderedSections.map((section) => ({
      key: laneKey(section.id),
      sectionId: section.id,
      title: section.title,
      description: section.description || "Section lessons appear together in this stage.",
      isVisible: Boolean(section.is_visible),
      lessons: orderedLessons.filter((lesson) => Number(lesson.section_id) === Number(section.id))
    }))
  ];
}
function reindexLessonsFromLanes(sections = [], lessons = []) {
  const lanes = buildLessonLanes(sections, lessons);
  return lanes.flatMap((lane) => lane.lessons.map((lesson, index2) => ({
    ...lesson,
    section_id: lane.sectionId,
    order_num: index2
  })));
}
function moveLessonToPosition(sections = [], lessons = [], lessonId, nextSectionId, targetIndex) {
  const lanes = buildLessonLanes(sections, lessons).map((lane) => ({ ...lane, lessons: [...lane.lessons] }));
  let draggedLesson = null;
  lanes.forEach((lane) => {
    const lessonIndex = lane.lessons.findIndex((lesson) => Number(lesson.id) === Number(lessonId));
    if (lessonIndex === -1) return;
    draggedLesson = { ...lane.lessons[lessonIndex], section_id: nextSectionId };
    lane.lessons.splice(lessonIndex, 1);
  });
  if (!draggedLesson) return lessons;
  const destinationLane = lanes.find((lane) => lane.sectionId === nextSectionId);
  if (!destinationLane) return lessons;
  const nextIndex = Math.max(0, Math.min(Number(targetIndex), destinationLane.lessons.length));
  destinationLane.lessons.splice(nextIndex, 0, draggedLesson);
  return reindexLessonsFromLanes(sections, lanes.flatMap((lane) => lane.lessons));
}
function shiftLesson(sections = [], lessons = [], lessonId, direction) {
  const lanes = buildLessonLanes(sections, lessons);
  for (const lane of lanes) {
    const lessonIndex = lane.lessons.findIndex((lesson) => Number(lesson.id) === Number(lessonId));
    if (lessonIndex === -1) continue;
    const nextIndex = lessonIndex + direction;
    if (nextIndex < 0 || nextIndex >= lane.lessons.length) {
      return lessons;
    }
    return moveLessonToPosition(sections, lessons, lessonId, lane.sectionId, nextIndex);
  }
  return lessons;
}
function placementSignature(lessons = []) {
  return JSON.stringify(sortLessons(lessons).map((lesson) => ({
    id: Number(lesson.id),
    section_id: lesson.section_id == null ? null : Number(lesson.section_id),
    order_num: Number(lesson.order_num || 0)
  })));
}
function formatStepLabel(value) {
  return `Step ${String(value).padStart(2, "0")}`;
}
function resolveDraggedLessonId(event, fallbackLessonId = null) {
  const nativeLessonId = event?.dataTransfer?.getData("text/plain") || "";
  if (nativeLessonId !== "") {
    return Number(nativeLessonId);
  }
  return fallbackLessonId == null ? null : Number(fallbackLessonId);
}
function FormCard({ title, description, children }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Course builder"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.04em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, description) : null), children);
}
function CheckboxCardField$1({ label, checked, onChange, description }) {
  return /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer items-start gap-4 rounded-[28px] border px-5 py-4 transition ${checked ? "border-[#f39a24]/35 bg-[#f39a24]/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "sr-only" }), /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border text-sm transition ${checked ? "border-[#f39a24] bg-[#f39a24] text-white" : "border-white/10 bg-[#151a29] text-transparent"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check" })), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, label), description ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, description) : null));
}
function EditableSectionCard({ section }) {
  const form = G$1({
    title: section.title || "",
    slug: section.slug || "",
    description: section.description || "",
    order_num: section.order_num || 0,
    is_visible: Boolean(section.is_visible)
  });
  return /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    form.patch(section.updateUrl);
  }, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.data.slug, onChange: (event) => form.setData("slug", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200 lg:col-span-2" }, /* @__PURE__ */ React.createElement("span", null, "Description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), rows: 3, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Order"), /* @__PURE__ */ React.createElement("input", { type: "number", value: form.data.order_num, onChange: (event) => form.setData("order_num", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(
    CheckboxCardField$1,
    {
      label: "Visible section",
      checked: Boolean(form.data.is_visible),
      onChange: (event) => form.setData("is_visible", event.target.checked),
      description: "Hide the whole section from the public course outline without deleting its lessons or structure."
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save section"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this section?")) return;
    At.delete(section.destroyUrl);
  }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Delete")));
}
function EditableCourseLessonCard({ courseLesson, sectionOptions, stepLabel }) {
  const form = G$1({
    section_id: courseLesson.section_id || "",
    order_num: courseLesson.order_num || 0,
    is_required: Boolean(courseLesson.is_required),
    access_override: courseLesson.access_override || "",
    unlock_after_lesson_id: courseLesson.unlock_after_lesson_id || ""
  });
  const accessOptions = [
    { value: "", label: "Use lesson access" },
    { value: "free", label: "Free" },
    { value: "creator", label: "Creator" },
    { value: "pro", label: "Pro" },
    { value: "premium", label: "Premium" }
  ];
  reactExports.useEffect(() => {
    form.setData("section_id", courseLesson.section_id || "");
    form.setData("order_num", courseLesson.order_num || 0);
  }, [courseLesson.order_num, courseLesson.section_id]);
  return /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    form.patch(courseLesson.updateUrl);
  }, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, stepLabel ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, stepLabel) : null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, courseLesson.category || "Academy", " · ", courseLesson.difficulty || "lesson")), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, courseLesson.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, courseLesson.excerpt || "This lesson is attached to the course."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Section", value: form.data.section_id, onChange: (nextValue) => form.setData("section_id", nextValue || ""), options: sectionOptions, searchable: false, className: "rounded-2xl bg-white/[0.04]" }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Order"), /* @__PURE__ */ React.createElement("input", { type: "number", value: form.data.order_num, onChange: (event) => form.setData("order_num", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(NovaSelect, { label: "Access override", value: form.data.access_override, onChange: (nextValue) => form.setData("access_override", nextValue || ""), options: accessOptions, searchable: false, className: "rounded-2xl bg-white/[0.04]" })), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(
    CheckboxCardField$1,
    {
      label: "Required for course completion",
      checked: Boolean(form.data.is_required),
      onChange: (event) => form.setData("is_required", event.target.checked),
      description: "Only required lessons count toward the course completion percentage."
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save lesson settings"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Remove this lesson from the course?")) return;
    At.delete(courseLesson.destroyUrl);
  }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Detach")));
}
function ReorderLessonCard({
  lesson,
  lane,
  laneIndex,
  laneCount,
  globalStepNumber,
  isDragging,
  isDropTarget,
  onDragStart,
  onDragEnd,
  onDragOver,
  onDrop,
  onMoveUp,
  onMoveDown,
  onMoveLeft,
  onMoveRight
}) {
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      draggable: true,
      onDragStart: (event) => {
        event.dataTransfer.effectAllowed = "move";
        event.dataTransfer.setData("text/plain", String(lesson.id));
        onDragStart(lesson.id);
      },
      onDragEnd,
      onDragOver: (event) => {
        event.preventDefault();
        event.dataTransfer.dropEffect = "move";
        onDragOver(lesson.id);
      },
      onDrop: (event) => {
        event.preventDefault();
        event.stopPropagation();
        onDrop(event, lane.sectionId, lesson.id);
      },
      className: [
        "rounded-[24px] border bg-black/20 p-4 transition",
        isDragging ? "border-sky-300/40 opacity-60" : "border-white/10 hover:border-white/20",
        isDropTarget ? "ring-2 ring-sky-300/35" : ""
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, formatStepLabel(globalStepNumber)), lesson.is_required ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Required") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Optional")), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-base font-semibold tracking-[-0.03em] text-white" }, lesson.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, lesson.category || "Academy", " · ", lesson.difficulty || "lesson", " · order ", Number(lesson.order_num) + 1), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, lesson.excerpt || "Drag this lesson to reposition it inside the course flow.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onMoveUp, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white disabled:opacity-40", disabled: lane.lessons[0]?.id === lesson.id }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onMoveDown, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white disabled:opacity-40", disabled: lane.lessons[lane.lessons.length - 1]?.id === lesson.id }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onMoveLeft, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white disabled:opacity-40", disabled: laneIndex <= 0 }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onMoveRight, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white disabled:opacity-40", disabled: laneIndex >= laneCount - 1 }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))
  );
}
function AcademyCourseBuilder({ course, sections = [], courseLessons = [], availableLessons = [], routes = {} }) {
  const flash = X$1().props.flash || {};
  const sectionForm = G$1({ title: "", slug: "", description: "", order_num: sections.length, is_visible: true });
  const attachForm = G$1({ lesson_id: "", section_id: "", order_num: courseLessons.length, is_required: true, access_override: "", unlock_after_lesson_id: "" });
  const [draftLessons, setDraftLessons] = reactExports.useState(() => reindexLessonsFromLanes(sections, courseLessons));
  const [draggedLessonId, setDraggedLessonId] = reactExports.useState(null);
  const [dropTargetLessonId, setDropTargetLessonId] = reactExports.useState(null);
  const [reorderProcessing, setReorderProcessing] = reactExports.useState(false);
  const sectionOptions = [{ value: "", label: "Unsectioned" }, ...sections.map((section) => ({ value: section.id, label: section.title }))];
  const lessonOptions = availableLessons.map((lesson) => ({ value: lesson.id, label: `${lesson.title}${lesson.attached ? " · attached" : ""}` }));
  const attachableLessonOptions = availableLessons.filter((lesson) => !lesson.attached).map((lesson) => ({ value: lesson.id, label: lesson.title }));
  const accessOverrideOptions = [
    { value: "", label: "Use lesson access" },
    { value: "free", label: "Free" },
    { value: "creator", label: "Creator" },
    { value: "pro", label: "Pro" },
    { value: "premium", label: "Premium" }
  ];
  const lessonLanes = reactExports.useMemo(() => buildLessonLanes(sections, draftLessons), [sections, draftLessons]);
  const reorderDirty = reactExports.useMemo(() => placementSignature(draftLessons) !== placementSignature(reindexLessonsFromLanes(sections, courseLessons)), [courseLessons, draftLessons, sections]);
  const courseLessonMap = reactExports.useMemo(() => new Map(courseLessons.map((courseLesson) => [Number(courseLesson.id), courseLesson])), [courseLessons]);
  const orderedCourseLessons = reactExports.useMemo(() => reindexLessonsFromLanes(sections, courseLessons.map((courseLesson) => ({
    ...courseLesson,
    ...draftLessons.find((draftLesson) => Number(draftLesson.id) === Number(courseLesson.id)) || {}
  }))), [courseLessons, draftLessons, sections]);
  const globalStepMap = reactExports.useMemo(() => new Map(lessonLanes.flatMap((lane) => lane.lessons).map((lesson, index2) => [Number(lesson.id), index2 + 1])), [lessonLanes]);
  reactExports.useEffect(() => {
    setDraftLessons(reindexLessonsFromLanes(sections, courseLessons));
  }, [courseLessons, sections]);
  const moveLessonAcrossLanes = (lessonId, laneIndexDelta) => {
    const lanes = buildLessonLanes(sections, draftLessons);
    const currentLaneIndex = lanes.findIndex((lane) => lane.lessons.some((lesson) => Number(lesson.id) === Number(lessonId)));
    if (currentLaneIndex === -1) return;
    const nextLane = lanes[currentLaneIndex + laneIndexDelta];
    if (!nextLane) return;
    setDraftLessons((current) => moveLessonToPosition(sections, current, lessonId, nextLane.sectionId, nextLane.lessons.length));
  };
  const saveReorder = () => {
    setReorderProcessing(true);
    At.patch(routes.reorder, {
      sections: sortSections(sections).map((section, index2) => ({ id: section.id, order_num: index2 })),
      lessons: reindexLessonsFromLanes(sections, draftLessons).map((lesson) => ({
        id: lesson.id,
        order_num: lesson.order_num,
        section_id: lesson.section_id
      }))
    }, {
      preserveScroll: true,
      onFinish: () => setReorderProcessing(false)
    });
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: `${course.title} Builder`, subtitle: "Arrange sections, attach lessons, and control course flow." }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${course.title} Builder` }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: routes.index, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back to courses"), /* @__PURE__ */ React.createElement(xe, { href: routes.edit, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Edit course"), /* @__PURE__ */ React.createElement(xe, { href: routes.preview, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Preview public page")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_420px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(FormCard, { title: "Structure overview", description: "The course builder keeps the lesson content reusable while controlling order, access, and required progress here." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Sections"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold text-white" }, sections.length)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Attached lessons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold text-white" }, courseLessons.length)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Published course lessons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold text-white" }, courseLessons.filter((lesson) => lesson.title).length)))), /* @__PURE__ */ React.createElement(FormCard, { title: "Sections", description: "Chapters are optional, but they help group lessons into cleaner stages." }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, sections.map((section) => /* @__PURE__ */ React.createElement(EditableSectionCard, { key: section.id, section })))), /* @__PURE__ */ React.createElement(FormCard, { title: "Lesson flow", description: "Manage the course order as one visual path. Drag lessons between lanes, use arrows for exact moves, then save the sequence in one action." }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Flow board"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, "Core lessons stay first, then each visible section keeps its own ordered lane.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, reorderDirty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/25 bg-amber-300/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Unsaved order changes") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Order is saved"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setDraftLessons(reindexLessonsFromLanes(sections, courseLessons)), disabled: !reorderDirty || reorderProcessing, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white disabled:opacity-40" }, "Reset"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveReorder, disabled: !reorderDirty || reorderProcessing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-40" }, reorderProcessing ? "Saving order..." : "Save order"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 xl:grid-cols-2" }, lessonLanes.map((lane, laneIndex) => /* @__PURE__ */ React.createElement(
    "section",
    {
      key: lane.key,
      onDragOver: (event) => event.preventDefault(),
      onDrop: (event) => {
        event.preventDefault();
        event.stopPropagation();
        const activeLessonId = resolveDraggedLessonId(event, draggedLessonId);
        if (activeLessonId == null) return;
        setDraftLessons((current) => moveLessonToPosition(sections, current, activeLessonId, lane.sectionId, lane.lessons.length));
        setDraggedLessonId(null);
        setDropTargetLessonId(null);
      },
      className: `rounded-[26px] border p-4 ${lane.isVisible ? "border-white/10 bg-white/[0.03]" : "border-amber-300/20 bg-amber-300/8"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, lane.sectionId == null ? "Core lane" : "Section lane"), !lane.isVisible ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Hidden on public page") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold tracking-[-0.03em] text-white" }, lane.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, lane.description)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, lane.lessons.length, " lessons")),
    /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 min-h-20" }, lane.lessons.length ? lane.lessons.map((lesson) => /* @__PURE__ */ React.createElement(
      ReorderLessonCard,
      {
        key: lesson.id,
        lesson,
        lane,
        laneIndex,
        laneCount: lessonLanes.length,
        globalStepNumber: globalStepMap.get(Number(lesson.id)) || 1,
        isDragging: Number(draggedLessonId) === Number(lesson.id),
        isDropTarget: Number(dropTargetLessonId) === Number(lesson.id),
        onDragStart: setDraggedLessonId,
        onDragEnd: () => {
          setDraggedLessonId(null);
          setDropTargetLessonId(null);
        },
        onDragOver: setDropTargetLessonId,
        onDrop: (event, targetSectionId, targetLessonId) => {
          const activeLessonId = resolveDraggedLessonId(event, draggedLessonId);
          if (activeLessonId == null) return;
          if (Number(activeLessonId) === Number(targetLessonId)) return;
          const targetLane = lessonLanes.find((entry) => entry.sectionId === targetSectionId);
          const targetIndex = Math.max(0, (targetLane?.lessons || []).findIndex((entry) => Number(entry.id) === Number(targetLessonId)));
          setDraftLessons((current) => moveLessonToPosition(sections, current, activeLessonId, targetSectionId, targetIndex));
          setDraggedLessonId(null);
          setDropTargetLessonId(null);
        },
        onMoveUp: () => setDraftLessons((current) => shiftLesson(sections, current, lesson.id, -1)),
        onMoveDown: () => setDraftLessons((current) => shiftLesson(sections, current, lesson.id, 1)),
        onMoveLeft: () => moveLessonAcrossLanes(lesson.id, -1),
        onMoveRight: () => moveLessonAcrossLanes(lesson.id, 1)
      }
    )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-dashed border-white/10 bg-black/20 px-4 py-6 text-sm text-slate-500" }, "Drop lessons here to move them into this lane."))
  )))), /* @__PURE__ */ React.createElement(FormCard, { title: "Attached lessons", description: "Each lesson stays reusable across courses. Adjust order, requirement status, and access overrides here." }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, orderedCourseLessons.map((courseLesson, index2) => /* @__PURE__ */ React.createElement(EditableCourseLessonCard, { key: courseLesson.id, courseLesson: { ...courseLessonMap.get(Number(courseLesson.id)), ...courseLesson }, sectionOptions, stepLabel: formatStepLabel(index2 + 1) }))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6 xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement(FormCard, { title: "Create section", description: "Create a chapter before attaching lessons into it." }, /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    sectionForm.post(routes.sectionStore);
  }, className: "space-y-4" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Title"), /* @__PURE__ */ React.createElement("input", { value: sectionForm.data.title, onChange: (event) => sectionForm.setData("title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: sectionForm.data.slug, onChange: (event) => sectionForm.setData("slug", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none", placeholder: "auto-generated if blank" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Description"), /* @__PURE__ */ React.createElement("textarea", { value: sectionForm.data.description, onChange: (event) => sectionForm.setData("description", event.target.value), rows: 4, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-7 text-white outline-none" })), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: sectionForm.processing, className: "w-full rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, sectionForm.processing ? "Creating..." : "Create section"))), /* @__PURE__ */ React.createElement(FormCard, { title: "Attach lesson", description: "Attach an existing Academy lesson to this course without duplicating content." }, /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    attachForm.post(routes.attachLesson);
  }, className: "space-y-4" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Lesson", value: attachForm.data.lesson_id, onChange: (nextValue) => attachForm.setData("lesson_id", nextValue || ""), options: attachableLessonOptions.length ? attachableLessonOptions : lessonOptions, className: "rounded-2xl bg-black/20" }), /* @__PURE__ */ React.createElement(NovaSelect, { label: "Section", value: attachForm.data.section_id, onChange: (nextValue) => attachForm.setData("section_id", nextValue || ""), options: sectionOptions, searchable: false, className: "rounded-2xl bg-black/20" }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Order"), /* @__PURE__ */ React.createElement("input", { type: "number", value: attachForm.data.order_num, onChange: (event) => attachForm.setData("order_num", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement(NovaSelect, { label: "Access override", value: attachForm.data.access_override, onChange: (nextValue) => attachForm.setData("access_override", nextValue || ""), options: accessOverrideOptions, searchable: false, className: "rounded-2xl bg-black/20" }), /* @__PURE__ */ React.createElement(
    CheckboxCardField$1,
    {
      label: "Required for completion",
      checked: Boolean(attachForm.data.is_required),
      onChange: (event) => attachForm.setData("is_required", event.target.checked),
      description: "Only required lessons count toward course completion."
    }
  ), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: attachForm.processing || !attachForm.data.lesson_id, className: "w-full rounded-full border border-amber-300/25 bg-amber-300/12 px-5 py-3 text-sm font-semibold text-amber-100" }, attachForm.processing ? "Attaching..." : "Attach lesson"))))));
}
const __vite_glob_0_18 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyCourseBuilder
}, Symbol.toStringTag, { value: "Module" }));
const MentionList = reactExports.forwardRef(function MentionList2({ items, command }, ref2) {
  const [selectedIndex, setSelectedIndex] = reactExports.useState(0);
  reactExports.useEffect(() => setSelectedIndex(0), [items]);
  reactExports.useImperativeHandle(ref2, () => ({
    onKeyDown: ({ event }) => {
      if (event.key === "ArrowUp") {
        setSelectedIndex((i) => (i + items.length - 1) % items.length);
        return true;
      }
      if (event.key === "ArrowDown") {
        setSelectedIndex((i) => (i + 1) % items.length);
        return true;
      }
      if (event.key === "Enter") {
        selectItem(selectedIndex);
        return true;
      }
      return false;
    }
  }));
  const selectItem = (index2) => {
    const item = items[index2];
    if (item) {
      command({ id: item.username, label: item.username });
    }
  };
  if (!items.length) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/[0.08] bg-nova-800 p-3 shadow-xl backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-zinc-500" }, "No users found"));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "min-w-[200px] overflow-hidden rounded-xl border border-white/[0.08] bg-nova-800 shadow-xl backdrop-blur" }, items.map((item, index2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: item.id,
      type: "button",
      onClick: () => selectItem(index2),
      className: [
        "flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm transition-colors",
        index2 === selectedIndex ? "bg-sky-600/20 text-white" : "text-zinc-300 hover:bg-white/[0.04]"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: item.avatar_url,
        alt: "",
        className: "h-6 w-6 rounded-full border border-white/10 object-cover"
      }
    ),
    /* @__PURE__ */ React.createElement("span", { className: "truncate font-medium" }, "@", item.username),
    item.name && item.name !== item.username && /* @__PURE__ */ React.createElement("span", { className: "truncate text-xs text-zinc-500" }, item.name)
  )));
});
const mentionSuggestion = {
  items: async ({ query }) => {
    if (!query || query.length < 2) return [];
    try {
      const res = await fetch(`/api/search/users?q=${encodeURIComponent(query)}&per_page=6`);
      if (!res.ok) return [];
      const json = await res.json();
      return json.data ?? [];
    } catch {
      return [];
    }
  },
  render: () => {
    let component;
    let popup;
    return {
      onStart: (props) => {
        component = new ReactRenderer(MentionList, {
          props,
          editor: props.editor
        });
        if (!props.clientRect) return;
        popup = tippy("body", {
          getReferenceClientRect: props.clientRect,
          appendTo: () => document.body,
          content: component.element,
          showOnCreate: true,
          interactive: true,
          trigger: "manual",
          placement: "bottom-start",
          theme: "mention",
          arrow: false,
          offset: [0, 8]
        });
      },
      onUpdate: (props) => {
        component?.updateProps(props);
        if (!props.clientRect) return;
        popup?.[0]?.setProps({
          getReferenceClientRect: props.clientRect
        });
      },
      onKeyDown: (props) => {
        if (props.event.key === "Escape") {
          popup?.[0]?.hide();
          return true;
        }
        return component?.ref?.onKeyDown(props) ?? false;
      },
      onExit: () => {
        popup?.[0]?.destroy();
        component?.destroy();
      }
    };
  }
};
let emojiMartPromise = null;
function ensureEmojiMart() {
  if (!emojiMartPromise) {
    emojiMartPromise = import("./assets/emoji-ui-C_DZUNyP.js");
  }
  return emojiMartPromise;
}
function EmojiMartPicker({
  data,
  onEmojiSelect,
  onClickOutside,
  theme = "auto",
  previewPosition = "bottom",
  skinTonePosition = "preview",
  maxFrequentRows = 4,
  perLine = 9,
  navPosition = "top",
  set = "native",
  locale = "en",
  autoFocus = false,
  searchPosition,
  dynamicWidth,
  noCountryFlags,
  className = ""
}) {
  const hostRef = reactExports.useRef(null);
  const pickerRef = reactExports.useRef(null);
  const onEmojiSelectRef = reactExports.useRef(onEmojiSelect);
  const onClickOutsideRef = reactExports.useRef(onClickOutside);
  onEmojiSelectRef.current = onEmojiSelect;
  onClickOutsideRef.current = onClickOutside;
  const stableOnEmojiSelect = reactExports.useCallback((emoji) => {
    onEmojiSelectRef.current?.(emoji);
  }, []);
  const stableOnClickOutside = reactExports.useCallback((e) => {
    onClickOutsideRef.current?.(e);
  }, []);
  reactExports.useEffect(() => {
    let cancelled = false;
    ensureEmojiMart().then(({ Picker }) => {
      if (cancelled || !hostRef.current) return;
      if (!pickerRef.current) {
        const pickerProps = {
          data,
          onEmojiSelect: stableOnEmojiSelect,
          onClickOutside: stableOnClickOutside,
          theme,
          previewPosition,
          skinTonePosition,
          maxFrequentRows,
          perLine,
          navPosition,
          set,
          locale,
          autoFocus
        };
        if (searchPosition !== void 0) pickerProps.searchPosition = searchPosition;
        if (dynamicWidth !== void 0) pickerProps.dynamicWidth = dynamicWidth;
        if (noCountryFlags !== void 0) pickerProps.noCountryFlags = noCountryFlags;
        const el = new Picker(pickerProps);
        pickerRef.current = el;
        hostRef.current.replaceChildren(el);
      }
    });
    return () => {
      cancelled = true;
    };
  }, []);
  reactExports.useEffect(() => {
    return () => {
      if (hostRef.current) {
        hostRef.current.replaceChildren();
      }
      pickerRef.current = null;
    };
  }, []);
  return /* @__PURE__ */ React.createElement("div", { ref: hostRef, className });
}
function extractNativeEmoji(selection) {
  if (typeof selection === "string") {
    return selection;
  }
  const detail = selection?.detail ?? null;
  return selection?.native ?? selection?.emoji ?? selection?.unicode ?? selection?.skins?.[0]?.native ?? detail?.native ?? detail?.emoji ?? detail?.unicode ?? detail?.skins?.[0]?.native ?? "";
}
function isEventWithinNode(event, node2) {
  if (!event || !node2) {
    return false;
  }
  if (typeof event.composedPath === "function") {
    return event.composedPath().includes(node2);
  }
  return node2.contains(event.target);
}
let emojiMartDataPromise = null;
function loadEmojiMartData() {
  if (!emojiMartDataPromise) {
    emojiMartDataPromise = import("./assets/emoji-data-4xGXbtDn.js").then((module) => module.default);
  }
  return emojiMartDataPromise;
}
function EmojiPicker({ onSelect, editor }) {
  const [open, setOpen] = reactExports.useState(false);
  const [pickerData, setPickerData] = reactExports.useState(null);
  const [panelStyle, setPanelStyle] = reactExports.useState({});
  const panelRef = reactExports.useRef(null);
  const buttonRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open || pickerData) return;
    let cancelled = false;
    loadEmojiMartData().then((data) => {
      if (!cancelled) {
        setPickerData(data);
      }
    });
    return () => {
      cancelled = true;
    };
  }, [open, pickerData]);
  reactExports.useEffect(() => {
    if (!open || !buttonRef.current) return;
    const rect = buttonRef.current.getBoundingClientRect();
    const panelWidth = 352;
    const panelHeight = 435;
    const spaceAbove = rect.top;
    const openAbove = spaceAbove > panelHeight + 8;
    setPanelStyle({
      position: "fixed",
      zIndex: 9999,
      left: Math.max(8, Math.min(rect.right - panelWidth, window.innerWidth - panelWidth - 8)),
      ...openAbove ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 }
    });
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (!isEventWithinNode(e, panelRef.current) && !isEventWithinNode(e, buttonRef.current)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [open]);
  const handleSelect = reactExports.useCallback((emoji) => {
    const native = extractNativeEmoji(emoji);
    if (!native) {
      setOpen(false);
      return;
    }
    onSelect?.(native);
    if (editor) {
      editor.chain().focus().insertContent(native).run();
    }
    setOpen(false);
  }, [onSelect, editor]);
  const panel = open ? reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: panelRef,
        style: panelStyle,
        className: "rounded-xl shadow-2xl overflow-hidden"
      },
      pickerData ? /* @__PURE__ */ React.createElement(
        EmojiMartPicker,
        {
          data: pickerData,
          onEmojiSelect: handleSelect,
          theme: "dark",
          previewPosition: "none",
          skinTonePosition: "search",
          maxFrequentRows: 2,
          perLine: 9
        }
      ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-[352px] items-center justify-center bg-zinc-900 px-4 text-sm text-zinc-300" }, "Loading emojis...")
    ),
    document.body
  ) : null;
  return /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      ref: buttonRef,
      type: "button",
      onClick: () => setOpen((v2) => !v2),
      title: "Insert emoji",
      "aria-label": "Open emoji picker",
      "aria-expanded": open,
      className: [
        "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400",
        open ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("span", { className: "text-[15px]" }, "😊")
  ), panel);
}
function clamp$1(value, min2, max2) {
  return Math.min(max2, Math.max(min2, value));
}
function parsePixelValue(rawValue) {
  const normalized = String(rawValue || "").trim();
  if (!normalized) {
    return null;
  }
  const parsed = Number.parseFloat(normalized.replace(/px$/i, ""));
  return Number.isFinite(parsed) ? Math.round(parsed) : null;
}
function readImageAttrs$1(element2) {
  const imageElement = element2.tagName?.toLowerCase() === "img" ? element2 : element2.querySelector?.("img");
  const captionElement = element2.querySelector?.("figcaption");
  return {
    src: imageElement?.getAttribute("src") || "",
    alt: imageElement?.getAttribute("alt") || "",
    title: imageElement?.getAttribute("title") || "",
    caption: captionElement?.textContent?.trim() || "",
    width: parsePixelValue(
      element2.getAttribute?.("data-width") || element2.getAttribute?.("width") || imageElement?.getAttribute("width") || element2.style?.width || ""
    )
  };
}
function RichImageNodeView({ editor, node: node2, selected, updateAttributes, deleteNode, getPos }) {
  const imageRef = reactExports.useRef(null);
  const cleanupResizeRef = reactExports.useRef(null);
  reactExports.useEffect(() => () => {
    if (typeof cleanupResizeRef.current === "function") {
      cleanupResizeRef.current();
    }
  }, []);
  const selectNode = reactExports.useCallback(() => {
    if (!editor || typeof getPos !== "function") {
      return;
    }
    editor.chain().focus().setNodeSelection(getPos()).run();
  }, [editor, getPos]);
  const startResize = reactExports.useCallback((event) => {
    if (!imageRef.current || event.button !== 0) {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    selectNode();
    const imageElement = imageRef.current;
    const parentWidth = imageElement.parentElement?.getBoundingClientRect().width || imageElement.getBoundingClientRect().width || 0;
    const startX = event.clientX;
    const startWidth = node2.attrs.width || Math.round(imageElement.getBoundingClientRect().width) || 0;
    const minWidth = 180;
    const maxWidth = Math.max(minWidth, Math.round(parentWidth || 1280));
    const handleMove = (moveEvent) => {
      const nextWidth = clamp$1(Math.round(startWidth + (moveEvent.clientX - startX)), minWidth, maxWidth);
      updateAttributes({ width: nextWidth });
    };
    const handleUp = () => {
      window.removeEventListener("pointermove", handleMove);
      window.removeEventListener("pointerup", handleUp);
      cleanupResizeRef.current = null;
    };
    cleanupResizeRef.current = handleUp;
    window.addEventListener("pointermove", handleMove);
    window.addEventListener("pointerup", handleUp);
  }, [node2.attrs.width, selectNode, updateAttributes]);
  const width = Number.isFinite(Number(node2.attrs.width)) && Number(node2.attrs.width) > 0 ? Number(node2.attrs.width) : null;
  return /* @__PURE__ */ React.createElement(
    NodeViewWrapper,
    {
      as: "figure",
      className: [
        "rich-image-node",
        selected ? "is-selected" : ""
      ].filter(Boolean).join(" "),
      "data-rich-image": "true",
      onMouseDown: (event) => {
        if (event.target instanceof HTMLElement && event.target.closest("input, textarea, button, select, label")) {
          return;
        }
        selectNode();
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "rich-image-node__frame" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        ref: imageRef,
        src: node2.attrs.src,
        alt: node2.attrs.alt || "",
        title: node2.attrs.title || "",
        className: "rich-image-node__img",
        style: width ? { width: `${width}px` } : void 0
      }
    ), selected ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        "data-drag-handle": true,
        className: "rich-image-node__drag-handle",
        title: "Drag to move image",
        onMouseDown: selectNode
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip-lines" })
    ) : null, selected ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        className: "rich-image-node__resize-handle",
        title: "Resize image",
        onPointerDown: startResize
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-up-right-and-down-left-from-center" })
    ) : null),
    !selected && node2.attrs.caption ? /* @__PURE__ */ React.createElement("figcaption", { className: "rich-image-node__caption" }, node2.attrs.caption) : null,
    selected ? /* @__PURE__ */ React.createElement("div", { className: "rich-image-node__editor", contentEditable: false }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Alt text"), /* @__PURE__ */ React.createElement(
      "input",
      {
        value: node2.attrs.alt || "",
        onChange: (event) => updateAttributes({ alt: event.target.value }),
        placeholder: "Describe the image for screen readers",
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Caption"), /* @__PURE__ */ React.createElement(
      "input",
      {
        value: node2.attrs.caption || "",
        onChange: (event) => updateAttributes({ caption: event.target.value }),
        placeholder: "Visible caption below the image",
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-[minmax(0,1fr)_auto_auto] md:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Width"), /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "number",
        min: "180",
        max: "2400",
        value: width || "",
        onChange: (event) => {
          const nextValue = Number.parseInt(event.target.value, 10);
          updateAttributes({ width: Number.isFinite(nextValue) ? nextValue : null });
        },
        placeholder: "Auto",
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => updateAttributes({ width: null }),
        className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
      },
      "Fit"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: deleteNode,
        className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15"
      },
      "Remove"
    ))) : null
  );
}
const RichImage = index_default.extend({
  addOptions() {
    return {
      ...this.parent?.(),
      HTMLAttributes: {
        class: "rich-image-node"
      }
    };
  },
  addAttributes() {
    return {
      ...this.parent?.(),
      alt: {
        default: ""
      },
      title: {
        default: ""
      },
      caption: {
        default: ""
      },
      width: {
        default: null,
        parseHTML: (element2) => parsePixelValue(
          element2.getAttribute?.("data-width") || element2.getAttribute?.("width") || element2.style?.width || ""
        ),
        renderHTML: (attributes) => {
          const width = Number(attributes.width);
          if (!Number.isFinite(width) || width <= 0) {
            return {};
          }
          return {
            "data-width": String(Math.round(width)),
            style: `width:${Math.round(width)}px;max-width:100%;`
          };
        }
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "figure[data-rich-image]",
        getAttrs: (element2) => readImageAttrs$1(element2)
      },
      {
        tag: "img[src]",
        getAttrs: (element2) => readImageAttrs$1(element2)
      }
    ];
  },
  renderHTML({ node: node2, HTMLAttributes }) {
    const {
      src: _src,
      alt: _alt,
      title: _title,
      caption: _caption,
      width: _width,
      "data-width": _dataWidth,
      ...figureHTMLAttributes
    } = HTMLAttributes;
    const figureAttributes = mergeAttributes(this.options.HTMLAttributes, figureHTMLAttributes, {
      "data-rich-image": "true"
    });
    const imageAttributes = {
      src: node2.attrs.src,
      alt: node2.attrs.alt || "",
      title: node2.attrs.title || "",
      loading: "lazy",
      decoding: "async"
    };
    if (Number.isFinite(Number(node2.attrs.width)) && Number(node2.attrs.width) > 0) {
      const width = Math.round(Number(node2.attrs.width));
      imageAttributes.style = `width:${width}px;max-width:100%;`;
      imageAttributes["data-width"] = String(width);
    }
    const children = [
      ["img", imageAttributes]
    ];
    if (node2.attrs.caption) {
      children.push(["figcaption", { class: "rich-image-node__caption" }, node2.attrs.caption]);
    }
    return ["figure", figureAttributes, ...children];
  },
  addNodeView() {
    return ReactNodeViewRenderer(RichImageNodeView);
  }
});
function readImageAttrs(element2) {
  const imageElements = Array.from(element2.querySelectorAll?.("img") || []);
  const subtitleElement = element2.querySelector?.("figcaption");
  return {
    leftSrc: imageElements[0]?.getAttribute("src") || "",
    leftAlt: imageElements[0]?.getAttribute("alt") || "",
    rightSrc: imageElements[1]?.getAttribute("src") || "",
    rightAlt: imageElements[1]?.getAttribute("alt") || "",
    subtitle: subtitleElement?.textContent?.trim() || ""
  };
}
function RichCompareNodeView({ editor, node: node2, selected, updateAttributes, deleteNode, getPos }) {
  const selectNode = reactExports.useCallback(() => {
    if (!editor || typeof getPos !== "function") {
      return;
    }
    editor.chain().focus().setNodeSelection(getPos()).run();
  }, [editor, getPos]);
  return /* @__PURE__ */ React.createElement(
    NodeViewWrapper,
    {
      as: "figure",
      className: ["rich-compare-node", selected ? "is-selected" : ""].filter(Boolean).join(" "),
      "data-rich-compare": "true",
      onMouseDown: (event) => {
        if (event.target instanceof HTMLElement && event.target.closest("input, textarea, button, select, label")) {
          return;
        }
        selectNode();
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__grid" }, /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__tile" }, /* @__PURE__ */ React.createElement("span", { className: "rich-compare-node__badge" }, "Left"), /* @__PURE__ */ React.createElement(
      "img",
      {
        src: node2.attrs.leftSrc,
        alt: node2.attrs.leftAlt || "",
        className: "rich-compare-node__img",
        loading: "lazy",
        decoding: "async"
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__tile" }, /* @__PURE__ */ React.createElement("span", { className: "rich-compare-node__badge" }, "Right"), /* @__PURE__ */ React.createElement(
      "img",
      {
        src: node2.attrs.rightSrc,
        alt: node2.attrs.rightAlt || "",
        className: "rich-compare-node__img",
        loading: "lazy",
        decoding: "async"
      }
    ))),
    !selected && node2.attrs.subtitle ? /* @__PURE__ */ React.createElement("figcaption", { className: "rich-compare-node__subtitle" }, node2.attrs.subtitle) : null,
    selected ? /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__editor", contentEditable: false }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Left alt text"), /* @__PURE__ */ React.createElement(
      "input",
      {
        value: node2.attrs.leftAlt || "",
        onChange: (event) => updateAttributes({ leftAlt: event.target.value }),
        placeholder: "Describe the left image",
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Right alt text"), /* @__PURE__ */ React.createElement(
      "input",
      {
        value: node2.attrs.rightAlt || "",
        onChange: (event) => updateAttributes({ rightAlt: event.target.value }),
        placeholder: "Describe the right image",
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    ))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Subtitle"), /* @__PURE__ */ React.createElement(
      "input",
      {
        value: node2.attrs.subtitle || "",
        onChange: (event) => updateAttributes({ subtitle: event.target.value }),
        placeholder: "Visible caption below the comparison",
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: selectNode,
        className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
      },
      "Keep selected"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: deleteNode,
        className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15"
      },
      "Remove comparison"
    ))) : null
  );
}
const RichCompare = Node3.create({
  name: "imageCompare",
  group: "block",
  atom: true,
  addAttributes() {
    return {
      leftSrc: { default: "" },
      leftAlt: { default: "" },
      rightSrc: { default: "" },
      rightAlt: { default: "" },
      subtitle: { default: "" }
    };
  },
  parseHTML() {
    return [
      {
        tag: "figure[data-rich-compare]",
        getAttrs: (element2) => readImageAttrs(element2)
      }
    ];
  },
  renderHTML({ node: node2, HTMLAttributes }) {
    const {
      leftSrc: _leftSrc,
      leftAlt: _leftAlt,
      rightSrc: _rightSrc,
      rightAlt: _rightAlt,
      subtitle: _subtitle,
      ...figureHTMLAttributes
    } = HTMLAttributes;
    const leftImageAttributes = {
      src: node2.attrs.leftSrc,
      alt: node2.attrs.leftAlt || "",
      loading: "lazy",
      decoding: "async",
      class: "rich-compare-node__img"
    };
    const rightImageAttributes = {
      src: node2.attrs.rightSrc,
      alt: node2.attrs.rightAlt || "",
      loading: "lazy",
      decoding: "async",
      class: "rich-compare-node__img"
    };
    return [
      "figure",
      mergeAttributes(this.options.HTMLAttributes, figureHTMLAttributes, {
        "data-rich-compare": "true"
      }),
      [
        "div",
        { class: "rich-compare-node__grid" },
        ["div", { class: "rich-compare-node__tile" }, ["img", leftImageAttributes]],
        ["div", { class: "rich-compare-node__tile" }, ["img", rightImageAttributes]]
      ],
      ...node2.attrs.subtitle ? [["figcaption", { class: "rich-compare-node__subtitle" }, node2.attrs.subtitle]] : []
    ];
  },
  addNodeView() {
    return ReactNodeViewRenderer(RichCompareNodeView);
  }
});
function TableButton({ onClick, active = false, disabled = false, title, children }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onMouseDown: (event) => {
        event.preventDefault();
      },
      onClick,
      disabled,
      title,
      className: [
        "inline-flex h-8 items-center justify-center rounded-lg px-2.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition-colors",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400",
        active ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200",
        disabled && "pointer-events-none opacity-30"
      ].filter(Boolean).join(" ")
    },
    children
  );
}
function TableInsertDialog({
  open,
  rows,
  cols,
  withHeaderRow,
  withHeaderColumn,
  onRowsChange,
  onColsChange,
  onHeaderRowChange,
  onHeaderColumnChange,
  onClose,
  onInsert
}) {
  if (!open) return null;
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
      onClick: (event) => {
        if (event.target === event.currentTarget) {
          onClose?.();
        }
      },
      role: "presentation"
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-2xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Table"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Insert table"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Create a table and edit rows and columns directly in the editor.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 px-6 py-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Rows"), /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "number",
        min: "1",
        max: "12",
        value: rows,
        onChange: (event) => onRowsChange?.(Number.parseInt(event.target.value, 10) || 1),
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Columns"), /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "number",
        min: "1",
        max: "12",
        value: cols,
        onChange: (event) => onColsChange?.(Number.parseInt(event.target.value, 10) || 1),
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )), /* @__PURE__ */ React.createElement("label", { className: "flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200 md:col-span-2" }, /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "checkbox",
        checked: withHeaderRow,
        onChange: (event) => onHeaderRowChange?.(event.target.checked),
        className: "mt-1"
      }
    ), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, "Header row"), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, "Use a header row for column labels."))), /* @__PURE__ */ React.createElement("label", { className: "flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200 md:col-span-2" }, /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "checkbox",
        checked: withHeaderColumn,
        onChange: (event) => onHeaderColumnChange?.(event.target.checked),
        className: "mt-1"
      }
    ), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, "Header column"), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, "Use a header column for row labels.")))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onInsert, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Insert table")))
  );
}
function RichTableControls({ editor }) {
  const isTableActive = Boolean(editor?.isActive("table"));
  const canRun = reactExports.useCallback((commandName) => {
    if (!editor) return false;
    try {
      const chain = editor.can().chain().focus();
      const next = typeof chain[commandName] === "function" ? chain[commandName]() : null;
      return Boolean(next?.run?.());
    } catch {
      return false;
    }
  }, [editor]);
  const runCommand = reactExports.useCallback((commandName) => {
    if (!editor) return;
    const chain = editor.chain().focus();
    if (typeof chain[commandName] !== "function") return;
    chain[commandName]().run();
  }, [editor]);
  const deleteTable = reactExports.useCallback(() => {
    if (!editor) return;
    editor.chain().focus().deleteTable().run();
  }, [editor]);
  const getActiveTable = reactExports.useCallback(() => {
    if (!editor) return null;
    const { state } = editor;
    const { $from } = state.selection;
    for (let depth = $from.depth; depth >= 0; depth -= 1) {
      const node2 = $from.node(depth);
      if (node2?.type?.name !== "table") {
        continue;
      }
      return {
        node: node2,
        depth,
        pos: $from.before(depth)
      };
    }
    return null;
  }, [editor]);
  const moveTable = reactExports.useCallback((direction) => {
    if (!editor) return;
    const tableInfo = getActiveTable();
    if (!tableInfo) return;
    const { state, view } = editor;
    const { doc } = state;
    const tableNode = tableInfo.node;
    const tablePos = tableInfo.pos;
    const tableSize = tableNode.nodeSize;
    let childPos = 1;
    let previous2 = null;
    let current = null;
    let next = null;
    for (let index2 = 0; index2 < doc.childCount; index2 += 1) {
      const child = doc.child(index2);
      if (childPos === tablePos) {
        current = { node: child, pos: childPos };
        next = index2 + 1 < doc.childCount ? { node: doc.child(index2 + 1), pos: childPos + child.nodeSize } : null;
        break;
      }
      previous2 = { node: child, pos: childPos };
      childPos += child.nodeSize;
    }
    if (!current) return;
    const tr = state.tr.delete(tablePos, tablePos + tableSize);
    let insertPos = tablePos;
    if (direction === "up") {
      if (!previous2) return;
      insertPos = previous2.pos;
    } else if (direction === "down") {
      if (!next) return;
      insertPos = next.pos + next.node.nodeSize - tableSize;
    } else {
      return;
    }
    tr.insert(insertPos, tableNode.type.create(tableNode.attrs, tableNode.content, tableNode.marks));
    view.dispatch(tr);
    editor.chain().focus().setNodeSelection(insertPos).run();
  }, [editor, getActiveTable]);
  if (!editor) return null;
  return /* @__PURE__ */ React.createElement(
    BubbleMenu,
    {
      editor,
      shouldShow: ({ editor: bubbleEditor }) => Boolean(bubbleEditor?.isActive("table")),
      tippyOptions: {
        placement: "top-start",
        offset: [0, 12],
        duration: 100
      },
      className: "rich-table-toolbar"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 rounded-2xl border border-sky-300/25 bg-[linear-gradient(180deg,rgba(12,18,29,0.98),rgba(6,10,16,0.98))] px-3 py-2 text-xs text-slate-400 shadow-[0_18px_50px_rgba(0,0,0,0.35)]" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 font-semibold uppercase tracking-[0.16em] text-slate-300" }, "Table tools"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addRowBefore"), disabled: !canRun("addRowBefore"), title: "Add row before" }, "Row +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addRowAfter"), disabled: !canRun("addRowAfter"), title: "Add row after" }, "Row +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("deleteRow"), disabled: !canRun("deleteRow"), title: "Delete row" }, "Del row"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addColumnBefore"), disabled: !canRun("addColumnBefore"), title: "Add column before" }, "Col +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addColumnAfter"), disabled: !canRun("addColumnAfter"), title: "Add column after" }, "Col +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("deleteColumn"), disabled: !canRun("deleteColumn"), title: "Delete column" }, "Del col"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("mergeCells"), disabled: !canRun("mergeCells"), title: "Merge selected cells" }, "Merge"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("splitCell"), disabled: !canRun("splitCell"), title: "Split selected cell" }, "Split"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("toggleHeaderRow"), disabled: !canRun("toggleHeaderRow"), active: isTableActive, title: "Toggle header row" }, "Header row"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("toggleHeaderColumn"), disabled: !canRun("toggleHeaderColumn"), active: isTableActive, title: "Toggle header column" }, "Header col"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => moveTable("up"), disabled: !getActiveTable(), title: "Move table up" }, "Move up"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => moveTable("down"), disabled: !getActiveTable(), title: "Move table down" }, "Move down"), /* @__PURE__ */ React.createElement(TableButton, { onClick: deleteTable, title: "Delete table" }, "Delete table"))
  );
}
function ToolbarBtn$2({ onClick, active, disabled, title, children, className = "" }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onMouseDown: (event) => {
        event.preventDefault();
      },
      onClick,
      disabled,
      title,
      className: [
        "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400",
        active ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200",
        disabled && "pointer-events-none opacity-30",
        className
      ].filter(Boolean).join(" ")
    },
    children
  );
}
function Divider$1() {
  return /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-5 w-px bg-white/10" });
}
function getRootFontSizePx() {
  if (typeof window === "undefined") {
    return 16;
  }
  return Number.parseFloat(window.getComputedStyle(document.documentElement).fontSize) || 16;
}
function formatViewportHeightLabel(value) {
  const rounded = Number(value || 0);
  const displayValue = Number.isInteger(rounded) ? rounded : Number(rounded.toFixed(1));
  return `${displayValue}rem`;
}
function normalizeHttpUrl(rawValue) {
  const trimmed = String(rawValue || "").trim();
  if (trimmed === "") {
    return null;
  }
  const withProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed.replace(/^\/+/, "")}`;
  try {
    const parsed = new URL(withProtocol);
    if (!["http:", "https:"].includes(parsed.protocol)) {
      return null;
    }
    return parsed.toString();
  } catch {
    return null;
  }
}
function normalizeVideoEmbedUrl(rawValue) {
  const normalized = normalizeHttpUrl(rawValue);
  if (!normalized) {
    return null;
  }
  const parsed = new URL(normalized);
  const host = parsed.hostname.replace(/^www\./i, "").toLowerCase();
  const path = parsed.pathname;
  if (host === "youtu.be") {
    const videoId = path.replace(/^\//, "").split("/")[0];
    return videoId ? `https://www.youtube.com/embed/${videoId}` : normalized;
  }
  if (host === "youtube.com" || host === "m.youtube.com") {
    if (path === "/watch") {
      const videoId = parsed.searchParams.get("v");
      return videoId ? `https://www.youtube.com/embed/${videoId}` : normalized;
    }
    const pathMatch = path.match(/^\/(embed|shorts|live)\/([^/?#]+)/i);
    if (pathMatch?.[2]) {
      return `https://www.youtube.com/embed/${pathMatch[2]}`;
    }
  }
  return normalized;
}
function detectSocialPlatform(rawUrl) {
  const normalized = normalizeHttpUrl(rawUrl);
  if (!normalized) {
    return { platform: "social", label: "Social post", url: null };
  }
  const host = new URL(normalized).hostname.replace(/^www\./i, "").toLowerCase();
  if (host.includes("instagram.")) return { platform: "instagram", label: "Instagram post", url: normalized };
  if (host.includes("facebook.")) return { platform: "facebook", label: "Facebook post", url: normalized };
  if (host.includes("tiktok.")) return { platform: "tiktok", label: "TikTok post", url: normalized };
  if (host.includes("twitter.") || host.includes("x.com")) return { platform: "x", label: "X post", url: normalized };
  if (host.includes("linkedin.")) return { platform: "linkedin", label: "LinkedIn post", url: normalized };
  if (host.includes("threads.")) return { platform: "threads", label: "Threads post", url: normalized };
  if (host.includes("pinterest.")) return { platform: "pinterest", label: "Pinterest pin", url: normalized };
  return { platform: "social", label: "Social post", url: normalized };
}
const ArtworkEmbed = Node3.create({
  name: "artworkEmbed",
  group: "block",
  atom: true,
  addAttributes() {
    return {
      title: { default: "Artwork" },
      url: { default: "" },
      thumb: { default: "" }
    };
  },
  parseHTML() {
    return [{ tag: "figure[data-artwork-embed]" }];
  },
  renderHTML({ HTMLAttributes }) {
    const preview = [];
    if (HTMLAttributes.thumb) {
      preview.push([
        "img",
        {
          src: HTMLAttributes.thumb,
          alt: HTMLAttributes.title || "Artwork",
          class: "block h-auto w-full object-cover",
          loading: "lazy"
        }
      ]);
    }
    preview.push([
      "figcaption",
      { class: "news-embed-caption" },
      HTMLAttributes.title || "Artwork"
    ]);
    return [
      "figure",
      mergeAttributes(HTMLAttributes, {
        "data-artwork-embed": "true",
        class: "news-embed news-embed-artwork"
      }),
      [
        "a",
        {
          href: HTMLAttributes.url || "#",
          class: "news-embed-link",
          rel: "noopener noreferrer nofollow",
          target: "_blank"
        },
        ...preview
      ]
    ];
  }
});
const VideoEmbed = Node3.create({
  name: "videoEmbed",
  group: "block",
  atom: true,
  addAttributes() {
    return {
      src: { default: "" },
      url: { default: "" },
      title: { default: "Embedded video" }
    };
  },
  parseHTML() {
    return [{ tag: "figure[data-video-embed]" }];
  },
  renderHTML({ HTMLAttributes }) {
    return [
      "figure",
      mergeAttributes(HTMLAttributes, {
        "data-video-embed": "true",
        class: "news-embed news-embed-video w-full"
      }),
      [
        "iframe",
        {
          src: HTMLAttributes.src || "",
          title: HTMLAttributes.title || "Embedded video",
          loading: "lazy",
          frameborder: "0",
          allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",
          allowfullscreen: "true",
          referrerpolicy: "strict-origin-when-cross-origin"
        }
      ]
    ];
  }
});
const SocialEmbed = Node3.create({
  name: "socialEmbed",
  group: "block",
  atom: true,
  addAttributes() {
    return {
      url: { default: "" },
      platform: { default: "social" },
      label: { default: "Social post" }
    };
  },
  parseHTML() {
    return [{ tag: "figure[data-social-embed]" }];
  },
  renderHTML({ HTMLAttributes }) {
    const platform2 = String(HTMLAttributes.platform || "social");
    const url = HTMLAttributes.url || "#";
    const label = HTMLAttributes.label || "Social post";
    if (platform2 === "instagram") {
      return [
        "figure",
        mergeAttributes(HTMLAttributes, {
          "data-social-embed": "true",
          "data-platform": platform2,
          class: "news-embed news-embed-social"
        }),
        [
          "blockquote",
          {
            class: "instagram-media",
            "data-instgrm-captioned": "true",
            "data-instgrm-permalink": url,
            "data-instgrm-version": "14"
          },
          [
            "a",
            { href: url, rel: "noopener noreferrer nofollow", target: "_blank" },
            label
          ]
        ]
      ];
    }
    if (platform2 === "facebook") {
      return [
        "figure",
        mergeAttributes(HTMLAttributes, {
          "data-social-embed": "true",
          "data-platform": platform2,
          class: "news-embed news-embed-social"
        }),
        [
          "div",
          { class: "fb-post", "data-href": url, "data-show-text": "true" },
          [
            "blockquote",
            { cite: url, class: "fb-xfbml-parse-ignore" },
            [
              "a",
              { href: url, rel: "noopener noreferrer nofollow", target: "_blank" },
              label
            ]
          ]
        ]
      ];
    }
    if (platform2 === "tiktok") {
      return [
        "figure",
        mergeAttributes(HTMLAttributes, {
          "data-social-embed": "true",
          "data-platform": platform2,
          class: "news-embed news-embed-social"
        }),
        [
          "blockquote",
          { class: "tiktok-embed", cite: url },
          [
            "section",
            null,
            [
              "a",
              { href: url, rel: "noopener noreferrer nofollow", target: "_blank" },
              label
            ]
          ]
        ]
      ];
    }
    if (platform2 === "x") {
      return [
        "figure",
        mergeAttributes(HTMLAttributes, {
          "data-social-embed": "true",
          "data-platform": platform2,
          class: "news-embed news-embed-social"
        }),
        [
          "blockquote",
          { class: "twitter-tweet" },
          [
            "a",
            { href: url, rel: "noopener noreferrer nofollow", target: "_blank" },
            label
          ]
        ]
      ];
    }
    return [
      "figure",
      mergeAttributes(HTMLAttributes, {
        "data-social-embed": "true",
        "data-platform": platform2,
        class: "news-embed news-embed-social"
      }),
      [
        "a",
        {
          href: url,
          class: "news-embed-link",
          rel: "noopener noreferrer nofollow",
          target: "_blank"
        },
        ["span", { class: "news-embed-badge" }, label],
        ["span", { class: "news-embed-url" }, url]
      ]
    ];
  }
});
function ArtworkPickerDialog({
  open,
  query,
  items,
  loading,
  onQueryChange,
  onClose,
  onSearch,
  onSelect
}) {
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === event.currentTarget) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-3xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Artwork embed"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Choose artwork"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Search existing artworks and insert a linked artwork card into the News article body.")), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement(
        "input",
        {
          value: query,
          onChange: (event) => onQueryChange?.(event.target.value),
          onKeyDown: (event) => {
            if (event.key === "Enter") {
              event.preventDefault();
              onSearch?.();
            }
          },
          placeholder: "Search by title, slug, or creator",
          className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
        }
      ), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onSearch, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Search"))), /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar max-h-[60vh] overflow-y-auto px-6 py-5" }, loading ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, "Searching artworks…") : null, !loading && (!Array.isArray(items) || items.length === 0) ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No artworks found yet. Try a broader title or creator search.") : null, !loading && Array.isArray(items) && items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, items.map((item) => {
        const previewImage2 = item.image || item.avatar || "";
        return /* @__PURE__ */ React.createElement(
          "button",
          {
            key: `${item.entity_type || "artwork"}-${item.id}`,
            type: "button",
            onClick: () => onSelect?.(item),
            className: "flex items-center gap-4 rounded-[24px] border border-white/10 bg-black/20 p-3 text-left transition hover:border-white/20 hover:bg-white/[0.04]"
          },
          /* @__PURE__ */ React.createElement("div", { className: "h-20 w-28 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03]" }, previewImage2 ? /* @__PURE__ */ React.createElement("img", { src: previewImage2, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-xs uppercase tracking-[0.18em] text-slate-500" }, "No thumb")),
          /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-xs leading-5 text-slate-400" }, item.description) : null)
        );
      })) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel")))
    ),
    document.body
  );
}
function MediaImageDialog({
  open,
  uploading,
  error,
  previewUrl,
  imageUrl,
  altText,
  uploadLabel,
  helperText,
  allowUpload,
  onClose,
  onImageUrlChange,
  onAltTextChange,
  onPickFile,
  onBrowseAssets,
  onInsert,
  onClearUploaded
}) {
  const inputRef = reactExports.useRef(null);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === event.currentTarget) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-4xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Media"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Add image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Upload, drag, paste, or link an image without leaving the editor.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 px-6 py-5 lg:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, allowUpload ? /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "button",
          tabIndex: 0,
          onClick: () => !uploading && inputRef.current?.click(),
          onKeyDown: (event) => {
            if (uploading) return;
            if (event.key === "Enter" || event.key === " ") {
              event.preventDefault();
              inputRef.current?.click();
            }
          },
          onDragOver: (event) => {
            event.preventDefault();
          },
          onDrop: (event) => {
            event.preventDefault();
            void onPickFile?.(event.dataTransfer?.files?.[0] || null);
          },
          className: [
            "rounded-[24px] border border-dashed px-5 py-5 transition outline-none",
            uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"
          ].join(" ")
        },
        /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-cloud-arrow-up"}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, uploading ? "Uploading image…" : uploadLabel || "Drop image here or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, helperText), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "You can also paste an image directly into the editor or drag one into the writing area."))),
        /* @__PURE__ */ React.createElement(
          "input",
          {
            ref: inputRef,
            type: "file",
            accept: "image/jpeg,image/png,image/webp",
            className: "hidden",
            onChange: (event) => {
              void onPickFile?.(event.target.files?.[0] || null);
              event.target.value = "";
            }
          }
        )
      ) : null, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Image URL"), /* @__PURE__ */ React.createElement(
        "input",
        {
          value: imageUrl,
          onChange: (event) => onImageUrlChange?.(event.target.value),
          placeholder: "https://files.skinbase.org/...",
          className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
        }
      )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Alt text"), /* @__PURE__ */ React.createElement(
        "input",
        {
          value: altText,
          onChange: (event) => onAltTextChange?.(event.target.value),
          placeholder: "Describe what the image shows",
          className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
        }
      )), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-slate-950" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "Media preview", className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-64 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No media selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, allowUpload ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => inputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse") : null, onBrowseAssets ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onBrowseAssets, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Choose from assets") : null, previewUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClearUploaded?.(), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300 transition hover:bg-white/[0.04]" }, "Clear") : null))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onInsert, disabled: !previewUrl || uploading, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-40" }, "Insert image")))
    ),
    document.body
  );
}
function CompareImageDialog({
  open,
  uploading,
  error,
  subtitle,
  leftImage,
  rightImage,
  allowUpload,
  onClose,
  onSubtitleChange,
  onLeftAltTextChange,
  onRightAltTextChange,
  onLeftPickFile,
  onRightPickFile,
  onLeftBrowseAssets,
  onRightBrowseAssets,
  onLeftClear,
  onRightClear,
  onInsert
}) {
  const leftInputRef = reactExports.useRef(null);
  const rightInputRef = reactExports.useRef(null);
  if (!open) return null;
  const renderSide = (sideLabel, image2, inputRef, onPickFile, onClear, onAltTextChange, onBrowseAssets) => /* @__PURE__ */ React.createElement(
    "div",
    {
      role: "button",
      tabIndex: 0,
      onClick: (event) => {
        if (event.target !== event.currentTarget) {
          return;
        }
        if (!uploading && allowUpload) {
          inputRef.current?.click();
        }
      },
      onKeyDown: (event) => {
        if (event.target !== event.currentTarget) {
          return;
        }
        if (uploading || !allowUpload) return;
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          inputRef.current?.click();
        }
      },
      onDragOver: (event) => {
        event.preventDefault();
      },
      onDrop: (event) => {
        event.preventDefault();
        void onPickFile?.(event.dataTransfer?.files?.[0] || null);
      },
      className: [
        "grid gap-4 rounded-[24px] border border-dashed px-5 py-5 transition outline-none",
        uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-images"}` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, sideLabel), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, "Upload the image for this side of the comparison."))),
    /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, image2.previewUrl ? /* @__PURE__ */ React.createElement("img", { src: image2.previewUrl, alt: `${sideLabel} preview`, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No image selected yet.")),
    /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300", onClick: (event) => event.stopPropagation() }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Alt text"), /* @__PURE__ */ React.createElement(
      "input",
      {
        value: image2.altText,
        onChange: (event) => onAltTextChange?.(event.target.value),
        placeholder: `Describe the ${sideLabel.toLowerCase()} image`,
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2", onClick: (event) => event.stopPropagation() }, allowUpload ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: (event) => {
          event.stopPropagation();
          inputRef.current?.click();
        },
        className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
      },
      "Browse"
    ) : null, onBrowseAssets ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: (event) => {
          event.stopPropagation();
          onBrowseAssets();
        },
        className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
      },
      "Choose from assets"
    ) : null, image2.previewUrl ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: (event) => {
          event.stopPropagation();
          onClear?.();
        },
        className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300 transition hover:bg-white/[0.04]"
      },
      "Clear"
    ) : null),
    /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: inputRef,
        type: "file",
        accept: "image/jpeg,image/png,image/webp",
        className: "hidden",
        onChange: (event) => {
          void onPickFile?.(event.target.files?.[0] || null);
          event.target.value = "";
        }
      }
    )
  );
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === event.currentTarget) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-6xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Image comparison"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Add side-by-side images"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Upload two images, add alt text for each, and include a subtitle under the comparison.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 px-6 py-5 xl:grid-cols-2" }, renderSide("Left image", leftImage, leftInputRef, onLeftPickFile, onLeftClear, onLeftAltTextChange, onLeftBrowseAssets), renderSide("Right image", rightImage, rightInputRef, onRightPickFile, onRightClear, onRightAltTextChange, onRightBrowseAssets)), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Subtitle"), /* @__PURE__ */ React.createElement(
        "input",
        {
          value: subtitle,
          onChange: (event) => onSubtitleChange?.(event.target.value),
          placeholder: "Visible subtitle below the comparison",
          className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
        }
      )), error ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onInsert, disabled: !leftImage.previewUrl || !rightImage.previewUrl || uploading, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-40" }, "Insert comparison")))
    ),
    document.body
  );
}
function AssetPickerDialog({
  open,
  searchQuery,
  assets,
  loading,
  error,
  pagination,
  onClose,
  onRefresh,
  onSearchQueryChange,
  onSearch,
  onPreviousPage,
  onNextPage,
  onSelect
}) {
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === event.currentTarget) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-6xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4 border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Academy assets"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Choose an uploaded image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Pick from previously uploaded Academy lesson images instead of uploading a new file.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onRefresh, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Refresh"))), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center" }, /* @__PURE__ */ React.createElement(
        "input",
        {
          value: searchQuery,
          onChange: (event) => onSearchQueryChange?.(event.target.value),
          onKeyDown: (event) => {
            if (event.key === "Enter") {
              event.preventDefault();
              onSearch?.();
            }
          },
          placeholder: "Search academy assets",
          className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
        }
      ), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onSearch, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Search"))), /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar max-h-[68vh] overflow-y-auto px-6 py-5" }, loading ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, "Loading academy assets…") : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mb-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, !loading && (!Array.isArray(assets) || assets.length === 0) ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No academy images found yet. Upload one first.") : null, !loading && Array.isArray(assets) && assets.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-3" }, assets.map((asset) => /* @__PURE__ */ React.createElement(
        "button",
        {
          key: asset.path,
          type: "button",
          onClick: () => onSelect?.(asset),
          className: "group overflow-hidden rounded-[24px] border border-white/10 bg-black/20 text-left transition hover:border-sky-300/30 hover:bg-white/[0.04]"
        },
        /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-950" }, /* @__PURE__ */ React.createElement("img", { src: asset.url, alt: asset.name || "Academy asset", className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.02]", loading: "lazy" })),
        /* @__PURE__ */ React.createElement("div", { className: "space-y-2 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, asset.name || "Academy image"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, asset.slot ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, asset.slot) : null, asset.modified_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, new Date(asset.modified_at).toLocaleDateString()) : null))
      ))) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Page ", pagination?.page || 1, " of ", pagination?.last_page || 1, typeof pagination?.total === "number" ? ` · ${pagination.total} assets` : ""), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: onPreviousPage,
          disabled: (pagination?.page || 1) <= 1 || loading,
          className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40"
        },
        "Previous"
      ), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: onNextPage,
          disabled: !pagination?.has_more || loading,
          className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40"
        },
        "Next"
      ))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel")))
    ),
    document.body
  );
}
function Toolbar$1({
  editor,
  advancedNews = false,
  activeSourceMode = null,
  sourceModeLabel = "HTML",
  sourceModeTitle = "View or edit source HTML",
  secondarySourceModeLabel = null,
  secondarySourceModeTitle = "",
  showStructureOutlines = false,
  showComparisonTool = false,
  fullHeightMode = false,
  onToggleSourceMode,
  onToggleSecondarySourceMode,
  onToggleStructureOutlines,
  onInsertArtwork,
  onInsertImage,
  onInsertComparison,
  onInsertTable,
  onInsertSocialEmbed,
  onInsertVideoEmbed,
  onInsertHashtag,
  editorViewportHeight,
  onIncreaseEditorViewportHeight,
  onDecreaseEditorViewportHeight,
  onToggleFullHeightMode
}) {
  if (!editor) return null;
  const addLink = reactExports.useCallback(() => {
    const prev = editor.getAttributes("link").href;
    const url = window.prompt("URL", prev ?? "https://");
    if (url === null) return;
    if (url === "") {
      editor.chain().focus().extendMarkRange("link").unsetLink().run();
    } else {
      editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
    }
  }, [editor]);
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-0.5 border-b border-white/[0.06] px-2.5 py-2" }, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold"), title: "Bold (Ctrl+B)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6zm0 8h9a4 4 0 014 4 4 4 0 01-4 4H6z" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic"), title: "Italic (Ctrl+I)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline"), title: "Underline (Ctrl+U)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("path", { d: "M6 3v7a6 6 0 006 6 6 6 0 006-6V3" }), /* @__PURE__ */ React.createElement("line", { x1: "4", y1: "21", x2: "20", y2: "21" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike"), title: "Strikethrough" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "4", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("path", { d: "M17.5 7.5c0-2-1.5-3.5-5.5-3.5S6.5 5.5 6.5 7.5c0 4 11 4 11 8 0 2-1.5 3.5-5.5 3.5s-5.5-1.5-5.5-3.5" }))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: editor.isActive("heading", { level: 2 }), title: "Heading 2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H2")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: editor.isActive("heading", { level: 3 }), title: "Heading 3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H3")), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList"), title: "Bullet list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "6", x2: "20", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "18", x2: "20", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "6", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "12", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "18", r: "1", fill: "currentColor" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList"), title: "Numbered list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("text", { x: "3", y: "8", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "1"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "14", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "2"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "20", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "3"))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleBlockquote().run(), active: editor.isActive("blockquote"), title: "Quote" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.24 11 15.14c0 .94-.36 1.84-1.001 2.503A3.34 3.34 0 017.559 18.6a3.77 3.77 0 01-2.976-.879zm10.4 0C13.953 16.227 13.4 15 13.4 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.986.169 3.395 1.729 3.395 3.629 0 .94-.36 1.84-1.001 2.503a3.34 3.34 0 01-2.44.957 3.77 3.77 0 01-2.976-.879z" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleCodeBlock().run(), active: editor.isActive("codeBlock"), title: "Code block" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "16 18 22 12 16 6" }), /* @__PURE__ */ React.createElement("polyline", { points: "8 6 2 12 8 18" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleCode().run(), active: editor.isActive("code"), title: "Inline code" }, /* @__PURE__ */ React.createElement("span", { className: "font-mono text-[11px] font-bold" }, "{}")), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: addLink, active: editor.isActive("link"), title: "Link" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertImage, title: "Insert image" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }), /* @__PURE__ */ React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5" }), /* @__PURE__ */ React.createElement("polyline", { points: "21 15 16 10 5 21" }))), showComparisonTool ? /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertComparison, title: "Insert image comparison" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "4", width: "8", height: "16", rx: "1.5" }), /* @__PURE__ */ React.createElement("rect", { x: "13", y: "4", width: "8", height: "16", rx: "1.5" }), /* @__PURE__ */ React.createElement("path", { d: "M9 8h1M14 8h1M9 16h1M14 16h1" }))) : null, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertTable, title: "Insert table" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }), /* @__PURE__ */ React.createElement("path", { d: "M3 9h18M3 15h18M9 3v18M15 3v18" }))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().setHorizontalRule().run(), title: "Horizontal rule" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "3", y1: "12", x2: "21", y2: "12" }))), /* @__PURE__ */ React.createElement(EmojiPicker, { editor }), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().insertContent("@").run(), title: "Mention a user (type @username)" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "@")), advancedNews ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onToggleSourceMode, active: activeSourceMode === "primary", title: sourceModeTitle, className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, sourceModeLabel)), secondarySourceModeLabel ? /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onToggleSecondarySourceMode, active: activeSourceMode === "secondary", title: secondarySourceModeTitle, className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, secondarySourceModeLabel)) : null, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onToggleStructureOutlines, active: showStructureOutlines, title: "Outline blocks (p, div, figure, list)", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "DOM")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertArtwork, title: "Embed artwork", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Art")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertSocialEmbed, title: "Embed social post", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Social")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertVideoEmbed, title: "Embed YouTube", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "YT")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertHashtag, title: "Insert hashtag", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "#"))) : null, /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-0.5" }, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onDecreaseEditorViewportHeight, title: "Shorter editor", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "A-")), /* @__PURE__ */ React.createElement("div", { className: "mx-1 flex min-w-[5.25rem] items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, formatViewportHeightLabel(editorViewportHeight)), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onIncreaseEditorViewportHeight, title: "Taller editor", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "A+")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onToggleFullHeightMode, active: fullHeightMode, title: fullHeightMode ? "Exit full height editor" : "Expand editor to full browser size", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Fit")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo(), title: "Undo (Ctrl+Z)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "1 4 1 10 7 10" }), /* @__PURE__ */ React.createElement("path", { d: "M3.51 15a9 9 0 102.13-9.36L1 10" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo(), title: "Redo (Ctrl+Shift+Z)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "23 4 23 10 17 10" }), /* @__PURE__ */ React.createElement("path", { d: "M20.49 15a9 9 0 11-2.13-9.36L23 10" })))));
}
function RichTextEditor({
  content: content2 = "",
  onChange,
  placeholder = "Write something…",
  error,
  minHeight = 12,
  maxHeightRem = 42,
  autofocus = false,
  advancedNews = false,
  sourceModeLabel = "HTML",
  sourceModeTitle = "View or edit source HTML",
  sourceModeDescription = "Edit the stored article HTML directly. Saving while in this mode keeps the HTML exactly as written here.",
  secondarySourceModeLabel = null,
  secondarySourceModeTitle = "",
  secondarySourceModeDescription = "",
  secondarySourceModeValue = null,
  onSecondarySourceModeValueChange = null,
  searchEntities = null,
  mediaSupport = null
}) {
  const viewportStorageKey = "rich-text-editor.viewport-height";
  const viewportMinHeight = Math.max(minHeight + 6, 18);
  const viewportMaxHeight = Math.max(viewportMinHeight, Number(maxHeightRem) || 42);
  const viewportStep = 4;
  const [activeSourceMode, setActiveSourceMode] = reactExports.useState(null);
  const [fullHeightMode, setFullHeightMode] = reactExports.useState(false);
  const [sourceValue, setSourceValue] = reactExports.useState(String(content2 || ""));
  const [showStructureOutlines, setShowStructureOutlines] = reactExports.useState(false);
  const [helperMessage, setHelperMessage] = reactExports.useState("");
  const [artworkPickerOpen, setArtworkPickerOpen] = reactExports.useState(false);
  const [artworkQuery, setArtworkQuery] = reactExports.useState("");
  const [artworkResults, setArtworkResults] = reactExports.useState([]);
  const [artworkLoading, setArtworkLoading] = reactExports.useState(false);
  const [mediaDialogOpen, setMediaDialogOpen] = reactExports.useState(false);
  const [mediaUploading, setMediaUploading] = reactExports.useState(false);
  const [mediaError, setMediaError] = reactExports.useState("");
  const [mediaUrlValue, setMediaUrlValue] = reactExports.useState("");
  const [mediaPreviewUrl, setMediaPreviewUrl] = reactExports.useState("");
  const [mediaAltText, setMediaAltText] = reactExports.useState("");
  const [mediaUploadedPath, setMediaUploadedPath] = reactExports.useState("");
  const [academyAssetsOpen, setAcademyAssetsOpen] = reactExports.useState(false);
  const [academyAssetsQuery, setAcademyAssetsQuery] = reactExports.useState("");
  const [academyAssetsSearch, setAcademyAssetsSearch] = reactExports.useState("");
  const [academyAssetsPage, setAcademyAssetsPage] = reactExports.useState(1);
  const [academyAssetsPagination, setAcademyAssetsPagination] = reactExports.useState({
    page: 1,
    per_page: 24,
    total: 0,
    last_page: 1,
    has_more: false
  });
  const [academyAssetsLoading, setAcademyAssetsLoading] = reactExports.useState(false);
  const [academyAssetsError, setAcademyAssetsError] = reactExports.useState("");
  const [academyAssets, setAcademyAssets] = reactExports.useState([]);
  const [academyAssetsTarget, setAcademyAssetsTarget] = reactExports.useState(null);
  const [compareDialogOpen, setCompareDialogOpen] = reactExports.useState(false);
  const [compareUploading, setCompareUploading] = reactExports.useState(false);
  const [compareError, setCompareError] = reactExports.useState("");
  const [compareSubtitle, setCompareSubtitle] = reactExports.useState("");
  const [compareLeftImage, setCompareLeftImage] = reactExports.useState({ previewUrl: "", altText: "", uploadedPath: "" });
  const [compareRightImage, setCompareRightImage] = reactExports.useState({ previewUrl: "", altText: "", uploadedPath: "" });
  const [tableInsertOpen, setTableInsertOpen] = reactExports.useState(false);
  const [tableRows, setTableRows] = reactExports.useState(3);
  const [tableCols, setTableCols] = reactExports.useState(3);
  const [tableHeaderRow, setTableHeaderRow] = reactExports.useState(true);
  const [tableHeaderColumn, setTableHeaderColumn] = reactExports.useState(false);
  const [editorViewportHeight, setEditorViewportHeight] = reactExports.useState(() => {
    if (typeof window === "undefined") {
      return Math.min(viewportMaxHeight, viewportMinHeight);
    }
    const storedValue = Number(window.localStorage.getItem(viewportStorageKey));
    if (Number.isFinite(storedValue)) {
      return Math.min(viewportMaxHeight, Math.max(viewportMinHeight, storedValue));
    }
    return Math.min(viewportMaxHeight, viewportMinHeight);
  });
  const editorRef = reactExports.useRef(null);
  const resizeCleanupRef = reactExports.useRef(null);
  const usesSecondarySourceMode = typeof onSecondarySourceModeValueChange === "function" && secondarySourceModeValue != null;
  const csrfToken2 = reactExports.useMemo(() => {
    if (typeof document === "undefined") {
      return "";
    }
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
  }, []);
  const deleteTemporaryMedia = reactExports.useCallback(async (path) => {
    if (!mediaSupport?.deleteUrl || !path) return;
    const response = await fetch(mediaSupport.deleteUrl, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken2,
        Accept: "application/json"
      },
      credentials: "same-origin",
      body: JSON.stringify({ path })
    });
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(payload?.message || payload?.error || "Could not remove uploaded media.");
    }
  }, [csrfToken2, mediaSupport]);
  const resetMediaState = reactExports.useCallback(() => {
    setMediaUploading(false);
    setMediaError("");
    setMediaUrlValue("");
    setMediaPreviewUrl("");
    setMediaAltText("");
    setMediaUploadedPath("");
  }, []);
  const insertImageIntoEditor = reactExports.useCallback((src2, alt = "") => {
    if (!src2 || !editorRef.current) return false;
    editorRef.current.chain().focus().insertContent({
      type: "image",
      attrs: {
        src: src2,
        alt: alt || "",
        title: alt || "",
        caption: "",
        width: null
      }
    }).run();
    return true;
  }, []);
  const uploadMediaFile = reactExports.useCallback(async (file, previousPath = "") => {
    if (!file || !mediaSupport?.uploadUrl) {
      return null;
    }
    if (!String(file.type || "").startsWith("image/")) {
      throw new Error("Use an image file to insert media.");
    }
    setMediaUploading(true);
    setMediaError("");
    try {
      if (previousPath) {
        await deleteTemporaryMedia(previousPath);
      }
      const body2 = new FormData();
      body2.append("image", file);
      body2.append("slot", mediaSupport.slot || "body");
      const response = await fetch(mediaSupport.uploadUrl, {
        method: "POST",
        headers: {
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        },
        credentials: "same-origin",
        body: body2
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || payload?.error || "Image upload failed.");
      }
      return payload;
    } finally {
      setMediaUploading(false);
    }
  }, [csrfToken2, deleteTemporaryMedia, mediaSupport]);
  const loadAcademyAssets = reactExports.useCallback(async ({ page = academyAssetsPage, query = academyAssetsSearch } = {}) => {
    if (!mediaSupport?.assetsUrl) {
      setAcademyAssets([]);
      setAcademyAssetsPagination({ page: 1, per_page: 24, total: 0, last_page: 1, has_more: false });
      return;
    }
    setAcademyAssetsLoading(true);
    setAcademyAssetsError("");
    try {
      const params = new URLSearchParams();
      params.set("limit", "24");
      params.set("page", String(Math.max(1, page)));
      if (String(query || "").trim() !== "") {
        params.set("q", String(query).trim());
      }
      const requestUrl = new URL(mediaSupport.assetsUrl, window.location.origin);
      requestUrl.search = params.toString();
      const response = await fetch(requestUrl.toString(), {
        headers: {
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        },
        credentials: "same-origin",
        cache: "no-store"
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || "Could not load academy assets.");
      }
      setAcademyAssets(Array.isArray(payload?.items) ? payload.items : []);
      setAcademyAssetsPagination({
        page: Number(payload?.pagination?.page) || 1,
        per_page: Number(payload?.pagination?.per_page) || 24,
        total: Number(payload?.pagination?.total) || 0,
        last_page: Number(payload?.pagination?.last_page) || 1,
        has_more: Boolean(payload?.pagination?.has_more)
      });
    } catch (loadError) {
      setAcademyAssets([]);
      setAcademyAssetsPagination({ page: 1, per_page: 24, total: 0, last_page: 1, has_more: false });
      setAcademyAssetsError(loadError?.message || "Could not load academy assets.");
    } finally {
      setAcademyAssetsLoading(false);
    }
  }, [academyAssetsPage, academyAssetsSearch, csrfToken2, mediaSupport?.assetsUrl]);
  const openAcademyAssets = reactExports.useCallback((target) => {
    setAcademyAssetsTarget(target);
    setAcademyAssetsQuery("");
    setAcademyAssetsSearch("");
    setAcademyAssetsPage(1);
    setAcademyAssetsOpen(true);
  }, []);
  const submitAcademyAssetSearch = reactExports.useCallback(() => {
    setAcademyAssetsPage(1);
    setAcademyAssetsSearch(academyAssetsQuery.trim());
  }, [academyAssetsQuery]);
  const goToNextAcademyAssetsPage = reactExports.useCallback(() => {
    setAcademyAssetsPage((current) => Math.min(current + 1, academyAssetsPagination.last_page || current + 1));
  }, [academyAssetsPagination.last_page]);
  const goToPreviousAcademyAssetsPage = reactExports.useCallback(() => {
    setAcademyAssetsPage((current) => Math.max(1, current - 1));
  }, []);
  const closeAcademyAssets = reactExports.useCallback(() => {
    setAcademyAssetsOpen(false);
    setAcademyAssetsTarget(null);
    setAcademyAssetsError("");
    setAcademyAssetsQuery("");
    setAcademyAssetsSearch("");
    setAcademyAssetsPage(1);
  }, []);
  const chooseAcademyAsset = reactExports.useCallback((asset) => {
    if (!asset?.url) {
      return;
    }
    const target = academyAssetsTarget || { type: "media" };
    if (target.type === "compare-left") {
      if (compareLeftImage.uploadedPath) {
        void deleteTemporaryMedia(compareLeftImage.uploadedPath).catch(() => {
        });
      }
      setCompareLeftImage({
        previewUrl: asset.url,
        altText: compareLeftImage.altText || asset.name || "",
        uploadedPath: ""
      });
    } else if (target.type === "compare-right") {
      if (compareRightImage.uploadedPath) {
        void deleteTemporaryMedia(compareRightImage.uploadedPath).catch(() => {
        });
      }
      setCompareRightImage({
        previewUrl: asset.url,
        altText: compareRightImage.altText || asset.name || "",
        uploadedPath: ""
      });
    } else {
      if (mediaUploadedPath) {
        void deleteTemporaryMedia(mediaUploadedPath).catch(() => {
        });
      }
      setMediaUploadedPath("");
      setMediaPreviewUrl(asset.url);
      setMediaUrlValue(asset.url);
      setMediaAltText((current) => current || asset.name || "");
      setMediaError("");
    }
    closeAcademyAssets();
  }, [academyAssetsTarget, closeAcademyAssets, compareLeftImage, compareRightImage, deleteTemporaryMedia, mediaUploadedPath]);
  const handleEditorImageFile = reactExports.useCallback(async (file) => {
    if (!file) return false;
    if (!mediaSupport?.uploadUrl) {
      setHelperMessage("Image uploads are not configured for this editor.");
      return false;
    }
    try {
      setHelperMessage("Uploading image...");
      const payload = await uploadMediaFile(file, mediaUploadedPath);
      if (!payload?.url) {
        setHelperMessage("Image upload failed.");
        return false;
      }
      setMediaUploadedPath(payload?.path || "");
      setMediaPreviewUrl(payload?.url || "");
      setMediaUrlValue(payload?.url || "");
      insertImageIntoEditor(payload.url, file.name?.replace(/\.[^.]+$/, "") || "");
      setHelperMessage("Image uploaded.");
      resetMediaState();
      return true;
    } catch (uploadError) {
      setMediaError(uploadError?.message || "Image upload failed.");
      setHelperMessage("Image upload failed.");
      return false;
    }
  }, [insertImageIntoEditor, mediaSupport, mediaUploadedPath, resetMediaState, uploadMediaFile]);
  const extensions = reactExports.useMemo(() => {
    const base = [
      index_default$2.configure({
        link: false,
        underline: false,
        heading: { levels: [2, 3] },
        codeBlock: {
          HTMLAttributes: { class: "forum-code-block" }
        }
      }),
      index_default$1,
      index_default$3.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: "text-sky-300 underline hover:text-sky-200",
          rel: "noopener noreferrer nofollow"
        }
      }),
      RichImage.configure({
        HTMLAttributes: { class: "rich-image-node" }
      }),
      RichCompare.configure({
        HTMLAttributes: { class: "rich-compare-node" }
      }),
      Table$1.configure({
        resizable: true,
        allowTableNodeSelection: true,
        HTMLAttributes: {
          class: "rich-table"
        }
      }),
      TableRow,
      TableHeader.configure({
        HTMLAttributes: {
          class: "rich-table__header"
        }
      }),
      TableCell.configure({
        HTMLAttributes: {
          class: "rich-table__cell"
        }
      }),
      index_default$4.configure({ placeholder }),
      index_default$5.configure({
        HTMLAttributes: {
          class: "mention"
        },
        suggestion: mentionSuggestion
      })
    ];
    if (advancedNews) {
      base.push(ArtworkEmbed, VideoEmbed, SocialEmbed);
    }
    return base;
  }, [advancedNews, placeholder]);
  const editor = useEditor({
    extensions,
    immediatelyRender: false,
    content: content2,
    autofocus,
    editorProps: {
      attributes: {
        class: [
          "prose prose-invert prose-base max-w-none",
          "focus:outline-none",
          "px-4 py-3",
          "prose-headings:text-white prose-headings:font-bold",
          "prose-p:text-zinc-200 prose-p:leading-relaxed prose-p:mb-5",
          "prose-h2:mb-5 prose-h3:mb-4 prose-hr:my-8",
          "prose-a:text-sky-300 prose-a:no-underline hover:prose-a:text-sky-200",
          "prose-blockquote:border-l-sky-500/50 prose-blockquote:text-zinc-400",
          "prose-code:text-amber-300 prose-code:bg-white/[0.06] prose-code:rounded prose-code:px-1.5 prose-code:py-0.5 prose-code:text-xs",
          "prose-pre:bg-white/[0.04] prose-pre:border prose-pre:border-white/[0.06] prose-pre:rounded-xl",
          "prose-img:rounded-xl",
          "prose-hr:border-white/10"
        ].join(" "),
        style: `min-height: ${minHeight}rem`
      },
      handleDrop: (_view, event) => {
        const file = event.dataTransfer?.files?.[0];
        if (!file || !String(file.type || "").startsWith("image/")) return false;
        event.preventDefault();
        void handleEditorImageFile(file);
        return true;
      },
      handlePaste: (_view, event) => {
        const file = event.clipboardData?.files?.[0];
        if (!file || !String(file.type || "").startsWith("image/")) return false;
        event.preventDefault();
        void handleEditorImageFile(file);
        return true;
      }
    },
    onUpdate: ({ editor: currentEditor }) => {
      if (!activeSourceMode) {
        onChange?.(currentEditor.getHTML());
      }
    }
  });
  reactExports.useEffect(() => {
    editorRef.current = editor;
  }, [editor]);
  reactExports.useEffect(() => {
    if (!helperMessage) {
      return void 0;
    }
    const timeout = window.setTimeout(() => setHelperMessage(""), 2200);
    return () => window.clearTimeout(timeout);
  }, [helperMessage]);
  reactExports.useEffect(() => {
    if (!academyAssetsOpen) {
      return;
    }
    void loadAcademyAssets({ page: academyAssetsPage, query: academyAssetsSearch });
  }, [academyAssetsOpen, academyAssetsPage, academyAssetsSearch, loadAcademyAssets]);
  reactExports.useEffect(() => {
    if (!editor) return;
    if (activeSourceMode) return;
    if ((content2 || "") === editor.getHTML()) return;
    editor.commands.setContent(content2 || "", false);
    const normalizedHtml = editor.getHTML();
    if (normalizedHtml !== (content2 || "")) {
      onChange?.(normalizedHtml);
    }
  }, [activeSourceMode, content2, editor, onChange]);
  reactExports.useEffect(() => {
    if (activeSourceMode === "primary") {
      setSourceValue(String(content2 || editor?.getHTML() || ""));
    }
  }, [activeSourceMode, content2, editor]);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") {
      return;
    }
    window.localStorage.setItem(viewportStorageKey, String(editorViewportHeight));
  }, [editorViewportHeight]);
  const stopViewportResize = reactExports.useCallback(() => {
    if (resizeCleanupRef.current) {
      resizeCleanupRef.current();
      resizeCleanupRef.current = null;
    }
    if (typeof document !== "undefined") {
      document.body.style.userSelect = "";
      document.body.style.cursor = "";
    }
  }, []);
  reactExports.useEffect(() => stopViewportResize, [stopViewportResize]);
  reactExports.useEffect(() => {
    if (!fullHeightMode || typeof window === "undefined") {
      return void 0;
    }
    const previousOverflow = document.body.style.overflow;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        setFullHeightMode(false);
      }
    };
    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", handleKeyDown2);
    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", handleKeyDown2);
    };
  }, [fullHeightMode]);
  const decreaseEditorViewportHeight = reactExports.useCallback(() => {
    setEditorViewportHeight((current) => Math.max(viewportMinHeight, Number((current - viewportStep).toFixed(1))));
  }, [viewportMinHeight, viewportStep]);
  const increaseEditorViewportHeight = reactExports.useCallback(() => {
    setEditorViewportHeight((current) => Math.min(viewportMaxHeight, Number((current + viewportStep).toFixed(1))));
  }, [viewportMaxHeight, viewportStep]);
  const toggleFullHeightMode = reactExports.useCallback(() => {
    setFullHeightMode((current) => !current);
  }, []);
  const startViewportResize = reactExports.useCallback((event) => {
    if (fullHeightMode || event.button !== 0 || typeof window === "undefined") {
      return;
    }
    event.preventDefault();
    const startY = event.clientY;
    const startHeight = editorViewportHeight;
    const handlePointerMove = (moveEvent) => {
      const deltaRem = (moveEvent.clientY - startY) / getRootFontSizePx();
      const nextHeight = Number((startHeight + deltaRem).toFixed(1));
      setEditorViewportHeight(Math.min(viewportMaxHeight, Math.max(viewportMinHeight, nextHeight)));
    };
    const handlePointerUp = () => {
      stopViewportResize();
    };
    window.addEventListener("pointermove", handlePointerMove);
    window.addEventListener("pointerup", handlePointerUp);
    window.addEventListener("pointercancel", handlePointerUp);
    resizeCleanupRef.current = () => {
      window.removeEventListener("pointermove", handlePointerMove);
      window.removeEventListener("pointerup", handlePointerUp);
      window.removeEventListener("pointercancel", handlePointerUp);
    };
    document.body.style.userSelect = "none";
    document.body.style.cursor = "ns-resize";
  }, [editorViewportHeight, fullHeightMode, stopViewportResize, viewportMaxHeight, viewportMinHeight]);
  const pushHelperMessage = reactExports.useCallback((message) => {
    setHelperMessage(message);
  }, []);
  const commitPrimarySourceToEditor = reactExports.useCallback(() => {
    if (editor) {
      editor.commands.setContent(sourceValue || "", false);
    }
  }, [editor, sourceValue]);
  const handleToggleSourceMode = reactExports.useCallback(() => {
    if (activeSourceMode === "primary") {
      setActiveSourceMode(null);
      commitPrimarySourceToEditor();
      pushHelperMessage("Returned to visual editor.");
      return;
    }
    if (activeSourceMode === "secondary") {
      setActiveSourceMode("primary");
      setSourceValue(String(content2 || editor?.getHTML() || ""));
      return;
    }
    setSourceValue(String(content2 || editor?.getHTML() || ""));
    setActiveSourceMode("primary");
  }, [activeSourceMode, commitPrimarySourceToEditor, content2, editor, pushHelperMessage]);
  const handleToggleSecondarySourceMode = reactExports.useCallback(() => {
    if (!usesSecondarySourceMode) {
      return;
    }
    if (activeSourceMode === "secondary") {
      setActiveSourceMode(null);
      pushHelperMessage("Returned to visual editor.");
      return;
    }
    if (activeSourceMode === "primary") {
      commitPrimarySourceToEditor();
    }
    setActiveSourceMode("secondary");
  }, [activeSourceMode, commitPrimarySourceToEditor, pushHelperMessage, usesSecondarySourceMode]);
  const handleCloseSourceMode = reactExports.useCallback(() => {
    if (activeSourceMode === "primary") {
      commitPrimarySourceToEditor();
    }
    setActiveSourceMode(null);
    pushHelperMessage("Returned to visual editor.");
  }, [activeSourceMode, commitPrimarySourceToEditor, pushHelperMessage]);
  const insertArtworkEmbed = reactExports.useCallback((item) => {
    if (!editor || !item) return;
    editor.chain().focus().insertContent({
      type: "artworkEmbed",
      attrs: {
        title: item.title || "Embedded artwork",
        url: item.url || "#",
        thumb: item.image || item.avatar || ""
      }
    }).run();
  }, [editor]);
  const runArtworkSearch = reactExports.useCallback(async () => {
    if (typeof searchEntities !== "function") {
      return;
    }
    setArtworkLoading(true);
    try {
      const items = await searchEntities("artwork", artworkQuery);
      setArtworkResults(Array.isArray(items) ? items : []);
    } finally {
      setArtworkLoading(false);
    }
  }, [artworkQuery, searchEntities]);
  reactExports.useEffect(() => {
    if (!artworkPickerOpen || typeof searchEntities !== "function") {
      return;
    }
    runArtworkSearch();
  }, [artworkPickerOpen, runArtworkSearch, searchEntities]);
  const handleInsertArtwork = reactExports.useCallback(() => {
    if (!editor) return;
    if (typeof searchEntities === "function") {
      setArtworkPickerOpen(true);
      return;
    }
    const url = normalizeHttpUrl(window.prompt("Artwork URL", "https://skinbase.org/art/") || "");
    if (!url) {
      pushHelperMessage("Artwork URL is required.");
      return;
    }
    const title = window.prompt("Artwork title", "Embedded artwork");
    if (title === null) return;
    const thumb = normalizeHttpUrl(window.prompt("Artwork thumbnail URL (optional)", "") || "") || "";
    insertArtworkEmbed({
      title: title || "Embedded artwork",
      url,
      image: thumb
    });
  }, [editor, insertArtworkEmbed, pushHelperMessage, searchEntities]);
  const handleInsertImage = reactExports.useCallback(() => {
    setMediaDialogOpen(true);
    setMediaError("");
  }, []);
  const handleInsertTable = reactExports.useCallback(() => {
    setTableInsertOpen(true);
  }, []);
  const handleTableInsert = reactExports.useCallback(() => {
    if (!editor) return;
    editor.chain().focus().insertTable({
      rows: Math.max(1, tableRows),
      cols: Math.max(1, tableCols),
      withHeaderRow: tableHeaderRow,
      withHeaderColumn: tableHeaderColumn
    }).run();
    setTableInsertOpen(false);
  }, [editor, tableCols, tableHeaderColumn, tableHeaderRow, tableRows]);
  const handleMediaDialogClose = reactExports.useCallback(() => {
    const uploadedPath = mediaUploadedPath;
    setMediaDialogOpen(false);
    resetMediaState();
    if (uploadedPath) {
      void deleteTemporaryMedia(uploadedPath).catch(() => {
      });
    }
  }, [deleteTemporaryMedia, mediaUploadedPath, resetMediaState]);
  const handleMediaInsert = reactExports.useCallback(() => {
    const normalizedUrl = normalizeHttpUrl(mediaUrlValue) || mediaUrlValue.trim();
    if (!normalizedUrl) {
      setMediaError("Choose or upload an image first.");
      return;
    }
    if (!insertImageIntoEditor(normalizedUrl, mediaAltText.trim())) {
      setMediaError("Editor is not ready yet.");
      return;
    }
    setMediaDialogOpen(false);
    resetMediaState();
    pushHelperMessage("Image inserted.");
  }, [insertImageIntoEditor, mediaAltText, mediaUrlValue, pushHelperMessage, resetMediaState]);
  const handleMediaPickFile = reactExports.useCallback(async (file) => {
    if (!file) return;
    try {
      const payload = await uploadMediaFile(file, mediaUploadedPath);
      if (!payload?.url) {
        throw new Error("Image upload failed.");
      }
      setMediaUploadedPath(payload?.path || "");
      setMediaPreviewUrl(payload?.url || "");
      setMediaUrlValue(payload?.url || "");
      setMediaError("");
    } catch (uploadError) {
      setMediaError(uploadError?.message || "Image upload failed.");
    }
  }, [mediaUploadedPath, uploadMediaFile]);
  const handleMediaClear = reactExports.useCallback(() => {
    const uploadedPath = mediaUploadedPath;
    resetMediaState();
    if (uploadedPath) {
      void deleteTemporaryMedia(uploadedPath).catch((deleteError) => {
        setMediaError(deleteError?.message || "Could not remove uploaded media.");
      });
    }
  }, [deleteTemporaryMedia, mediaUploadedPath, resetMediaState]);
  const handleInsertComparison = reactExports.useCallback(() => {
    setCompareDialogOpen(true);
    setCompareError("");
  }, []);
  const resetCompareState = reactExports.useCallback(() => {
    setCompareUploading(false);
    setCompareError("");
    setCompareSubtitle("");
    setCompareLeftImage({ previewUrl: "", altText: "", uploadedPath: "" });
    setCompareRightImage({ previewUrl: "", altText: "", uploadedPath: "" });
  }, []);
  const handleComparisonDialogClose = reactExports.useCallback(() => {
    const uploadedPaths = [compareLeftImage.uploadedPath, compareRightImage.uploadedPath].filter(Boolean);
    setCompareDialogOpen(false);
    resetCompareState();
    uploadedPaths.forEach((path) => {
      void deleteTemporaryMedia(path).catch(() => {
      });
    });
  }, [compareLeftImage.uploadedPath, compareRightImage.uploadedPath, deleteTemporaryMedia, resetCompareState]);
  const handleComparisonSidePick = reactExports.useCallback(async (side, file) => {
    if (!file) return;
    if (!mediaSupport?.uploadUrl) {
      setCompareError("Image uploads are not configured for this editor.");
      return;
    }
    const currentImage = side === "left" ? compareLeftImage : compareRightImage;
    try {
      setCompareUploading(true);
      setCompareError("");
      const payload = await uploadMediaFile(file, currentImage.uploadedPath);
      if (!payload?.url) {
        throw new Error("Image upload failed.");
      }
      const nextImage = {
        previewUrl: payload.url || "",
        altText: currentImage.altText || file.name?.replace(/\.[^.]+$/, "") || "",
        uploadedPath: payload.path || ""
      };
      if (side === "left") {
        setCompareLeftImage(nextImage);
      } else {
        setCompareRightImage(nextImage);
      }
    } catch (uploadError) {
      setCompareError(uploadError?.message || "Image upload failed.");
    } finally {
      setCompareUploading(false);
    }
  }, [compareLeftImage, compareRightImage, mediaSupport, uploadMediaFile]);
  const handleComparisonSideClear = reactExports.useCallback((side) => {
    const currentImage = side === "left" ? compareLeftImage : compareRightImage;
    if (currentImage.uploadedPath) {
      void deleteTemporaryMedia(currentImage.uploadedPath).catch(() => {
      });
    }
    const nextImage = { previewUrl: "", altText: "", uploadedPath: "" };
    if (side === "left") {
      setCompareLeftImage(nextImage);
    } else {
      setCompareRightImage(nextImage);
    }
  }, [compareLeftImage, compareRightImage, deleteTemporaryMedia]);
  const handleComparisonInsert = reactExports.useCallback(() => {
    if (!editor) return;
    if (!compareLeftImage.previewUrl || !compareRightImage.previewUrl) {
      setCompareError("Upload both images before inserting the comparison.");
      return;
    }
    editor.chain().focus().insertContent({
      type: "imageCompare",
      attrs: {
        leftSrc: compareLeftImage.previewUrl,
        leftAlt: compareLeftImage.altText.trim(),
        rightSrc: compareRightImage.previewUrl,
        rightAlt: compareRightImage.altText.trim(),
        subtitle: compareSubtitle.trim()
      }
    }).run();
    setCompareDialogOpen(false);
    resetCompareState();
    pushHelperMessage("Comparison inserted.");
  }, [compareLeftImage, compareRightImage, compareSubtitle, editor, pushHelperMessage, resetCompareState]);
  const handleInsertSocialEmbed = reactExports.useCallback(() => {
    if (!editor) return;
    const detected = detectSocialPlatform(window.prompt("Social post URL", "https://") || "");
    if (!detected.url) {
      pushHelperMessage("Social post URL is required.");
      return;
    }
    const label = window.prompt("Label (optional)", detected.label);
    if (label === null) return;
    editor.chain().focus().insertContent({
      type: "socialEmbed",
      attrs: {
        url: detected.url,
        platform: detected.platform,
        label: label || detected.label
      }
    }).run();
  }, [editor, pushHelperMessage]);
  const handleInsertVideoEmbed = reactExports.useCallback(() => {
    if (!editor) return;
    const rawUrl = window.prompt("YouTube URL", "https://www.youtube.com/watch?v=") || "";
    const embedUrl = normalizeVideoEmbedUrl(rawUrl);
    const sourceUrl = normalizeHttpUrl(rawUrl);
    if (!embedUrl || !sourceUrl) {
      pushHelperMessage("A valid YouTube URL is required.");
      return;
    }
    const title = window.prompt("Video title (optional)", "Embedded YouTube video");
    if (title === null) return;
    editor.chain().focus().insertContent({
      type: "videoEmbed",
      attrs: {
        src: embedUrl,
        url: sourceUrl,
        title: title.trim() || "Embedded video"
      }
    }).run();
  }, [editor, pushHelperMessage]);
  const handleInsertHashtag = reactExports.useCallback(() => {
    if (!editor) return;
    const value = String(window.prompt("Hashtag", "release") || "").trim().replace(/^#+/, "").replace(/\s+/g, "-");
    if (!value) return;
    editor.chain().focus().insertContent(`#${value}`).run();
  }, [editor]);
  const shellClassName = fullHeightMode ? "fixed inset-0 z-[980] flex min-h-0 w-screen flex-col bg-[#04070df2] p-3 backdrop-blur-sm md:p-4" : "flex w-full min-w-0 flex-col gap-1.5";
  const bodyClassName = fullHeightMode ? "flex min-h-0 w-full flex-1 flex-col gap-1.5" : "flex w-full min-w-0 flex-col gap-1.5";
  const editorCardClassName = [
    "news-rich-text-editor w-full min-w-0 overflow-hidden rounded-xl border bg-white/[0.04] transition-colors",
    fullHeightMode ? "flex min-h-0 flex-1 flex-col rounded-2xl" : "",
    error ? "border-red-500/60 focus-within:border-red-500/70 focus-within:ring-2 focus-within:ring-red-500/30" : "border-white/12 hover:border-white/20 focus-within:border-sky-500/50 focus-within:ring-2 focus-within:ring-sky-500/20"
  ].filter(Boolean).join(" ");
  const editorViewportStyle = fullHeightMode ? { flex: 1 } : { height: `${editorViewportHeight}rem` };
  const sourceTextareaStyle = fullHeightMode ? { flex: 1 } : {
    height: `${Math.max(minHeight, editorViewportHeight)}rem`,
    minHeight: `${Math.max(minHeight, 20)}rem`
  };
  return /* @__PURE__ */ React.createElement("div", { className: shellClassName }, /* @__PURE__ */ React.createElement("div", { className: bodyClassName }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: editorCardClassName
    },
    /* @__PURE__ */ React.createElement(
      Toolbar$1,
      {
        editor,
        advancedNews,
        activeSourceMode,
        sourceModeLabel,
        sourceModeTitle,
        secondarySourceModeLabel,
        secondarySourceModeTitle,
        showStructureOutlines,
        showComparisonTool: Boolean(mediaSupport?.uploadUrl),
        fullHeightMode,
        onToggleSourceMode: handleToggleSourceMode,
        onToggleSecondarySourceMode: handleToggleSecondarySourceMode,
        onToggleStructureOutlines: () => setShowStructureOutlines((current) => !current),
        onInsertArtwork: handleInsertArtwork,
        onInsertImage: handleInsertImage,
        onInsertComparison: handleInsertComparison,
        onInsertTable: handleInsertTable,
        onInsertSocialEmbed: handleInsertSocialEmbed,
        onInsertVideoEmbed: handleInsertVideoEmbed,
        onInsertHashtag: handleInsertHashtag,
        editorViewportHeight,
        onIncreaseEditorViewportHeight: increaseEditorViewportHeight,
        onDecreaseEditorViewportHeight: decreaseEditorViewportHeight,
        onToggleFullHeightMode: toggleFullHeightMode
      }
    ),
    advancedNews && activeSourceMode ? /* @__PURE__ */ React.createElement("div", { className: [
      "border-t border-white/[0.04] bg-black/10 px-4 py-3",
      fullHeightMode ? "flex min-h-0 flex-1 flex-col" : ""
    ].filter(Boolean).join(" ") }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center justify-between gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, activeSourceMode === "secondary" ? secondarySourceModeDescription : sourceModeDescription), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleCloseSourceMode, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to visual")), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: activeSourceMode === "secondary" ? String(secondarySourceModeValue || "") : sourceValue,
        onChange: (event) => {
          const nextValue = event.target.value;
          if (activeSourceMode === "secondary") {
            onSecondarySourceModeValueChange?.(nextValue);
            return;
          }
          setSourceValue(nextValue);
          onChange?.(nextValue);
        },
        spellCheck: false,
        className: "nova-scrollbar w-full rounded-xl border border-white/10 bg-slate-950/85 px-4 py-3 font-mono text-sm leading-6 text-slate-100 outline-none",
        style: sourceTextareaStyle
      }
    )) : /* @__PURE__ */ React.createElement("div", { className: [
      "rich-text-editor-viewport nova-scrollbar w-full min-w-0 border-t border-white/[0.04] bg-black/15",
      fullHeightMode ? "flex min-h-0 flex-1 flex-col" : "",
      advancedNews && showStructureOutlines ? "news-editor-outline" : ""
    ].filter(Boolean).join(" "), style: editorViewportStyle }, /* @__PURE__ */ React.createElement(EditorContent, { editor })),
    !fullHeightMode ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        "aria-label": "Resize editor height",
        title: "Drag to resize editor height",
        onPointerDown: startViewportResize,
        className: "group flex h-5 w-full cursor-row-resize items-center justify-center border-t border-white/[0.04] bg-black/10 text-slate-500 transition hover:bg-white/[0.03] hover:text-slate-300"
      },
      /* @__PURE__ */ React.createElement("span", { className: "h-1 w-16 rounded-full bg-current opacity-70 transition group-hover:opacity-100" })
    ) : null
  ), advancedNews && helperMessage ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-sky-300" }, helperMessage) : null, !activeSourceMode ? /* @__PURE__ */ React.createElement(RichTableControls, { editor }) : null, error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error) : null, /* @__PURE__ */ React.createElement(
    ArtworkPickerDialog,
    {
      open: artworkPickerOpen,
      query: artworkQuery,
      items: artworkResults,
      loading: artworkLoading,
      onQueryChange: setArtworkQuery,
      onClose: () => setArtworkPickerOpen(false),
      onSearch: runArtworkSearch,
      onSelect: (item) => {
        insertArtworkEmbed(item);
        setArtworkPickerOpen(false);
        pushHelperMessage(`Embedded artwork: ${item.title || "Artwork"}.`);
      }
    }
  ), /* @__PURE__ */ React.createElement(
    MediaImageDialog,
    {
      open: mediaDialogOpen,
      uploading: mediaUploading,
      error: mediaError,
      previewUrl: mediaPreviewUrl || normalizeHttpUrl(mediaUrlValue) || mediaUrlValue,
      imageUrl: mediaUrlValue,
      altText: mediaAltText,
      uploadLabel: "Drop image here or browse",
      helperText: "Upload media directly to lesson storage or paste a CDN URL when you already have one.",
      allowUpload: Boolean(mediaSupport?.uploadUrl),
      onClose: handleMediaDialogClose,
      onImageUrlChange: (nextValue) => {
        setMediaUrlValue(nextValue);
        setMediaPreviewUrl(normalizeHttpUrl(nextValue) || nextValue);
        setMediaError("");
      },
      onAltTextChange: setMediaAltText,
      onPickFile: handleMediaPickFile,
      onBrowseAssets: mediaSupport?.assetsUrl ? () => openAcademyAssets({ type: "media" }) : null,
      onInsert: handleMediaInsert,
      onClearUploaded: handleMediaClear
    }
  ), /* @__PURE__ */ React.createElement(
    CompareImageDialog,
    {
      open: compareDialogOpen,
      uploading: compareUploading,
      error: compareError,
      subtitle: compareSubtitle,
      leftImage: compareLeftImage,
      rightImage: compareRightImage,
      allowUpload: Boolean(mediaSupport?.uploadUrl),
      onClose: handleComparisonDialogClose,
      onSubtitleChange: setCompareSubtitle,
      onLeftAltTextChange: (nextValue) => setCompareLeftImage((current) => ({ ...current, altText: nextValue })),
      onRightAltTextChange: (nextValue) => setCompareRightImage((current) => ({ ...current, altText: nextValue })),
      onLeftPickFile: (file) => handleComparisonSidePick("left", file),
      onRightPickFile: (file) => handleComparisonSidePick("right", file),
      onLeftBrowseAssets: mediaSupport?.assetsUrl ? () => openAcademyAssets({ type: "compare-left" }) : null,
      onRightBrowseAssets: mediaSupport?.assetsUrl ? () => openAcademyAssets({ type: "compare-right" }) : null,
      onLeftClear: () => handleComparisonSideClear("left"),
      onRightClear: () => handleComparisonSideClear("right"),
      onInsert: handleComparisonInsert
    }
  ), /* @__PURE__ */ React.createElement(
    AssetPickerDialog,
    {
      open: academyAssetsOpen,
      searchQuery: academyAssetsQuery,
      assets: academyAssets,
      loading: academyAssetsLoading,
      error: academyAssetsError,
      pagination: academyAssetsPagination,
      onClose: closeAcademyAssets,
      onRefresh: () => loadAcademyAssets({ page: academyAssetsPage, query: academyAssetsSearch }),
      onSearchQueryChange: setAcademyAssetsQuery,
      onSearch: submitAcademyAssetSearch,
      onPreviousPage: goToPreviousAcademyAssetsPage,
      onNextPage: goToNextAcademyAssetsPage,
      onSelect: chooseAcademyAsset
    }
  ), /* @__PURE__ */ React.createElement(
    TableInsertDialog,
    {
      open: tableInsertOpen,
      rows: tableRows,
      cols: tableCols,
      withHeaderRow: tableHeaderRow,
      withHeaderColumn: tableHeaderColumn,
      onRowsChange: setTableRows,
      onColsChange: setTableCols,
      onHeaderRowChange: setTableHeaderRow,
      onHeaderColumnChange: setTableHeaderColumn,
      onClose: () => setTableInsertOpen(false),
      onInsert: handleTableInsert
    }
  )));
}
const COURSE_EDITOR_TABS = [
  {
    id: "overview",
    label: "Overview",
    description: "Title, slug, positioning, and the short summary shown on course cards.",
    icon: "fa-compass-drafting",
    sections: ["course-identity"]
  },
  {
    id: "content",
    label: "Content",
    description: "Use the richer WYSIWYG surface for the main course description and learning pitch.",
    icon: "fa-pen-nib",
    sections: ["course-description"]
  },
  {
    id: "media",
    label: "Media",
    description: "Upload and tune the cover and teaser visuals used across the public course surfaces.",
    icon: "fa-images",
    sections: ["course-media"]
  },
  {
    id: "lessons",
    label: "Lessons",
    description: "Build the lesson sequence, drag to reorder, and add or remove lessons without opening the full builder.",
    icon: "fa-list-ol",
    sections: ["course-lessons-manager"]
  },
  {
    id: "publish",
    label: "Publish",
    description: "Control access, status, ordering, scheduling, and featured placement.",
    icon: "fa-rocket-launch",
    sections: ["course-publishing", "course-seo"]
  },
  {
    id: "preview",
    label: "Preview",
    description: "Scan the public-facing course card, media, and rendered long description before publishing.",
    icon: "fa-eye",
    sections: ["course-preview"]
  }
];
const COURSE_FIELD_TAB_MAP = {
  title: "overview",
  slug: "overview",
  subtitle: "overview",
  excerpt: "overview",
  description: "content",
  cover_image: "media",
  teaser_image: "media",
  access_level: "publish",
  difficulty: "publish",
  status: "publish",
  order_num: "publish",
  estimated_minutes: "publish",
  published_at: "publish",
  is_featured: "publish",
  seo_title: "publish",
  seo_description: "publish",
  meta_keywords: "publish",
  og_title: "publish",
  og_description: "publish",
  og_image: "publish"
};
function getField$2(fields, name2) {
  return fields.find((field) => field.name === name2) || null;
}
function FieldError$3({ message }) {
  if (!message) return null;
  return /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, message);
}
function SectionCard$6({ id, eyebrow, title, description, actions, children, tone = "default", className = "", contentClassName = "" }) {
  const toneClass = tone === "feature" ? "bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] shadow-[0_24px_70px_rgba(2,6,23,0.28)]" : "bg-white/[0.03]";
  return /* @__PURE__ */ React.createElement("section", { id, className: `min-w-0 scroll-mt-24 rounded-[28px] border border-white/10 p-5 ${toneClass} ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/75" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, description) : null), actions ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, actions) : null), /* @__PURE__ */ React.createElement("div", { className: `mt-5 ${contentClassName}`.trim() }, children));
}
function EditorWorkspaceTabs$1({ tabs, activeTab, onChange, errorCounts }) {
  const activeMeta = tabs.find((tab2) => tab2.id === activeTab) || tabs[0];
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-4 z-20 rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(7,11,18,0.92),rgba(5,8,14,0.88))] px-3 py-3 shadow-[0_18px_50px_rgba(2,6,23,0.18)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2", role: "tablist", "aria-label": "Course editor sections" }, tabs.map((tab2) => {
    const isActive = tab2.id === activeTab;
    const errorCount = Number(errorCounts?.[tab2.id] || 0);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.id,
        type: "button",
        role: "tab",
        "aria-selected": isActive,
        "aria-controls": `course-editor-panel-${tab2.id}`,
        id: `course-editor-tab-${tab2.id}`,
        onClick: () => onChange(tab2.id),
        className: [
          "inline-flex items-center gap-2 rounded-2xl border px-4 py-2.5 text-sm font-semibold transition",
          isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-white/80 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} text-xs` }),
      /* @__PURE__ */ React.createElement("span", null, tab2.label),
      errorCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-rose-100" }, errorCount) : null
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center justify-between gap-3 px-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-400" }, activeMeta.description), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, activeMeta.sections.map((section) => /* @__PURE__ */ React.createElement("span", { key: section, className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, section.replace("course-", "").replace(/-/g, " "))))));
}
function TextField$3({ label, value, onChange, error, hint, ...rest }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("input", { value: value ?? "", onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", ...rest }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$3, { message: error }));
}
function TextAreaField$2({ label, value, onChange, error, rows = 4, hint }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("textarea", { value: value ?? "", onChange, rows, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$3, { message: error }));
}
function CheckboxCardField({ label, checked, onChange, description, error }) {
  return /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer items-start gap-4 rounded-[28px] border px-5 py-4 transition ${checked ? "border-[#f39a24]/35 bg-[#f39a24]/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "sr-only" }), /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border text-sm transition ${checked ? "border-[#f39a24] bg-[#f39a24] text-white" : "border-white/10 bg-[#151a29] text-transparent"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check" })), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block text-lg font-semibold tracking-[-0.02em] text-white" }, label), description ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-sm leading-6 text-slate-300" }, description) : null, /* @__PURE__ */ React.createElement(FieldError$3, { message: error })));
}
function OutlineSectionPill({ section }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-semibold text-white" }, section.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, section.is_visible ? "Visible section" : "Hidden section")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold text-slate-200" }, section.lesson_count)));
}
function slugifyCourseTitle(value) {
  return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 180);
}
function formatLessonStep(orderNum) {
  const numeric = Number(orderNum);
  if (!Number.isFinite(numeric) || numeric < 0) return null;
  return `Step ${String(numeric + 1).padStart(2, "0")}`;
}
function lessonActivityBadgeMeta(lesson) {
  const isActive = Boolean(lesson?.active);
  return {
    label: isActive ? "Active" : "Inactive",
    className: isActive ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border-amber-300/20 bg-amber-300/10 text-amber-200"
  };
}
function lessonPublicationBadgeMeta(lesson) {
  const state = String(lesson?.publication_state || "draft");
  const label = String(lesson?.publication_label || (state === "published" ? "Published" : state === "scheduled" ? "Scheduled" : "Unscheduled"));
  if (state === "published") {
    return {
      label,
      className: "border-sky-300/20 bg-sky-300/10 text-sky-100"
    };
  }
  if (state === "scheduled") {
    return {
      label,
      className: "border-fuchsia-300/20 bg-fuchsia-300/10 text-fuchsia-100"
    };
  }
  return {
    label,
    className: "border-white/10 bg-white/[0.04] text-slate-400"
  };
}
function CourseSectionCreateCard({ storeUrl, nextOrderNum }) {
  const form = G$1({
    title: "",
    slug: "",
    description: "",
    order_num: nextOrderNum,
    is_visible: true
  });
  reactExports.useEffect(() => {
    form.setData("order_num", nextOrderNum);
  }, [nextOrderNum]);
  const createSection = () => {
    if (!storeUrl) return;
    form.post(storeUrl, {
      preserveScroll: true,
      onSuccess: () => {
        form.setData({
          title: "",
          slug: "",
          description: "",
          order_num: nextOrderNum,
          is_visible: true
        });
      }
    });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "New section"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Create a new course section here, then assign lessons into it below.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, "Order ", Number(nextOrderNum || 0) + 1)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Section 1 - Foundations", className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.title })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.data.slug, onChange: (event) => form.setData("slug", event.target.value), placeholder: "section-1-foundations", className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.slug })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200 lg:col-span-2" }, /* @__PURE__ */ React.createElement("span", null, "Description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), rows: 3, placeholder: "What this section covers and why it matters.", className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.description })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Order"), /* @__PURE__ */ React.createElement("input", { type: "number", min: "0", value: form.data.order_num, onChange: (event) => form.setData("order_num", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.order_num })), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(form.data.is_visible), onChange: (event) => form.setData("is_visible", event.target.checked), className: "h-4 w-4 rounded border-white/20 bg-slate-950 text-sky-300" }), /* @__PURE__ */ React.createElement("span", null, "Visible on the public course outline"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: createSection, disabled: form.processing || !String(form.data.title || "").trim(), className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-40" }, form.processing ? "Creating…" : "Create section")));
}
function CourseSectionCard({ section }) {
  const form = G$1({
    title: section.title || "",
    slug: section.slug || "",
    description: section.description || "",
    order_num: section.order_num || 0,
    is_visible: Boolean(section.is_visible)
  });
  reactExports.useEffect(() => {
    form.setData({
      title: section.title || "",
      slug: section.slug || "",
      description: section.description || "",
      order_num: section.order_num || 0,
      is_visible: Boolean(section.is_visible)
    });
  }, [section.description, section.is_visible, section.order_num, section.slug, section.title]);
  const saveSection = () => {
    if (!section.update_url) return;
    form.patch(section.update_url, { preserveScroll: true });
  };
  const deleteSection = () => {
    if (!section.destroy_url) return;
    if (!window.confirm(`Delete section "${section.title}"? Lessons assigned to it will become unsectioned.`)) return;
    At.delete(section.destroy_url, { preserveScroll: true });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.title })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.data.slug, onChange: (event) => form.setData("slug", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.slug })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200 lg:col-span-2" }, /* @__PURE__ */ React.createElement("span", null, "Description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), rows: 3, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.description })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Order"), /* @__PURE__ */ React.createElement("input", { type: "number", min: "0", value: form.data.order_num, onChange: (event) => form.setData("order_num", event.target.value), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.order_num })), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(form.data.is_visible), onChange: (event) => form.setData("is_visible", event.target.checked), className: "h-4 w-4 rounded border-white/20 bg-slate-950 text-sky-300" }), /* @__PURE__ */ React.createElement("span", null, "Visible on the public course outline"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveSection, disabled: form.processing || !String(form.data.title || "").trim(), className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-40" }, form.processing ? "Saving…" : "Save section"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteSection, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Delete")));
}
function normalizeLessonManagerLessons(lessons) {
  return (Array.isArray(lessons) ? [...lessons] : []).sort((a, b2) => {
    const diff = Number(a?.order_num || 0) - Number(b2?.order_num || 0);
    return diff !== 0 ? diff : Number(a?.id || 0) - Number(b2?.id || 0);
  }).map((lesson, index2) => ({ ...lesson, order_num: index2, display_order: index2 + 1 }));
}
function reorderLessonManagerLessons(lessons, draggedId, targetId) {
  const current = normalizeLessonManagerLessons(lessons);
  const di = current.findIndex((l3) => Number(l3.id) === Number(draggedId));
  const ti = current.findIndex((l3) => Number(l3.id) === Number(targetId));
  if (di === -1 || ti === -1 || di === ti) return current;
  const next = [...current];
  const [moved] = next.splice(di, 1);
  next.splice(ti, 0, moved);
  return normalizeLessonManagerLessons(next);
}
function moveLessonManagerLesson(lessons, lessonId, direction) {
  const current = normalizeLessonManagerLessons(lessons);
  const idx = current.findIndex((l3) => Number(l3.id) === Number(lessonId));
  const nextIdx = idx + direction;
  if (idx === -1 || nextIdx < 0 || nextIdx >= current.length) return current;
  const next = [...current];
  const [moved] = next.splice(idx, 1);
  next.splice(nextIdx, 0, moved);
  return normalizeLessonManagerLessons(next);
}
function lessonManagerSignature(lessons) {
  return JSON.stringify(normalizeLessonManagerLessons(lessons).map((l3) => ({
    id: Number(l3.id),
    order_num: Number(l3.order_num || 0),
    section_id: l3.section_id == null ? null : Number(l3.section_id)
  })));
}
function stripHtml$5(value) {
  return String(value || "").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
}
function countWords$1(value) {
  const text2 = stripHtml$5(value);
  return text2 ? text2.split(/\s+/).length : 0;
}
function normalizeAssetPreview(value, cdnBaseUrl) {
  const trimmed = String(value || "").trim();
  if (!trimmed) return "";
  if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) return trimmed;
  return `${String(cdnBaseUrl || "").replace(/\/$/, "")}/${trimmed.replace(/^\//, "")}`;
}
function firstCourseErrorTab(errors) {
  const firstKey = Object.keys(errors || {})[0];
  if (!firstKey) return null;
  return COURSE_FIELD_TAB_MAP[firstKey] || null;
}
function courseTabErrorCounts(errors) {
  const counts = {};
  Object.keys(errors || {}).forEach((key) => {
    const tabId = COURSE_FIELD_TAB_MAP[key];
    if (!tabId) return;
    counts[tabId] = Number(counts[tabId] || 0) + 1;
  });
  return counts;
}
function firstErrorMessage$3(errors, fallback = "Please correct the highlighted fields and try again.") {
  const queue = [errors];
  while (queue.length > 0) {
    const current = queue.shift();
    if (typeof current === "string") {
      const message = current.trim();
      if (message) {
        return message;
      }
      continue;
    }
    if (Array.isArray(current)) {
      queue.push(...current);
      continue;
    }
    if (current && typeof current === "object") {
      queue.push(...Object.values(current));
    }
  }
  return fallback;
}
function normalizeImportBoolean(value, fallback = false) {
  if (typeof value === "boolean") return value;
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (["true", "1", "yes", "y"].includes(normalized)) return true;
    if (["false", "0", "no", "n"].includes(normalized)) return false;
  }
  if (typeof value === "number") {
    if (value === 1) return true;
    if (value === 0) return false;
  }
  return fallback;
}
function normalizeImportTags(value) {
  if (Array.isArray(value)) {
    return value.map((tag) => String(tag || "").trim()).filter(Boolean);
  }
  if (typeof value === "string") {
    return value.split(/[\n,]/).map((tag) => tag.trim()).filter(Boolean);
  }
  return [];
}
function normalizeImportedDateTime$1(value) {
  const raw = String(value || "").trim();
  if (!raw) return "";
  const dateTimeMatch = raw.match(/^(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2})(?::\d{2})?)?$/);
  if (dateTimeMatch) {
    return dateTimeMatch[2] ? `${dateTimeMatch[1]}T${dateTimeMatch[2]}` : dateTimeMatch[1];
  }
  const parsed = new Date(raw);
  if (Number.isNaN(parsed.getTime())) {
    return raw;
  }
  const pad2 = (input) => String(input).padStart(2, "0");
  return `${parsed.getFullYear()}-${pad2(parsed.getMonth() + 1)}-${pad2(parsed.getDate())}T${pad2(parsed.getHours())}:${pad2(parsed.getMinutes())}`;
}
function buildCourseJsonImportPrompt(courseTitle) {
  return [
    "Create valid JSON only for a Skinbase Academy course import.",
    "Do not wrap the answer in markdown fences or extra explanation.",
    "Return a single object with course fields as keys.",
    "Use strings for text values, booleans for featured flags, and YYYY-MM-DDTHH:mm for published_at when present.",
    "Allowed keys: title, slug, subtitle, excerpt, description, cover_image, teaser_image, access_level, difficulty, status, order_num, estimated_minutes, published_at, seo_title, seo_description, meta_keywords, og_title, og_description, og_image, is_featured.",
    "meta_keywords may be an array of strings or a comma-separated string.",
    "Omit unknown keys.",
    "Example shape:",
    "{",
    '  "title": "Course title",',
    '  "slug": "course-title",',
    '  "subtitle": "Short positioning line",',
    '  "excerpt": "Short summary for cards.",',
    '  "description": "Long form course description.",',
    '  "access_level": "free",',
    '  "difficulty": "beginner",',
    '  "status": "draft",',
    '  "is_featured": false',
    "}",
    `Course title context: ${String(courseTitle || "Untitled academy course")}`
  ].join("\n");
}
function parseCourseJsonImport(rawText) {
  let parsed;
  try {
    parsed = JSON.parse(String(rawText || ""));
  } catch {
    throw new Error("Could not parse JSON.");
  }
  const root2 = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed.course && typeof parsed.course === "object" && !Array.isArray(parsed.course) ? parsed.course : parsed.data && typeof parsed.data === "object" && !Array.isArray(parsed.data) ? parsed.data : parsed.record && typeof parsed.record === "object" && !Array.isArray(parsed.record) ? parsed.record : parsed : null;
  if (!root2 || typeof root2 !== "object" || Array.isArray(root2)) {
    throw new Error("Import JSON must be an object.");
  }
  const next = {};
  const applyString = (targetKey, sourceKeys = [targetKey]) => {
    const keys2 = Array.isArray(sourceKeys) ? sourceKeys : [sourceKeys];
    for (const key of keys2) {
      if (root2[key] == null) continue;
      const value = String(root2[key]).trim();
      if (!value) continue;
      next[targetKey] = value;
      return;
    }
  };
  const applyNumber = (targetKey, sourceKeys = [targetKey]) => {
    const keys2 = Array.isArray(sourceKeys) ? sourceKeys : [sourceKeys];
    for (const key of keys2) {
      if (root2[key] == null || String(root2[key]).trim() === "") continue;
      const value = Number(root2[key]);
      if (!Number.isFinite(value)) continue;
      next[targetKey] = value;
      return;
    }
  };
  const applyBoolean = (targetKey, sourceKeys = [targetKey]) => {
    const keys2 = Array.isArray(sourceKeys) ? sourceKeys : [sourceKeys];
    for (const key of keys2) {
      if (root2[key] == null) continue;
      next[targetKey] = normalizeImportBoolean(root2[key], false);
      return;
    }
  };
  applyString("title");
  applyString("slug");
  applyString("subtitle");
  applyString("excerpt");
  applyString("description");
  applyString("cover_image", ["cover_image", "cover_image_url", "hero_image", "hero_image_url"]);
  applyString("teaser_image", ["teaser_image", "teaser_image_url"]);
  applyString("access_level");
  applyString("difficulty");
  applyString("status");
  applyNumber("order_num");
  applyNumber("estimated_minutes");
  applyString("published_at");
  applyString("seo_title");
  applyString("seo_description");
  applyString("og_title");
  applyString("og_description");
  applyString("og_image");
  applyBoolean("is_featured", ["is_featured", "featured"]);
  if (root2.meta_keywords != null) {
    next.meta_keywords = Array.isArray(root2.meta_keywords) ? root2.meta_keywords.map((keyword) => String(keyword || "").trim()).filter(Boolean).join(", ") : String(root2.meta_keywords).trim();
  }
  if (!next.slug && next.title) {
    next.slug = slugifyCourseTitle(next.title);
  }
  if (next.published_at) {
    next.published_at = normalizeImportedDateTime$1(next.published_at);
  }
  return next;
}
function buildCourseLessonImportPrompt(courseTitle, difficulty) {
  return [
    "Create valid JSON only for a Skinbase Academy course lesson import.",
    "Do not wrap the answer in markdown fences.",
    "Return an object with this shape:",
    "{",
    '  "defaults": {',
    `    "difficulty": "${String(difficulty)}",`,
    '    "access_level": "free",',
    '    "lesson_type": "article",',
    '    "active": false',
    "  },",
    '  "lessons": [',
    "    {",
    '      "order": 1,',
    '      "title": "Lesson title",',
    '      "slug": "lesson-title",',
    '      "goal": "One sentence learning goal for the lesson."',
    "    }",
    "  ]",
    "}",
    "Requirements:",
    "- One lesson object per TOC row.",
    "- Keep slugs lowercase and hyphenated.",
    "- Keep goal concise and outcome-focused.",
    "- Do not include body content or HTML. These should stay empty lesson shells.",
    "- If category is known, you may include category or category_slug.",
    `Course title: ${String(courseTitle || "Untitled academy course")}`
  ].join("\n");
}
function CourseJsonImportDialog({ open, value, error, exampleValue, promptValue, actionLabel = "Apply JSON", processing = false, onChange, onClose, onApply, onCopyExample, onCopyPrompt }) {
  const backdropRef = reactExports.useRef(null);
  const [activeReferenceTab, setActiveReferenceTab] = reactExports.useState("import");
  reactExports.useEffect(() => {
    if (open) {
      setActiveReferenceTab("import");
    }
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-start justify-center overflow-y-auto bg-[#04070dcc] px-4 py-4 backdrop-blur-md sm:items-center sm:px-6 sm:py-6",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { role: "dialog", "aria-modal": "true", "aria-labelledby": "course-json-import-title", className: "flex max-h-[calc(100vh-2rem)] w-full max-w-6xl flex-col overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)] sm:max-h-[calc(100vh-3rem)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Course JSON import"), /* @__PURE__ */ React.createElement("h3", { id: "course-json-import-title", className: "mt-2 text-lg font-semibold text-white" }, "Paste course import JSON"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-4xl text-sm leading-6 text-white/65" }, "Use this to seed the course form from AI output, editorial drafts, or migrated course data without opening each field manually.")), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 md:grid-cols-3" }, [
        { id: "import", label: "Import", description: "Paste course JSON and apply it to the form." },
        { id: "docs", label: "Documentation", description: "Field guide and import rules." },
        { id: "prompts", label: "Prompt library", description: "Copy prompts for ChatGPT." }
      ].map((tab2) => {
        const isActive = tab2.id === activeReferenceTab;
        return /* @__PURE__ */ React.createElement("button", { key: tab2.id, type: "button", onClick: () => setActiveReferenceTab(tab2.id), className: [
          "rounded-2xl border px-4 py-3 text-left transition",
          isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-slate-300 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
        ].join(" ") }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, tab2.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-current/70" }, tab2.description));
      }))), /* @__PURE__ */ React.createElement("div", { className: "min-h-0 flex-1 overflow-y-auto px-6 py-5" }, activeReferenceTab === "import" ? /* @__PURE__ */ React.createElement("div", { className: "grid min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
        "textarea",
        {
          value,
          onChange: (event) => onChange?.(event.target.value),
          rows: 18,
          placeholder: exampleValue,
          className: "w-full rounded-[24px] border border-white/10 bg-black/20 px-4 py-4 font-mono text-sm leading-6 text-white outline-none placeholder:text-white/30"
        }
      ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "grid content-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Example JSON"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCopyExample, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy example")), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 max-h-[360px] overflow-auto rounded-2xl border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-300 whitespace-pre-wrap" }, exampleValue)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recognized keys"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "title, slug, subtitle, excerpt, description"), /* @__PURE__ */ React.createElement("p", null, "cover_image, teaser_image"), /* @__PURE__ */ React.createElement("p", null, "access_level, difficulty, status"), /* @__PURE__ */ React.createElement("p", null, "order_num, estimated_minutes, published_at"), /* @__PURE__ */ React.createElement("p", null, "seo_title, seo_description"), /* @__PURE__ */ React.createElement("p", null, "meta_keywords"), /* @__PURE__ */ React.createElement("p", null, "og_title, og_description, og_image"), /* @__PURE__ */ React.createElement("p", null, "is_featured"))))) : null, activeReferenceTab === "docs" ? /* @__PURE__ */ React.createElement("div", { className: "grid min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Field guide"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "title"), " - public course name used on cards, headers, and metadata."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "slug"), " - URL slug. If omitted, it will be generated from the title."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "subtitle"), " - compact supporting line shown near the title."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "excerpt"), " - short summary for cards and compact previews."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "description"), " - longer editorial description or syllabus overview."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "cover_image"), " and ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "teaser_image"), " - stored paths or external URLs."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "access_level"), " - use ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "free"), ", ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "premium"), ", or ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "mixed"), "."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "difficulty"), " - use ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "beginner"), ", ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "intermediate"), ", or ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "advanced"), "."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "status"), " - use ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "draft"), ", ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "review"), ", ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "published"), ", or ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "archived"), "."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "published_at"), " - accepts ISO strings or ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "YYYY-MM-DDTHH:mm"), "."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "meta_keywords"), " - array or comma-separated string."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "is_featured"), " - JSON boolean."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Import rules"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Unknown keys are ignored, so broader AI output is safe to paste."), /* @__PURE__ */ React.createElement("p", null, "Use JSON booleans for ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "is_featured"), "."), /* @__PURE__ */ React.createElement("p", null, "Keep ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "order_num"), " and ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "estimated_minutes"), " numeric."), /* @__PURE__ */ React.createElement("p", null, "Use ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "published_at"), " only when you want a prefilled publish timestamp."), /* @__PURE__ */ React.createElement("p", null, "Separate title, summary, and metadata so the course form stays readable after import.")))) : null, activeReferenceTab === "prompts" ? /* @__PURE__ */ React.createElement("div", { className: "grid min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid min-w-0 gap-4" }, [
        {
          title: "Draft a course JSON object from a syllabus",
          prompt: `Create valid JSON only for a Skinbase Academy course import.

Return a single object with these keys when relevant: title, slug, subtitle, excerpt, description, cover_image, teaser_image, access_level, difficulty, status, order_num, estimated_minutes, published_at, seo_title, seo_description, meta_keywords, og_title, og_description, og_image, is_featured.

Rules:
- Do not use markdown fences or explanation text.
- Omit unknown keys.
- Use strings for text, booleans for featured flags, and YYYY-MM-DDTHH:mm for published_at.
- meta_keywords may be an array or comma-separated string.
- Keep the tone editorial, concise, and import-safe.`
        },
        {
          title: "Turn AI notes into course import JSON",
          prompt: `You are preparing JSON for a Skinbase Academy course form. Output JSON only.

Write a single object with clean course metadata. Use lowercase hyphenated slugs, concise excerpts, and production-ready SEO fields. If the source notes do not mention a field, omit it. Set is_featured to true only when the course should be highlighted.`
        }
      ].map((example) => /* @__PURE__ */ React.createElement("div", { key: example.title, className: "min-w-0 overflow-hidden rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-200/70" }, example.title), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onCopyPrompt?.(example.prompt, example.title), className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy prompt")), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 max-h-56 min-w-0 overflow-auto whitespace-pre-wrap break-words rounded-[18px] border border-white/10 bg-slate-950/80 p-4 text-sm leading-6 text-slate-200 [overflow-wrap:anywhere]" }, example.prompt)))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 self-start rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Prompt tips"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Ask the model to return JSON only, with no markdown or commentary."), /* @__PURE__ */ React.createElement("p", null, "Tell it to omit any field it cannot populate confidently."), /* @__PURE__ */ React.createElement("p", null, "Use ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "slug"), " only when you need a custom URL, otherwise let the form derive it from the title."), /* @__PURE__ */ React.createElement("p", null, "Keep ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "meta_keywords"), " short and focused on search intent.")))) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClose?.(), className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApply?.(), disabled: processing, className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-60" }, processing ? "Working..." : actionLabel)))
    ),
    document.body
  );
}
function parseCourseLessonImport(rawText, categoryOptions = []) {
  let parsed;
  try {
    parsed = JSON.parse(String(rawText || ""));
  } catch {
    throw new Error("Could not parse JSON.");
  }
  const root2 = Array.isArray(parsed) ? { lessons: parsed } : parsed;
  if (!root2 || typeof root2 !== "object" || Array.isArray(root2)) {
    throw new Error("Import JSON must be an array or an object with a lessons array.");
  }
  const lessonSource = Array.isArray(root2.lessons) ? root2.lessons : Array.isArray(root2.toc) ? root2.toc : Array.isArray(root2.items) ? root2.items : null;
  if (!Array.isArray(lessonSource) || lessonSource.length === 0) {
    throw new Error("Import JSON must contain a lessons array with at least one item.");
  }
  const categoryMatches = Array.isArray(categoryOptions) ? categoryOptions : [];
  const defaultsSource = root2.defaults && typeof root2.defaults === "object" && !Array.isArray(root2.defaults) ? root2.defaults : {};
  const defaults2 = {};
  if (defaultsSource.category_id != null) defaults2.category_id = Number(defaultsSource.category_id);
  if (defaultsSource.category_slug != null) defaults2.category_slug = String(defaultsSource.category_slug).trim();
  if (defaultsSource.category != null) defaults2.category = String(defaultsSource.category).trim();
  if (defaultsSource.difficulty != null) defaults2.difficulty = String(defaultsSource.difficulty).trim();
  if (defaultsSource.access_level != null) defaults2.access_level = String(defaultsSource.access_level).trim();
  if (defaultsSource.lesson_type != null) defaults2.lesson_type = String(defaultsSource.lesson_type).trim();
  if (defaultsSource.series_name != null) defaults2.series_name = String(defaultsSource.series_name).trim();
  if (defaultsSource.active != null) defaults2.active = normalizeImportBoolean(defaultsSource.active, false);
  const lessons = lessonSource.map((item, index2) => {
    const source = item && typeof item === "object" && !Array.isArray(item) ? item : { title: String(item || "") };
    const title = String(source.title ?? source.lesson_title ?? source.lesson ?? source.name ?? "").trim();
    if (!title) {
      return null;
    }
    const next = {
      title,
      slug: String(source.slug ?? "").trim(),
      goal: String(source.goal ?? source.objective ?? source.summary ?? source.description ?? "").trim(),
      excerpt: String(source.excerpt ?? "").trim(),
      difficulty: String(source.difficulty ?? "").trim(),
      access_level: String(source.access_level ?? source.access ?? "").trim(),
      lesson_type: String(source.lesson_type ?? source.type ?? "").trim(),
      series_name: String(source.series_name ?? "").trim(),
      tags: normalizeImportTags(source.tags),
      active: source.active == null ? void 0 : normalizeImportBoolean(source.active, false),
      _sortOrder: Number(source.order ?? source.lesson_number ?? source.position ?? index2 + 1)
    };
    const requestedCategory = String(source.category_id ?? source.category_slug ?? source.category ?? "").trim().toLowerCase();
    if (requestedCategory) {
      const match = categoryMatches.find((option) => [option.id, option.value, option.slug, option.name, option.label].filter((candidate) => candidate != null).map((candidate) => String(candidate).trim().toLowerCase()).includes(requestedCategory));
      if (match?.id != null) {
        next.category_id = Number(match.id);
      } else if (source.category_slug != null) {
        next.category_slug = String(source.category_slug).trim();
      } else if (source.category != null) {
        next.category = String(source.category).trim();
      }
    }
    return next;
  }).filter(Boolean).sort((a, b2) => a._sortOrder - b2._sortOrder).map(({ _sortOrder, ...lesson }) => lesson);
  if (lessons.length === 0) {
    throw new Error("The JSON did not contain any lesson rows with a title.");
  }
  return { defaults: defaults2, lessons };
}
function CourseLessonJsonImportDialog({ open, value, error, exampleValue, promptValue, onChange, onClose, onApply, onCopyExample, onCopyPrompt }) {
  const backdropRef = reactExports.useRef(null);
  const [activeReferenceTab, setActiveReferenceTab] = reactExports.useState("structure");
  reactExports.useEffect(() => {
    if (open) {
      setActiveReferenceTab("structure");
    }
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-start justify-center overflow-y-auto bg-[#04070dcc] px-4 py-4 backdrop-blur-md sm:items-center sm:px-6 sm:py-6",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex max-h-[calc(100vh-2rem)] w-full max-w-6xl flex-col overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)] sm:max-h-[calc(100vh-3rem)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Course TOC Import"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Paste lesson import JSON"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-4xl text-sm leading-6 text-white/65" }, "Paste a table-of-contents payload here and the editor will create empty lesson pages already attached to this course in the imported order.")), /* @__PURE__ */ React.createElement("div", { className: "min-h-0 flex-1 overflow-y-auto" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 px-6 py-5 xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
        "textarea",
        {
          value,
          onChange: (event) => onChange?.(event.target.value),
          rows: 16,
          placeholder: exampleValue,
          className: "min-h-[320px] rounded-[24px] border border-white/10 bg-slate-950/80 px-4 py-4 font-mono text-sm leading-6 text-slate-100 outline-none"
        }
      ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "grid content-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2", role: "tablist", "aria-label": "Import help panels" }, [
        { id: "structure", label: "Structure", icon: "fa-brackets-curly" },
        { id: "prompt", label: "Prompt", icon: "fa-wand-magic-sparkles" },
        { id: "applied", label: "Applied", icon: "fa-list-check" }
      ].map((tab2) => {
        const isActive = tab2.id === activeReferenceTab;
        return /* @__PURE__ */ React.createElement(
          "button",
          {
            key: tab2.id,
            type: "button",
            role: "tab",
            "aria-selected": isActive,
            onClick: () => setActiveReferenceTab(tab2.id),
            className: [
              "inline-flex items-center gap-2 rounded-2xl border px-3.5 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition",
              isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-slate-400 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
            ].join(" ")
          },
          /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} text-[10px]` }),
          /* @__PURE__ */ React.createElement("span", null, tab2.label)
        );
      })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-[20px] border border-white/10 bg-slate-950/50 p-4 text-sm text-slate-300" }, activeReferenceTab === "structure" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Accepted structure"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCopyExample, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy example")), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 max-h-[360px] overflow-auto rounded-2xl border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-300" }, exampleValue)) : null, activeReferenceTab === "prompt" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "ChatGPT helper prompt"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCopyPrompt, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy prompt")), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 max-h-[360px] overflow-auto rounded-2xl border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-300 whitespace-pre-wrap" }, promptValue)) : null, activeReferenceTab === "applied" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "What gets applied"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Each row creates a new Academy lesson record."), /* @__PURE__ */ React.createElement("p", null, "The lesson is attached to this course in the imported order."), /* @__PURE__ */ React.createElement("p", null, "Title, slug, goal/excerpt, category, difficulty, access, and lesson type can be imported."), /* @__PURE__ */ React.createElement("p", null, "Body content stays empty so the lesson can be written later."))) : null))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClose?.(), className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApply?.(), className: "inline-flex items-center gap-2 justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-file-import text-xs" }), /* @__PURE__ */ React.createElement("span", null, "Import lessons"))))
    ),
    document.body
  );
}
function renderMetaKeywords(value) {
  return String(value || "").split(/[\n,]/).map((item) => item.trim()).filter(Boolean).slice(0, 6);
}
function CourseEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext = {} }) {
  const form = G$1({
    ...record,
    description: String(record.description || ""),
    cover_image: String(record.cover_image || ""),
    teaser_image: String(record.teaser_image || "")
  });
  const slugTouchedRef = reactExports.useRef(Boolean(String(record.slug || "").trim()));
  const [activeTab, setActiveTab] = reactExports.useState("overview");
  const [coverPreviewUrl, setCoverPreviewUrl] = reactExports.useState(record.cover_image_url || normalizeAssetPreview(record.cover_image, editorContext.coverCdnBaseUrl));
  const [teaserPreviewUrl, setTeaserPreviewUrl] = reactExports.useState(record.teaser_image_url || normalizeAssetPreview(record.teaser_image, editorContext.coverCdnBaseUrl));
  const [stagedCoverPath, setStagedCoverPath] = reactExports.useState("");
  const [stagedTeaserPath, setStagedTeaserPath] = reactExports.useState("");
  const accessField = reactExports.useMemo(() => getField$2(fields, "access_level"), [fields]);
  const difficultyField = reactExports.useMemo(() => getField$2(fields, "difficulty"), [fields]);
  const statusField = reactExports.useMemo(() => getField$2(fields, "status"), [fields]);
  const wordCount = reactExports.useMemo(() => countWords$1(form.data.description), [form.data.description]);
  const excerptLength = String(form.data.excerpt || "").length;
  const tabErrorCounts = reactExports.useMemo(() => courseTabErrorCounts(form.errors), [form.errors]);
  const deferredDescription = reactExports.useDeferredValue(form.data.description || "");
  const visibleSections = reactExports.useMemo(() => new Set(COURSE_EDITOR_TABS.find((tab2) => tab2.id === activeTab)?.sections || []), [activeTab]);
  const activeTabMeta = reactExports.useMemo(() => COURSE_EDITOR_TABS.find((tab2) => tab2.id === activeTab) || COURSE_EDITOR_TABS[0], [activeTab]);
  const sectionClassName = (sectionId, className = "") => `${visibleSections.has(sectionId) ? "" : "hidden"} ${className}`.trim();
  const editorLinks = editorContext?.links || {};
  const outlineSummary = editorContext?.outlineSummary || null;
  const courseSectionsSource = reactExports.useMemo(() => Array.isArray(editorContext?.courseSections) ? editorContext.courseSections : [], [editorContext]);
  const coursePathPreview = form.data.slug ? `/academy/courses/${form.data.slug}` : "/academy/courses/course-slug";
  const metaKeywordItems = renderMetaKeywords(form.data.meta_keywords);
  const attachLessonUrl = editorContext?.attachLessonUrl || null;
  const importLessonsUrl = editorContext?.importLessonsUrl || null;
  const sectionStoreUrl = editorContext?.sectionStoreUrl || null;
  const reorderUrl = editorContext?.reorderUrl || null;
  const courseLessonsSource = reactExports.useMemo(() => Array.isArray(editorContext?.courseLessons) ? editorContext.courseLessons : [], [editorContext]);
  const availableLessons = reactExports.useMemo(() => Array.isArray(editorContext?.availableLessons) ? editorContext.availableLessons : [], [editorContext]);
  const lessonCategoryOptions = reactExports.useMemo(() => Array.isArray(editorContext?.lessonCategoryOptions) ? editorContext.lessonCategoryOptions : [], [editorContext]);
  const courseImportUrl = editorContext?.courseImportUrl || null;
  const [lessonManagerDraft, setLessonManagerDraft] = reactExports.useState(() => normalizeLessonManagerLessons(Array.isArray(editorContext?.courseLessons) ? editorContext.courseLessons : []));
  const [lessonDragActive, setLessonDragActive] = reactExports.useState(null);
  const [lessonSaveProcessing, setLessonSaveProcessing] = reactExports.useState(false);
  const [lessonSearch, setLessonSearch] = reactExports.useState("");
  const [jsonImportOpen, setJsonImportOpen] = reactExports.useState(false);
  const [jsonImportValue, setJsonImportValue] = reactExports.useState("");
  const [jsonImportError, setJsonImportError] = reactExports.useState("");
  const [courseJsonImportOpen, setCourseJsonImportOpen] = reactExports.useState(false);
  const [courseJsonImportValue, setCourseJsonImportValue] = reactExports.useState("");
  const [courseJsonImportError, setCourseJsonImportError] = reactExports.useState("");
  const [courseJsonImportProcessing, setCourseJsonImportProcessing] = reactExports.useState(false);
  const [toast, setToast] = reactExports.useState({ id: 0, visible: false, message: "", variant: "success" });
  const lessonManagerIsDirty = reactExports.useMemo(() => lessonManagerSignature(lessonManagerDraft) !== lessonManagerSignature(courseLessonsSource), [lessonManagerDraft, courseLessonsSource]);
  const importPromptValue = reactExports.useMemo(() => buildCourseLessonImportPrompt(form.data.title || title, form.data.difficulty || "beginner"), [form.data.difficulty, form.data.title, title]);
  const importExampleValue = reactExports.useMemo(() => JSON.stringify({
    defaults: {
      difficulty: String(form.data.difficulty || "beginner"),
      access_level: "free",
      lesson_type: "article",
      active: false
    },
    lessons: [
      {
        order: 1,
        title: "What Makes a Great Wallpaper Prompt?",
        slug: "what-makes-a-great-wallpaper-prompt",
        goal: "Explain what separates random AI images from clean, usable wallpapers."
      },
      {
        order: 2,
        title: "The Anatomy of a Strong AI Art Prompt",
        slug: "the-anatomy-of-a-strong-ai-art-prompt",
        goal: "Teach the core prompt structure: subject, scene, style, lighting, composition, quality, and restrictions."
      }
    ]
  }, null, 2), [form.data.difficulty]);
  const courseImportPromptValue = reactExports.useMemo(() => buildCourseJsonImportPrompt(form.data.title || title), [form.data.title, title]);
  const courseImportExampleValue = reactExports.useMemo(() => JSON.stringify({
    title: form.data.title || "Editorial course title",
    slug: slugifyCourseTitle(form.data.title || "Editorial course title"),
    subtitle: "Short positioning line for the course.",
    excerpt: "One or two sentences that summarize the course.",
    description: "Long form course description, syllabus overview, or editorial pitch.",
    cover_image: "https://files.skinbase.org/path/to/course-cover.webp",
    teaser_image: "https://files.skinbase.org/path/to/course-teaser.webp",
    access_level: String(form.data.access_level || "free"),
    difficulty: String(form.data.difficulty || "beginner"),
    status: String(form.data.status || "draft"),
    order_num: Number(form.data.order_num || 0),
    estimated_minutes: Number(form.data.estimated_minutes || 45),
    published_at: "2026-05-17T10:00",
    seo_title: "Editorial course SEO title",
    seo_description: "Editorial course SEO description for search and social previews.",
    meta_keywords: ["academy course", "editorial workflow", "learning path"],
    og_title: "OpenGraph title",
    og_description: "OpenGraph description",
    og_image: "https://files.skinbase.org/path/to/course-og.webp",
    is_featured: Boolean(form.data.is_featured)
  }, null, 2), [form.data.access_level, form.data.difficulty, form.data.estimated_minutes, form.data.is_featured, form.data.order_num, form.data.status, form.data.title, title]);
  const showToast = (message, variant = "error") => {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant
    });
  };
  const filteredAvailableLessons = reactExports.useMemo(() => {
    const q2 = lessonSearch.trim().toLowerCase();
    const unattached = availableLessons.filter((l3) => !l3.attached);
    if (!q2) return unattached;
    return unattached.filter((l3) => l3.title.toLowerCase().includes(q2) || l3.category.toLowerCase().includes(q2));
  }, [availableLessons, lessonSearch]);
  const sectionOptions = reactExports.useMemo(() => [{ value: "", label: "No section" }, ...courseSectionsSource.map((section) => ({ value: String(section.id), label: section.title }))], [courseSectionsSource]);
  const nextSectionOrderNum = reactExports.useMemo(() => courseSectionsSource.reduce((maxOrder, section) => Math.max(maxOrder, Number(section?.order_num || 0)), -1) + 1, [courseSectionsSource]);
  reactExports.useEffect(() => {
    setLessonManagerDraft(normalizeLessonManagerLessons(courseLessonsSource));
  }, [courseLessonsSource]);
  reactExports.useEffect(() => {
    if (slugTouchedRef.current) return;
    form.setData("slug", slugifyCourseTitle(form.data.title));
  }, [form, form.data.title]);
  reactExports.useEffect(() => {
    const nextTab = firstCourseErrorTab(form.errors);
    if (!nextTab) return;
    setActiveTab(nextTab);
  }, [form.errors]);
  const handleManualCoverChange = (nextValue) => {
    setStagedCoverPath("");
    form.setData("cover_image", nextValue);
    setCoverPreviewUrl(normalizeAssetPreview(nextValue, editorContext.coverCdnBaseUrl));
  };
  const attachLesson = (lesson) => {
    if (!attachLessonUrl) return;
    At.post(attachLessonUrl, {
      lesson_id: lesson.id,
      order_num: courseLessonsSource.length,
      is_required: true
    }, { preserveScroll: true });
  };
  const detachLesson = (courseLesson) => {
    if (!courseLesson.destroy_url) return;
    if (!window.confirm(`Remove "${courseLesson.title}" from this course?`)) return;
    At.delete(courseLesson.destroy_url, { preserveScroll: true });
  };
  const saveLessonOrder = () => {
    if (!reorderUrl) return;
    setLessonSaveProcessing(true);
    At.patch(reorderUrl, {
      sections: courseSectionsSource.map((section) => ({
        id: section.id,
        order_num: Number(section.order_num || 0)
      })),
      lessons: lessonManagerDraft.map((l3) => ({
        id: l3.id,
        order_num: l3.order_num,
        section_id: l3.section_id ?? null
      }))
    }, {
      preserveScroll: true,
      onFinish: () => setLessonSaveProcessing(false)
    });
  };
  const copyImportText = async (value, label) => {
    try {
      await navigator.clipboard.writeText(value);
      showToast(`${label} copied.`, "success");
    } catch {
      showToast(`Could not copy ${label.toLowerCase()}.`, "error");
    }
  };
  const applyCourseJsonImport = () => {
    try {
      const payload = parseCourseJsonImport(courseJsonImportValue);
      setCourseJsonImportError("");
      if (courseImportUrl && method === "post") {
        setCourseJsonImportProcessing(true);
        At.post(courseImportUrl, payload, {
          preserveScroll: true,
          onError: (errors) => {
            const message = firstErrorMessage$3(errors, "Could not import the course JSON.");
            setCourseJsonImportError(message);
            showToast(message, "error");
          },
          onSuccess: () => {
            setCourseJsonImportOpen(false);
            setCourseJsonImportValue("");
            setCourseJsonImportError("");
            showToast("Course JSON imported.", "success");
          },
          onFinish: () => setCourseJsonImportProcessing(false)
        });
        return;
      }
      Object.entries(payload).forEach(([key, value]) => {
        form.setData(key, value);
      });
      if (!payload.slug && payload.title) {
        form.setData("slug", slugifyCourseTitle(payload.title));
      }
      setCourseJsonImportOpen(false);
      setCourseJsonImportValue("");
      showToast("Course JSON applied.", "success");
    } catch (error) {
      setCourseJsonImportError(error instanceof Error ? error.message : "Could not parse JSON.");
    }
  };
  const applyLessonImport = () => {
    if (!importLessonsUrl) return;
    try {
      const payload = parseCourseLessonImport(jsonImportValue, lessonCategoryOptions);
      setJsonImportError("");
      At.post(importLessonsUrl, payload, {
        preserveScroll: true,
        onError: (errors) => {
          const message = firstErrorMessage$3(errors, "Could not import the lesson TOC.");
          setJsonImportError(message);
          showToast(message, "error");
        },
        onSuccess: () => {
          setJsonImportOpen(false);
          setJsonImportValue("");
          setJsonImportError("");
          showToast("Lesson TOC imported.", "success");
        }
      });
    } catch (error) {
      setJsonImportError(error instanceof Error ? error.message : "Could not parse JSON.");
    }
  };
  const updateDraftLessonSection = (lessonId, nextSectionId) => {
    setLessonManagerDraft((current) => normalizeLessonManagerLessons(current.map((lesson) => {
      if (Number(lesson.id) !== Number(lessonId)) {
        return lesson;
      }
      return {
        ...lesson,
        section_id: nextSectionId === "" ? null : Number(nextSectionId),
        section_title: nextSectionId === "" ? "" : courseSectionsSource.find((section) => String(section.id) === String(nextSectionId))?.title || ""
      };
    })));
  };
  const handleManualTeaserChange = (nextValue) => {
    setStagedTeaserPath("");
    form.setData("teaser_image", nextValue);
    setTeaserPreviewUrl(normalizeAssetPreview(nextValue, editorContext.coverCdnBaseUrl));
  };
  const submit = (event) => {
    event.preventDefault();
    const submitOptions = {
      preserveScroll: true,
      onError: (errors) => {
        const nextTab = firstCourseErrorTab(errors);
        if (nextTab) {
          setActiveTab(nextTab);
        }
        showToast(firstErrorMessage$3(errors), "error");
      }
    };
    if (method === "patch") {
      form.patch(submitUrl, submitOptions);
      return;
    }
    form.post(submitUrl, submitOptions);
  };
  const deleteCourse = () => {
    if (!destroyUrl) return;
    if (!window.confirm("Delete this course?")) return;
    At.delete(destroyUrl);
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-6 pb-16" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] shadow-[0_24px_70px_rgba(2,6,23,0.34)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white transition hover:bg-white/[0.08]" }, "Back to courses"), /* @__PURE__ */ React.createElement("span", null, destroyUrl ? "Edit course" : "New course")), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy course"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-7 text-slate-300" }, "Design the course like a polished editorial landing page: keep the structure clear, use the rich description editor, and upload visuals that look intentional on the public cards and hero.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, importLessonsUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-file-import text-xs" }), /* @__PURE__ */ React.createElement("span", null, "Import lessons JSON")) : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setCourseJsonImportOpen(true), className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-file-import text-xs" }), /* @__PURE__ */ React.createElement("span", null, "Import JSON")), editorLinks.builder ? /* @__PURE__ */ React.createElement(xe, { href: editorLinks.builder, className: "rounded-2xl border border-amber-300/20 bg-amber-300/10 px-4 py-2.5 text-sm font-semibold text-amber-100 transition hover:brightness-110" }, "Open builder") : null, editorLinks.preview ? /* @__PURE__ */ React.createElement(xe, { href: editorLinks.preview, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Preview public page") : null, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-2xl border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save course")))), /* @__PURE__ */ React.createElement(EditorWorkspaceTabs$1, { tabs: COURSE_EDITOR_TABS, activeTab, onChange: setActiveTab, errorCounts: tabErrorCounts }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.14)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Current workspace"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, activeTabMeta.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, activeTabMeta.description)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Words"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, wordCount.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Excerpt"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, excerptLength, "/800")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Errors"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Object.keys(form.errors || {}).length))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6", role: "tabpanel", id: `course-editor-panel-${activeTab}`, "aria-labelledby": `course-editor-tab-${activeTab}` }, /* @__PURE__ */ React.createElement(SectionCard$6, { id: "course-identity", eyebrow: "Positioning", title: "Identity and summary", description: "Start with the public-facing identity shown on the course index, hero, and internal Academy modules.", tone: "feature", className: sectionClassName("course-identity") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    TextField$3,
    {
      label: "Title",
      value: form.data.title,
      onChange: (event) => form.setData("title", event.target.value),
      error: form.errors.title,
      maxLength: 180,
      placeholder: "AI-Assisted Digital Art Foundations"
    }
  ), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    slugTouchedRef.current = false;
    form.setData("slug", slugifyCourseTitle(form.data.title));
  }, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Sync")), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: form.data.slug,
      onChange: (event) => {
        slugTouchedRef.current = String(event.target.value).trim() !== "";
        form.setData("slug", event.target.value);
      },
      className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none",
      placeholder: "ai-assisted-digital-art-foundations",
      maxLength: 180
    }
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "The public course URL updates from the title until you override it."), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.slug }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    TextField$3,
    {
      label: "Subtitle",
      value: form.data.subtitle,
      onChange: (event) => form.setData("subtitle", event.target.value),
      error: form.errors.subtitle,
      maxLength: 255,
      placeholder: "A guided path for Skinbase creators"
    }
  ), /* @__PURE__ */ React.createElement(
    TextField$3,
    {
      label: "Estimated minutes",
      value: form.data.estimated_minutes ?? "",
      onChange: (event) => form.setData("estimated_minutes", event.target.value),
      error: form.errors.estimated_minutes,
      type: "number",
      min: "1",
      placeholder: "90",
      hint: "Shown on public course cards and the course hero."
    }
  )), /* @__PURE__ */ React.createElement(
    TextAreaField$2,
    {
      label: "Excerpt",
      value: form.data.excerpt,
      onChange: (event) => form.setData("excerpt", event.target.value),
      error: form.errors.excerpt,
      rows: 5,
      hint: "Keep this tight and outcome-focused. This summary is reused on cards, related modules, and SEO helpers."
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$6, { id: "course-description", eyebrow: "Long-form content", title: "Course description", description: "Use the same richer WYSIWYG surface as lessons so the course page can carry structured copy, lists, and supporting media.", tone: "feature", className: sectionClassName("course-description") }, /* @__PURE__ */ React.createElement(
    RichTextEditor,
    {
      content: form.data.description,
      onChange: (nextHtml) => form.setData("description", nextHtml),
      placeholder: "Explain what the course covers, who it is for, what workflows it teaches, and why a Skinbase creator should follow this path from start to finish.",
      error: form.errors.description,
      minHeight: 24,
      maxHeightRem: 42,
      autofocus: false,
      advancedNews: true,
      mediaSupport: {
        uploadUrl: editorContext.bodyMediaUploadUrl,
        deleteUrl: editorContext.bodyMediaDeleteUrl,
        assetsUrl: editorContext.bodyMediaAssetsUrl,
        slot: "body"
      }
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$6, { id: "course-media", eyebrow: "Visual system", title: "Cover and teaser media", description: "Upload clean landscape images that work across the featured course rail, the course index cards, and the public course hero.", className: sectionClassName("course-media") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Cover image",
      slot: "cover",
      value: form.data.cover_image,
      previewUrl: coverPreviewUrl,
      emptyLabel: "Course cover",
      helperText: "Preferred 1600×900 at 16:9. Minimum upload is 1200×630. Use this as the main hero image for the course page and featured cards.",
      uploadUrl: editorContext.coverUploadUrl,
      deleteUrl: editorContext.coverDeleteUrl,
      isTemporaryValue: Boolean(stagedCoverPath) && stagedCoverPath === form.data.cover_image,
      onChange: ({ path, url }) => {
        setStagedCoverPath(path || "");
        form.setData("cover_image", path || "");
        setCoverPreviewUrl(url || normalizeAssetPreview(path || "", editorContext.coverCdnBaseUrl));
      }
    }
  ), /* @__PURE__ */ React.createElement(
    TextField$3,
    {
      label: "Cover image path override",
      value: form.data.cover_image,
      onChange: (event) => handleManualCoverChange(event.target.value),
      error: form.errors.cover_image,
      placeholder: "academy/lessons/covers/..."
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Teaser image",
      slot: "cover",
      value: form.data.teaser_image,
      previewUrl: teaserPreviewUrl,
      emptyLabel: "Course teaser",
      helperText: "Preferred 1600×900 at 16:9. Use this as the lighter secondary image for index cards or fallback thumbnail treatment when the main cover is too dense.",
      uploadUrl: editorContext.coverUploadUrl,
      deleteUrl: editorContext.coverDeleteUrl,
      isTemporaryValue: Boolean(stagedTeaserPath) && stagedTeaserPath === form.data.teaser_image,
      onChange: ({ path, url }) => {
        setStagedTeaserPath(path || "");
        form.setData("teaser_image", path || "");
        setTeaserPreviewUrl(url || normalizeAssetPreview(path || "", editorContext.coverCdnBaseUrl));
      }
    }
  ), /* @__PURE__ */ React.createElement(
    TextField$3,
    {
      label: "Teaser image path override",
      value: form.data.teaser_image,
      onChange: (event) => handleManualTeaserChange(event.target.value),
      error: form.errors.teaser_image,
      placeholder: "academy/lessons/covers/..."
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/18 bg-sky-300/8 px-4 py-4 text-sm leading-7 text-slate-300" }, "The public course index and the course hero both render landscape imagery first. If you only prepare one asset, prioritize the cover image. If you prepare both, keep them in the same visual family so the course feels consistent across list and detail pages.")), /* @__PURE__ */ React.createElement(
    SectionCard$6,
    {
      id: "course-lessons-manager",
      eyebrow: "Lesson sequence",
      title: "Manage course lessons",
      description: "Add lessons from the library, drag rows to reorder, use the arrows for precision, and save the updated sequence. Removing a lesson detaches it from this course immediately.",
      tone: "feature",
      className: sectionClassName("course-lessons-manager"),
      actions: /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, importLessonsUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-file-import text-xs" }), /* @__PURE__ */ React.createElement("span", null, "Import TOC JSON")) : null, editorLinks.builder ? /* @__PURE__ */ React.createElement("a", { href: editorLinks.builder, className: "rounded-2xl border border-amber-300/20 bg-amber-300/10 px-4 py-2.5 text-sm font-semibold text-amber-100 transition hover:brightness-110" }, "Open full builder") : null)
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement(CourseSectionCreateCard, { storeUrl: sectionStoreUrl, nextOrderNum: nextSectionOrderNum }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Sections in this course"), courseSectionsSource.length > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, courseSectionsSource.length, " total") : null), courseSectionsSource.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[20px] border border-dashed border-white/10 bg-black/20 px-4 py-5 text-sm text-slate-400" }, "No sections yet. Create one here, then assign lessons into it below.") : /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, courseSectionsSource.map((section) => /* @__PURE__ */ React.createElement(CourseSectionCard, { key: section.id, section }))))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Lesson sequence", lessonManagerDraft.length > 0 ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-0.5 text-[10px] text-slate-300" }, lessonManagerDraft.length) : null, lessonManagerIsDirty ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-0.5 text-[10px] text-amber-200" }, "Unsaved order") : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setLessonManagerDraft(normalizeLessonManagerLessons(courseLessonsSource)),
        disabled: !lessonManagerIsDirty || lessonSaveProcessing,
        className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white disabled:opacity-40"
      },
      "Reset order"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: saveLessonOrder,
        disabled: !lessonManagerIsDirty || lessonSaveProcessing,
        className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-3 py-1.5 text-xs font-semibold text-sky-100 disabled:opacity-40"
      },
      lessonSaveProcessing ? "Saving…" : "Save order"
    ))), lessonManagerDraft.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-6 text-sm text-slate-400" }, "No lessons attached to this course yet. Add lessons from the library below.") : lessonManagerDraft.map((lesson, lessonIndex) => /* @__PURE__ */ React.createElement(
      "div",
      {
        key: lesson.id,
        draggable: true,
        onDragStart: () => setLessonDragActive({ id: lesson.id }),
        onDragEnd: () => setLessonDragActive(null),
        onDragOver: (e) => e.preventDefault(),
        onDrop: (e) => {
          e.preventDefault();
          if (!lessonDragActive) return;
          setLessonManagerDraft(reorderLessonManagerLessons(lessonManagerDraft, lessonDragActive.id, lesson.id));
          setLessonDragActive(null);
        },
        className: [
          "flex flex-wrap items-center justify-between gap-3 rounded-2xl border px-4 py-3 transition",
          "border-white/10 bg-white/[0.03] cursor-grab",
          lessonDragActive && Number(lessonDragActive.id) === Number(lesson.id) ? "opacity-50 border-sky-300/30" : ""
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip-vertical text-xs text-slate-600" }), lesson.cover_image_url ? /* @__PURE__ */ React.createElement("div", { className: "h-14 w-20 overflow-hidden rounded-2xl border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("img", { src: lesson.cover_image_url, alt: "", className: "h-full w-full object-cover", loading: "lazy" })) : null, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, formatLessonStep(lesson.order_num) || `#${lesson.display_order}`), lesson.formatted_lesson_number ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, lesson.formatted_lesson_number) : null, lesson.section_title ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, lesson.section_title) : null, lesson.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, lesson.difficulty) : null, /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${lessonActivityBadgeMeta(lesson).className}` }, lessonActivityBadgeMeta(lesson).label), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${lessonPublicationBadgeMeta(lesson).className}` }, lessonPublicationBadgeMeta(lesson).label)), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 truncate text-sm font-semibold text-white" }, lesson.title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("label", { className: "text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, "Section"), /* @__PURE__ */ React.createElement(
        "select",
        {
          value: lesson.section_id == null ? "" : String(lesson.section_id),
          onChange: (event) => updateDraftLessonSection(lesson.id, event.target.value),
          className: "rounded-full border border-white/10 bg-black/20 px-3 py-1.5 text-xs font-semibold text-white outline-none"
        },
        sectionOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value || "none", value: option.value, className: "bg-slate-950 text-white" }, option.label))
      ), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "Pick a section here, then save order to apply the grouping.")))),
      /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => setLessonManagerDraft(moveLessonManagerLesson(lessonManagerDraft, lesson.id, -1)),
          disabled: lessonIndex === 0,
          className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1.5 text-xs font-semibold text-white disabled:opacity-30",
          title: "Move up"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up" })
      ), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => setLessonManagerDraft(moveLessonManagerLesson(lessonManagerDraft, lesson.id, 1)),
          disabled: lessonIndex === lessonManagerDraft.length - 1,
          className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1.5 text-xs font-semibold text-white disabled:opacity-30",
          title: "Move down"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down" })
      ), lesson.edit_url ? /* @__PURE__ */ React.createElement("a", { href: lesson.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Edit") : null, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => detachLesson(lesson),
          className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs font-semibold text-rose-100"
        },
        "Remove"
      ))
    ))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Add from unassigned lesson library"), /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-xs text-slate-500" }), /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "search",
        value: lessonSearch,
        onChange: (e) => setLessonSearch(e.target.value),
        placeholder: "Search unassigned lessons by title or category…",
        className: "w-full rounded-2xl border border-white/10 bg-black/20 py-2.5 pl-9 pr-4 text-sm text-white outline-none placeholder:text-slate-600"
      }
    )), filteredAvailableLessons.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-5 py-4 text-sm text-slate-500" }, lessonSearch.trim() ? "No unassigned lessons match your search." : "All lessons are already assigned to a course.") : /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, filteredAvailableLessons.map((lesson) => /* @__PURE__ */ React.createElement("div", { key: lesson.id, className: "flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-3" }, lesson.cover_image_url ? /* @__PURE__ */ React.createElement("div", { className: "h-14 w-20 overflow-hidden rounded-2xl border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("img", { src: lesson.cover_image_url, alt: "", className: "h-full w-full object-cover", loading: "lazy" })) : null, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, lesson.difficulty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, lesson.difficulty) : null, lesson.category ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, lesson.category) : null, /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${lessonActivityBadgeMeta(lesson).className}` }, lessonActivityBadgeMeta(lesson).label), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${lessonPublicationBadgeMeta(lesson).className}` }, lessonPublicationBadgeMeta(lesson).label)), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 truncate text-sm font-semibold text-white" }, lesson.title))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, lesson.edit_url ? /* @__PURE__ */ React.createElement("a", { href: lesson.edit_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square text-[10px]" }), /* @__PURE__ */ React.createElement("span", null, "Edit lesson")) : null, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => attachLesson(lesson),
        className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-3 py-1.5 text-xs font-semibold text-sky-100"
      },
      "Add to course"
    ))))))
  ), /* @__PURE__ */ React.createElement(SectionCard$6, { id: "course-publishing", eyebrow: "Release controls", title: "Access, status, and placement", description: "Choose how the course appears in Academy discovery surfaces and when it goes live.", className: sectionClassName("course-publishing") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Access", value: form.data.access_level || "", onChange: (nextValue) => form.setData("access_level", String(nextValue || "")), options: accessField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.access_level })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Difficulty", value: form.data.difficulty || "", onChange: (nextValue) => form.setData("difficulty", String(nextValue || "")), options: difficultyField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.difficulty })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Status", value: form.data.status || "", onChange: (nextValue) => form.setData("status", String(nextValue || "")), options: statusField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.status }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    TextField$3,
    {
      label: "Order number",
      value: form.data.order_num ?? "",
      onChange: (event) => form.setData("order_num", event.target.value),
      error: form.errors.order_num,
      type: "number",
      min: "0",
      placeholder: "10",
      hint: "Lower numbers float higher in featured and published course lists."
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Publish at"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.published_at || "", onChange: (nextValue) => form.setData("published_at", nextValue || ""), clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "If the status is set to published and this is empty, the backend will timestamp it automatically."), /* @__PURE__ */ React.createElement(FieldError$3, { message: form.errors.published_at }))), /* @__PURE__ */ React.createElement(
    CheckboxCardField,
    {
      label: "Feature on newsroom surfaces",
      checked: Boolean(form.data.is_featured),
      onChange: (event) => form.setData("is_featured", event.target.checked),
      description: "Use the featured treatment on Academy homepage rails and the course index. Keep this for courses with strong cover art and a finished outline.",
      error: form.errors.is_featured
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$6, { id: "course-seo", eyebrow: "Search surfaces", title: "SEO and OpenGraph", description: "Keep the course crawlable and shareable without overstuffing the main title.", className: sectionClassName("course-seo") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$3, { label: "SEO title", value: form.data.seo_title, onChange: (event) => form.setData("seo_title", event.target.value), error: form.errors.seo_title, maxLength: 180, placeholder: "Optional search title" }), /* @__PURE__ */ React.createElement(TextField$3, { label: "OpenGraph title", value: form.data.og_title, onChange: (event) => form.setData("og_title", event.target.value), error: form.errors.og_title, maxLength: 180, placeholder: "Optional social title" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextAreaField$2, { label: "SEO description", value: form.data.seo_description, onChange: (event) => form.setData("seo_description", event.target.value), error: form.errors.seo_description, rows: 4, hint: "Keep this short and aligned with the course promise." }), /* @__PURE__ */ React.createElement(TextAreaField$2, { label: "OpenGraph description", value: form.data.og_description, onChange: (event) => form.setData("og_description", event.target.value), error: form.errors.og_description, rows: 4, hint: "Used when the course page is shared into external platforms." })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextAreaField$2, { label: "Meta keywords", value: form.data.meta_keywords, onChange: (event) => form.setData("meta_keywords", event.target.value), error: form.errors.meta_keywords, rows: 3, hint: "Comma-separated terms. Keep this focused and editorial, not spammy." }), /* @__PURE__ */ React.createElement(TextField$3, { label: "OpenGraph image", value: form.data.og_image, onChange: (event) => form.setData("og_image", event.target.value), error: form.errors.og_image, placeholder: "Leave empty to fall back to the course artwork" }))), /* @__PURE__ */ React.createElement(SectionCard$6, { id: "course-preview", eyebrow: "Public preview", title: "Rendered course snapshot", description: "Use this tab to scan the media mix, course promise, and rendered long description without the rest of the form competing for attention.", tone: "feature", className: sectionClassName("course-preview") }, /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-slate-950" }, coverPreviewUrl || teaserPreviewUrl ? /* @__PURE__ */ React.createElement("img", { src: coverPreviewUrl || teaserPreviewUrl, alt: "Course hero preview", className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-64 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No course artwork selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, form.data.difficulty || "beginner"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, form.data.access_level || "free"), form.data.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/15 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy course"), form.data.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold uppercase tracking-[0.18em] text-amber-100" }, form.data.subtitle) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, form.data.excerpt || "Add a short course summary to explain what this path helps creators accomplish.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Description preview"), String(deferredDescription || "").trim() ? /* @__PURE__ */ React.createElement("div", { className: "prose prose-invert mt-4 max-w-none prose-headings:tracking-[-0.03em] prose-p:text-slate-300 prose-li:text-slate-300", dangerouslySetInnerHTML: { __html: deferredDescription } }) : /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-400" }, "The long description is still empty."))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6 xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement(SectionCard$6, { eyebrow: "At a glance", title: "Course summary", description: "A compact view of the public URL, media readiness, and the metadata editors see most often." }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/18 bg-sky-300/8 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Public path"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 break-all text-sm font-semibold text-white" }, coursePathPreview), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Use a concise slug so the course URL stays readable in search results and internal links.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Cover"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, coverPreviewUrl ? "Ready" : "Missing")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Teaser"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, teaserPreviewUrl ? "Ready" : "Missing")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, form.data.status || "draft")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Duration"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, form.data.estimated_minutes ? `${form.data.estimated_minutes} min` : "Flexible")))), outlineSummary ? /* @__PURE__ */ React.createElement(SectionCard$6, { eyebrow: "Builder pulse", title: "Course outline", description: "A quick summary of what the course builder currently contains so editors do not need to leave this form just to check structure." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Sections"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, outlineSummary.section_count)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Visible sections"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, outlineSummary.visible_section_count)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Attached lessons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, outlineSummary.lesson_count)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Required lessons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, outlineSummary.required_lesson_count))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/18 bg-sky-300/8 px-4 py-4 text-sm leading-7 text-slate-300" }, outlineSummary.unsectioned_lesson_count > 0 ? `${outlineSummary.unsectioned_lesson_count} lesson${outlineSummary.unsectioned_lesson_count === 1 ? "" : "s"} still sit outside sections. Use the section controls above to group them into chapters.` : "All attached lessons are currently grouped into sections."), outlineSummary.sections?.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, outlineSummary.sections.map((section) => /* @__PURE__ */ React.createElement(OutlineSectionPill, { key: section.id, section }))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-5 text-sm text-slate-400" }, "No sections yet. The builder will still allow unsectioned lessons, but adding chapters usually makes the public course easier to scan.")) : null, /* @__PURE__ */ React.createElement(SectionCard$6, { eyebrow: "Metadata pulse", title: "Search and share", description: "A quick scan of the metadata that most often gets missed before publish." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "SEO title"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white" }, form.data.seo_title || "Uses course title by default")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Keywords"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, metaKeywordItems.length ? metaKeywordItems.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold text-slate-200" }, item)) : /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, "No meta keywords yet."))))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save course"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteCourse, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null)), /* @__PURE__ */ React.createElement(
    CourseJsonImportDialog,
    {
      open: courseJsonImportOpen,
      value: courseJsonImportValue,
      error: courseJsonImportError,
      exampleValue: courseImportExampleValue,
      promptValue: courseImportPromptValue,
      actionLabel: courseImportUrl && method === "post" ? "Create course from JSON" : "Apply JSON",
      processing: courseJsonImportProcessing,
      onChange: setCourseJsonImportValue,
      onClose: () => {
        setCourseJsonImportOpen(false);
        setCourseJsonImportError("");
      },
      onApply: applyCourseJsonImport,
      onCopyExample: () => copyImportText(courseImportExampleValue, "Course example"),
      onCopyPrompt: () => copyImportText(courseImportPromptValue, "Course prompt")
    }
  ), /* @__PURE__ */ React.createElement(
    CourseLessonJsonImportDialog,
    {
      open: jsonImportOpen,
      value: jsonImportValue,
      error: jsonImportError,
      exampleValue: importExampleValue,
      promptValue: importPromptValue,
      onChange: setJsonImportValue,
      onClose: () => setJsonImportOpen(false),
      onApply: applyLessonImport,
      onCopyExample: () => copyImportText(importExampleValue, "Example JSON"),
      onCopyPrompt: () => copyImportText(importPromptValue, "ChatGPT prompt")
    }
  ), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ));
}
const __vite_glob_0_19 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CourseEditor
}, Symbol.toStringTag, { value: "Module" }));
function z() {
  return { async: false, breaks: false, extensions: null, gfm: true, hooks: null, pedantic: false, renderer: null, silent: false, tokenizer: null, walkTokens: null };
}
var T = z();
function G(l3) {
  T = l3;
}
var _ = { exec: () => null };
function d$1(l3, e = "") {
  let t = typeof l3 == "string" ? l3 : l3.source, n = { replace: (s2, r) => {
    let i = typeof r == "string" ? r : r.source;
    return i = i.replace(m.caret, "$1"), t = t.replace(s2, i), n;
  }, getRegex: () => new RegExp(t, e) };
  return n;
}
var Re = ((l3 = "") => {
  try {
    return !!new RegExp("(?<=1)(?<!1)" + l3);
  } catch {
    return false;
  }
})(), m = { codeRemoveIndent: /^(?: {1,4}| {0,3}\t)/gm, outputLinkReplace: /\\([\[\]])/g, indentCodeCompensation: /^(\s+)(?:```)/, beginningSpace: /^\s+/, endingHash: /#$/, startingSpaceChar: /^ /, endingSpaceChar: / $/, nonSpaceChar: /[^ ]/, newLineCharGlobal: /\n/g, tabCharGlobal: /\t/g, multipleSpaceGlobal: /\s+/g, blankLine: /^[ \t]*$/, doubleBlankLine: /\n[ \t]*\n[ \t]*$/, blockquoteStart: /^ {0,3}>/, blockquoteSetextReplace: /\n {0,3}((?:=+|-+) *)(?=\n|$)/g, blockquoteSetextReplace2: /^ {0,3}>[ \t]?/gm, listReplaceNesting: /^ {1,4}(?=( {4})*[^ ])/g, listIsTask: /^\[[ xX]\] +\S/, listReplaceTask: /^\[[ xX]\] +/, listTaskCheckbox: /\[[ xX]\]/, anyLine: /\n.*\n/, hrefBrackets: /^<(.*)>$/, tableDelimiter: /[:|]/, tableAlignChars: /^\||\| *$/g, tableRowBlankLine: /\n[ \t]*$/, tableAlignRight: /^ *-+: *$/, tableAlignCenter: /^ *:-+: *$/, tableAlignLeft: /^ *:-+ *$/, startATag: /^<a /i, endATag: /^<\/a>/i, startPreScriptTag: /^<(pre|code|kbd|script)(\s|>)/i, endPreScriptTag: /^<\/(pre|code|kbd|script)(\s|>)/i, startAngleBracket: /^</, endAngleBracket: />$/, pedanticHrefTitle: /^([^'"]*[^\s])\s+(['"])(.*)\2/, unicodeAlphaNumeric: /[\p{L}\p{N}]/u, escapeTest: /[&<>"']/, escapeReplace: /[&<>"']/g, escapeTestNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/, escapeReplaceNoEncode: /[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g, caret: /(^|[^\[])\^/g, percentDecode: /%25/g, findPipe: /\|/g, splitPipe: / \|/, slashPipe: /\\\|/g, carriageReturn: /\r\n|\r/g, spaceLine: /^ +$/gm, notSpaceStart: /^\S*/, endingNewline: /\n$/, listItemRegex: (l3) => new RegExp(`^( {0,3}${l3})((?:[	 ][^\\n]*)?(?:\\n|$))`), nextBulletRegex: (l3) => new RegExp(`^ {0,${Math.min(3, l3 - 1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ 	][^\\n]*)?(?:\\n|$))`), hrRegex: (l3) => new RegExp(`^ {0,${Math.min(3, l3 - 1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`), fencesBeginRegex: (l3) => new RegExp(`^ {0,${Math.min(3, l3 - 1)}}(?:\`\`\`|~~~)`), headingBeginRegex: (l3) => new RegExp(`^ {0,${Math.min(3, l3 - 1)}}#`), htmlBeginRegex: (l3) => new RegExp(`^ {0,${Math.min(3, l3 - 1)}}<(?:[a-z].*>|!--)`, "i"), blockquoteBeginRegex: (l3) => new RegExp(`^ {0,${Math.min(3, l3 - 1)}}>`) }, Te = /^(?:[ \t]*(?:\n|$))+/, Oe = /^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/, we = /^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/, I = /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/, ye = /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/, Q = / {0,3}(?:[*+-]|\d{1,9}[.)])/, ie = /^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/, oe = d$1(ie).replace(/bull/g, Q).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/\|table/g, "").getRegex(), Pe = d$1(ie).replace(/bull/g, Q).replace(/blockCode/g, /(?: {4}| {0,3}\t)/).replace(/fences/g, / {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g, / {0,3}>/).replace(/heading/g, / {0,3}#{1,6}/).replace(/html/g, / {0,3}<[^\n>]+>\n/).replace(/table/g, / {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(), j = /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/, Se = /^[^\n]+/, F2 = /(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/, $e = d$1(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label", F2).replace("title", /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(), Le = d$1(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g, Q).getRegex(), v = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul", U = /<!--(?:-?>|[\s\S]*?(?:-->|$))/, _e = d$1("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ 	]*)+\\n|$))", "i").replace("comment", U).replace("tag", v).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(), ae = d$1(j).replace("hr", I).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(), Me = d$1(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph", ae).getRegex(), K = { blockquote: Me, code: Oe, def: $e, fences: we, heading: ye, hr: I, html: _e, lheading: oe, list: Le, newline: Te, paragraph: ae, table: _, text: Se }, re$1 = d$1("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr", I).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("blockquote", " {0,3}>").replace("code", "(?: {4}| {0,3}	)[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex(), ze = { ...K, lheading: Pe, table: re$1, paragraph: d$1(j).replace("hr", I).replace("heading", " {0,3}#{1,6}(?:\\s|$)").replace("|lheading", "").replace("table", re$1).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", v).getRegex() }, Ee = { ...K, html: d$1(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", U).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(), def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/, heading: /^(#{1,6})(.*)(?:\n+|$)/, fences: _, lheading: /^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/, paragraph: d$1(j).replace("hr", I).replace("heading", ` *#{1,6} *[^
]`).replace("lheading", oe).replace("|table", "").replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").replace("|tag", "").getRegex() }, Ae = /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/, Ce = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/, le = /^( {2,}|\\)\n(?!\s*$)/, Ie = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/, E = /[\p{P}\p{S}]/u, H = /[\s\p{P}\p{S}]/u, W = /[^\s\p{P}\p{S}]/u, Be = d$1(/^((?![*_])punctSpace)/, "u").replace(/punctSpace/g, H).getRegex(), ue = /(?!~)[\p{P}\p{S}]/u, De = /(?!~)[\s\p{P}\p{S}]/u, qe = /(?:[^\s\p{P}\p{S}]|~)/u, ve = d$1(/link|precode-code|html/, "g").replace("link", /\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-", Re ? "(?<!`)()" : "(^^|[^`])").replace("code", /(?<b>`+)[^`]+\k<b>(?!`)/).replace("html", /<(?! )[^<>]*?>/).getRegex(), pe = /^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/, He = d$1(pe, "u").replace(/punct/g, E).getRegex(), Ze = d$1(pe, "u").replace(/punct/g, ue).getRegex(), ce = "^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)", Ge = d$1(ce, "gu").replace(/notPunctSpace/g, W).replace(/punctSpace/g, H).replace(/punct/g, E).getRegex(), Ne = d$1(ce, "gu").replace(/notPunctSpace/g, qe).replace(/punctSpace/g, De).replace(/punct/g, ue).getRegex(), Qe = d$1("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)", "gu").replace(/notPunctSpace/g, W).replace(/punctSpace/g, H).replace(/punct/g, E).getRegex(), je = d$1(/^~~?(?:((?!~)punct)|[^\s~])/, "u").replace(/punct/g, E).getRegex(), Fe = "^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)", Ue = d$1(Fe, "gu").replace(/notPunctSpace/g, W).replace(/punctSpace/g, H).replace(/punct/g, E).getRegex(), Ke = d$1(/\\(punct)/, "gu").replace(/punct/g, E).getRegex(), We = d$1(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme", /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email", /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(), Xe = d$1(U).replace("(?:-->|$)", "-->").getRegex(), Je = d$1("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment", Xe).replace("attribute", /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(), q = /(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/, Ve = d$1(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label", q).replace("href", /<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title", /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(), he = d$1(/^!?\[(label)\]\[(ref)\]/).replace("label", q).replace("ref", F2).getRegex(), ke = d$1(/^!?\[(ref)\](?:\[\])?/).replace("ref", F2).getRegex(), Ye = d$1("reflink|nolink(?!\\()", "g").replace("reflink", he).replace("nolink", ke).getRegex(), se = /[hH][tT][tT][pP][sS]?|[fF][tT][pP]/, X = { _backpedal: _, anyPunctuation: Ke, autolink: We, blockSkip: ve, br: le, code: Ce, del: _, delLDelim: _, delRDelim: _, emStrongLDelim: He, emStrongRDelimAst: Ge, emStrongRDelimUnd: Qe, escape: Ae, link: Ve, nolink: ke, punctuation: Be, reflink: he, reflinkSearch: Ye, tag: Je, text: Ie, url: _ }, et = { ...X, link: d$1(/^!?\[(label)\]\((.*?)\)/).replace("label", q).getRegex(), reflink: d$1(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", q).getRegex() }, N = { ...X, emStrongRDelimAst: Ne, emStrongLDelim: Ze, delLDelim: je, delRDelim: Ue, url: d$1(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol", se).replace("email", /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(), _backpedal: /(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/, del: /^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/, text: d$1(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol", se).getRegex() }, tt = { ...N, br: d$1(le).replace("{2,}", "*").getRegex(), text: d$1(N.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex() }, B = { normal: K, gfm: ze, pedantic: Ee }, A = { normal: X, gfm: N, breaks: tt, pedantic: et };
var nt = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }, de = (l3) => nt[l3];
function O(l3, e) {
  if (e) {
    if (m.escapeTest.test(l3)) return l3.replace(m.escapeReplace, de);
  } else if (m.escapeTestNoEncode.test(l3)) return l3.replace(m.escapeReplaceNoEncode, de);
  return l3;
}
function J(l3) {
  try {
    l3 = encodeURI(l3).replace(m.percentDecode, "%");
  } catch {
    return null;
  }
  return l3;
}
function V(l3, e) {
  let t = l3.replace(m.findPipe, (r, i, o) => {
    let u2 = false, a = i;
    for (; --a >= 0 && o[a] === "\\"; ) u2 = !u2;
    return u2 ? "|" : " |";
  }), n = t.split(m.splitPipe), s2 = 0;
  if (n[0].trim() || n.shift(), n.length > 0 && !n.at(-1)?.trim() && n.pop(), e) if (n.length > e) n.splice(e);
  else for (; n.length < e; ) n.push("");
  for (; s2 < n.length; s2++) n[s2] = n[s2].trim().replace(m.slashPipe, "|");
  return n;
}
function $(l3, e, t) {
  let n = l3.length;
  if (n === 0) return "";
  let s2 = 0;
  for (; s2 < n; ) {
    let r = l3.charAt(n - s2 - 1);
    if (r === e && true) s2++;
    else break;
  }
  return l3.slice(0, n - s2);
}
function Y(l3) {
  let e = l3.split(`
`), t = e.length - 1;
  for (; t >= 0 && m.blankLine.test(e[t]); ) t--;
  return e.length - t <= 2 ? l3 : e.slice(0, t + 1).join(`
`);
}
function ge(l3, e) {
  if (l3.indexOf(e[1]) === -1) return -1;
  let t = 0;
  for (let n = 0; n < l3.length; n++) if (l3[n] === "\\") n++;
  else if (l3[n] === e[0]) t++;
  else if (l3[n] === e[1] && (t--, t < 0)) return n;
  return t > 0 ? -2 : -1;
}
function fe(l3, e = 0) {
  let t = e, n = "";
  for (let s2 of l3) if (s2 === "	") {
    let r = 4 - t % 4;
    n += " ".repeat(r), t += r;
  } else n += s2, t++;
  return n;
}
function me(l3, e, t, n, s2) {
  let r = e.href, i = e.title || null, o = l3[1].replace(s2.other.outputLinkReplace, "$1");
  n.state.inLink = true;
  let u2 = { type: l3[0].charAt(0) === "!" ? "image" : "link", raw: t, href: r, title: i, text: o, tokens: n.inlineTokens(o) };
  return n.state.inLink = false, u2;
}
function rt(l3, e, t) {
  let n = l3.match(t.other.indentCodeCompensation);
  if (n === null) return e;
  let s2 = n[1];
  return e.split(`
`).map((r) => {
    let i = r.match(t.other.beginningSpace);
    if (i === null) return r;
    let [o] = i;
    return o.length >= s2.length ? r.slice(s2.length) : r;
  }).join(`
`);
}
var w = class {
  options;
  rules;
  lexer;
  constructor(e) {
    this.options = e || T;
  }
  space(e) {
    let t = this.rules.block.newline.exec(e);
    if (t && t[0].length > 0) return { type: "space", raw: t[0] };
  }
  code(e) {
    let t = this.rules.block.code.exec(e);
    if (t) {
      let n = this.options.pedantic ? t[0] : Y(t[0]), s2 = n.replace(this.rules.other.codeRemoveIndent, "");
      return { type: "code", raw: n, codeBlockStyle: "indented", text: s2 };
    }
  }
  fences(e) {
    let t = this.rules.block.fences.exec(e);
    if (t) {
      let n = t[0], s2 = rt(n, t[3] || "", this.rules);
      return { type: "code", raw: n, lang: t[2] ? t[2].trim().replace(this.rules.inline.anyPunctuation, "$1") : t[2], text: s2 };
    }
  }
  heading(e) {
    let t = this.rules.block.heading.exec(e);
    if (t) {
      let n = t[2].trim();
      if (this.rules.other.endingHash.test(n)) {
        let s2 = $(n, "#");
        (this.options.pedantic || !s2 || this.rules.other.endingSpaceChar.test(s2)) && (n = s2.trim());
      }
      return { type: "heading", raw: $(t[0], `
`), depth: t[1].length, text: n, tokens: this.lexer.inline(n) };
    }
  }
  hr(e) {
    let t = this.rules.block.hr.exec(e);
    if (t) return { type: "hr", raw: $(t[0], `
`) };
  }
  blockquote(e) {
    let t = this.rules.block.blockquote.exec(e);
    if (t) {
      let n = $(t[0], `
`).split(`
`), s2 = "", r = "", i = [];
      for (; n.length > 0; ) {
        let o = false, u2 = [], a;
        for (a = 0; a < n.length; a++) if (this.rules.other.blockquoteStart.test(n[a])) u2.push(n[a]), o = true;
        else if (!o) u2.push(n[a]);
        else break;
        n = n.slice(a);
        let c = u2.join(`
`), p = c.replace(this.rules.other.blockquoteSetextReplace, `
    $1`).replace(this.rules.other.blockquoteSetextReplace2, "");
        s2 = s2 ? `${s2}
${c}` : c, r = r ? `${r}
${p}` : p;
        let k2 = this.lexer.state.top;
        if (this.lexer.state.top = true, this.lexer.blockTokens(p, i, true), this.lexer.state.top = k2, n.length === 0) break;
        let h = i.at(-1);
        if (h?.type === "code") break;
        if (h?.type === "blockquote") {
          let R = h, f2 = R.raw + `
` + n.join(`
`), S = this.blockquote(f2);
          i[i.length - 1] = S, s2 = s2.substring(0, s2.length - R.raw.length) + S.raw, r = r.substring(0, r.length - R.text.length) + S.text;
          break;
        } else if (h?.type === "list") {
          let R = h, f2 = R.raw + `
` + n.join(`
`), S = this.list(f2);
          i[i.length - 1] = S, s2 = s2.substring(0, s2.length - h.raw.length) + S.raw, r = r.substring(0, r.length - R.raw.length) + S.raw, n = f2.substring(i.at(-1).raw.length).split(`
`);
          continue;
        }
      }
      return { type: "blockquote", raw: s2, tokens: i, text: r };
    }
  }
  list(e) {
    let t = this.rules.block.list.exec(e);
    if (t) {
      let n = t[1].trim(), s2 = n.length > 1, r = { type: "list", raw: "", ordered: s2, start: s2 ? +n.slice(0, -1) : "", loose: false, items: [] };
      n = s2 ? `\\d{1,9}\\${n.slice(-1)}` : `\\${n}`, this.options.pedantic && (n = s2 ? n : "[*+-]");
      let i = this.rules.other.listItemRegex(n), o = false;
      for (; e; ) {
        let a = false, c = "", p = "";
        if (!(t = i.exec(e)) || this.rules.block.hr.test(e)) break;
        c = t[0], e = e.substring(c.length);
        let k2 = fe(t[2].split(`
`, 1)[0], t[1].length), h = e.split(`
`, 1)[0], R = !k2.trim(), f2 = 0;
        if (this.options.pedantic ? (f2 = 2, p = k2.trimStart()) : R ? f2 = t[1].length + 1 : (f2 = k2.search(this.rules.other.nonSpaceChar), f2 = f2 > 4 ? 1 : f2, p = k2.slice(f2), f2 += t[1].length), R && this.rules.other.blankLine.test(h) && (c += h + `
`, e = e.substring(h.length + 1), a = true), !a) {
          let S = this.rules.other.nextBulletRegex(f2), ee2 = this.rules.other.hrRegex(f2), te2 = this.rules.other.fencesBeginRegex(f2), ne = this.rules.other.headingBeginRegex(f2), xe2 = this.rules.other.htmlBeginRegex(f2), be = this.rules.other.blockquoteBeginRegex(f2);
          for (; e; ) {
            let Z2 = e.split(`
`, 1)[0], C2;
            if (h = Z2, this.options.pedantic ? (h = h.replace(this.rules.other.listReplaceNesting, "  "), C2 = h) : C2 = h.replace(this.rules.other.tabCharGlobal, "    "), te2.test(h) || ne.test(h) || xe2.test(h) || be.test(h) || S.test(h) || ee2.test(h)) break;
            if (C2.search(this.rules.other.nonSpaceChar) >= f2 || !h.trim()) p += `
` + C2.slice(f2);
            else {
              if (R || k2.replace(this.rules.other.tabCharGlobal, "    ").search(this.rules.other.nonSpaceChar) >= 4 || te2.test(k2) || ne.test(k2) || ee2.test(k2)) break;
              p += `
` + h;
            }
            R = !h.trim(), c += Z2 + `
`, e = e.substring(Z2.length + 1), k2 = C2.slice(f2);
          }
        }
        r.loose || (o ? r.loose = true : this.rules.other.doubleBlankLine.test(c) && (o = true)), r.items.push({ type: "list_item", raw: c, task: !!this.options.gfm && this.rules.other.listIsTask.test(p), loose: false, text: p, tokens: [] }), r.raw += c;
      }
      let u2 = r.items.at(-1);
      if (u2) u2.raw = u2.raw.trimEnd(), u2.text = u2.text.trimEnd();
      else return;
      r.raw = r.raw.trimEnd();
      for (let a of r.items) {
        this.lexer.state.top = false, a.tokens = this.lexer.blockTokens(a.text, []);
        let c = a.tokens[0];
        if (a.task && (c?.type === "text" || c?.type === "paragraph")) {
          a.text = a.text.replace(this.rules.other.listReplaceTask, ""), c.raw = c.raw.replace(this.rules.other.listReplaceTask, ""), c.text = c.text.replace(this.rules.other.listReplaceTask, "");
          for (let k2 = this.lexer.inlineQueue.length - 1; k2 >= 0; k2--) if (this.rules.other.listIsTask.test(this.lexer.inlineQueue[k2].src)) {
            this.lexer.inlineQueue[k2].src = this.lexer.inlineQueue[k2].src.replace(this.rules.other.listReplaceTask, "");
            break;
          }
          let p = this.rules.other.listTaskCheckbox.exec(a.raw);
          if (p) {
            let k2 = { type: "checkbox", raw: p[0] + " ", checked: p[0] !== "[ ]" };
            a.checked = k2.checked, r.loose ? a.tokens[0] && ["paragraph", "text"].includes(a.tokens[0].type) && "tokens" in a.tokens[0] && a.tokens[0].tokens ? (a.tokens[0].raw = k2.raw + a.tokens[0].raw, a.tokens[0].text = k2.raw + a.tokens[0].text, a.tokens[0].tokens.unshift(k2)) : a.tokens.unshift({ type: "paragraph", raw: k2.raw, text: k2.raw, tokens: [k2] }) : a.tokens.unshift(k2);
          }
        } else a.task && (a.task = false);
        if (!r.loose) {
          let p = a.tokens.filter((h) => h.type === "space"), k2 = p.length > 0 && p.some((h) => this.rules.other.anyLine.test(h.raw));
          r.loose = k2;
        }
      }
      if (r.loose) for (let a of r.items) {
        a.loose = true;
        for (let c of a.tokens) c.type === "text" && (c.type = "paragraph");
      }
      return r;
    }
  }
  html(e) {
    let t = this.rules.block.html.exec(e);
    if (t) {
      let n = Y(t[0]);
      return { type: "html", block: true, raw: n, pre: t[1] === "pre" || t[1] === "script" || t[1] === "style", text: n };
    }
  }
  def(e) {
    let t = this.rules.block.def.exec(e);
    if (t) {
      let n = t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal, " "), s2 = t[2] ? t[2].replace(this.rules.other.hrefBrackets, "$1").replace(this.rules.inline.anyPunctuation, "$1") : "", r = t[3] ? t[3].substring(1, t[3].length - 1).replace(this.rules.inline.anyPunctuation, "$1") : t[3];
      return { type: "def", tag: n, raw: $(t[0], `
`), href: s2, title: r };
    }
  }
  table(e) {
    let t = this.rules.block.table.exec(e);
    if (!t || !this.rules.other.tableDelimiter.test(t[2])) return;
    let n = V(t[1]), s2 = t[2].replace(this.rules.other.tableAlignChars, "").split("|"), r = t[3]?.trim() ? t[3].replace(this.rules.other.tableRowBlankLine, "").split(`
`) : [], i = { type: "table", raw: $(t[0], `
`), header: [], align: [], rows: [] };
    if (n.length === s2.length) {
      for (let o of s2) this.rules.other.tableAlignRight.test(o) ? i.align.push("right") : this.rules.other.tableAlignCenter.test(o) ? i.align.push("center") : this.rules.other.tableAlignLeft.test(o) ? i.align.push("left") : i.align.push(null);
      for (let o = 0; o < n.length; o++) i.header.push({ text: n[o], tokens: this.lexer.inline(n[o]), header: true, align: i.align[o] });
      for (let o of r) i.rows.push(V(o, i.header.length).map((u2, a) => ({ text: u2, tokens: this.lexer.inline(u2), header: false, align: i.align[a] })));
      return i;
    }
  }
  lheading(e) {
    let t = this.rules.block.lheading.exec(e);
    if (t) {
      let n = t[1].trim();
      return { type: "heading", raw: $(t[0], `
`), depth: t[2].charAt(0) === "=" ? 1 : 2, text: n, tokens: this.lexer.inline(n) };
    }
  }
  paragraph(e) {
    let t = this.rules.block.paragraph.exec(e);
    if (t) {
      let n = t[1].charAt(t[1].length - 1) === `
` ? t[1].slice(0, -1) : t[1];
      return { type: "paragraph", raw: t[0], text: n, tokens: this.lexer.inline(n) };
    }
  }
  text(e) {
    let t = this.rules.block.text.exec(e);
    if (t) return { type: "text", raw: t[0], text: t[0], tokens: this.lexer.inline(t[0]) };
  }
  escape(e) {
    let t = this.rules.inline.escape.exec(e);
    if (t) return { type: "escape", raw: t[0], text: t[1] };
  }
  tag(e) {
    let t = this.rules.inline.tag.exec(e);
    if (t) return !this.lexer.state.inLink && this.rules.other.startATag.test(t[0]) ? this.lexer.state.inLink = true : this.lexer.state.inLink && this.rules.other.endATag.test(t[0]) && (this.lexer.state.inLink = false), !this.lexer.state.inRawBlock && this.rules.other.startPreScriptTag.test(t[0]) ? this.lexer.state.inRawBlock = true : this.lexer.state.inRawBlock && this.rules.other.endPreScriptTag.test(t[0]) && (this.lexer.state.inRawBlock = false), { type: "html", raw: t[0], inLink: this.lexer.state.inLink, inRawBlock: this.lexer.state.inRawBlock, block: false, text: t[0] };
  }
  link(e) {
    let t = this.rules.inline.link.exec(e);
    if (t) {
      let n = t[2].trim();
      if (!this.options.pedantic && this.rules.other.startAngleBracket.test(n)) {
        if (!this.rules.other.endAngleBracket.test(n)) return;
        let i = $(n.slice(0, -1), "\\");
        if ((n.length - i.length) % 2 === 0) return;
      } else {
        let i = ge(t[2], "()");
        if (i === -2) return;
        if (i > -1) {
          let u2 = (t[0].indexOf("!") === 0 ? 5 : 4) + t[1].length + i;
          t[2] = t[2].substring(0, i), t[0] = t[0].substring(0, u2).trim(), t[3] = "";
        }
      }
      let s2 = t[2], r = "";
      if (this.options.pedantic) {
        let i = this.rules.other.pedanticHrefTitle.exec(s2);
        i && (s2 = i[1], r = i[3]);
      } else r = t[3] ? t[3].slice(1, -1) : "";
      return s2 = s2.trim(), this.rules.other.startAngleBracket.test(s2) && (this.options.pedantic && !this.rules.other.endAngleBracket.test(n) ? s2 = s2.slice(1) : s2 = s2.slice(1, -1)), me(t, { href: s2 && s2.replace(this.rules.inline.anyPunctuation, "$1"), title: r && r.replace(this.rules.inline.anyPunctuation, "$1") }, t[0], this.lexer, this.rules);
    }
  }
  reflink(e, t) {
    let n;
    if ((n = this.rules.inline.reflink.exec(e)) || (n = this.rules.inline.nolink.exec(e))) {
      let s2 = (n[2] || n[1]).replace(this.rules.other.multipleSpaceGlobal, " "), r = t[s2.toLowerCase()];
      if (!r) {
        let i = n[0].charAt(0);
        return { type: "text", raw: i, text: i };
      }
      return me(n, r, n[0], this.lexer, this.rules);
    }
  }
  emStrong(e, t, n = "") {
    let s2 = this.rules.inline.emStrongLDelim.exec(e);
    if (!s2 || !s2[1] && !s2[2] && !s2[3] && !s2[4] || s2[4] && n.match(this.rules.other.unicodeAlphaNumeric)) return;
    if (!(s2[1] || s2[3] || "") || !n || this.rules.inline.punctuation.exec(n)) {
      let i = [...s2[0]].length - 1, o, u2, a = i, c = 0, p = s2[0][0] === "*" ? this.rules.inline.emStrongRDelimAst : this.rules.inline.emStrongRDelimUnd;
      for (p.lastIndex = 0, t = t.slice(-1 * e.length + i); (s2 = p.exec(t)) !== null; ) {
        if (o = s2[1] || s2[2] || s2[3] || s2[4] || s2[5] || s2[6], !o) continue;
        if (u2 = [...o].length, s2[3] || s2[4]) {
          a += u2;
          continue;
        } else if ((s2[5] || s2[6]) && i % 3 && !((i + u2) % 3)) {
          c += u2;
          continue;
        }
        if (a -= u2, a > 0) continue;
        u2 = Math.min(u2, u2 + a + c);
        let k2 = [...s2[0]][0].length, h = e.slice(0, i + s2.index + k2 + u2);
        if (Math.min(i, u2) % 2) {
          let f2 = h.slice(1, -1);
          return { type: "em", raw: h, text: f2, tokens: this.lexer.inlineTokens(f2) };
        }
        let R = h.slice(2, -2);
        return { type: "strong", raw: h, text: R, tokens: this.lexer.inlineTokens(R) };
      }
    }
  }
  codespan(e) {
    let t = this.rules.inline.code.exec(e);
    if (t) {
      let n = t[2].replace(this.rules.other.newLineCharGlobal, " "), s2 = this.rules.other.nonSpaceChar.test(n), r = this.rules.other.startingSpaceChar.test(n) && this.rules.other.endingSpaceChar.test(n);
      return s2 && r && (n = n.substring(1, n.length - 1)), { type: "codespan", raw: t[0], text: n };
    }
  }
  br(e) {
    let t = this.rules.inline.br.exec(e);
    if (t) return { type: "br", raw: t[0] };
  }
  del(e, t, n = "") {
    let s2 = this.rules.inline.delLDelim.exec(e);
    if (!s2) return;
    if (!(s2[1] || "") || !n || this.rules.inline.punctuation.exec(n)) {
      let i = [...s2[0]].length - 1, o, u2, a = i, c = this.rules.inline.delRDelim;
      for (c.lastIndex = 0, t = t.slice(-1 * e.length + i); (s2 = c.exec(t)) !== null; ) {
        if (o = s2[1] || s2[2] || s2[3] || s2[4] || s2[5] || s2[6], !o || (u2 = [...o].length, u2 !== i)) continue;
        if (s2[3] || s2[4]) {
          a += u2;
          continue;
        }
        if (a -= u2, a > 0) continue;
        u2 = Math.min(u2, u2 + a);
        let p = [...s2[0]][0].length, k2 = e.slice(0, i + s2.index + p + u2), h = k2.slice(i, -i);
        return { type: "del", raw: k2, text: h, tokens: this.lexer.inlineTokens(h) };
      }
    }
  }
  autolink(e) {
    let t = this.rules.inline.autolink.exec(e);
    if (t) {
      let n, s2;
      return t[2] === "@" ? (n = t[1], s2 = "mailto:" + n) : (n = t[1], s2 = n), { type: "link", raw: t[0], text: n, href: s2, tokens: [{ type: "text", raw: n, text: n }] };
    }
  }
  url(e) {
    let t;
    if (t = this.rules.inline.url.exec(e)) {
      let n, s2;
      if (t[2] === "@") n = t[0], s2 = "mailto:" + n;
      else {
        let r;
        do
          r = t[0], t[0] = this.rules.inline._backpedal.exec(t[0])?.[0] ?? "";
        while (r !== t[0]);
        n = t[0], t[1] === "www." ? s2 = "http://" + t[0] : s2 = t[0];
      }
      return { type: "link", raw: t[0], text: n, href: s2, tokens: [{ type: "text", raw: n, text: n }] };
    }
  }
  inlineText(e) {
    let t = this.rules.inline.text.exec(e);
    if (t) {
      let n = this.lexer.state.inRawBlock;
      return { type: "text", raw: t[0], text: t[0], escaped: n };
    }
  }
};
var x = class l {
  tokens;
  options;
  state;
  inlineQueue;
  tokenizer;
  constructor(e) {
    this.tokens = [], this.tokens.links = /* @__PURE__ */ Object.create(null), this.options = e || T, this.options.tokenizer = this.options.tokenizer || new w(), this.tokenizer = this.options.tokenizer, this.tokenizer.options = this.options, this.tokenizer.lexer = this, this.inlineQueue = [], this.state = { inLink: false, inRawBlock: false, top: true };
    let t = { other: m, block: B.normal, inline: A.normal };
    this.options.pedantic ? (t.block = B.pedantic, t.inline = A.pedantic) : this.options.gfm && (t.block = B.gfm, this.options.breaks ? t.inline = A.breaks : t.inline = A.gfm), this.tokenizer.rules = t;
  }
  static get rules() {
    return { block: B, inline: A };
  }
  static lex(e, t) {
    return new l(t).lex(e);
  }
  static lexInline(e, t) {
    return new l(t).inlineTokens(e);
  }
  lex(e) {
    e = e.replace(m.carriageReturn, `
`), this.blockTokens(e, this.tokens);
    for (let t = 0; t < this.inlineQueue.length; t++) {
      let n = this.inlineQueue[t];
      this.inlineTokens(n.src, n.tokens);
    }
    return this.inlineQueue = [], this.tokens;
  }
  blockTokens(e, t = [], n = false) {
    this.tokenizer.lexer = this, this.options.pedantic && (e = e.replace(m.tabCharGlobal, "    ").replace(m.spaceLine, ""));
    let s2 = 1 / 0;
    for (; e; ) {
      if (e.length < s2) s2 = e.length;
      else {
        this.infiniteLoopError(e.charCodeAt(0));
        break;
      }
      let r;
      if (this.options.extensions?.block?.some((o) => (r = o.call({ lexer: this }, e, t)) ? (e = e.substring(r.raw.length), t.push(r), true) : false)) continue;
      if (r = this.tokenizer.space(e)) {
        e = e.substring(r.raw.length);
        let o = t.at(-1);
        r.raw.length === 1 && o !== void 0 ? o.raw += `
` : t.push(r);
        continue;
      }
      if (r = this.tokenizer.code(e)) {
        e = e.substring(r.raw.length);
        let o = t.at(-1);
        o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(`
`) ? "" : `
`) + r.raw, o.text += `
` + r.text, this.inlineQueue.at(-1).src = o.text) : t.push(r);
        continue;
      }
      if (r = this.tokenizer.fences(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.heading(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.hr(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.blockquote(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.list(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.html(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.def(e)) {
        e = e.substring(r.raw.length);
        let o = t.at(-1);
        o?.type === "paragraph" || o?.type === "text" ? (o.raw += (o.raw.endsWith(`
`) ? "" : `
`) + r.raw, o.text += `
` + r.raw, this.inlineQueue.at(-1).src = o.text) : this.tokens.links[r.tag] || (this.tokens.links[r.tag] = { href: r.href, title: r.title }, t.push(r));
        continue;
      }
      if (r = this.tokenizer.table(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      if (r = this.tokenizer.lheading(e)) {
        e = e.substring(r.raw.length), t.push(r);
        continue;
      }
      let i = e;
      if (this.options.extensions?.startBlock) {
        let o = 1 / 0, u2 = e.slice(1), a;
        this.options.extensions.startBlock.forEach((c) => {
          a = c.call({ lexer: this }, u2), typeof a == "number" && a >= 0 && (o = Math.min(o, a));
        }), o < 1 / 0 && o >= 0 && (i = e.substring(0, o + 1));
      }
      if (this.state.top && (r = this.tokenizer.paragraph(i))) {
        let o = t.at(-1);
        n && o?.type === "paragraph" ? (o.raw += (o.raw.endsWith(`
`) ? "" : `
`) + r.raw, o.text += `
` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r), n = i.length !== e.length, e = e.substring(r.raw.length);
        continue;
      }
      if (r = this.tokenizer.text(e)) {
        e = e.substring(r.raw.length);
        let o = t.at(-1);
        o?.type === "text" ? (o.raw += (o.raw.endsWith(`
`) ? "" : `
`) + r.raw, o.text += `
` + r.text, this.inlineQueue.pop(), this.inlineQueue.at(-1).src = o.text) : t.push(r);
        continue;
      }
      if (e) {
        this.infiniteLoopError(e.charCodeAt(0));
        break;
      }
    }
    return this.state.top = true, t;
  }
  inline(e, t = []) {
    return this.inlineQueue.push({ src: e, tokens: t }), t;
  }
  inlineTokens(e, t = []) {
    this.tokenizer.lexer = this;
    let n = e, s2 = null;
    if (this.tokens.links) {
      let a = Object.keys(this.tokens.links);
      if (a.length > 0) for (; (s2 = this.tokenizer.rules.inline.reflinkSearch.exec(n)) !== null; ) a.includes(s2[0].slice(s2[0].lastIndexOf("[") + 1, -1)) && (n = n.slice(0, s2.index) + "[" + "a".repeat(s2[0].length - 2) + "]" + n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex));
    }
    for (; (s2 = this.tokenizer.rules.inline.anyPunctuation.exec(n)) !== null; ) n = n.slice(0, s2.index) + "++" + n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);
    let r;
    for (; (s2 = this.tokenizer.rules.inline.blockSkip.exec(n)) !== null; ) r = s2[2] ? s2[2].length : 0, n = n.slice(0, s2.index + r) + "[" + "a".repeat(s2[0].length - r - 2) + "]" + n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
    n = this.options.hooks?.emStrongMask?.call({ lexer: this }, n) ?? n;
    let i = false, o = "", u2 = 1 / 0;
    for (; e; ) {
      if (e.length < u2) u2 = e.length;
      else {
        this.infiniteLoopError(e.charCodeAt(0));
        break;
      }
      i || (o = ""), i = false;
      let a;
      if (this.options.extensions?.inline?.some((p) => (a = p.call({ lexer: this }, e, t)) ? (e = e.substring(a.raw.length), t.push(a), true) : false)) continue;
      if (a = this.tokenizer.escape(e)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.tag(e)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.link(e)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.reflink(e, this.tokens.links)) {
        e = e.substring(a.raw.length);
        let p = t.at(-1);
        a.type === "text" && p?.type === "text" ? (p.raw += a.raw, p.text += a.text) : t.push(a);
        continue;
      }
      if (a = this.tokenizer.emStrong(e, n, o)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.codespan(e)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.br(e)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.del(e, n, o)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (a = this.tokenizer.autolink(e)) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      if (!this.state.inLink && (a = this.tokenizer.url(e))) {
        e = e.substring(a.raw.length), t.push(a);
        continue;
      }
      let c = e;
      if (this.options.extensions?.startInline) {
        let p = 1 / 0, k2 = e.slice(1), h;
        this.options.extensions.startInline.forEach((R) => {
          h = R.call({ lexer: this }, k2), typeof h == "number" && h >= 0 && (p = Math.min(p, h));
        }), p < 1 / 0 && p >= 0 && (c = e.substring(0, p + 1));
      }
      if (a = this.tokenizer.inlineText(c)) {
        e = e.substring(a.raw.length), a.raw.slice(-1) !== "_" && (o = a.raw.slice(-1)), i = true;
        let p = t.at(-1);
        p?.type === "text" ? (p.raw += a.raw, p.text += a.text) : t.push(a);
        continue;
      }
      if (e) {
        this.infiniteLoopError(e.charCodeAt(0));
        break;
      }
    }
    return t;
  }
  infiniteLoopError(e) {
    let t = "Infinite loop on byte: " + e;
    if (this.options.silent) console.error(t);
    else throw new Error(t);
  }
};
var y = class {
  options;
  parser;
  constructor(e) {
    this.options = e || T;
  }
  space(e) {
    return "";
  }
  code({ text: e, lang: t, escaped: n }) {
    let s2 = (t || "").match(m.notSpaceStart)?.[0], r = e.replace(m.endingNewline, "") + `
`;
    return s2 ? '<pre><code class="language-' + O(s2) + '">' + (n ? r : O(r, true)) + `</code></pre>
` : "<pre><code>" + (n ? r : O(r, true)) + `</code></pre>
`;
  }
  blockquote({ tokens: e }) {
    return `<blockquote>
${this.parser.parse(e)}</blockquote>
`;
  }
  html({ text: e }) {
    return e;
  }
  def(e) {
    return "";
  }
  heading({ tokens: e, depth: t }) {
    return `<h${t}>${this.parser.parseInline(e)}</h${t}>
`;
  }
  hr(e) {
    return `<hr>
`;
  }
  list(e) {
    let t = e.ordered, n = e.start, s2 = "";
    for (let o = 0; o < e.items.length; o++) {
      let u2 = e.items[o];
      s2 += this.listitem(u2);
    }
    let r = t ? "ol" : "ul", i = t && n !== 1 ? ' start="' + n + '"' : "";
    return "<" + r + i + `>
` + s2 + "</" + r + `>
`;
  }
  listitem(e) {
    return `<li>${this.parser.parse(e.tokens)}</li>
`;
  }
  checkbox({ checked: e }) {
    return "<input " + (e ? 'checked="" ' : "") + 'disabled="" type="checkbox"> ';
  }
  paragraph({ tokens: e }) {
    return `<p>${this.parser.parseInline(e)}</p>
`;
  }
  table(e) {
    let t = "", n = "";
    for (let r = 0; r < e.header.length; r++) n += this.tablecell(e.header[r]);
    t += this.tablerow({ text: n });
    let s2 = "";
    for (let r = 0; r < e.rows.length; r++) {
      let i = e.rows[r];
      n = "";
      for (let o = 0; o < i.length; o++) n += this.tablecell(i[o]);
      s2 += this.tablerow({ text: n });
    }
    return s2 && (s2 = `<tbody>${s2}</tbody>`), `<table>
<thead>
` + t + `</thead>
` + s2 + `</table>
`;
  }
  tablerow({ text: e }) {
    return `<tr>
${e}</tr>
`;
  }
  tablecell(e) {
    let t = this.parser.parseInline(e.tokens), n = e.header ? "th" : "td";
    return (e.align ? `<${n} align="${e.align}">` : `<${n}>`) + t + `</${n}>
`;
  }
  strong({ tokens: e }) {
    return `<strong>${this.parser.parseInline(e)}</strong>`;
  }
  em({ tokens: e }) {
    return `<em>${this.parser.parseInline(e)}</em>`;
  }
  codespan({ text: e }) {
    return `<code>${O(e, true)}</code>`;
  }
  br(e) {
    return "<br>";
  }
  del({ tokens: e }) {
    return `<del>${this.parser.parseInline(e)}</del>`;
  }
  link({ href: e, title: t, tokens: n }) {
    let s2 = this.parser.parseInline(n), r = J(e);
    if (r === null) return s2;
    e = r;
    let i = '<a href="' + e + '"';
    return t && (i += ' title="' + O(t) + '"'), i += ">" + s2 + "</a>", i;
  }
  image({ href: e, title: t, text: n, tokens: s2 }) {
    s2 && (n = this.parser.parseInline(s2, this.parser.textRenderer));
    let r = J(e);
    if (r === null) return O(n);
    e = r;
    let i = `<img src="${e}" alt="${O(n)}"`;
    return t && (i += ` title="${O(t)}"`), i += ">", i;
  }
  text(e) {
    return "tokens" in e && e.tokens ? this.parser.parseInline(e.tokens) : "escaped" in e && e.escaped ? e.text : O(e.text);
  }
};
var L = class {
  strong({ text: e }) {
    return e;
  }
  em({ text: e }) {
    return e;
  }
  codespan({ text: e }) {
    return e;
  }
  del({ text: e }) {
    return e;
  }
  html({ text: e }) {
    return e;
  }
  text({ text: e }) {
    return e;
  }
  link({ text: e }) {
    return "" + e;
  }
  image({ text: e }) {
    return "" + e;
  }
  br() {
    return "";
  }
  checkbox({ raw: e }) {
    return e;
  }
};
var b = class l2 {
  options;
  renderer;
  textRenderer;
  constructor(e) {
    this.options = e || T, this.options.renderer = this.options.renderer || new y(), this.renderer = this.options.renderer, this.renderer.options = this.options, this.renderer.parser = this, this.textRenderer = new L();
  }
  static parse(e, t) {
    return new l2(t).parse(e);
  }
  static parseInline(e, t) {
    return new l2(t).parseInline(e);
  }
  parse(e) {
    this.renderer.parser = this;
    let t = "";
    for (let n = 0; n < e.length; n++) {
      let s2 = e[n];
      if (this.options.extensions?.renderers?.[s2.type]) {
        let i = s2, o = this.options.extensions.renderers[i.type].call({ parser: this }, i);
        if (o !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "def", "paragraph", "text"].includes(i.type)) {
          t += o || "";
          continue;
        }
      }
      let r = s2;
      switch (r.type) {
        case "space": {
          t += this.renderer.space(r);
          break;
        }
        case "hr": {
          t += this.renderer.hr(r);
          break;
        }
        case "heading": {
          t += this.renderer.heading(r);
          break;
        }
        case "code": {
          t += this.renderer.code(r);
          break;
        }
        case "table": {
          t += this.renderer.table(r);
          break;
        }
        case "blockquote": {
          t += this.renderer.blockquote(r);
          break;
        }
        case "list": {
          t += this.renderer.list(r);
          break;
        }
        case "checkbox": {
          t += this.renderer.checkbox(r);
          break;
        }
        case "html": {
          t += this.renderer.html(r);
          break;
        }
        case "def": {
          t += this.renderer.def(r);
          break;
        }
        case "paragraph": {
          t += this.renderer.paragraph(r);
          break;
        }
        case "text": {
          t += this.renderer.text(r);
          break;
        }
        default: {
          let i = 'Token with "' + r.type + '" type was not found.';
          if (this.options.silent) return console.error(i), "";
          throw new Error(i);
        }
      }
    }
    return t;
  }
  parseInline(e, t = this.renderer) {
    this.renderer.parser = this;
    let n = "";
    for (let s2 = 0; s2 < e.length; s2++) {
      let r = e[s2];
      if (this.options.extensions?.renderers?.[r.type]) {
        let o = this.options.extensions.renderers[r.type].call({ parser: this }, r);
        if (o !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(r.type)) {
          n += o || "";
          continue;
        }
      }
      let i = r;
      switch (i.type) {
        case "escape": {
          n += t.text(i);
          break;
        }
        case "html": {
          n += t.html(i);
          break;
        }
        case "link": {
          n += t.link(i);
          break;
        }
        case "image": {
          n += t.image(i);
          break;
        }
        case "checkbox": {
          n += t.checkbox(i);
          break;
        }
        case "strong": {
          n += t.strong(i);
          break;
        }
        case "em": {
          n += t.em(i);
          break;
        }
        case "codespan": {
          n += t.codespan(i);
          break;
        }
        case "br": {
          n += t.br(i);
          break;
        }
        case "del": {
          n += t.del(i);
          break;
        }
        case "text": {
          n += t.text(i);
          break;
        }
        default: {
          let o = 'Token with "' + i.type + '" type was not found.';
          if (this.options.silent) return console.error(o), "";
          throw new Error(o);
        }
      }
    }
    return n;
  }
};
var P = class {
  options;
  block;
  constructor(e) {
    this.options = e || T;
  }
  static passThroughHooks = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens", "emStrongMask"]);
  static passThroughHooksRespectAsync = /* @__PURE__ */ new Set(["preprocess", "postprocess", "processAllTokens"]);
  preprocess(e) {
    return e;
  }
  postprocess(e) {
    return e;
  }
  processAllTokens(e) {
    return e;
  }
  emStrongMask(e) {
    return e;
  }
  provideLexer(e = this.block) {
    return e ? x.lex : x.lexInline;
  }
  provideParser(e = this.block) {
    return e ? b.parse : b.parseInline;
  }
};
var D = class {
  defaults = z();
  options = this.setOptions;
  parse = this.parseMarkdown(true);
  parseInline = this.parseMarkdown(false);
  Parser = b;
  Renderer = y;
  TextRenderer = L;
  Lexer = x;
  Tokenizer = w;
  Hooks = P;
  constructor(...e) {
    this.use(...e);
  }
  walkTokens(e, t) {
    let n = [];
    for (let s2 of e) switch (n = n.concat(t.call(this, s2)), s2.type) {
      case "table": {
        let r = s2;
        for (let i of r.header) n = n.concat(this.walkTokens(i.tokens, t));
        for (let i of r.rows) for (let o of i) n = n.concat(this.walkTokens(o.tokens, t));
        break;
      }
      case "list": {
        let r = s2;
        n = n.concat(this.walkTokens(r.items, t));
        break;
      }
      default: {
        let r = s2;
        this.defaults.extensions?.childTokens?.[r.type] ? this.defaults.extensions.childTokens[r.type].forEach((i) => {
          let o = r[i].flat(1 / 0);
          n = n.concat(this.walkTokens(o, t));
        }) : r.tokens && (n = n.concat(this.walkTokens(r.tokens, t)));
      }
    }
    return n;
  }
  use(...e) {
    let t = this.defaults.extensions || { renderers: {}, childTokens: {} };
    return e.forEach((n) => {
      let s2 = { ...n };
      if (s2.async = this.defaults.async || s2.async || false, n.extensions && (n.extensions.forEach((r) => {
        if (!r.name) throw new Error("extension name required");
        if ("renderer" in r) {
          let i = t.renderers[r.name];
          i ? t.renderers[r.name] = function(...o) {
            let u2 = r.renderer.apply(this, o);
            return u2 === false && (u2 = i.apply(this, o)), u2;
          } : t.renderers[r.name] = r.renderer;
        }
        if ("tokenizer" in r) {
          if (!r.level || r.level !== "block" && r.level !== "inline") throw new Error("extension level must be 'block' or 'inline'");
          let i = t[r.level];
          i ? i.unshift(r.tokenizer) : t[r.level] = [r.tokenizer], r.start && (r.level === "block" ? t.startBlock ? t.startBlock.push(r.start) : t.startBlock = [r.start] : r.level === "inline" && (t.startInline ? t.startInline.push(r.start) : t.startInline = [r.start]));
        }
        "childTokens" in r && r.childTokens && (t.childTokens[r.name] = r.childTokens);
      }), s2.extensions = t), n.renderer) {
        let r = this.defaults.renderer || new y(this.defaults);
        for (let i in n.renderer) {
          if (!(i in r)) throw new Error(`renderer '${i}' does not exist`);
          if (["options", "parser"].includes(i)) continue;
          let o = i, u2 = n.renderer[o], a = r[o];
          r[o] = (...c) => {
            let p = u2.apply(r, c);
            return p === false && (p = a.apply(r, c)), p || "";
          };
        }
        s2.renderer = r;
      }
      if (n.tokenizer) {
        let r = this.defaults.tokenizer || new w(this.defaults);
        for (let i in n.tokenizer) {
          if (!(i in r)) throw new Error(`tokenizer '${i}' does not exist`);
          if (["options", "rules", "lexer"].includes(i)) continue;
          let o = i, u2 = n.tokenizer[o], a = r[o];
          r[o] = (...c) => {
            let p = u2.apply(r, c);
            return p === false && (p = a.apply(r, c)), p;
          };
        }
        s2.tokenizer = r;
      }
      if (n.hooks) {
        let r = this.defaults.hooks || new P();
        for (let i in n.hooks) {
          if (!(i in r)) throw new Error(`hook '${i}' does not exist`);
          if (["options", "block"].includes(i)) continue;
          let o = i, u2 = n.hooks[o], a = r[o];
          P.passThroughHooks.has(i) ? r[o] = (c) => {
            if (this.defaults.async && P.passThroughHooksRespectAsync.has(i)) return (async () => {
              let k2 = await u2.call(r, c);
              return a.call(r, k2);
            })();
            let p = u2.call(r, c);
            return a.call(r, p);
          } : r[o] = (...c) => {
            if (this.defaults.async) return (async () => {
              let k2 = await u2.apply(r, c);
              return k2 === false && (k2 = await a.apply(r, c)), k2;
            })();
            let p = u2.apply(r, c);
            return p === false && (p = a.apply(r, c)), p;
          };
        }
        s2.hooks = r;
      }
      if (n.walkTokens) {
        let r = this.defaults.walkTokens, i = n.walkTokens;
        s2.walkTokens = function(o) {
          let u2 = [];
          return u2.push(i.call(this, o)), r && (u2 = u2.concat(r.call(this, o))), u2;
        };
      }
      this.defaults = { ...this.defaults, ...s2 };
    }), this;
  }
  setOptions(e) {
    return this.defaults = { ...this.defaults, ...e }, this;
  }
  lexer(e, t) {
    return x.lex(e, t ?? this.defaults);
  }
  parser(e, t) {
    return b.parse(e, t ?? this.defaults);
  }
  parseMarkdown(e) {
    return (n, s2) => {
      let r = { ...s2 }, i = { ...this.defaults, ...r }, o = this.onError(!!i.silent, !!i.async);
      if (this.defaults.async === true && r.async === false) return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));
      if (typeof n > "u" || n === null) return o(new Error("marked(): input parameter is undefined or null"));
      if (typeof n != "string") return o(new Error("marked(): input parameter is of type " + Object.prototype.toString.call(n) + ", string expected"));
      if (i.hooks && (i.hooks.options = i, i.hooks.block = e), i.async) return (async () => {
        let u2 = i.hooks ? await i.hooks.preprocess(n) : n, c = await (i.hooks ? await i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(u2, i), p = i.hooks ? await i.hooks.processAllTokens(c) : c;
        i.walkTokens && await Promise.all(this.walkTokens(p, i.walkTokens));
        let h = await (i.hooks ? await i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(p, i);
        return i.hooks ? await i.hooks.postprocess(h) : h;
      })().catch(o);
      try {
        i.hooks && (n = i.hooks.preprocess(n));
        let a = (i.hooks ? i.hooks.provideLexer(e) : e ? x.lex : x.lexInline)(n, i);
        i.hooks && (a = i.hooks.processAllTokens(a)), i.walkTokens && this.walkTokens(a, i.walkTokens);
        let p = (i.hooks ? i.hooks.provideParser(e) : e ? b.parse : b.parseInline)(a, i);
        return i.hooks && (p = i.hooks.postprocess(p)), p;
      } catch (u2) {
        return o(u2);
      }
    };
  }
  onError(e, t) {
    return (n) => {
      if (n.message += `
Please report this to https://github.com/markedjs/marked.`, e) {
        let s2 = "<p>An error occurred:</p><pre>" + O(n.message + "", true) + "</pre>";
        return t ? Promise.resolve(s2) : s2;
      }
      if (t) return Promise.reject(n);
      throw n;
    };
  }
};
var M = new D();
function g$1(l3, e) {
  return M.parse(l3, e);
}
g$1.options = g$1.setOptions = function(l3) {
  return M.setOptions(l3), g$1.defaults = M.defaults, G(g$1.defaults), g$1;
};
g$1.getDefaults = z;
g$1.defaults = T;
g$1.use = function(...l3) {
  return M.use(...l3), g$1.defaults = M.defaults, G(g$1.defaults), g$1;
};
g$1.walkTokens = function(l3, e) {
  return M.walkTokens(l3, e);
};
g$1.parseInline = M.parseInline;
g$1.Parser = b;
g$1.parser = b.parse;
g$1.Renderer = y;
g$1.TextRenderer = L;
g$1.Lexer = x;
g$1.lexer = x.lex;
g$1.Tokenizer = w;
g$1.Hooks = P;
g$1.parse = g$1;
g$1.options;
g$1.setOptions;
g$1.use;
g$1.walkTokens;
g$1.parseInline;
b.parse;
x.lex;
let lessonMarkdownTurndown = null;
let lessonMarkdownTurndownPromise = null;
async function loadLessonMarkdownTurndown() {
  if (lessonMarkdownTurndown) {
    return lessonMarkdownTurndown;
  }
  if (typeof window === "undefined") {
    return null;
  }
  if (!lessonMarkdownTurndownPromise) {
    lessonMarkdownTurndownPromise = import("./assets/turndown.es-8lfE8z0s.js").then(({ default: TurndownService }) => new TurndownService({
      headingStyle: "atx",
      codeBlockStyle: "fenced",
      bulletListMarker: "-",
      emDelimiter: "*"
    })).then((service) => {
      lessonMarkdownTurndown = service;
      return service;
    }).catch(() => null);
  }
  return lessonMarkdownTurndownPromise;
}
function getField$1(fields, name2) {
  return fields.find((field) => field.name === name2) || null;
}
const LESSON_EDITOR_TABS = [
  {
    id: "write",
    label: "Write",
    description: "Headline, summary, and the full lesson article.",
    icon: "fa-pen-nib",
    sections: ["lesson-story-setup", "lesson-body-editor"]
  },
  {
    id: "blocks",
    label: "Blocks",
    description: "Reusable AI comparison modules and structured lesson inserts.",
    icon: "fa-layer-group",
    sections: ["lesson-ai-comparisons"]
  },
  {
    id: "courses",
    label: "Courses",
    description: "Attach this lesson to courses, manage its public numbering, and reorder it inside guided paths.",
    icon: "fa-diagram-project",
    sections: ["lesson-course-numbering", "lesson-course-manager"]
  },
  {
    id: "publish",
    label: "Publish",
    description: "Visibility, discovery settings, scheduling, and search surfaces.",
    icon: "fa-rocket-launch",
    sections: ["lesson-publishing", "lesson-seo"]
  },
  {
    id: "assets",
    label: "Assets",
    description: "Hero cover, article cover, and lesson categories.",
    icon: "fa-images",
    sections: ["lesson-cover", "lesson-article-cover", "lesson-categories"]
  },
  {
    id: "revisions",
    label: "Revisions",
    description: "Review saved lesson snapshots and restore the full lesson or a single field.",
    icon: "fa-clock-rotate-left",
    sections: ["lesson-revisions"]
  },
  {
    id: "preview",
    label: "Preview",
    description: "Preview the lesson card, article imagery, and rendered body.",
    icon: "fa-eye",
    sections: ["lesson-preview"]
  }
];
const LESSON_FIELD_TAB_MAP = {
  title: "write",
  slug: "write",
  excerpt: "write",
  content: "write",
  content_markdown: "write",
  lesson_type: "publish",
  difficulty: "publish",
  access_level: "publish",
  reading_minutes: "publish",
  tags: "publish",
  series_name: "publish",
  lesson_number: "courses",
  course_order: "courses",
  course_ids: "courses",
  category_id: "assets",
  published_at: "publish",
  featured: "publish",
  active: "publish",
  seo_title: "publish",
  seo_description: "publish",
  video_url: "publish",
  cover_image: "assets",
  article_cover_image: "assets"
};
const LESSON_REVISION_FIELD_OPTIONS = [
  { value: "title", label: "Title" },
  { value: "slug", label: "Slug" },
  { value: "lesson_number", label: "Lesson number" },
  { value: "course_order", label: "Course order" },
  { value: "series_name", label: "Series name" },
  { value: "excerpt", label: "Excerpt" },
  { value: "content", label: "Article body" },
  { value: "difficulty", label: "Difficulty" },
  { value: "access_level", label: "Access level" },
  { value: "lesson_type", label: "Lesson type" },
  { value: "cover_image", label: "Cover image" },
  { value: "article_cover_image", label: "Article cover image" },
  { value: "tags", label: "Microtags" },
  { value: "video_url", label: "Video URL" },
  { value: "reading_minutes", label: "Reading minutes" },
  { value: "featured", label: "Featured toggle" },
  { value: "active", label: "Active toggle" },
  { value: "published_at", label: "Publish date" },
  { value: "seo_title", label: "SEO title" },
  { value: "seo_description", label: "SEO description" },
  { value: "course_ids", label: "Course attachments" },
  { value: "blocks", label: "AI comparison blocks" }
];
let comparisonEditorSequence = 0;
function nextComparisonEditorKey(prefix) {
  comparisonEditorSequence += 1;
  return `${prefix}-${comparisonEditorSequence}`;
}
function FieldError$2({ message }) {
  if (!message) return null;
  return /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, message);
}
function CopyablePromptCard({ eyebrow, title, description, prompt, onCopy }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, eyebrow), /* @__PURE__ */ React.createElement("h3", { className: "mt-1 text-base font-semibold text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, description) : null), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCopy, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy prompt")), /* @__PURE__ */ React.createElement("textarea", { readOnly: true, value: prompt, rows: 10, spellCheck: false, className: "mt-4 w-full rounded-2xl border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-300 outline-none" }));
}
function SectionCard$5({ id, eyebrow, title, description, actions, children, tone = "default", className = "", contentClassName = "" }) {
  const toneClass = tone === "feature" ? "bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] shadow-[0_24px_70px_rgba(2,6,23,0.28)]" : "bg-white/[0.03]";
  return /* @__PURE__ */ React.createElement("section", { id, className: `min-w-0 scroll-mt-24 rounded-[28px] border border-white/10 p-5 ${toneClass} ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/75" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, description) : null), actions ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, actions) : null), /* @__PURE__ */ React.createElement("div", { className: `mt-5 ${contentClassName}`.trim() }, children));
}
function EditorWorkspaceTabs({ tabs, activeTab, onChange, errorCounts }) {
  const activeMeta = tabs.find((tab2) => tab2.id === activeTab) || tabs[0];
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-4 z-20 rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(7,11,18,0.92),rgba(5,8,14,0.88))] px-3 py-3 shadow-[0_18px_50px_rgba(2,6,23,0.18)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2", role: "tablist", "aria-label": "Lesson editor sections" }, tabs.map((tab2) => {
    const isActive = tab2.id === activeTab;
    const errorCount = Number(errorCounts?.[tab2.id] || 0);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.id,
        type: "button",
        role: "tab",
        "aria-selected": isActive,
        "aria-controls": `lesson-editor-panel-${tab2.id}`,
        id: `lesson-editor-tab-${tab2.id}`,
        onClick: () => onChange(tab2.id),
        className: [
          "inline-flex items-center gap-2 rounded-2xl border px-4 py-2.5 text-sm font-semibold transition",
          isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-white/80 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} text-xs` }),
      /* @__PURE__ */ React.createElement("span", null, tab2.label),
      errorCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-rose-100" }, errorCount) : null
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center justify-between gap-3 px-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-400" }, activeMeta.description), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, activeMeta.sections.map((section) => /* @__PURE__ */ React.createElement("span", { key: section, className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, section.replace("lesson-", "").replace(/-/g, " "))))));
}
function firstLessonErrorTab(errors) {
  const firstKey = Object.keys(errors || {})[0];
  if (!firstKey) return null;
  if (firstKey.startsWith("blocks.")) return "blocks";
  return LESSON_FIELD_TAB_MAP[firstKey] || null;
}
function lessonTabErrorCounts(errors) {
  const counts = {};
  Object.keys(errors || {}).forEach((key) => {
    const tabId = key.startsWith("blocks.") ? "blocks" : LESSON_FIELD_TAB_MAP[key];
    if (!tabId) return;
    counts[tabId] = Number(counts[tabId] || 0) + 1;
  });
  return counts;
}
function firstErrorMessage$2(errors, fallback = "Please correct the highlighted fields and try again.") {
  const queue = [errors];
  while (queue.length > 0) {
    const current = queue.shift();
    if (typeof current === "string") {
      const message = current.trim();
      if (message) {
        return message;
      }
      continue;
    }
    if (Array.isArray(current)) {
      queue.push(...current);
      continue;
    }
    if (current && typeof current === "object") {
      queue.push(...Object.values(current));
    }
  }
  return fallback;
}
function TextField$2({ label, value, onChange, error, hint, ...rest }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("input", { value: value ?? "", onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", ...rest }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$2, { message: error }));
}
function TextAreaField$1({ label, value, onChange, error, rows = 4, hint }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("textarea", { value: value ?? "", onChange, rows, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$2, { message: error }));
}
function ToggleField$2({ label, checked, onChange, help, error }) {
  return /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer items-start gap-4 rounded-[28px] border px-5 py-4 transition ${checked ? "border-[#f39a24]/35 bg-[#f39a24]/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "sr-only" }), /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border text-sm transition ${checked ? "border-[#f39a24] bg-[#f39a24] text-white" : "border-white/10 bg-[#151a29] text-transparent"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check" })), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block text-base font-semibold tracking-[-0.02em] text-white" }, label), help ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-sm leading-6 text-slate-300" }, help) : null, /* @__PURE__ */ React.createElement(FieldError$2, { message: error })));
}
function formatMissingNumbers(values) {
  const items = Array.isArray(values) ? values.map((value) => Number(value)).filter((value) => Number.isInteger(value) && value > 0) : [];
  if (items.length === 0) return "No gaps right now.";
  return items.join(", ");
}
function formatCourseStep(orderNum) {
  const numeric = Number(orderNum);
  if (!Number.isFinite(numeric) || numeric < 0) return null;
  return `Step ${String(numeric + 1).padStart(2, "0")}`;
}
function normalizeCourseManagerLessons(lessons) {
  return (Array.isArray(lessons) ? [...lessons] : []).sort((left, right) => {
    const orderDiff = Number(left?.order_num || 0) - Number(right?.order_num || 0);
    if (orderDiff !== 0) return orderDiff;
    return Number(left?.id || 0) - Number(right?.id || 0);
  }).map((lesson, index2) => ({
    ...lesson,
    order_num: index2,
    display_order: index2 + 1
  }));
}
function reorderCourseManagerLessons(lessons, draggedLessonId, targetLessonId) {
  const current = normalizeCourseManagerLessons(lessons);
  const draggedIndex = current.findIndex((lesson) => Number(lesson.id) === Number(draggedLessonId));
  const targetIndex = current.findIndex((lesson) => Number(lesson.id) === Number(targetLessonId));
  if (draggedIndex === -1 || targetIndex === -1 || draggedIndex === targetIndex) {
    return current;
  }
  const nextLessons = [...current];
  const [draggedLesson] = nextLessons.splice(draggedIndex, 1);
  nextLessons.splice(targetIndex, 0, draggedLesson);
  return normalizeCourseManagerLessons(nextLessons);
}
function moveCourseManagerLesson(lessons, lessonId, direction) {
  const current = normalizeCourseManagerLessons(lessons);
  const lessonIndex = current.findIndex((lesson) => Number(lesson.id) === Number(lessonId));
  const nextIndex = lessonIndex + direction;
  if (lessonIndex === -1 || nextIndex < 0 || nextIndex >= current.length) {
    return current;
  }
  const nextLessons = [...current];
  const [movedLesson] = nextLessons.splice(lessonIndex, 1);
  nextLessons.splice(nextIndex, 0, movedLesson);
  return normalizeCourseManagerLessons(nextLessons);
}
function courseManagerSignature(lessons) {
  return JSON.stringify(normalizeCourseManagerLessons(lessons).map((lesson) => ({
    id: Number(lesson.id),
    order_num: Number(lesson.order_num || 0),
    section_id: lesson.section_id == null ? null : Number(lesson.section_id)
  })));
}
function slugifyLessonTitle(value) {
  return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 180);
}
function stripHtml$4(value) {
  return String(value || "").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
}
function stripMarkdown(value) {
  return String(value || "").replace(/```[\s\S]*?```/g, " ").replace(/`([^`]+)`/g, "$1").replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1").replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/^#{1,6}\s+/gm, "").replace(/^\s{0,3}>\s?/gm, "").replace(/^\s*([-*+]|\d+\.)\s+/gm, "").replace(/\*\*|__|\*|_|~~/g, "").replace(/^\s*\|/gm, " ").replace(/\|/g, " ").replace(/^\s*[-:]{3,}\s*$/gm, " ");
}
function convertLessonMarkdownToHtml(value) {
  const markdown = String(value || "").trim();
  if (!markdown) return "";
  return String(g$1.parse(markdown, {
    async: false,
    gfm: true,
    breaks: false
  }) || "").trim();
}
function convertLessonHtmlToMarkdown(value) {
  const html2 = String(value || "").trim();
  if (!html2) return "";
  if (!lessonMarkdownTurndown) {
    return stripHtml$4(html2);
  }
  return lessonMarkdownTurndown.turndown(html2).trim();
}
function countWords(value) {
  const text2 = stripMarkdown(stripHtml$4(value));
  return text2 ? text2.split(/\s+/).length : 0;
}
function normalizeCoverPreview(value, cdnBaseUrl) {
  const trimmed = String(value || "").trim();
  if (!trimmed) return "";
  if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) return trimmed;
  return `${String(cdnBaseUrl || "").replace(/\/$/, "")}/${trimmed.replace(/^\//, "")}`;
}
function normalizeCategoryValue(value) {
  if (value === "" || value == null) return "";
  return String(value);
}
function normalizeBoolean(value, fallback = false) {
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return value !== 0;
  const normalized = String(value || "").trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(normalized)) return true;
  if (["0", "false", "no", "off"].includes(normalized)) return false;
  return fallback;
}
const DEFAULT_AI_COMPARISON_TITLE = "Same Prompt, Different AI Models";
const DEFAULT_AI_COMPARISON_PAYLOAD = {
  title: DEFAULT_AI_COMPARISON_TITLE,
  intro: "We used the same prompt in multiple image generators to compare composition, mood, detail, and wallpaper quality.",
  prompt: "",
  negative_prompt: "",
  aspect_ratio: "16:9",
  criteria: ["Composition", "Lighting", "Wallpaper quality", "Prompt accuracy", "Detail quality"]
};
function normalizeCriteria(value) {
  return (Array.isArray(value) ? value : []).map((criterion) => String(criterion || "").trim()).filter(Boolean);
}
function normalizeComparisonResult(result, index2, cdnBaseUrl) {
  const imagePath = String(result?.image_path || "");
  const thumbPath = String(result?.thumb_path || "");
  return {
    client_key: result?.client_key || nextComparisonEditorKey("comparison-result"),
    id: result?.id ?? null,
    provider: String(result?.provider || ""),
    model_name: String(result?.model_name || ""),
    image_path: imagePath,
    image_url: String(result?.image_url || normalizeCoverPreview(imagePath, cdnBaseUrl) || ""),
    image_temp_path: String(result?.image_temp_path || ""),
    thumb_path: thumbPath,
    thumb_url: String(result?.thumb_url || normalizeCoverPreview(thumbPath, cdnBaseUrl) || ""),
    thumb_temp_path: String(result?.thumb_temp_path || ""),
    settings: String(result?.settings || ""),
    strengths: String(result?.strengths || ""),
    weaknesses: String(result?.weaknesses || ""),
    best_for: String(result?.best_for || ""),
    score: result?.score == null || result?.score === "" ? "" : Number(result.score),
    sort_order: Number(result?.sort_order ?? index2),
    active: normalizeBoolean(result?.active, true)
  };
}
function createEmptyComparisonResult(sortOrder = 0) {
  return normalizeComparisonResult({ sort_order: sortOrder, active: true }, sortOrder, "");
}
function normalizeComparisonBlock(block, index2, cdnBaseUrl) {
  const payload = block?.payload && typeof block.payload === "object" ? block.payload : {};
  return {
    client_key: block?.client_key || nextComparisonEditorKey("comparison-block"),
    id: block?.id ?? null,
    type: "ai_comparison",
    title: String(block?.title || payload?.title || DEFAULT_AI_COMPARISON_TITLE),
    payload: {
      ...DEFAULT_AI_COMPARISON_PAYLOAD,
      title: String(payload?.title || block?.title || DEFAULT_AI_COMPARISON_TITLE),
      intro: String(payload?.intro || ""),
      prompt: String(payload?.prompt || ""),
      negative_prompt: String(payload?.negative_prompt || ""),
      aspect_ratio: String(payload?.aspect_ratio || DEFAULT_AI_COMPARISON_PAYLOAD.aspect_ratio),
      criteria: normalizeCriteria(payload?.criteria || DEFAULT_AI_COMPARISON_PAYLOAD.criteria)
    },
    sort_order: Number(block?.sort_order ?? index2),
    active: normalizeBoolean(block?.active, true),
    comparison_results: (Array.isArray(block?.comparison_results) ? block.comparison_results : []).map((result, resultIndex) => normalizeComparisonResult(result, resultIndex, cdnBaseUrl))
  };
}
function createEmptyComparisonBlock(sortOrder = 0, cdnBaseUrl = "") {
  return normalizeComparisonBlock({
    title: DEFAULT_AI_COMPARISON_TITLE,
    payload: DEFAULT_AI_COMPARISON_PAYLOAD,
    sort_order: sortOrder,
    active: true,
    comparison_results: []
  }, sortOrder, cdnBaseUrl);
}
function normalizeComparisonBlocks(blocks, cdnBaseUrl) {
  return (Array.isArray(blocks) ? blocks : []).filter((block) => String(block?.type || "ai_comparison") === "ai_comparison").map((block, index2) => normalizeComparisonBlock(block, index2, cdnBaseUrl));
}
function serializeComparisonBlocks(blocks) {
  return (Array.isArray(blocks) ? blocks : []).map((block, index2) => ({
    id: block.id || void 0,
    type: "ai_comparison",
    title: String(block.title || block.payload?.title || DEFAULT_AI_COMPARISON_TITLE),
    payload: {
      title: String(block.payload?.title || block.title || DEFAULT_AI_COMPARISON_TITLE),
      intro: String(block.payload?.intro || ""),
      prompt: String(block.payload?.prompt || ""),
      negative_prompt: String(block.payload?.negative_prompt || ""),
      aspect_ratio: String(block.payload?.aspect_ratio || ""),
      criteria: normalizeCriteria(block.payload?.criteria || [])
    },
    sort_order: Number(block.sort_order ?? index2),
    active: Boolean(block.active),
    comparison_results: (Array.isArray(block.comparison_results) ? block.comparison_results : []).map((result, resultIndex) => ({
      id: result.id || void 0,
      provider: String(result.provider || ""),
      model_name: String(result.model_name || ""),
      image_path: String(result.image_path || ""),
      thumb_path: String(result.thumb_path || ""),
      settings: String(result.settings || ""),
      strengths: String(result.strengths || ""),
      weaknesses: String(result.weaknesses || ""),
      best_for: String(result.best_for || ""),
      score: result.score === "" || result.score == null ? null : Number(result.score),
      sort_order: Number(result.sort_order ?? resultIndex),
      active: Boolean(result.active)
    }))
  }));
}
function getFormError(errors, path) {
  return errors?.[path] || "";
}
function buildLessonPayload(data) {
  return {
    category_id: data.category_id === "" || data.category_id == null ? null : Number(data.category_id),
    title: String(data.title || ""),
    slug: String(data.slug || ""),
    lesson_number: data.lesson_number === "" || data.lesson_number == null ? "" : Number(data.lesson_number),
    course_order: data.course_order === "" || data.course_order == null ? "" : Number(data.course_order),
    course_ids: Array.isArray(data.course_ids) ? data.course_ids.map((courseId) => Number(courseId)).filter((courseId) => Number.isInteger(courseId) && courseId > 0) : [],
    series_name: String(data.series_name || ""),
    excerpt: String(data.excerpt || ""),
    content: String(data.content || ""),
    content_markdown: String(data.content_markdown || ""),
    content_source: String(data.content_source || "html"),
    difficulty: String(data.difficulty || ""),
    access_level: String(data.access_level || ""),
    lesson_type: String(data.lesson_type || ""),
    cover_image: String(data.cover_image || ""),
    article_cover_image: String(data.article_cover_image || ""),
    tags: String(data.tags || ""),
    video_url: String(data.video_url || ""),
    reading_minutes: data.reading_minutes === "" || data.reading_minutes == null ? "" : Number(data.reading_minutes),
    published_at: data.published_at || "",
    seo_title: String(data.seo_title || ""),
    seo_description: String(data.seo_description || ""),
    featured: Boolean(data.featured),
    active: Boolean(data.active),
    blocks: serializeComparisonBlocks(data.blocks)
  };
}
function parseLessonImport(rawText, categoryOptions) {
  let parsed;
  try {
    parsed = JSON.parse(String(rawText || ""));
  } catch {
    throw new Error("Could not parse JSON.");
  }
  if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
    throw new Error("Import JSON must be an object.");
  }
  const next = {};
  const applied = [];
  const apply = (key, value) => {
    next[key] = value;
    applied.push(key);
  };
  if (parsed.title != null) apply("title", String(parsed.title));
  if (parsed.slug != null) apply("slug", String(parsed.slug));
  if (parsed.lesson_number != null) apply("lesson_number", String(parsed.lesson_number));
  if (parsed.course_order != null) apply("course_order", String(parsed.course_order));
  if (parsed.series_name != null) apply("series_name", String(parsed.series_name));
  if (parsed.excerpt != null) apply("excerpt", String(parsed.excerpt));
  if (parsed.content_markdown != null) apply("content_markdown", String(parsed.content_markdown));
  if (parsed.markdown != null && parsed.content_markdown == null) apply("content_markdown", String(parsed.markdown));
  if (parsed.md != null && parsed.content_markdown == null && parsed.markdown == null) apply("content_markdown", String(parsed.md));
  if (parsed.content != null) apply("content", String(parsed.content));
  if (parsed.body != null && parsed.content == null) apply("content", String(parsed.body));
  if (parsed.html != null && parsed.content == null && parsed.body == null) apply("content", String(parsed.html));
  if (parsed.difficulty != null) apply("difficulty", String(parsed.difficulty));
  if (parsed.access_level != null) apply("access_level", String(parsed.access_level));
  if (parsed.access != null && parsed.access_level == null) apply("access_level", String(parsed.access));
  if (parsed.lesson_type != null) apply("lesson_type", String(parsed.lesson_type));
  if (parsed.type != null && parsed.lesson_type == null) apply("lesson_type", String(parsed.type));
  if (parsed.cover_image != null) apply("cover_image", String(parsed.cover_image));
  if (parsed.cover != null && parsed.cover_image == null) apply("cover_image", String(parsed.cover));
  if (parsed.cover_url != null && parsed.cover_image == null && parsed.cover == null) apply("cover_image", String(parsed.cover_url));
  if (parsed.article_cover_image != null) apply("article_cover_image", String(parsed.article_cover_image));
  if (parsed.article_cover != null && parsed.article_cover_image == null) apply("article_cover_image", String(parsed.article_cover));
  if (parsed.article_cover_url != null && parsed.article_cover_image == null && parsed.article_cover == null) apply("article_cover_image", String(parsed.article_cover_url));
  if (parsed.tags != null) apply("tags", Array.isArray(parsed.tags) ? parsed.tags.join(", ") : String(parsed.tags));
  if (parsed.video_url != null) apply("video_url", String(parsed.video_url));
  if (parsed.reading_minutes != null) apply("reading_minutes", String(parsed.reading_minutes));
  if (parsed.published_at != null) apply("published_at", String(parsed.published_at));
  if (parsed.seo_title != null) apply("seo_title", String(parsed.seo_title));
  if (parsed.seo_description != null) apply("seo_description", String(parsed.seo_description));
  if (parsed.featured != null) apply("featured", normalizeBoolean(parsed.featured));
  if (parsed.active != null) apply("active", normalizeBoolean(parsed.active, true));
  if (parsed.category_id != null || parsed.category_slug != null || parsed.category != null) {
    const requested = String(parsed.category_id ?? parsed.category_slug ?? parsed.category).trim().toLowerCase();
    const match = (Array.isArray(categoryOptions) ? categoryOptions : []).find((option) => [option.id, option.value, option.slug, option.name, option.label].filter((candidate) => candidate != null).map((candidate) => String(candidate).trim().toLowerCase()).includes(requested));
    if (match) {
      apply("category_id", String(match.id ?? match.value ?? ""));
    }
  }
  if (applied.length === 0) {
    throw new Error("The JSON did not contain any recognized lesson fields.");
  }
  return { next, applied };
}
function buildLessonImportExample({ title, excerpt, difficulty, accessLevel, lessonType, categoryName }) {
  const nextTitle = String(title || "").trim() || "How to Build Cleaner Prompt References";
  const nextExcerpt = String(excerpt || "").trim() || "Build a lesson draft with a clear promise, practical steps, and reusable examples.";
  return JSON.stringify({
    title: nextTitle,
    slug: slugifyLessonTitle(nextTitle),
    excerpt: nextExcerpt,
    category: String(categoryName || "").trim() || "Prompting",
    difficulty: String(difficulty || "").trim() || "beginner",
    access_level: String(accessLevel || "").trim() || "free",
    lesson_type: String(lessonType || "").trim() || "article",
    tags: ["prompting", "workflow", "editing"],
    content_markdown: [
      "# Why this lesson matters",
      "",
      "Open with the promise of the lesson and the result the reader should get.",
      "",
      "## Core workflow",
      "",
      "- Step 1: Define the goal clearly.",
      "- Step 2: Show the pattern or framework.",
      "- Step 3: Add one concrete example.",
      "",
      "## Wrap up",
      "",
      "Close with the next action or checklist the reader should follow."
    ].join("\n"),
    reading_minutes: 8,
    seo_title: nextTitle,
    seo_description: nextExcerpt,
    active: false
  }, null, 2);
}
function buildLessonImportPrompt({ title, difficulty, accessLevel, lessonType, categoryName }) {
  return [
    "Create valid JSON only for a Skinbase Academy lesson import.",
    "Do not wrap the answer in markdown fences.",
    "Return one object with this shape:",
    "{",
    '  "title": "Lesson title",',
    '  "slug": "lesson-title",',
    '  "excerpt": "One short summary sentence.",',
    `  "category": "${String(categoryName || "Prompting")}",`,
    `  "difficulty": "${String(difficulty || "beginner")}",`,
    `  "access_level": "${String(accessLevel || "free")}",`,
    `  "lesson_type": "${String(lessonType || "article")}",`,
    '  "tags": ["tag-one", "tag-two"],',
    '  "content_markdown": "# Heading\\n\\nWrite the lesson body in Markdown.",',
    '  "reading_minutes": 8,',
    '  "seo_title": "Optional SEO title",',
    '  "seo_description": "Optional SEO description",',
    '  "active": false',
    "}",
    "Requirements:",
    "- Keep the response as valid JSON only.",
    "- Prefer content_markdown over HTML unless HTML is explicitly requested.",
    "- Keep excerpt concise and specific.",
    "- Keep tags short and relevant.",
    "- Use lowercase hyphenated slugs.",
    "- Do not invent image URLs unless source assets are provided.",
    `Current lesson title: ${String(title || "Untitled lesson")}`
  ].join("\n");
}
function buildLessonHeroPrompt({ title, excerpt, categoryName, tags = [] }) {
  return [
    "Create a wide hero cover image for a Skinbase Academy lesson.",
    `Lesson title: ${String(title || "Untitled lesson")}`,
    `Lesson summary: ${String(excerpt || "No summary added yet.")}`,
    `Category: ${String(categoryName || "Uncategorized")}`,
    `Tags: ${tags.length > 0 ? tags.join(", ") : "none"}`,
    "",
    "Aspect ratio: 16:9 landscape.",
    "Style: cinematic editorial artwork with premium lighting, a strong focal point, and a clean composition that still reads well when cropped into cards and previews.",
    "Text rules: no added text, no captions, no logos, no watermarks, and no visible UI.",
    "Composition: keep the center readable and leave safe space for future cropping.",
    "Output: a single final image prompt, not a report."
  ].join("\n");
}
function buildLessonArticleCoverPrompt({ courseName, lessonNumber, title, excerpt, categoryName, tags = [], aspectRatio = "3:2", mainVisualSubject, previewImageDescription }) {
  return [
    "Create a premium Skinbase Academy inline article cover image.",
    "",
    `Course name: ${String(courseName || "Unassigned")}`,
    `Lesson number: ${String(lessonNumber || "1")}`,
    `Lesson title: ${String(title || "Untitled lesson")}`,
    `Lesson summary: ${String(excerpt || "No summary added yet.")}`,
    `Category: ${String(categoryName || "Uncategorized")}`,
    `Tags: ${tags.length > 0 ? tags.join(", ") : "none"}`,
    "",
    `Aspect ratio: ${String(aspectRatio || "3:2")}, landscape article-cover format.`,
    "",
    "Visual direction:",
    "Design a polished dark editorial academy cover inspired by a modern creative-tech learning interface. The layout should feel like a premium lesson card for an online academy article.",
    "",
    "Composition:",
    "Use a strong two-column layout.",
    "Left side: large lesson-title area, lesson badge, short summary area, and a row of small educational icon blocks.",
    "Right side: a large cinematic preview image inside a rounded rectangular frame, showing the lesson concept visually.",
    "Below or near the preview image: add a subtle prompt/workflow card with abstract lines and interface-like blocks.",
    "Bottom area: add a clean row of small learning-step modules or icon cards.",
    "",
    "Main visual subject:",
    String(mainVisualSubject || `A premium editorial visual focused on ${String(title || "this lesson")}`),
    "",
    "The right preview image should show:",
    String(previewImageDescription || `A cinematic article-cover scene that clearly supports ${String(title || "the lesson topic")} and feels premium at thumbnail size.`),
    "",
    "Educational UI details:",
    "Include subtle composition guide lines, crop guides, small abstract icons, prompt-card shapes, clean rounded panels, soft glows, and thin purple outlines. Make the design feel structured, modern, and readable.",
    "",
    "Style:",
    "Dark modern Skinbase Academy aesthetic, polished editorial design, premium creative-tech interface, cinematic digital art, clean hierarchy, soft shadows, rounded cards, subtle grid background, elegant purple/cyan accents, high-end course-platform look.",
    "",
    "Color palette:",
    "Deep navy, black, dark violet, purple gradients, muted cyan highlights, soft white typography areas, warm cinematic orange/gold highlights inside the preview artwork.",
    "",
    "Text handling:",
    "Use clean title-like placeholder text areas only. Do not create messy fake text. Keep typography areas visually readable and leave enough space for real text to be added later. Avoid small unreadable paragraphs.",
    "",
    "Important:",
    "No logos, no watermarks, no brand marks, no fake signatures, no cluttered UI, no distorted icons, no random letters, no overcrowded composition. The cover must work as an inline article image and still be clear at thumbnail size."
  ].join("\n");
}
function JsonImportDialog$1({ open, value, error, exampleValue, promptValue, onChange, onClose, onApply, onCopyExample, onCopyPrompt }) {
  const backdropRef = reactExports.useRef(null);
  const [activeReferenceTab, setActiveReferenceTab] = reactExports.useState("structure");
  reactExports.useEffect(() => {
    if (open) {
      setActiveReferenceTab("structure");
    }
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-start justify-center overflow-y-auto bg-[#04070dcc] px-4 py-4 backdrop-blur-md sm:items-center sm:px-6 sm:py-6",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex max-h-[calc(100vh-2rem)] w-full max-w-6xl flex-col overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)] sm:max-h-[calc(100vh-3rem)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Structured Import"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Paste lesson JSON"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Use this to seed the lesson form with structured content before you refine it in the editor.")), /* @__PURE__ */ React.createElement("div", { className: "min-h-0 flex-1 overflow-y-auto" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 px-6 py-5 xl:grid-cols-[minmax(0,1.1fr)_minmax(320px,0.9fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
        "textarea",
        {
          value,
          onChange: (event) => onChange?.(event.target.value),
          rows: 16,
          placeholder: exampleValue,
          className: "min-h-[320px] rounded-[24px] border border-white/10 bg-slate-950/80 px-4 py-4 font-mono text-sm leading-6 text-slate-100 outline-none"
        }
      ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "grid content-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2", role: "tablist", "aria-label": "Lesson import reference panels" }, [
        { id: "structure", label: "Structure", icon: "fa-brackets-curly" },
        { id: "fields", label: "Fields", icon: "fa-table-columns" },
        { id: "prompt", label: "Prompt", icon: "fa-wand-magic-sparkles" },
        { id: "notes", label: "Notes", icon: "fa-list-check" }
      ].map((tab2) => {
        const isActive = tab2.id === activeReferenceTab;
        return /* @__PURE__ */ React.createElement(
          "button",
          {
            key: tab2.id,
            type: "button",
            role: "tab",
            "aria-selected": isActive,
            onClick: () => setActiveReferenceTab(tab2.id),
            className: [
              "inline-flex items-center gap-2 rounded-2xl border px-3.5 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition",
              isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-slate-400 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
            ].join(" ")
          },
          /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} text-[10px]` }),
          /* @__PURE__ */ React.createElement("span", null, tab2.label)
        );
      })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-[20px] border border-white/10 bg-slate-950/50 p-4 text-sm text-slate-300" }, activeReferenceTab === "structure" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Accepted structure"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCopyExample, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy example")), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 max-h-[360px] overflow-auto rounded-2xl border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-300" }, exampleValue)) : null, activeReferenceTab === "fields" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Accepted keys"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-3 text-slate-400 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Core"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6" }, "title, slug, excerpt"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "lesson_number, course_order, series_name"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "difficulty, access_level, lesson_type"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "reading_minutes, published_at")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Body"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6" }, "content_markdown, markdown, md"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "content, body, html"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "tags, video_url")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Taxonomy"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6" }, "category_id, category_slug, category"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "featured, active")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Media + SEO"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6" }, "cover_image, cover, cover_url"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "article_cover_image, article_cover, article_cover_url"), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6" }, "seo_title, seo_description")))) : null, activeReferenceTab === "prompt" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "ChatGPT helper prompt"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCopyPrompt, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy prompt")), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 max-h-[360px] overflow-auto rounded-2xl border border-white/10 bg-slate-950/70 p-3 text-xs leading-6 text-slate-300 whitespace-pre-wrap" }, promptValue)) : null, activeReferenceTab === "notes" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "What gets applied"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "The JSON updates only recognized lesson fields already supported by the editor."), /* @__PURE__ */ React.createElement("p", null, "Markdown import updates both the Markdown source and rendered HTML body."), /* @__PURE__ */ React.createElement("p", null, "Category values can match by id, slug, or visible category name."), /* @__PURE__ */ React.createElement("p", null, "Imported values become editable immediately before you save the lesson."))) : null))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClose?.(), className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApply?.(), className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110" }, "Apply JSON")))
    ),
    document.body
  );
}
function MarkdownImportDialog({ open, value, error, onChange, onClose, onApply }) {
  const backdropRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-4xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Markdown Import"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Paste lesson Markdown"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Paste Markdown here and apply it to regenerate the lesson HTML. This overwrites the current article body.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 px-6 py-5 xl:grid-cols-[minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
        "textarea",
        {
          value,
          onChange: (event) => onChange?.(event.target.value),
          rows: 18,
          placeholder: "## Introduction\n\nPaste Markdown here to regenerate the lesson body.",
          spellCheck: false,
          className: "rounded-[24px] border border-white/10 bg-slate-950/80 px-4 py-4 font-mono text-sm leading-6 text-slate-100 outline-none"
        }
      ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Result"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "The Markdown is stored in ", /* @__PURE__ */ React.createElement("span", { className: "font-mono text-slate-200" }, "content_markdown"), "."), /* @__PURE__ */ React.createElement("p", null, "The HTML editor is regenerated from it."), /* @__PURE__ */ React.createElement("p", null, "The visual lesson preview updates immediately."), /* @__PURE__ */ React.createElement("p", null, "Use the HTML button inside the editor for source-level HTML edits.")))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClose?.(), className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApply?.(), className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110" }, "Apply Markdown")))
    ),
    document.body
  );
}
function LessonEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext = {} }) {
  const recordContentMarkdown = String(record.content_markdown || "");
  String(record.content || "");
  const cdnBaseUrl = editorContext.coverCdnBaseUrl || "";
  const initialContentMarkdown = recordContentMarkdown.trim() !== "" ? recordContentMarkdown : "";
  const form = G$1({
    ...record,
    content: String(record.content || convertLessonMarkdownToHtml(initialContentMarkdown) || ""),
    content_markdown: initialContentMarkdown,
    content_source: recordContentMarkdown.trim() !== "" ? "markdown" : "html",
    lesson_number: record.lesson_number === "" || record.lesson_number == null ? "" : String(record.lesson_number),
    course_order: record.course_order === "" || record.course_order == null ? "" : String(record.course_order),
    series_name: String(record.series_name || ""),
    article_cover_image: String(record.article_cover_image || ""),
    course_ids: Array.isArray(record.course_ids) ? record.course_ids.map((courseId) => String(courseId)) : [],
    tags: String(record.tags || ""),
    category_id: normalizeCategoryValue(record.category_id),
    blocks: normalizeComparisonBlocks(record.blocks, cdnBaseUrl)
  });
  const [coverPreviewUrl, setCoverPreviewUrl] = reactExports.useState(record.cover_image_url || normalizeCoverPreview(record.cover_image, editorContext.coverCdnBaseUrl));
  const [stagedCoverPath, setStagedCoverPath] = reactExports.useState("");
  const [articleCoverPreviewUrl, setArticleCoverPreviewUrl] = reactExports.useState(record.article_cover_image_url || normalizeCoverPreview(record.article_cover_image, editorContext.coverCdnBaseUrl));
  const [stagedArticleCoverPath, setStagedArticleCoverPath] = reactExports.useState("");
  const [categories, setCategories] = reactExports.useState(Array.isArray(editorContext.categories) ? editorContext.categories : []);
  const [jsonImportOpen, setJsonImportOpen] = reactExports.useState(false);
  const [jsonImportValue, setJsonImportValue] = reactExports.useState("");
  const [jsonImportError, setJsonImportError] = reactExports.useState("");
  const [markdownImportOpen, setMarkdownImportOpen] = reactExports.useState(false);
  const [markdownImportValue, setMarkdownImportValue] = reactExports.useState("");
  const [markdownImportError, setMarkdownImportError] = reactExports.useState("");
  const [categoryError, setCategoryError] = reactExports.useState("");
  const [categorySaving, setCategorySaving] = reactExports.useState(false);
  const [isBrowserFullscreen, setIsBrowserFullscreen] = reactExports.useState(() => typeof document !== "undefined" && Boolean(document.fullscreenElement));
  const [isEditorFullHeight, setIsEditorFullHeight] = reactExports.useState(false);
  const [activeTab, setActiveTab] = reactExports.useState("write");
  const [categoryDraft, setCategoryDraft] = reactExports.useState({ type: "lesson", name: "", slug: "", description: "", order_num: 0, active: true });
  const slugTouchedRef = reactExports.useRef(Boolean(String(record.slug || "").trim()));
  const lessonNumberAutofillRef = reactExports.useRef(false);
  const courseOrderAutofillRef = reactExports.useRef(false);
  const difficultyField = reactExports.useMemo(() => getField$1(fields, "difficulty"), [fields]);
  const accessField = reactExports.useMemo(() => getField$1(fields, "access_level"), [fields]);
  const bodyWordCount = reactExports.useMemo(() => countWords(form.data.content_markdown || form.data.content), [form.data.content, form.data.content_markdown]);
  const estimatedReadingMinutes = reactExports.useMemo(() => Math.max(1, Math.ceil(bodyWordCount / 180)), [bodyWordCount]);
  const excerptLength = String(form.data.excerpt || "").length;
  const deferredArticlePreviewHtml = reactExports.useDeferredValue(form.data.content || "");
  const tabErrorCounts = reactExports.useMemo(() => lessonTabErrorCounts(form.errors), [form.errors]);
  const numberingContext = reactExports.useMemo(() => editorContext.numbering || {}, [editorContext.numbering]);
  const courseOptions = reactExports.useMemo(() => Array.isArray(editorContext.courses) ? editorContext.courses : [], [editorContext.courses]);
  const selectedCourses = reactExports.useMemo(() => {
    const selectedIds = new Set((Array.isArray(form.data.course_ids) ? form.data.course_ids : []).map((courseId) => String(courseId)));
    return courseOptions.filter((course) => selectedIds.has(String(course.value)));
  }, [courseOptions, form.data.course_ids]);
  const currentLessonId = reactExports.useMemo(() => Number(editorContext.currentLessonId || 0), [editorContext.currentLessonId]);
  const [courseManagerDrafts, setCourseManagerDrafts] = reactExports.useState({});
  const [draggedCourseLesson, setDraggedCourseLesson] = reactExports.useState(null);
  const [courseSaveProcessing, setCourseSaveProcessing] = reactExports.useState({});
  const revisions = reactExports.useMemo(() => Array.isArray(editorContext.revisions) ? editorContext.revisions : [], [editorContext.revisions]);
  const [revisionFieldSelections, setRevisionFieldSelections] = reactExports.useState({});
  const [toast, setToast] = reactExports.useState({ id: 0, visible: false, message: "", variant: "success" });
  const csrfToken2 = reactExports.useMemo(() => {
    if (typeof document === "undefined") return "";
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
  }, []);
  const showToast = (message, variant = "error") => {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant
    });
  };
  const handleMarkdownContentChange = (nextMarkdown) => {
    const nextHtml = convertLessonMarkdownToHtml(nextMarkdown);
    reactExports.startTransition(() => {
      form.setData("content_source", "markdown");
      form.setData("content_markdown", nextMarkdown);
      form.setData("content", nextHtml);
    });
  };
  const handleRichContentChange = (nextHtml) => {
    reactExports.startTransition(() => {
      form.setData("content", nextHtml);
      if (form.data.content_source === "markdown") {
        if (!lessonMarkdownTurndown) {
          form.setData("content_source", "html");
          form.setData("content_markdown", "");
          return;
        }
        form.setData("content_markdown", convertLessonHtmlToMarkdown(nextHtml));
        return;
      }
      form.setData("content_markdown", "");
    });
  };
  reactExports.useEffect(() => {
    void loadLessonMarkdownTurndown();
  }, []);
  reactExports.useEffect(() => {
    if (slugTouchedRef.current) return;
    form.setData("slug", slugifyLessonTitle(form.data.title));
  }, [form.data.title]);
  reactExports.useEffect(() => {
    if (typeof document === "undefined") return void 0;
    const handleFullscreenChange = () => {
      setIsBrowserFullscreen(Boolean(document.fullscreenElement));
    };
    document.addEventListener("fullscreenchange", handleFullscreenChange);
    return () => document.removeEventListener("fullscreenchange", handleFullscreenChange);
  }, []);
  reactExports.useEffect(() => {
    if (typeof document === "undefined") return void 0;
    const previousOverflow = document.body.style.overflow;
    if (isEditorFullHeight) {
      document.body.style.overflow = "hidden";
    }
    return () => {
      document.body.style.overflow = previousOverflow;
    };
  }, [isEditorFullHeight]);
  reactExports.useEffect(() => {
    const nextTab = firstLessonErrorTab(form.errors);
    if (!nextTab) return;
    setActiveTab(nextTab);
  }, [form.errors]);
  reactExports.useEffect(() => {
    setCourseManagerDrafts(Object.fromEntries(selectedCourses.map((course) => [String(course.value), normalizeCourseManagerLessons(course.lessons)])));
  }, [selectedCourses]);
  const categoryOptions = reactExports.useMemo(() => {
    const next = categories.map((category) => ({ value: String(category.id), label: category.name }));
    return [{ value: "", label: "No category" }, ...next];
  }, [categories]);
  const selectedCategoryName = reactExports.useMemo(() => {
    const selectedId = String(form.data.category_id || "").trim();
    if (!selectedId) return "";
    const match = categories.find((category) => String(category.id) === selectedId);
    return match ? String(match.name || "") : "";
  }, [categories, form.data.category_id]);
  const jsonImportExampleValue = reactExports.useMemo(() => buildLessonImportExample({
    title: form.data.title,
    excerpt: form.data.excerpt,
    difficulty: form.data.difficulty,
    accessLevel: form.data.access_level,
    lessonType: form.data.lesson_type,
    categoryName: selectedCategoryName
  }), [form.data.access_level, form.data.difficulty, form.data.excerpt, form.data.lesson_type, form.data.title, selectedCategoryName]);
  const jsonImportPromptValue = reactExports.useMemo(() => buildLessonImportPrompt({
    title: form.data.title,
    difficulty: form.data.difficulty,
    accessLevel: form.data.access_level,
    lessonType: form.data.lesson_type,
    categoryName: selectedCategoryName
  }), [form.data.access_level, form.data.difficulty, form.data.lesson_type, form.data.title, selectedCategoryName]);
  const selectedCourseName = reactExports.useMemo(() => selectedCourses[0]?.label || "Unassigned", [selectedCourses]);
  const lessonNumberValue = reactExports.useMemo(() => {
    const numeric = Number(form.data.lesson_number);
    if (Number.isFinite(numeric) && numeric > 0) return String(numeric);
    const suggested = Number(numberingContext?.lesson_number?.suggested || 0);
    if (Number.isFinite(suggested) && suggested > 0) return String(suggested);
    return "1";
  }, [form.data.lesson_number, numberingContext]);
  const lessonHeroPromptValue = reactExports.useMemo(() => buildLessonHeroPrompt({
    title: form.data.title,
    excerpt: form.data.excerpt,
    categoryName: selectedCategoryName,
    tags: String(form.data.tags || "").split(",").map((tag) => tag.trim()).filter(Boolean)
  }), [form.data.excerpt, form.data.tags, form.data.title, selectedCategoryName]);
  const lessonArticleCoverPromptValue = reactExports.useMemo(() => buildLessonArticleCoverPrompt({
    courseName: selectedCourseName,
    lessonNumber: lessonNumberValue,
    title: form.data.title,
    excerpt: form.data.excerpt,
    categoryName: selectedCategoryName,
    tags: String(form.data.tags || "").split(",").map((tag) => tag.trim()).filter(Boolean),
    aspectRatio: "3:2",
    mainVisualSubject: `A premium editorial visual focused on ${String(form.data.title || "this lesson")}`,
    previewImageDescription: `A cinematic article-cover scene that clearly supports ${String(form.data.title || "the lesson topic")} and feels premium at thumbnail size.`
  }), [form.data.excerpt, form.data.tags, form.data.title, lessonNumberValue, selectedCategoryName, selectedCourseName]);
  const lessonHeaderNumberLabel = reactExports.useMemo(() => {
    const numeric = Number(form.data.lesson_number);
    if (!Number.isFinite(numeric) || numeric < 1) {
      return "Unnumbered";
    }
    return `Lesson ${String(numeric).padStart(2, "0")}`;
  }, [form.data.lesson_number]);
  reactExports.useEffect(() => {
    if (method !== "post" || lessonNumberAutofillRef.current) return;
    if (String(form.data.lesson_number || "").trim() !== "") return;
    const suggested = Number(numberingContext?.lesson_number?.suggested || 0);
    if (!Number.isInteger(suggested) || suggested < 1) return;
    lessonNumberAutofillRef.current = true;
    form.setData("lesson_number", String(suggested));
  }, [form, form.data.lesson_number, method, numberingContext]);
  reactExports.useEffect(() => {
    if (method !== "post" || courseOrderAutofillRef.current) return;
    if (String(form.data.course_order || "").trim() !== "") return;
    const suggested = Number(numberingContext?.course_order?.suggested || 0);
    if (!Number.isInteger(suggested) || suggested < 1) return;
    courseOrderAutofillRef.current = true;
    form.setData("course_order", String(suggested));
  }, [form, form.data.course_order, method, numberingContext]);
  reactExports.useEffect(() => {
    const nextValue = String(estimatedReadingMinutes);
    if (String(form.data.reading_minutes || "") === nextValue) return;
    form.setData("reading_minutes", nextValue);
  }, [estimatedReadingMinutes, form, form.data.reading_minutes]);
  const handleManualCoverChange = (nextValue) => {
    form.setData("cover_image", nextValue);
    setCoverPreviewUrl(normalizeCoverPreview(nextValue, editorContext.coverCdnBaseUrl));
  };
  const handleManualArticleCoverChange = (nextValue) => {
    form.setData("article_cover_image", nextValue);
    setArticleCoverPreviewUrl(normalizeCoverPreview(nextValue, editorContext.coverCdnBaseUrl));
  };
  const updateBlocks = (updater) => {
    const currentBlocks = Array.isArray(form.data.blocks) ? form.data.blocks : [];
    const nextBlocks = typeof updater === "function" ? updater(currentBlocks) : updater;
    form.setData("blocks", nextBlocks);
  };
  const updateBlock = (blockKey, updater) => {
    updateBlocks((currentBlocks) => currentBlocks.map((block) => block.client_key === blockKey ? updater(block) : block));
  };
  const removeBlock = (blockKey) => {
    updateBlocks((currentBlocks) => currentBlocks.filter((block) => block.client_key !== blockKey));
  };
  const addComparisonBlock = () => {
    updateBlocks((currentBlocks) => [
      ...currentBlocks,
      createEmptyComparisonBlock(currentBlocks.length, cdnBaseUrl)
    ]);
  };
  const addComparisonResult = (blockKey) => {
    updateBlock(blockKey, (block) => ({
      ...block,
      comparison_results: [
        ...Array.isArray(block.comparison_results) ? block.comparison_results : [],
        createEmptyComparisonResult(Array.isArray(block.comparison_results) ? block.comparison_results.length : 0)
      ]
    }));
  };
  const updateComparisonResult = (blockKey, resultKey, updater) => {
    updateBlock(blockKey, (block) => ({
      ...block,
      comparison_results: (Array.isArray(block.comparison_results) ? block.comparison_results : []).map((result) => result.client_key === resultKey ? updater(result) : result)
    }));
  };
  const removeComparisonResult = (blockKey, resultKey) => {
    updateBlock(blockKey, (block) => ({
      ...block,
      comparison_results: (Array.isArray(block.comparison_results) ? block.comparison_results : []).filter((result) => result.client_key !== resultKey)
    }));
  };
  const submit = (event) => {
    event.preventDefault();
    const payload = buildLessonPayload(form.data);
    form.transform(() => payload);
    const submitOptions = {
      preserveScroll: true,
      onError: (errors) => {
        const nextTab = firstLessonErrorTab(errors);
        if (nextTab) {
          setActiveTab(nextTab);
        }
        showToast(firstErrorMessage$2(errors), "error");
      },
      onFinish: () => form.transform((data) => data)
    };
    if (method === "patch") {
      form.patch(submitUrl, submitOptions);
      return;
    }
    form.post(submitUrl, submitOptions);
  };
  const deleteLesson = () => {
    if (!destroyUrl) return;
    if (!window.confirm("Delete this lesson?")) return;
    At.delete(destroyUrl);
  };
  const updateCourseDraft = (courseId, nextLessons) => {
    setCourseManagerDrafts((current) => ({
      ...current,
      [String(courseId)]: normalizeCourseManagerLessons(nextLessons)
    }));
  };
  const attachLessonToCourseNow = (course) => {
    if (!currentLessonId) return;
    At.post(course.attach_url, {
      lesson_id: currentLessonId,
      order_num: Number(course.next_order_num || 0),
      is_required: true
    }, {
      preserveScroll: true,
      onSuccess: () => form.setData("course_ids", Array.from(/* @__PURE__ */ new Set([...Array.isArray(form.data.course_ids) ? form.data.course_ids : [], String(course.value)])))
    });
  };
  const detachLessonFromCourseNow = (course, courseLesson) => {
    At.delete(courseLesson.destroy_url, {
      preserveScroll: true,
      onSuccess: () => form.setData("course_ids", (Array.isArray(form.data.course_ids) ? form.data.course_ids : []).filter((courseId) => String(courseId) !== String(course.value)))
    });
  };
  const saveCourseDraftOrder = (course) => {
    const nextLessons = normalizeCourseManagerLessons(courseManagerDrafts[String(course.value)] || course.lessons);
    setCourseSaveProcessing((current) => ({ ...current, [String(course.value)]: true }));
    At.patch(course.reorder_url, {
      sections: [],
      lessons: nextLessons.map((lesson) => ({
        id: lesson.id,
        order_num: lesson.order_num,
        section_id: lesson.section_id
      }))
    }, {
      preserveScroll: true,
      onFinish: () => setCourseSaveProcessing((current) => ({ ...current, [String(course.value)]: false }))
    });
  };
  const applyJsonImport = () => {
    try {
      const parsed = parseLessonImport(jsonImportValue, categories);
      Object.entries(parsed.next).forEach(([key, value]) => {
        if (key === "content_markdown") {
          handleMarkdownContentChange(String(value || ""));
          return;
        }
        if (key === "content") {
          handleRichContentChange(String(value || ""));
          return;
        }
        form.setData(key, value);
      });
      if (parsed.next.cover_image != null) {
        handleManualCoverChange(String(parsed.next.cover_image || ""));
      }
      if (parsed.next.slug != null) {
        slugTouchedRef.current = true;
      }
      setJsonImportError("");
      setJsonImportOpen(false);
    } catch (error) {
      setJsonImportError(error instanceof Error ? error.message : "Could not parse JSON.");
    }
  };
  const openMarkdownImport = () => {
    setMarkdownImportValue(String(form.data.content_markdown || ""));
    setMarkdownImportError("");
    setMarkdownImportOpen(true);
  };
  const applyMarkdownImport = () => {
    const nextMarkdown = String(markdownImportValue || "").trim();
    if (nextMarkdown === "") {
      setMarkdownImportError("Paste Markdown before applying it to the lesson body.");
      return;
    }
    handleMarkdownContentChange(nextMarkdown);
    setMarkdownImportError("");
    setMarkdownImportOpen(false);
  };
  const copyImportHelperText = async (text2, successMessage) => {
    if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
      showToast("Clipboard copy is not available in this browser.", "error");
      return;
    }
    try {
      await navigator.clipboard.writeText(String(text2 || ""));
      showToast(successMessage, "success");
    } catch {
      showToast("Could not copy import helper text.", "error");
    }
  };
  const createCategory = async () => {
    setCategorySaving(true);
    setCategoryError("");
    try {
      const response = await fetch(editorContext.categoryStoreUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        },
        credentials: "same-origin",
        body: JSON.stringify({
          ...categoryDraft,
          order_num: Number(categoryDraft.order_num || 0),
          slug: categoryDraft.slug || slugifyLessonTitle(categoryDraft.name)
        })
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        const firstError = payload?.errors ? Object.values(payload.errors)[0]?.[0] : null;
        throw new Error(firstError || payload?.message || "Could not create category.");
      }
      const nextCategory = payload?.category;
      if (!nextCategory?.id) {
        throw new Error("Category response was incomplete.");
      }
      setCategories((current) => [...current, nextCategory].sort((left, right) => {
        if (left.order_num !== right.order_num) return Number(left.order_num || 0) - Number(right.order_num || 0);
        return String(left.name || "").localeCompare(String(right.name || ""));
      }));
      form.setData("category_id", String(nextCategory.id));
      setCategoryDraft({ type: "lesson", name: "", slug: "", description: "", order_num: 0, active: true });
    } catch (error) {
      setCategoryError(error instanceof Error ? error.message : "Could not create category.");
    } finally {
      setCategorySaving(false);
    }
  };
  const comparisonBlocks = Array.isArray(form.data.blocks) ? form.data.blocks : [];
  const toggleBrowserFullscreen = async () => {
    if (typeof document === "undefined") return;
    try {
      if (document.fullscreenElement) {
        await document.exitFullscreen();
        return;
      }
      await document.documentElement.requestFullscreen();
    } catch {
    }
  };
  const bodyEditorActions = /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, bodyWordCount.toLocaleString(), " words"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: openMarkdownImport,
      className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]"
    },
    "Import Markdown"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setIsEditorFullHeight((current) => !current),
      className: `rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition ${isEditorFullHeight ? "border-sky-300/35 bg-sky-300/12 text-sky-100" : "border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]"}`
    },
    isEditorFullHeight ? "Normal height" : "Full-height editor"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => void toggleBrowserFullscreen(),
      className: `rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition ${isBrowserFullscreen ? "border-[#ff9e8c]/35 bg-[#ff9e8c]/12 text-[#ffd5cd]" : "border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]"}`
    },
    isBrowserFullscreen ? "Exit browser fullscreen" : "Browser fullscreen"
  ));
  const visibleSections = reactExports.useMemo(() => new Set(LESSON_EDITOR_TABS.find((tab2) => tab2.id === activeTab)?.sections || []), [activeTab]);
  const isSectionVisible = (sectionId) => visibleSections.has(sectionId);
  const activeTabMeta = reactExports.useMemo(() => LESSON_EDITOR_TABS.find((tab2) => tab2.id === activeTab) || LESSON_EDITOR_TABS[0], [activeTab]);
  const sectionClassName = (sectionId, className = "") => `${isSectionVisible(sectionId) ? "" : "hidden"} ${className}`.trim();
  const showWriteCompanion = activeTab === "write" && !isEditorFullHeight;
  const showSupportRail = showWriteCompanion || isSectionVisible("lesson-preview");
  const lessonStatusItems = [
    { label: "Title", ready: String(form.data.title || "").trim() !== "" },
    { label: "Excerpt", ready: String(form.data.excerpt || "").trim() !== "" },
    { label: "Body", ready: String(form.data.content || form.data.content_markdown || "").trim() !== "" },
    { label: "Slug", ready: String(form.data.slug || "").trim() !== "" }
  ];
  const lessonPathPreview = form.data.slug ? `/academy/${form.data.slug}` : "/academy/lesson-slug";
  const restoreLessonRevision = (revision, field = "") => {
    if (!revision?.restore_url) return;
    const message = field ? `Restore ${LESSON_REVISION_FIELD_OPTIONS.find((option) => option.value === field)?.label || field} from revision #${revision.id}? A new safety revision will be created first.` : `Restore the full lesson from revision #${revision.id}? A new safety revision will be created first.`;
    if (!window.confirm(message)) return;
    At.post(revision.restore_url, field ? { field } : {}, { preserveScroll: true });
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${title}` }), isEditorFullHeight ? /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-[110] bg-[#02040add]/90 backdrop-blur-md", "aria-hidden": "true" }) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-6 pb-16" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] shadow-[0_24px_70px_rgba(2,6,23,0.34)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white transition hover:bg-white/[0.08]" }, "Back to lessons"), /* @__PURE__ */ React.createElement("span", null, destroyUrl ? "Edit lesson" : "New lesson"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-sky-100" }, lessonHeaderNumberLabel)), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy lesson"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-7 text-slate-300" }, "Use the same richer writing flow as the newsroom: drag in the cover, shape the article with the rich editor, and keep publishing details in the same place.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Import JSON"), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-2xl border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save lesson")))), /* @__PURE__ */ React.createElement(EditorWorkspaceTabs, { tabs: LESSON_EDITOR_TABS, activeTab, onChange: setActiveTab, errorCounts: tabErrorCounts }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.14)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Current workspace"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, activeTabMeta.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, activeTabMeta.description)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Words"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, bodyWordCount.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Excerpt"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, excerptLength, "/800")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Errors"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Object.keys(form.errors || {}).length))))), /* @__PURE__ */ React.createElement("div", { className: showSupportRail ? "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start" : "grid gap-6" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6", role: "tabpanel", id: `lesson-editor-panel-${activeTab}`, "aria-labelledby": `lesson-editor-tab-${activeTab}` }, activeTab === "preview" ? /* @__PURE__ */ React.createElement(SectionCard$5, { eyebrow: "Preview mode", title: "Rendered lesson review", description: "Use this tab to scan the public-facing lesson card, article imagery, and rendered article body without the rest of the form in the way.", tone: "feature" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Hero image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, coverPreviewUrl ? "Ready" : "Missing", " hero artwork for lesson cards and social previews.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Article image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, articleCoverPreviewUrl ? "Ready" : "Missing", " inline article cover shown before the lesson body.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Body length"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, bodyWordCount.toLocaleString(), " words currently in the lesson body.")))) : null, /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-story-setup", eyebrow: "Story setup", title: "Headline and framing", description: "Start with the lesson identity and summary, then move into the full article body.", tone: "feature", className: sectionClassName("lesson-story-setup") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    TextField$2,
    {
      label: "Title",
      value: form.data.title,
      onChange: (event) => form.setData("title", event.target.value),
      error: form.errors.title,
      maxLength: 180,
      placeholder: "Prompt engineering for cleaner scene direction"
    }
  ), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    slugTouchedRef.current = false;
    form.setData("slug", slugifyLessonTitle(form.data.title));
  }, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Sync")), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: form.data.slug,
      onChange: (event) => {
        slugTouchedRef.current = String(event.target.value).trim() !== "";
        form.setData("slug", event.target.value);
      },
      className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none",
      placeholder: "prompt-engineering-for-cleaner-scene-direction",
      maxLength: 180
    }
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "The slug follows the title until you override it manually."), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.slug }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Excerpt"), /* @__PURE__ */ React.createElement("span", null, excerptLength, "/800")), /* @__PURE__ */ React.createElement("textarea", { value: form.data.excerpt, onChange: (event) => form.setData("excerpt", event.target.value), rows: 5, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", placeholder: "Summarize what the lesson teaches, why it matters, and what a creator will walk away with." }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "This is the short summary used in cards, internal lists, and metadata surfaces."), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.excerpt }))), /* @__PURE__ */ React.createElement(
    SectionCard$5,
    {
      id: "lesson-body-editor",
      eyebrow: "Main article",
      title: "Lesson body editor",
      description: "Write the tutorial in the same richer editing surface used for newsroom articles.",
      actions: bodyEditorActions,
      className: sectionClassName("lesson-body-editor", isEditorFullHeight ? "fixed inset-4 z-[120] flex min-h-0 flex-col overflow-hidden border-sky-300/20 shadow-[0_32px_100px_rgba(2,6,23,0.72)]" : ""),
      contentClassName: isEditorFullHeight ? "flex min-h-0 flex-1 flex-col" : ""
    },
    /* @__PURE__ */ React.createElement("div", { className: `grid min-w-0 gap-3 text-sm text-slate-300 ${isEditorFullHeight ? "min-h-0 flex-1" : ""}`.trim() }, /* @__PURE__ */ React.createElement(
      RichTextEditor,
      {
        content: form.data.content,
        onChange: handleRichContentChange,
        placeholder: "Open with the problem, explain the workflow step by step, and use headings, media, and links where the lesson needs structure.",
        error: form.errors.content,
        minHeight: isEditorFullHeight ? 30 : 24,
        maxHeightRem: isEditorFullHeight ? 72 : 42,
        autofocus: false,
        advancedNews: true,
        mediaSupport: {
          uploadUrl: editorContext.bodyMediaUploadUrl,
          deleteUrl: editorContext.bodyMediaDeleteUrl,
          assetsUrl: editorContext.bodyMediaAssetsUrl,
          slot: "body"
        }
      }
    ))
  ), /* @__PURE__ */ React.createElement(
    SectionCard$5,
    {
      id: "lesson-ai-comparisons",
      eyebrow: "Structured blocks",
      title: "AI model comparisons",
      description: "Add reusable same-prompt comparison blocks without burying the data inside the lesson HTML body.",
      className: sectionClassName("lesson-ai-comparisons"),
      actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addComparisonBlock, className: "rounded-full border border-[#ff9e8c]/25 bg-[#ff9e8c]/12 px-4 py-2 text-sm font-semibold text-[#ffd5cd]" }, "+ Add AI Comparison")
    },
    /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, comparisonBlocks.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-black/20 px-5 py-6 text-sm leading-7 text-slate-400" }, "No comparison blocks yet. Add one when a lesson needs the same prompt analyzed across multiple AI image tools.") : comparisonBlocks.map((block, blockIndex) => /* @__PURE__ */ React.createElement("div", { key: block.client_key, className: "rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(255,158,140,0.12),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.82),rgba(6,10,18,0.95))] p-5 shadow-[0_24px_60px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-white/10 pb-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-[#ffc0b4]" }, "AI Model Comparison"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, block.payload?.title || block.title || DEFAULT_AI_COMPARISON_TITLE)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeBlock(block.client_key), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs font-semibold text-rose-100" }, "Remove block"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Block title",
        value: block.title,
        onChange: (event) => updateBlock(block.client_key, (current) => ({
          ...current,
          title: event.target.value,
          payload: { ...current.payload, title: event.target.value }
        })),
        error: getFormError(form.errors, `blocks.${blockIndex}.title`) || getFormError(form.errors, `blocks.${blockIndex}.payload.title`),
        placeholder: DEFAULT_AI_COMPARISON_TITLE
      }
    ), /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Aspect ratio",
        value: block.payload?.aspect_ratio,
        onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, aspect_ratio: event.target.value } })),
        error: getFormError(form.errors, `blocks.${blockIndex}.payload.aspect_ratio`),
        placeholder: "16:9"
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4" }, /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Intro",
        value: block.payload?.intro,
        onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, intro: event.target.value } })),
        error: getFormError(form.errors, `blocks.${blockIndex}.payload.intro`),
        rows: 3
      }
    ), /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Prompt",
        value: block.payload?.prompt,
        onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, prompt: event.target.value } })),
        error: getFormError(form.errors, `blocks.${blockIndex}.payload.prompt`),
        rows: 5
      }
    ), /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Negative prompt",
        value: block.payload?.negative_prompt,
        onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, negative_prompt: event.target.value } })),
        error: getFormError(form.errors, `blocks.${blockIndex}.payload.negative_prompt`),
        rows: 3
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-[minmax(0,1fr)_200px_200px]" }, /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Criteria (one per line)",
        value: (block.payload?.criteria || []).join("\n"),
        onChange: (event) => updateBlock(block.client_key, (current) => ({
          ...current,
          payload: { ...current.payload, criteria: normalizeCriteria(String(event.target.value || "").split(/\r?\n/)) }
        })),
        error: getFormError(form.errors, `blocks.${blockIndex}.payload.criteria`) || getFormError(form.errors, `blocks.${blockIndex}.payload.criteria.0`),
        rows: 6,
        hint: "Composition, lighting, wallpaper quality, and similar criteria work well here."
      }
    ), /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Sort order",
        value: block.sort_order,
        onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, sort_order: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.sort_order`),
        type: "number",
        min: "0"
      }
    ), /* @__PURE__ */ React.createElement(
      ToggleField$2,
      {
        label: "Active",
        checked: Boolean(block.active),
        onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, active: event.target.checked })),
        error: getFormError(form.errors, `blocks.${blockIndex}.active`),
        help: "Inactive comparison blocks stay stored but are hidden on the public lesson page."
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Results"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Add one card per tool or model you want to compare.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => addComparisonResult(block.client_key), className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100" }, "+ Add model result")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, (block.comparison_results || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-5 text-sm text-slate-500" }, "No model results yet.") : (block.comparison_results || []).map((result, resultIndex) => /* @__PURE__ */ React.createElement("div", { key: result.client_key, className: "rounded-[24px] border border-white/10 bg-slate-950/70 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, result.model_name || result.provider || `Model result ${resultIndex + 1}`), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Comparison card")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeComparisonResult(block.client_key, result.client_key), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs font-semibold text-rose-100" }, "Remove")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(
      WorldMediaUploadField,
      {
        label: "Generated image",
        slot: "body",
        value: result.image_path,
        previewUrl: result.image_url,
        emptyLabel: "Generated image",
        helperText: "Upload the main comparison image using the same Academy lesson media pipeline.",
        uploadUrl: editorContext.bodyMediaUploadUrl,
        deleteUrl: editorContext.bodyMediaDeleteUrl,
        isTemporaryValue: Boolean(result.image_temp_path) && result.image_temp_path === result.image_path,
        onChange: ({ path, url }) => updateComparisonResult(block.client_key, result.client_key, (current) => ({
          ...current,
          image_path: path || "",
          image_url: url || normalizeCoverPreview(path || "", cdnBaseUrl),
          image_temp_path: path || ""
        }))
      }
    ), /* @__PURE__ */ React.createElement(
      WorldMediaUploadField,
      {
        label: "Thumbnail image",
        slot: "body",
        value: result.thumb_path,
        previewUrl: result.thumb_url,
        emptyLabel: "Thumbnail",
        helperText: "Optional smaller variant. Leave empty to reuse the main image on the public lesson page.",
        uploadUrl: editorContext.bodyMediaUploadUrl,
        deleteUrl: editorContext.bodyMediaDeleteUrl,
        isTemporaryValue: Boolean(result.thumb_temp_path) && result.thumb_temp_path === result.thumb_path,
        onChange: ({ path, url }) => updateComparisonResult(block.client_key, result.client_key, (current) => ({
          ...current,
          thumb_path: path || "",
          thumb_url: url || normalizeCoverPreview(path || "", cdnBaseUrl),
          thumb_temp_path: path || ""
        }))
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Provider",
        value: result.provider,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, provider: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.provider`),
        placeholder: "OpenAI"
      }
    ), /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Model",
        value: result.model_name,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, model_name: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.model_name`),
        placeholder: "ChatGPT Images"
      }
    ), /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Score",
        value: result.score,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, score: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.score`),
        type: "number",
        min: "1",
        max: "10"
      }
    ), /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Sort order",
        value: result.sort_order,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, sort_order: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.sort_order`),
        type: "number",
        min: "0"
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Settings",
        value: result.settings,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, settings: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.settings`),
        rows: 3
      }
    ), /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Strengths",
        value: result.strengths,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, strengths: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.strengths`),
        rows: 3
      }
    ), /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Weaknesses",
        value: result.weaknesses,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, weaknesses: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.weaknesses`),
        rows: 3
      }
    ), /* @__PURE__ */ React.createElement(
      TextAreaField$1,
      {
        label: "Best for",
        value: result.best_for,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, best_for: event.target.value })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.best_for`),
        rows: 3
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Image path override",
        value: result.image_path,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({
          ...current,
          image_path: event.target.value,
          image_url: normalizeCoverPreview(event.target.value, cdnBaseUrl),
          image_temp_path: ""
        })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.image_path`),
        placeholder: "academy/lessons/body/..."
      }
    ), /* @__PURE__ */ React.createElement(
      TextField$2,
      {
        label: "Thumbnail path override",
        value: result.thumb_path,
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({
          ...current,
          thumb_path: event.target.value,
          thumb_url: normalizeCoverPreview(event.target.value, cdnBaseUrl),
          thumb_temp_path: ""
        })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.thumb_path`),
        placeholder: "Optional academy/lessons/body/..."
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(
      ToggleField$2,
      {
        label: "Result active",
        checked: Boolean(result.active),
        onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, active: event.target.checked })),
        error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.active`),
        help: "Inactive results stay saved but do not render on the public lesson page."
      }
    )))))))))
  ), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-course-numbering", eyebrow: "Course placement", title: "Courses and numbering", description: "Keep series numbering and course placement in one workspace so guided lesson management stays separate from publishing.", className: sectionClassName("lesson-course-numbering") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "Series name", value: form.data.series_name, onChange: (event) => form.setData("series_name", event.target.value), error: form.errors.series_name, maxLength: 120, placeholder: "AI Art Basics", hint: "Shown before the lesson number on public pages. Leave empty if this lesson is not part of a named series." })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "Reading minutes", value: form.data.reading_minutes, error: form.errors.reading_minutes, type: "number", min: "1", max: "999", readOnly: true, hint: `Auto-calculated from the lesson body. Current estimate: ${estimatedReadingMinutes} min for ${bodyWordCount.toLocaleString()} words.` }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Lesson number"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => form.setData("lesson_number", String(numberingContext?.lesson_number?.suggested || "")), className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Use ", numberingContext?.lesson_number?.suggested || "next")), /* @__PURE__ */ React.createElement("input", { value: form.data.lesson_number ?? "", onChange: (event) => form.setData("lesson_number", event.target.value), type: "number", min: "1", placeholder: String(numberingContext?.lesson_number?.suggested || 3), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Visible public numbering like Lesson 03. Suggested next slot: ", numberingContext?.lesson_number?.suggested || 1, ". Missing numbers: ", formatMissingNumbers(numberingContext?.lesson_number?.missing), "."), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.lesson_number }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Course order"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => form.setData("course_order", String(numberingContext?.course_order?.suggested || "")), className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Use ", numberingContext?.course_order?.suggested || "next")), /* @__PURE__ */ React.createElement("input", { value: form.data.course_order ?? "", onChange: (event) => form.setData("course_order", event.target.value), type: "number", min: "1", placeholder: String(numberingContext?.course_order?.suggested || 3), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Controls standalone lesson list sorting and previous or next lesson navigation. Suggested next slot: ", numberingContext?.course_order?.suggested || 1, ". Missing numbers: ", formatMissingNumbers(numberingContext?.course_order?.missing), "."), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.course_order })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Lesson numbering"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[11px] font-semibold text-sky-100" }, "Suggested ", numberingContext?.lesson_number?.suggested || 1), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold text-slate-200" }, numberingContext?.lesson_number?.used_count || 0, " used"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold text-slate-200" }, "Highest ", numberingContext?.lesson_number?.highest || 0)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, "Missing lesson numbers: ", formatMissingNumbers(numberingContext?.lesson_number?.missing))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Course order guidance"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold text-amber-100" }, "Suggested ", numberingContext?.course_order?.suggested || 1), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold text-slate-200" }, numberingContext?.course_order?.used_count || 0, " used"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold text-slate-200" }, "Highest ", numberingContext?.course_order?.highest || 0)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, "Missing course-order slots: ", formatMissingNumbers(numberingContext?.course_order?.missing)))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      multi: true,
      label: "Courses",
      value: form.data.course_ids || [],
      onChange: (nextValue) => form.setData("course_ids", Array.isArray(nextValue) ? nextValue.map((courseId) => String(courseId)) : []),
      options: courseOptions,
      className: "bg-black/20",
      error: form.errors.course_ids
    }
  ), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6 text-slate-400" }, "Attach this lesson to one or more existing courses. You can also attach or remove the current lesson immediately from the course manager cards below."))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-course-manager", eyebrow: "Course manager", title: "Manage course placement", description: "Attach the current lesson, drag to reorder it within each selected course, and save the updated path without leaving this lesson page.", className: sectionClassName("lesson-course-manager") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, selectedCourses.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-black/20 px-5 py-5 text-sm leading-7 text-slate-400" }, "Select one or more courses above to manage where this lesson sits in guided learning paths.") : selectedCourses.map((course) => {
    const currentCourseLesson = Array.isArray(course.lessons) ? course.lessons.find((lesson) => lesson.is_current) : null;
    const nextStepLabel = formatCourseStep(course.next_order_num);
    const draftLessons = normalizeCourseManagerLessons(courseManagerDrafts[String(course.value)] || course.lessons);
    const draftIsDirty = courseManagerSignature(draftLessons) !== courseManagerSignature(course.lessons);
    const courseIsSaving = Boolean(courseSaveProcessing[String(course.value)]);
    return /* @__PURE__ */ React.createElement("div", { key: course.value, className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-lg font-semibold tracking-[-0.03em] text-white" }, course.label), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, course.status), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, course.lesson_count, " lessons"), draftIsDirty ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Unsaved order") : null), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, currentCourseLesson ? `${currentCourseLesson.title} is currently attached in ${formatCourseStep(currentCourseLesson.order_num) || `slot ${currentCourseLesson.display_order}`}.` : `This lesson is not attached yet. Add it now at ${nextStepLabel || `slot ${Number(course.next_order_num || 0) + 1}`}.`)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, currentLessonId > 0 && !currentCourseLesson ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => attachLessonToCourseNow(course), className: "rounded-full border border-[#f39a24]/25 bg-[#f39a24]/12 px-3 py-1.5 text-xs font-semibold text-[#ffd5cd]" }, "Add this lesson now") : null, currentCourseLesson ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => detachLessonFromCourseNow(course, currentCourseLesson), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs font-semibold text-rose-100" }, "Remove from course") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateCourseDraft(course.value, course.lessons), disabled: !draftIsDirty || courseIsSaving, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white disabled:opacity-40" }, "Reset order"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveCourseDraftOrder(course), disabled: !draftIsDirty || courseIsSaving, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-3 py-1.5 text-xs font-semibold text-sky-100 disabled:opacity-40" }, courseIsSaving ? "Saving..." : "Save order"), /* @__PURE__ */ React.createElement("a", { href: course.builder_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Open builder"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2" }, draftLessons.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-500" }, "No lessons are attached to this course yet.") : draftLessons.map((lesson, lessonIndex) => /* @__PURE__ */ React.createElement(
      "div",
      {
        key: lesson.id,
        draggable: true,
        onDragStart: () => setDraggedCourseLesson({ courseId: String(course.value), lessonId: lesson.id }),
        onDragEnd: () => setDraggedCourseLesson(null),
        onDragOver: (event) => event.preventDefault(),
        onDrop: (event) => {
          event.preventDefault();
          if (!draggedCourseLesson || draggedCourseLesson.courseId !== String(course.value)) return;
          updateCourseDraft(course.value, reorderCourseManagerLessons(draftLessons, draggedCourseLesson.lessonId, lesson.id));
          setDraggedCourseLesson(null);
        },
        className: `flex flex-wrap items-center justify-between gap-3 rounded-2xl border px-4 py-3 transition ${lesson.is_current ? "border-[#f39a24]/30 bg-[#f39a24]/10" : "border-white/10 bg-white/[0.03]"} ${draggedCourseLesson?.courseId === String(course.value) && Number(draggedCourseLesson.lessonId) === Number(lesson.id) ? "opacity-60" : ""}`
      },
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, formatCourseStep(lesson.order_num) || `#${lesson.display_order}`), lesson.formatted_lesson_number ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, lesson.formatted_lesson_number) : null, lesson.section_title ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, lesson.section_title) : null, lesson.is_current ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#f39a24]/25 bg-[#f39a24]/12 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-[#ffd5cd]" }, "This lesson") : null), /* @__PURE__ */ React.createElement("p", { className: "mt-2 truncate text-sm font-semibold text-white" }, lesson.title)),
      /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateCourseDraft(course.value, moveCourseManagerLesson(draftLessons, lesson.id, -1)), disabled: lessonIndex === 0, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white disabled:opacity-40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateCourseDraft(course.value, moveCourseManagerLesson(draftLessons, lesson.id, 1)), disabled: lessonIndex === draftLessons.length - 1, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white disabled:opacity-40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down" })), lesson.edit_url ? /* @__PURE__ */ React.createElement("a", { href: lesson.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Open lesson") : null)
    ))));
  }))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-publishing", eyebrow: "Publishing", title: "Placement and visibility", description: "Set the lesson metadata, schedule, and discovery fields before it goes live.", className: sectionClassName("lesson-publishing") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Difficulty", value: form.data.difficulty || "", onChange: (nextValue) => form.setData("difficulty", String(nextValue || "")), options: difficultyField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.difficulty })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Access", value: form.data.access_level || "", onChange: (nextValue) => form.setData("access_level", String(nextValue || "")), options: accessField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.access_level }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "Lesson type", value: form.data.lesson_type, onChange: (event) => form.setData("lesson_type", event.target.value), error: form.errors.lesson_type, placeholder: "article, video, walkthrough" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "Microtags", value: form.data.tags, onChange: (event) => form.setData("tags", event.target.value), error: form.errors.tags, placeholder: "workflow, cleanup, publishing" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6 text-slate-400" }, "Comma-separated short tags for the public lesson page and article discovery context."))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Category", value: form.data.category_id || "", onChange: (nextValue) => form.setData("category_id", String(nextValue || "")), options: categoryOptions, searchable: false, className: "bg-black/20", error: form.errors.category_id })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Publish at"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.published_at || "", onChange: (nextValue) => form.setData("published_at", nextValue || ""), clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.published_at }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(ToggleField$2, { label: "Featured", checked: Boolean(form.data.featured), onChange: (event) => form.setData("featured", event.target.checked), help: "Highlight this lesson in featured academy surfaces.", error: form.errors.featured }), /* @__PURE__ */ React.createElement(ToggleField$2, { label: "Active", checked: Boolean(form.data.active), onChange: (event) => form.setData("active", event.target.checked), help: "Keep inactive lessons hidden until the draft is ready.", error: form.errors.active }))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-seo", eyebrow: "SEO", title: "Search metadata", description: "Keep the lesson search-ready without stuffing the headline.", className: sectionClassName("lesson-seo") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "SEO title", value: form.data.seo_title, onChange: (event) => form.setData("seo_title", event.target.value), error: form.errors.seo_title, maxLength: 180, placeholder: "Optional search title" }), /* @__PURE__ */ React.createElement(TextField$2, { label: "Video URL", value: form.data.video_url, onChange: (event) => form.setData("video_url", event.target.value), error: form.errors.video_url, placeholder: "Optional lesson video URL" })), /* @__PURE__ */ React.createElement(TextAreaField$1, { label: "SEO description", value: form.data.seo_description, onChange: (event) => form.setData("seo_description", event.target.value), error: form.errors.seo_description, rows: 4, hint: "Keep this tighter than the excerpt and focused on search intent." })), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-cover", eyebrow: "Cover image", title: "Hero asset", description: "Use drag and drop for the lesson image, or paste a direct URL when you already have one.", className: sectionClassName("lesson-cover") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-2 lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Hero cover",
      slot: "cover",
      value: form.data.cover_image,
      previewUrl: coverPreviewUrl,
      emptyLabel: "Drop a hero cover",
      helperText: "Upload a wide landscape image for academy cards, previews, and social sharing. Keep it cinematic, readable at small sizes, and free of embedded text.",
      uploadUrl: editorContext.coverUploadUrl,
      deleteUrl: editorContext.coverDeleteUrl,
      onChange: ({ path, url }) => {
        setStagedCoverPath(path || "");
        form.setData("cover_image", path || "");
        setCoverPreviewUrl(url || "");
      },
      isTemporaryValue: Boolean(stagedCoverPath) && form.data.cover_image === stagedCoverPath
    }
  ), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.cover_image }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Advanced hero cover path or URL"), /* @__PURE__ */ React.createElement("input", { value: form.data.cover_image, onChange: (event) => handleManualCoverChange(event.target.value), placeholder: "Optional external URL or stored object path", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Use this for migrations, imported lessons, or when you already know the exact asset path to use."))), /* @__PURE__ */ React.createElement(
    CopyablePromptCard,
    {
      eyebrow: "ChatGPT prompt",
      title: "Copy this for the hero cover",
      description: "Paste this into ChatGPT when you want a new hero image for the lesson.",
      prompt: lessonHeroPromptValue,
      onCopy: () => {
        void copyImportHelperText(lessonHeroPromptValue, "Hero cover prompt copied.");
      }
    }
  ))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-article-cover", eyebrow: "Article cover", title: "Inline article image", description: "This image is rendered just before the lesson content begins.", className: sectionClassName("lesson-article-cover") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-2 lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Inline article cover",
      slot: "cover",
      value: form.data.article_cover_image,
      previewUrl: articleCoverPreviewUrl,
      emptyLabel: "Drop an inline article cover",
      helperText: "Upload the image that appears above the lesson body. Use a strong landscape image that still reads well inside the article column.",
      uploadUrl: editorContext.coverUploadUrl,
      deleteUrl: editorContext.coverDeleteUrl,
      onChange: ({ path, url }) => {
        setStagedArticleCoverPath(path || "");
        form.setData("article_cover_image", path || "");
        setArticleCoverPreviewUrl(url || "");
      },
      isTemporaryValue: Boolean(stagedArticleCoverPath) && form.data.article_cover_image === stagedArticleCoverPath
    }
  ), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.article_cover_image }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Advanced inline article cover path or URL"), /* @__PURE__ */ React.createElement("input", { value: form.data.article_cover_image, onChange: (event) => handleManualArticleCoverChange(event.target.value), placeholder: "Optional external URL or stored object path", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Use this when the article image already exists in storage or needs to point to an external source."))), /* @__PURE__ */ React.createElement(
    CopyablePromptCard,
    {
      eyebrow: "ChatGPT prompt",
      title: "Copy this for the inline article image",
      description: "Paste this into ChatGPT when you want a cleaner image that sits above the lesson body.",
      prompt: lessonArticleCoverPromptValue,
      onCopy: () => {
        void copyImportHelperText(lessonArticleCoverPromptValue, "Article cover prompt copied.");
      }
    }
  ))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-categories", eyebrow: "Lesson categories", title: "Create category inline", description: "Add lesson categories without leaving the writing flow.", className: sectionClassName("lesson-categories"), actions: /* @__PURE__ */ React.createElement("a", { href: editorContext.categoryManageUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Manage all categories") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: categoryDraft.name, onChange: (event) => setCategoryDraft((current) => ({ ...current, name: event.target.value })), placeholder: "Category name", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: categoryDraft.slug, onChange: (event) => setCategoryDraft((current) => ({ ...current, slug: event.target.value })), placeholder: "Optional slug", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: categoryDraft.description, onChange: (event) => setCategoryDraft((current) => ({ ...current, description: event.target.value })), rows: 3, placeholder: "Description", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "number", value: categoryDraft.order_num, min: "0", onChange: (event) => setCategoryDraft((current) => ({ ...current, order_num: event.target.value })), className: "w-28 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "min-w-[260px] flex-1" }, /* @__PURE__ */ React.createElement(ToggleField$2, { label: "Category active", checked: categoryDraft.active, onChange: (event) => setCategoryDraft((current) => ({ ...current, active: event.target.checked })), help: "Inactive categories stay available for cleanup but disappear from regular lesson assignment." })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => void createCategory(), disabled: categorySaving, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, categorySaving ? "Creating..." : "Create category")), categoryError ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, categoryError) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, (categories || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-500" }, "No lesson categories yet.") : categories.map((category) => /* @__PURE__ */ React.createElement("div", { key: category.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, category.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, category.slug), category.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, category.description) : null), /* @__PURE__ */ React.createElement("a", { href: category.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Edit"))))))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-revisions", eyebrow: "Safety net", title: "Revision history", description: "Each lesson update now saves the previous state first. Restore the full lesson or a single field when something goes wrong.", className: sectionClassName("lesson-revisions") }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/18 bg-sky-300/8 p-4 text-sm leading-6 text-slate-300" }, "Restoring from a revision creates another revision first, so you can undo the restore if needed."), revisions.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-black/20 px-4 py-5 text-sm leading-7 text-slate-400" }, "No revisions yet. The first saved update will capture the current lesson state.") : revisions.map((revision) => {
    const selectedField = String(revisionFieldSelections[revision.id] || "content");
    return /* @__PURE__ */ React.createElement("div", { key: revision.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Revision #", revision.id), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, revision.created_label || "Recently saved", " by ", revision.actor_name || "Staff"), revision.change_note ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-5 text-slate-400" }, revision.change_note) : null), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => restoreLessonRevision(revision), className: "rounded-full border border-[#f39a24]/25 bg-[#f39a24]/12 px-3 py-1.5 text-xs font-semibold text-[#ffd5cd]" }, "Restore full lesson")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[20px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, revision.snapshot?.title || "Untitled lesson snapshot"), revision.snapshot?.excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-5 text-slate-400" }, revision.snapshot.excerpt) : null, revision.snapshot?.content_preview ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-5 text-slate-500" }, revision.snapshot.content_preview) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, revision.snapshot?.course_count || 0, " courses"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, revision.snapshot?.block_count || 0, " blocks"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Restore single field"), /* @__PURE__ */ React.createElement("select", { value: selectedField, onChange: (event) => setRevisionFieldSelections((current) => ({ ...current, [revision.id]: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }, LESSON_REVISION_FIELD_OPTIONS.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value }, option.label)))), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => restoreLessonRevision(revision, selectedField), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Restore selected field")));
  })))), showSupportRail ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6 xl:sticky xl:top-6 xl:self-start" }, showWriteCompanion ? /* @__PURE__ */ React.createElement(SectionCard$5, { eyebrow: "Writing flow", title: "Author companion", description: "Keep the lesson opening tight, then expand through headings and examples. This panel stays compact so the editor remains the focus." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/18 bg-sky-300/8 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Public path"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 break-all text-sm font-semibold text-white" }, lessonPathPreview), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Keep the headline specific enough that the slug reads clearly in search results and internal links.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Writing checklist"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-2" }, lessonStatusItems.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, item.label), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-1 text-[10px] font-bold uppercase tracking-[0.14em] ${item.ready ? "border border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border border-amber-300/20 bg-amber-300/10 text-amber-100"}` }, item.ready ? "Ready" : "Missing"))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Article rhythm"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 text-sm leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Lead with the problem in the first paragraph, then break the workflow into headline-sized steps."), /* @__PURE__ */ React.createElement("p", null, "Use Markdown import when you already have a draft, then switch back to the visual editor for structure, media, and cleanup."), /* @__PURE__ */ React.createElement("p", null, "Open full-height mode once the outline is stable so the body editor takes the entire screen."))))) : null, /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-preview", eyebrow: "Preview", title: "Lesson snapshot", description: "A quick view of what editors and visitors will scan first.", className: sectionClassName("lesson-preview") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/30" }, coverPreviewUrl ? /* @__PURE__ */ React.createElement("img", { src: coverPreviewUrl, alt: "Lesson cover preview", className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No hero cover image selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/30" }, articleCoverPreviewUrl ? /* @__PURE__ */ React.createElement("img", { src: articleCoverPreviewUrl, alt: "Lesson article cover preview", className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No article cover image selected yet."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Lesson summary"), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white" }, form.data.title || "Untitled lesson"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, form.data.excerpt || "Add a concise excerpt to frame the lesson before someone opens it."), /* @__PURE__ */ React.createElement("dl", { className: "mt-4 grid grid-cols-2 gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Difficulty"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.difficulty || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Access"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.access_level || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Reading"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.reading_minutes || "—", " min")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Body"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, bodyWordCount.toLocaleString(), " words")))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Article preview"), deferredArticlePreviewHtml ? /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "prose prose-invert mt-4 max-w-none prose-headings:text-white prose-p:text-slate-300 prose-p:leading-7 prose-li:text-slate-300 prose-strong:text-white prose-code:text-amber-300 prose-pre:border prose-pre:border-white/10 prose-pre:bg-slate-950/70 prose-blockquote:border-sky-300/30 prose-a:text-sky-300",
      dangerouslySetInnerHTML: { __html: deferredArticlePreviewHtml }
    }
  ) : /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-500" }, "Add lesson body content to see the rendered article preview here.")))) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save lesson"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteLesson, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null)), /* @__PURE__ */ React.createElement(
    JsonImportDialog$1,
    {
      open: jsonImportOpen,
      value: jsonImportValue,
      error: jsonImportError,
      exampleValue: jsonImportExampleValue,
      promptValue: jsonImportPromptValue,
      onChange: (nextValue) => {
        setJsonImportValue(nextValue);
        if (jsonImportError) {
          setJsonImportError("");
        }
      },
      onCopyExample: () => {
        void copyImportHelperText(jsonImportExampleValue, "Lesson JSON example copied.");
      },
      onCopyPrompt: () => {
        void copyImportHelperText(jsonImportPromptValue, "Lesson import prompt copied.");
      },
      onClose: () => {
        setJsonImportOpen(false);
        setJsonImportError("");
      },
      onApply: applyJsonImport
    }
  ), /* @__PURE__ */ React.createElement(
    MarkdownImportDialog,
    {
      open: markdownImportOpen,
      value: markdownImportValue,
      error: markdownImportError,
      onChange: (nextValue) => {
        setMarkdownImportValue(nextValue);
        if (markdownImportError) {
          setMarkdownImportError("");
        }
      },
      onClose: () => {
        setMarkdownImportOpen(false);
        setMarkdownImportError("");
      },
      onApply: applyMarkdownImport
    }
  ), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ));
}
const __vite_glob_0_23 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: LessonEditor
}, Symbol.toStringTag, { value: "Module" }));
function normalizePayload(fields, data) {
  const payload = { ...data };
  fields.forEach((field) => {
    if (field.type === "csv") {
      payload[field.name] = String(payload[field.name] || "").split(/[,\n]/).map((item) => item.trim()).filter(Boolean);
    }
    if (field.type === "json") {
      if (typeof payload[field.name] === "string") {
        const trimmed = payload[field.name].trim();
        if (!trimmed) {
          payload[field.name] = null;
          return;
        }
        try {
          payload[field.name] = JSON.parse(trimmed);
        } catch {
        }
      }
    }
  });
  return payload;
}
function serializeStructuredJson(value) {
  if (value == null || value === "") return "";
  if (typeof value === "string") return value;
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    return "";
  }
}
function copyTextToClipboard(text2) {
  const source = String(text2 || "");
  if (!source) return Promise.reject(new Error("Nothing to copy"));
  if (typeof navigator !== "undefined" && navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
    return navigator.clipboard.writeText(source);
  }
  if (typeof document === "undefined" || !document.body) {
    return Promise.reject(new Error("Clipboard unavailable"));
  }
  const textarea = document.createElement("textarea");
  textarea.value = source;
  textarea.setAttribute("readonly", "true");
  textarea.style.position = "fixed";
  textarea.style.top = "-1000px";
  textarea.style.left = "-1000px";
  document.body.appendChild(textarea);
  textarea.select();
  try {
    if (document.execCommand("copy")) {
      return Promise.resolve();
    }
  } finally {
    document.body.removeChild(textarea);
  }
  return Promise.reject(new Error("Clipboard unavailable"));
}
function getField(fields, name2) {
  return fields.find((field) => field.name === name2) || null;
}
function firstErrorMessage$1(errors, fallback = "Please correct the highlighted fields and try again.") {
  const queue = [errors];
  while (queue.length > 0) {
    const current = queue.shift();
    if (typeof current === "string") {
      const message = current.trim();
      if (message) {
        return message;
      }
      continue;
    }
    if (Array.isArray(current)) {
      queue.push(...current);
      continue;
    }
    if (current && typeof current === "object") {
      queue.push(...Object.values(current));
    }
  }
  return fallback;
}
function SectionCard$4({ eyebrow, title, description, children, className = "" }) {
  return /* @__PURE__ */ React.createElement("section", { className: `w-full min-w-0 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_20px_80px_rgba(15,23,42,0.18)] ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.04em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, description) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, children));
}
function TextField$1({ label, value, onChange, error, ...rest }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("input", { value: value ?? "", onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none", ...rest }), error ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, error) : null);
}
function TextAreaField({ label, value, onChange, error, rows = 6, hint }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("textarea", { value: value ?? "", onChange, rows, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-7 text-white outline-none" }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, error ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, error) : null);
}
function ToggleField$1({ label, checked, onChange, help, error }) {
  return /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer items-start gap-4 rounded-[28px] border px-5 py-4 transition ${checked ? "border-[#f39a24]/35 bg-[#f39a24]/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "sr-only" }), /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border text-sm transition ${checked ? "border-[#f39a24] bg-[#f39a24] text-white" : "border-white/10 bg-[#151a29] text-transparent"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check" })), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block text-base font-semibold tracking-[-0.02em] text-white" }, label), help ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-sm leading-6 text-slate-300" }, help) : null, error ? /* @__PURE__ */ React.createElement("span", { className: "mt-2 block text-xs text-rose-300" }, error) : null));
}
const PROMPT_EDITOR_TABS = [
  {
    id: "overview",
    label: "Overview",
    description: "Set the prompt identity, category, access level, and the short summary shown in the library.",
    icon: "fa-compass-drafting",
    sections: ["prompt-identity"]
  },
  {
    id: "prompt",
    label: "Prompt Body",
    description: "Write the main prompt, exclusions, usage notes, and workflow direction without crowding the rest of the form.",
    icon: "fa-wand-magic-sparkles",
    sections: ["prompt-body"]
  },
  {
    id: "advanced",
    label: "Advanced Docs",
    description: "Store structured documentation, placeholders, helper prompts, and prompt variants without burying them in plain text notes.",
    icon: "fa-layer-group",
    sections: ["prompt-advanced"]
  },
  {
    id: "comparisons",
    label: "AI Model Comparisons",
    description: "Compare how different AI models or providers behave on the same prompt so editors can keep the guidance reusable.",
    icon: "fa-scale-balanced",
    sections: ["prompt-comparisons"]
  },
  {
    id: "media",
    label: "Media",
    description: "Upload the preview image used across the prompt library and public prompt detail page.",
    icon: "fa-image",
    sections: ["prompt-media"]
  },
  {
    id: "publish",
    label: "Publish",
    description: "Control timing, SEO, and promotion state without showing every publishing option at once.",
    icon: "fa-rocket-launch",
    sections: ["prompt-publishing", "prompt-preview"]
  }
];
const PROMPT_FIELD_TAB_MAP = {
  category_id: "overview",
  title: "overview",
  slug: "overview",
  excerpt: "overview",
  difficulty: "overview",
  access_level: "overview",
  aspect_ratio: "overview",
  tags: "overview",
  prompt: "prompt",
  negative_prompt: "prompt",
  usage_notes: "prompt",
  workflow_notes: "prompt",
  documentation: "advanced",
  placeholders: "advanced",
  helper_prompts: "advanced",
  prompt_variants: "advanced",
  preview_image: "media",
  preview_image_file: "media",
  published_at: "publish",
  seo_title: "publish",
  seo_description: "publish",
  featured: "publish",
  prompt_of_week: "publish",
  active: "publish"
};
function slugifyPromptTitle(value) {
  return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 180);
}
function stripPlainText(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}
function countPlainWords(value) {
  const text2 = stripPlainText(value);
  return text2 ? text2.split(/\s+/).length : 0;
}
function emptyPromptComparison() {
  return {
    client_key: `comparison-${Math.random().toString(36).slice(2, 10)}`,
    display_type: "",
    provider: "",
    model_name: "",
    notes: "",
    strengths: "",
    weaknesses: "",
    best_for: "",
    image_path: "",
    image_url: "",
    thumb_path: "",
    thumb_url: "",
    settings: "",
    score: "",
    active: true
  };
}
function sanitizePromptComparison(value) {
  if (!value || typeof value !== "object") {
    return emptyPromptComparison();
  }
  return {
    client_key: String(value.client_key || emptyPromptComparison().client_key),
    display_type: String(value.display_type || "").trim(),
    provider: String(value.provider || "").trim(),
    model_name: String(value.model_name || "").trim(),
    notes: String(value.notes || "").trim(),
    strengths: String(value.strengths || "").trim(),
    weaknesses: String(value.weaknesses || "").trim(),
    best_for: String(value.best_for || "").trim(),
    image_path: String(value.image_path || "").trim(),
    image_url: String(value.image_url || "").trim(),
    thumb_path: String(value.thumb_path || "").trim(),
    thumb_url: String(value.thumb_url || "").trim(),
    settings: String(value.settings || "").trim(),
    score: value.score === "" || value.score === null || typeof value.score === "undefined" ? "" : String(value.score).trim(),
    active: typeof value.active === "boolean" ? value.active : true
  };
}
function normalizePromptComparisons(value, { preserveEmpty = false } = {}) {
  if (!Array.isArray(value)) return [];
  return value.map((item) => {
    if (typeof item === "string") {
      const normalized2 = { ...emptyPromptComparison(), notes: item.trim() };
      return normalized2.notes || preserveEmpty ? normalized2 : null;
    }
    if (!item || typeof item !== "object") return preserveEmpty ? emptyPromptComparison() : null;
    const normalized = sanitizePromptComparison(item);
    const hasContent = [
      normalized.display_type,
      normalized.provider,
      normalized.model_name,
      normalized.notes,
      normalized.strengths,
      normalized.weaknesses,
      normalized.best_for,
      normalized.image_path,
      normalized.thumb_path,
      normalized.settings,
      normalized.score
    ].some(Boolean);
    return hasContent || preserveEmpty ? normalized : null;
  }).filter(Boolean);
}
function serializePromptComparisons(value) {
  return normalizePromptComparisons(value).map((comparison) => ({
    display_type: comparison.display_type,
    provider: comparison.provider,
    model_name: comparison.model_name,
    notes: comparison.notes,
    strengths: comparison.strengths,
    weaknesses: comparison.weaknesses,
    best_for: comparison.best_for,
    image_path: comparison.image_path,
    thumb_path: comparison.thumb_path,
    settings: comparison.settings,
    score: comparison.score === "" ? null : Number(comparison.score),
    active: Boolean(comparison.active)
  }));
}
const PROMPT_COMPARISON_TYPE_OPTIONS = [
  { value: "", label: "Default" },
  { value: "Comparison", label: "Comparison" },
  { value: "Variation", label: "Variation" },
  { value: "Iteration", label: "Iteration" },
  { value: "Refinement", label: "Refinement" },
  { value: "Remix", label: "Remix" }
];
const PROMPT_COMPARISON_EDITOR_TABS = [
  {
    id: "summary",
    label: "Summary",
    description: "Keep the main comparison details visible while editing this block."
  },
  {
    id: "setup",
    label: "Setup",
    description: "Store generation settings and workflow context for this model output."
  },
  {
    id: "review",
    label: "Review",
    description: "Capture strengths and weaknesses without crowding the main editor view."
  }
];
function normalizeCodeList(values) {
  return Array.from(new Set((Array.isArray(values) ? values : []).map((value) => String(value || "").trim()).filter(Boolean)));
}
function loadCodeList(storageKey2) {
  if (typeof window === "undefined") return [];
  try {
    return normalizeCodeList(JSON.parse(window.localStorage.getItem(storageKey2) || "[]"));
  } catch {
    return [];
  }
}
function saveCodeList(storageKey2, values) {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(storageKey2, JSON.stringify(normalizeCodeList(values)));
}
function parsePromptImport(rawText, categoryOptions) {
  let parsed;
  try {
    parsed = JSON.parse(String(rawText || ""));
  } catch {
    throw new Error("Could not parse JSON.");
  }
  if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") {
    throw new Error("Import JSON must be an object.");
  }
  const next = {};
  const applied = [];
  const apply = (key, value) => {
    next[key] = value;
    applied.push(key);
  };
  if (parsed.title != null) apply("title", String(parsed.title));
  if (parsed.slug != null) apply("slug", String(parsed.slug));
  if (parsed.excerpt != null) apply("excerpt", String(parsed.excerpt));
  if (parsed.difficulty != null) apply("difficulty", String(parsed.difficulty));
  if (parsed.access_level != null) apply("access_level", String(parsed.access_level));
  if (parsed.access != null && parsed.access_level == null) apply("access_level", String(parsed.access));
  if (parsed.aspect_ratio != null) apply("aspect_ratio", String(parsed.aspect_ratio));
  if (parsed.tags != null) apply("tags", Array.isArray(parsed.tags) ? parsed.tags.map((tag) => typeof tag === "string" ? tag : tag?.name || tag?.label || tag?.title || tag?.slug || "").filter(Boolean).join(", ") : String(parsed.tags));
  if (parsed.prompt != null) apply("prompt", String(parsed.prompt));
  if (parsed.negative_prompt != null) apply("negative_prompt", String(parsed.negative_prompt));
  if (parsed.usage_notes != null) apply("usage_notes", String(parsed.usage_notes));
  if (parsed.workflow_notes != null) apply("workflow_notes", String(parsed.workflow_notes));
  if (parsed.documentation != null) apply("documentation", serializeStructuredJson(parsed.documentation));
  if (parsed.placeholders != null) apply("placeholders", serializeStructuredJson(parsed.placeholders));
  if (parsed.helper_prompts != null) apply("helper_prompts", serializeStructuredJson(parsed.helper_prompts));
  if (parsed.prompt_variants != null) apply("prompt_variants", serializeStructuredJson(parsed.prompt_variants));
  if (parsed.preview_image != null) apply("preview_image", String(parsed.preview_image));
  if (parsed.preview_image_url != null && parsed.preview_image == null) apply("preview_image", String(parsed.preview_image_url));
  if (parsed.published_at != null) apply("published_at", String(parsed.published_at));
  if (parsed.seo_title != null) apply("seo_title", String(parsed.seo_title));
  if (parsed.seo_description != null) apply("seo_description", String(parsed.seo_description));
  if (parsed.featured != null) apply("featured", Boolean(parsed.featured));
  if (parsed.prompt_of_week != null) apply("prompt_of_week", Boolean(parsed.prompt_of_week));
  if (parsed.active != null) apply("active", Boolean(parsed.active));
  if (parsed.tool_notes != null || parsed.comparisons != null) {
    const comparisonSource = Array.isArray(parsed.tool_notes) ? parsed.tool_notes : Array.isArray(parsed.comparisons) ? parsed.comparisons : [];
    apply("tool_notes", normalizePromptComparisons(comparisonSource, { preserveEmpty: true }));
  }
  if (parsed.category_id != null || parsed.category_slug != null || parsed.category != null) {
    const requested = String(parsed.category_id ?? parsed.category_slug ?? parsed.category).trim().toLowerCase();
    const match = (Array.isArray(categoryOptions) ? categoryOptions : []).find((option) => [option.id, option.value, option.slug, option.name, option.label].filter((candidate) => candidate != null).map((candidate) => String(candidate).trim().toLowerCase()).includes(requested));
    if (match) {
      apply("category_id", String(match.id ?? match.value ?? ""));
    }
  }
  if (applied.length === 0) {
    throw new Error("The JSON did not contain any recognized prompt fields.");
  }
  return { next, applied };
}
function getCsrfToken$i() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function uploadPromptComparisonMedia(uploadUrl, file) {
  const formData = new FormData();
  formData.append("slot", "body");
  formData.append("image", file);
  const response = await fetch(uploadUrl, {
    method: "POST",
    headers: {
      "X-CSRF-TOKEN": getCsrfToken$i(),
      Accept: "application/json"
    },
    credentials: "same-origin",
    body: formData
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Could not upload comparison image right now.");
  }
  return payload;
}
async function deletePromptComparisonMedia(deleteUrl, path) {
  if (!deleteUrl || !path) return;
  await fetch(deleteUrl, {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$i(),
      Accept: "application/json"
    },
    credentials: "same-origin",
    body: JSON.stringify({ path })
  });
}
function isSupportedPromptComparisonImage(file) {
  if (!(file instanceof File)) return false;
  if (["image/jpeg", "image/png", "image/webp"].includes(file.type)) {
    return true;
  }
  return /\.(jpe?g|png|webp)$/i.test(String(file.name || ""));
}
function CodeListEditor({ title, description, items, customItems, draftValue, setDraftValue, onAdd, onRemove }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, description), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, items.map((item) => {
    const removable = customItems.includes(item);
    return /* @__PURE__ */ React.createElement("span", { key: item, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, /* @__PURE__ */ React.createElement("span", null, item), removable ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onRemove(item), className: "text-slate-300 transition hover:text-rose-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })) : null);
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("input", { value: draftValue, onChange: (event) => setDraftValue(event.target.value), className: "min-w-[220px] flex-1 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-white outline-none", placeholder: `Add ${title.toLowerCase().slice(0, -1)}` }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onAdd, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-sm font-semibold text-sky-100" }, "Add")));
}
function PromptJsonImportDialog({ open, value, error, onChange, onClose, onApply }) {
  const backdropRef = reactExports.useRef(null);
  const [activeImportTab, setActiveImportTab] = reactExports.useState("input");
  const [copyFeedback, setCopyFeedback] = reactExports.useState("");
  const importTabs = [
    { id: "input", label: "Input", description: "Paste structured prompt JSON and apply it." },
    { id: "structure", label: "Structure example", description: "Reference payload for prompt templates." },
    { id: "docs", label: "Documentation", description: "Field rules and import notes." },
    { id: "prompts", label: "AI prompts", description: "Prompt templates to generate valid JSON." }
  ];
  const structureExample = {
    title: "Peaceful Fantasy Forest Wallpaper",
    slug: "peaceful-fantasy-forest-wallpaper",
    excerpt: "Create a calm fantasy forest wallpaper with glowing flowers, soft morning light, and gentle mist.",
    category: "Academy",
    difficulty: "beginner",
    access_level: "free",
    aspect_ratio: "16:9",
    tags: ["wallpaper", "fantasy", "forest", "glowing flowers", "morning light"],
    prompt: "Create a calm fantasy forest wallpaper with glowing flowers, soft morning light, gentle mist, and a peaceful magical atmosphere.",
    negative_prompt: "blurry, muddy lighting, distorted tree trunks, low detail, oversaturated highlights",
    usage_notes: "Start with the base prompt, then increase atmosphere and foliage density gradually.",
    workflow_notes: "Good candidate for comparison across ChatGPT, Gemini, and Leonardo image models.",
    documentation: {
      summary: "Create a city wallpaper that blends landmark imagery with climate context.",
      best_for: ["travel wallpapers", "editorial posters"],
      how_to_use: ["Choose a city", "Collect climate data", "Insert the placeholders", "Generate and review the final image"],
      required_inputs: ["City name", "Country", "Landmarks", "Monthly weather data"],
      workflow: ["Research", "Prompt preparation", "Image generation"],
      tips: ["Keep the climate ribbon subtle and secondary to the city artwork."],
      common_mistakes: ["Inventing weather data"],
      data_accuracy_notes: ["Use long-term averages where available."],
      display_notes: "Use the image-safe variant when your image model struggles with text."
    },
    placeholders: [
      {
        key: "CITY_NAME",
        label: "City name",
        description: "The city featured in the final image.",
        required: true,
        example: "Paris",
        type: "text"
      }
    ],
    helper_prompts: [
      {
        title: "Collect city climate data",
        type: "data_collection",
        description: "Gather landmark and climate references before using the main prompt.",
        prompt: "Collect city and climate data for [CITY_NAME].",
        expected_output: "json",
        active: true
      }
    ],
    prompt_variants: [
      {
        title: "Image-safe version",
        slug: "image-safe-version",
        description: "Reduced text pressure for image models.",
        prompt: "Create an image-safe city climate portrait.",
        negative_prompt: "tiny text, clutter",
        recommended: true,
        recommended_for: ["general image generation"],
        risk_notes: ["Climate icons may still be abstract"],
        active: true
      }
    ],
    preview_image: "https://files.skinbase.org/prompts/peaceful-fantasy-forest.webp",
    featured: false,
    prompt_of_week: false,
    active: true,
    tool_notes: [
      {
        provider: "ChatGPT",
        model_name: "4o Image",
        settings: "High detail, cinematic natural light, 16:9",
        notes: "Strong mood and color harmony, slightly idealized lighting.",
        strengths: "Atmosphere, foliage glow, readable composition.",
        weaknesses: "Can over-soften foreground detail.",
        best_for: "Wallpaper-style fantasy environments.",
        score: 9,
        active: true
      }
    ]
  };
  const promptJsonSchemaSummary = `You are generating a Skinbase Academy prompt template JSON object.

Return only valid JSON. No markdown, no commentary, no code fences.

Recommended fields:
- title: string
- slug: SEO-friendly slug
- excerpt: concise summary for cards and search results
- category_id or category/category_slug
- difficulty: beginner|intermediate|advanced|pro
- access_level: free|creator|pro|admin
- aspect_ratio: string like 1:1, 16:9, 3:2
- tags: array of strings or objects with name/title/label/slug
- prompt: main prompt text
- negative_prompt: optional exclusions
- usage_notes: practical usage guidance
- workflow_notes: internal/editorial workflow notes
- documentation: object with structured guidance for how to use the prompt
- placeholders: array of prompt variable objects
- helper_prompts: array of supporting prompts used before or after the main prompt
- prompt_variants: array of alternative prompt versions
- preview_image: path or URL
- featured: boolean
- prompt_of_week: boolean
- active: boolean
- published_at: YYYY-MM-DD HH:MM:SS when known
- seo_title, seo_description
- tool_notes: array of model comparison objects

tool_notes object fields:
- provider
- model_name
- settings
- notes
- strengths
- weaknesses
- best_for
- image_path or image_url when available
- score (1-10)
- active boolean

helper_prompts object fields:
- title
- type: data_collection|prompt_preparation|refinement|validation|variation|translation|seo|other
- description
- prompt
- expected_output: json|text|markdown|image_prompt
- active boolean

prompt_variants object fields:
- title
- slug
- description
- prompt
- negative_prompt
- recommended boolean
- recommended_for
- risk_notes
- active boolean

Rules:
- Return one JSON object only.
- Keep excerpt concise and readable in cards.
- Keep tags relevant and production-usable.
- If you include tool_notes, keep them normalized and consistent.`;
  const aiPromptExamples = [
    {
      title: "Prompt template generator",
      prompt: `${promptJsonSchemaSummary}

Create a Skinbase Academy prompt template JSON object from the following creative brief.
- Keep the title concise and catalog-friendly.
- Write a prompt that is immediately usable.
- Write an excerpt that works in cards and search results.
- Add 5 to 12 focused tags.
- Include 2 to 4 tool_notes comparisons when the brief mentions multiple AI providers.

Creative brief:
{{CREATIVE_BRIEF}}`
    },
    {
      title: "Provider comparison generator",
      prompt: `${promptJsonSchemaSummary}

Generate a prompt template JSON object for Skinbase Academy.
- Focus on the same core prompt being tested across multiple AI image providers.
- Include tool_notes entries for each provider.
- Each tool_notes item should explain settings, strengths, weaknesses, and best_for in plain production language.
- Return JSON only.

Source notes:
{{MODEL_COMPARISON_NOTES}}`
    },
    {
      title: "Prompt migration import",
      prompt: `${promptJsonSchemaSummary}

Convert the following source prompt page into structured Skinbase Academy prompt JSON.
- Preserve the core instruction intent.
- Normalize tags and metadata.
- Convert provider reviews into tool_notes.
- Use category/category_slug when category_id is unknown.
- Return JSON only.

Source content:
{{SOURCE_PROMPT_PAGE}}`
    }
  ];
  function tabButtonClass(active) {
    return `flex-1 rounded-2xl border px-4 py-3 text-left transition ${active ? "border-sky-300/25 bg-sky-400/10 text-white" : "border-white/10 bg-white/[0.03] text-slate-400 hover:border-white/20 hover:bg-white/[0.05] hover:text-slate-200"}`;
  }
  const copyText = async (text2, label) => {
    try {
      await copyTextToClipboard(String(text2));
      setCopyFeedback(`${label} copied`);
      window.setTimeout(() => setCopyFeedback(""), 1800);
    } catch {
      setCopyFeedback("Copy failed");
      window.setTimeout(() => setCopyFeedback(""), 1800);
    }
  };
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement("div", { role: "dialog", "aria-modal": "true", "aria-labelledby": "prompt-json-import-title", className: "flex h-[min(90vh,780px)] w-full max-w-5xl flex-col overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Structured import"), /* @__PURE__ */ React.createElement("h3", { id: "prompt-json-import-title", className: "mt-2 text-lg font-semibold text-white" }, "Paste prompt JSON"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Use this to seed the prompt form from AI output, documentation drafts, or migrated prompt library content.")), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 md:grid-cols-4" }, importTabs.map((tab2) => /* @__PURE__ */ React.createElement("button", { key: tab2.id, type: "button", onClick: () => setActiveImportTab(tab2.id), className: tabButtonClass(activeImportTab === tab2.id) }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, tab2.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-current/70" }, tab2.description))))), /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar flex-1 min-h-0 overflow-y-auto px-6 py-5" }, activeImportTab === "input" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
        "textarea",
        {
          value,
          onChange: (event) => onChange?.(event.target.value),
          rows: 18,
          placeholder: '{\n  "title": "Peaceful Fantasy Forest Wallpaper",\n  "excerpt": "Short summary...",\n  "prompt": "Main prompt text...",\n  "tool_notes": []\n}',
          className: "nova-scrollbar w-full rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 font-mono text-sm text-white outline-none placeholder:text-white/30"
        }
      ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recognized keys"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "title, slug, excerpt"), /* @__PURE__ */ React.createElement("p", null, "category_id, category, category_slug"), /* @__PURE__ */ React.createElement("p", null, "difficulty, access_level, aspect_ratio"), /* @__PURE__ */ React.createElement("p", null, "tags"), /* @__PURE__ */ React.createElement("p", null, "prompt, negative_prompt"), /* @__PURE__ */ React.createElement("p", null, "usage_notes, workflow_notes"), /* @__PURE__ */ React.createElement("p", null, "documentation, placeholders"), /* @__PURE__ */ React.createElement("p", null, "helper_prompts, prompt_variants"), /* @__PURE__ */ React.createElement("p", null, "preview_image, preview_image_url"), /* @__PURE__ */ React.createElement("p", null, "published_at, seo_title, seo_description"), /* @__PURE__ */ React.createElement("p", null, "featured, prompt_of_week, active"), /* @__PURE__ */ React.createElement("p", null, "tool_notes, comparisons")))) : null, activeImportTab === "structure" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Structure example"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => copyText(JSON.stringify(structureExample, null, 2), "Structure example"), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy example")), /* @__PURE__ */ React.createElement("pre", { className: "nova-scrollbar max-h-[52vh] overflow-auto rounded-[20px] border border-white/10 bg-slate-950/80 p-4 text-xs leading-6 text-slate-200" }, JSON.stringify(structureExample, null, 2))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "`tool_notes` can be an array of comparison objects or a simpler array under `comparisons`."), /* @__PURE__ */ React.createElement("p", null, "`documentation`, `placeholders`, `helper_prompts`, and `prompt_variants` can be nested JSON and are preserved during import."), /* @__PURE__ */ React.createElement("p", null, "`tags` can be strings or objects with `name`, `label`, `title`, or `slug`."), /* @__PURE__ */ React.createElement("p", null, "`preview_image` accepts either a stored path or an external URL.")))) : null, activeImportTab === "docs" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Field guide"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "title"), " - public prompt name used in the library and detail page."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "excerpt"), " - short summary for cards, preview blocks, and search results."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "prompt"), " - the main instruction body shown to creators."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "negative_prompt"), " - exclusions, defects, or anti-patterns."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "documentation"), " - structured user-facing guidance for summary, workflow, tips, and common mistakes."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "placeholders"), " - prompt variables such as `CITY_NAME` or `MONTHLY_WEATHER_DATA`."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "helper_prompts"), " - supporting prompts for data collection, validation, or refinement."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "prompt_variants"), " - alternative versions of the same prompt for safer or model-specific output."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "tool_notes"), " - structured comparison notes for provider/model variants."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "preview_image"), " - existing asset URL or stored path. File upload still happens separately."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "category_id"), " is preferred when known. `category` or `category_slug` are used for best-effort matching."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Import rules"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Unknown keys are ignored, so broader AI output is safe to paste."), /* @__PURE__ */ React.createElement("p", null, "Use JSON booleans for featured, prompt_of_week, and active."), /* @__PURE__ */ React.createElement("p", null, "Use `YYYY-MM-DD HH:MM:SS` for `published_at` when scheduling is needed."), /* @__PURE__ */ React.createElement("p", null, "Use `documentation` for longer public guidance, and keep `usage_notes` short and practical."), /* @__PURE__ */ React.createElement("p", null, "Use `helper_prompts` for data collection or validation prompts, and `prompt_variants` for safer or model-specific alternatives."), /* @__PURE__ */ React.createElement("p", null, "Keep comparison rows normalized so provider/model names remain consistent in the frontend.")))) : null, activeImportTab === "prompts" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 items-start gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid min-w-0 gap-4" }, aiPromptExamples.map((example) => /* @__PURE__ */ React.createElement("div", { key: example.title, className: "min-w-0 overflow-hidden rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-200/70" }, example.title), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => copyText(example.prompt, example.title), className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Copy prompt")), /* @__PURE__ */ React.createElement("pre", { className: "nova-scrollbar mt-3 max-h-56 min-w-0 overflow-auto whitespace-pre-wrap break-words rounded-[18px] border border-white/10 bg-slate-950/80 p-4 text-sm leading-6 text-slate-200 [overflow-wrap:anywhere]" }, example.prompt)))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 self-start rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Prompt tips"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Tell the model to return JSON only, with no explanation text."), /* @__PURE__ */ React.createElement("p", null, "Ask for `tool_notes` when you want provider-by-provider comparison output."), /* @__PURE__ */ React.createElement("p", null, "Ask for `documentation`, `placeholders`, `helper_prompts`, and `prompt_variants` only when the prompt needs advanced structure."), /* @__PURE__ */ React.createElement("p", null, "Tell the model to keep titles and tags production-ready, not overly verbose.")))) : null), copyFeedback ? /* @__PURE__ */ React.createElement("div", { className: "px-6 pb-2 text-right text-xs font-medium text-sky-200/80" }, copyFeedback) : null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClose?.(), className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApply?.(), className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110" }, "Apply JSON")))
    ),
    document.body
  );
}
function firstPromptErrorTab(errors) {
  const firstKey = Object.keys(errors || {})[0];
  if (!firstKey) return null;
  return PROMPT_FIELD_TAB_MAP[firstKey] || null;
}
function promptTabErrorCounts(errors) {
  const counts = {};
  Object.keys(errors || {}).forEach((key) => {
    const tabId = PROMPT_FIELD_TAB_MAP[key];
    if (!tabId) return;
    counts[tabId] = Number(counts[tabId] || 0) + 1;
  });
  return counts;
}
function PromptEditorTabs({ activeTab, onChange, errorCounts }) {
  const activeMeta = PROMPT_EDITOR_TABS.find((tab2) => tab2.id === activeTab) || PROMPT_EDITOR_TABS[0];
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-4 z-20 rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(7,11,18,0.92),rgba(5,8,14,0.88))] px-3 py-3 shadow-[0_18px_50px_rgba(2,6,23,0.18)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2", role: "tablist", "aria-label": "Prompt editor sections" }, PROMPT_EDITOR_TABS.map((tab2) => {
    const isActive = tab2.id === activeTab;
    const errorCount = Number(errorCounts?.[tab2.id] || 0);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.id,
        type: "button",
        role: "tab",
        "aria-selected": isActive,
        "aria-controls": `prompt-editor-panel-${tab2.id}`,
        id: `prompt-editor-tab-${tab2.id}`,
        onClick: () => onChange(tab2.id),
        className: [
          "inline-flex items-center gap-2 rounded-2xl border px-4 py-2.5 text-sm font-semibold transition",
          isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-white/80 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} text-xs` }),
      /* @__PURE__ */ React.createElement("span", null, tab2.label),
      errorCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.14em] text-rose-100" }, errorCount) : null
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center justify-between gap-3 px-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-400" }, activeMeta.description), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, activeMeta.sections.map((section) => /* @__PURE__ */ React.createElement("span", { key: section, className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, section.replace("prompt-", "").replace(/-/g, " "))))));
}
function PromptComparisonEditor({ comparisons, setComparisons, editorContext }) {
  const [busyIndex, setBusyIndex] = reactExports.useState(null);
  const [comparisonEditorTabs, setComparisonEditorTabs] = reactExports.useState({});
  const [uploadError, setUploadError] = reactExports.useState("");
  const [bulkUploadState, setBulkUploadState] = reactExports.useState(null);
  const [bulkComparisonType, setBulkComparisonType] = reactExports.useState("");
  const [isBulkDropActive, setIsBulkDropActive] = reactExports.useState(false);
  const [draftProvider, setDraftProvider] = reactExports.useState("");
  const [draftModel, setDraftModel] = reactExports.useState("");
  const [customProviders, setCustomProviders] = reactExports.useState([]);
  const [customModels, setCustomModels] = reactExports.useState([]);
  const bulkFileInputRef = reactExports.useRef(null);
  const comparisonsRef = reactExports.useRef(Array.isArray(comparisons) ? comparisons : []);
  const providerStorageKey = "academy.prompt-comparison.providers";
  const modelStorageKey = "academy.prompt-comparison.models";
  const defaultProviders = normalizeCodeList(editorContext?.comparisonCodeLists?.providers || []);
  const defaultModels = normalizeCodeList(editorContext?.comparisonCodeLists?.models || []);
  const providerOptions = normalizeCodeList([...defaultProviders, ...customProviders, ...comparisons.map((comparison) => comparison.provider)]).map((value) => ({ value, label: value }));
  const modelOptions = normalizeCodeList([...defaultModels, ...customModels, ...comparisons.map((comparison) => comparison.model_name)]).map((value) => ({ value, label: value }));
  reactExports.useEffect(() => {
    setCustomProviders(loadCodeList(providerStorageKey));
    setCustomModels(loadCodeList(modelStorageKey));
  }, []);
  reactExports.useEffect(() => {
    comparisonsRef.current = Array.isArray(comparisons) ? comparisons : [];
  }, [comparisons]);
  const commitComparisons = (nextComparisons) => {
    const normalized = normalizePromptComparisons(nextComparisons, { preserveEmpty: true });
    comparisonsRef.current = normalized;
    setComparisons(normalized);
    return normalized;
  };
  const replaceComparison = (index2, nextComparison) => {
    const currentComparisons = comparisonsRef.current;
    if (index2 < 0 || index2 >= currentComparisons.length) return;
    commitComparisons(currentComparisons.map((comparison, currentIndex) => currentIndex === index2 ? sanitizePromptComparison(nextComparison) : comparison));
  };
  const updateComparison = (index2, field, value) => {
    const currentComparison = comparisonsRef.current[index2];
    if (!currentComparison) return;
    replaceComparison(index2, { ...currentComparison, [field]: value });
  };
  const removeStoredMedia = async (comparison) => {
    const deleteUrl = editorContext?.comparisonMediaDeleteUrl || "";
    const imagePaths = [comparison?.image_path, comparison?.thumb_path].filter(Boolean);
    await Promise.all(imagePaths.map((path) => deletePromptComparisonMedia(deleteUrl, path)));
  };
  const removeComparison = async (index2) => {
    const currentComparisons = comparisonsRef.current;
    const comparison = currentComparisons[index2];
    if (!comparison) return;
    commitComparisons(currentComparisons.filter((_2, currentIndex) => currentIndex !== index2));
    try {
      await removeStoredMedia(comparison);
    } catch {
    }
  };
  const moveComparison = (index2, direction) => {
    const nextIndex = index2 + direction;
    const currentComparisons = comparisonsRef.current;
    if (nextIndex < 0 || nextIndex >= currentComparisons.length) return;
    const nextComparisons = [...currentComparisons];
    const [entry] = nextComparisons.splice(index2, 1);
    nextComparisons.splice(nextIndex, 0, entry);
    commitComparisons(nextComparisons);
  };
  const resolvePreviewUrl = (comparison) => comparison.thumb_url || comparison.image_url || "";
  const addComparison = () => commitComparisons([
    ...comparisonsRef.current,
    sanitizePromptComparison({
      ...emptyPromptComparison(),
      display_type: bulkComparisonType
    })
  ]);
  const addCustomProvider = () => {
    const nextValue = String(draftProvider || "").trim();
    if (!nextValue) return;
    const nextItems = normalizeCodeList([...customProviders, nextValue]);
    setCustomProviders(nextItems);
    saveCodeList(providerStorageKey, nextItems);
    setDraftProvider("");
  };
  const addCustomModel = () => {
    const nextValue = String(draftModel || "").trim();
    if (!nextValue) return;
    const nextItems = normalizeCodeList([...customModels, nextValue]);
    setCustomModels(nextItems);
    saveCodeList(modelStorageKey, nextItems);
    setDraftModel("");
  };
  const removeCustomProvider = (value) => {
    const nextItems = customProviders.filter((item) => item !== value);
    setCustomProviders(nextItems);
    saveCodeList(providerStorageKey, nextItems);
  };
  const removeCustomModel = (value) => {
    const nextItems = customModels.filter((item) => item !== value);
    setCustomModels(nextItems);
    saveCodeList(modelStorageKey, nextItems);
  };
  const uploadComparisonImage = async (index2, file) => {
    const uploadUrl = editorContext?.comparisonMediaUploadUrl || "";
    if (!uploadUrl || !file) return;
    const previous2 = comparisonsRef.current[index2];
    if (!previous2) return;
    setBusyIndex(index2);
    try {
      const uploaded = await uploadPromptComparisonMedia(uploadUrl, file);
      const currentComparison = comparisonsRef.current[index2] || previous2;
      replaceComparison(index2, {
        ...currentComparison,
        image_path: uploaded.path || "",
        image_url: uploaded.url || "",
        thumb_path: uploaded.thumb_path || uploaded.path || "",
        thumb_url: uploaded.thumb_url || uploaded.url || ""
      });
      if (previous2?.image_path && previous2.image_path !== uploaded.path) {
        await deletePromptComparisonMedia(editorContext?.comparisonMediaDeleteUrl || "", previous2.image_path);
      }
      if (previous2?.thumb_path && previous2.thumb_path !== (uploaded.thumb_path || uploaded.path)) {
        await deletePromptComparisonMedia(editorContext?.comparisonMediaDeleteUrl || "", previous2.thumb_path);
      }
    } finally {
      setBusyIndex(null);
    }
  };
  const handleUpload = async (index2, file) => {
    setUploadError("");
    try {
      await uploadComparisonImage(index2, file);
    } catch (error) {
      setUploadError(error instanceof Error ? error.message : "Could not upload comparison image.");
    }
  };
  const handleBulkUpload = async (fileList) => {
    const incomingFiles = Array.from(fileList || []).filter((file) => file instanceof File);
    if (incomingFiles.length === 0) return;
    const validFiles = incomingFiles.filter((file) => isSupportedPromptComparisonImage(file));
    const invalidFiles = incomingFiles.filter((file) => !isSupportedPromptComparisonImage(file));
    if (validFiles.length === 0) {
      setUploadError("Select one or more JPG, PNG, or WebP images to create comparison blocks.");
      return;
    }
    setUploadError("");
    const startIndex = comparisonsRef.current.length;
    commitComparisons([
      ...comparisonsRef.current,
      ...validFiles.map(() => sanitizePromptComparison({
        ...emptyPromptComparison(),
        display_type: bulkComparisonType
      }))
    ]);
    const failedFiles = [];
    try {
      for (let offset = 0; offset < validFiles.length; offset += 1) {
        setBulkUploadState({ current: offset + 1, total: validFiles.length });
        try {
          await uploadComparisonImage(startIndex + offset, validFiles[offset]);
        } catch {
          failedFiles.push(validFiles[offset].name || `Image ${offset + 1}`);
        }
      }
    } finally {
      setBulkUploadState(null);
      setIsBulkDropActive(false);
    }
    const notices = [];
    if (invalidFiles.length > 0) {
      notices.push(`Skipped ${invalidFiles.length} unsupported ${invalidFiles.length === 1 ? "file" : "files"}.`);
    }
    if (failedFiles.length > 0) {
      notices.push(`${failedFiles.length} ${failedFiles.length === 1 ? "image failed" : "images failed"} to upload.`);
    }
    setUploadError(notices.join(" "));
  };
  const clearMedia = async (index2) => {
    const comparison = comparisonsRef.current[index2];
    if (!comparison) return;
    replaceComparison(index2, {
      ...comparison,
      image_path: "",
      image_url: "",
      thumb_path: "",
      thumb_url: ""
    });
    try {
      await removeStoredMedia(comparison);
    } catch {
    }
  };
  const setComparisonEditorTab = (comparisonKey, tabId) => {
    setComparisonEditorTabs((current) => current?.[comparisonKey] === tabId ? current : { ...current, [comparisonKey]: tabId });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Structured blocks"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, "Upload the generated output for each provider, then document what it does well, where it fails, and which workflow it fits best.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addComparison, className: "rounded-full border border-amber-300/25 bg-amber-300/12 px-4 py-2.5 text-sm font-semibold text-amber-100 transition hover:bg-amber-300/18" }, "+ Add AI Comparison")), uploadError ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, uploadError) : null, comparisons.length ? comparisons.map((comparison, index2) => {
    const comparisonKey = comparison.client_key || `comparison-${index2}`;
    const activeComparisonTab = comparisonEditorTabs[comparisonKey] || "summary";
    const activeComparisonTabMeta = PROMPT_COMPARISON_EDITOR_TABS.find((tab2) => tab2.id === activeComparisonTab) || PROMPT_COMPARISON_EDITOR_TABS[0];
    return /* @__PURE__ */ React.createElement("section", { key: comparisonKey, className: "overflow-hidden rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.72),rgba(8,12,20,0.92))] p-5 shadow-[0_24px_70px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-200/75" }, "AI model comparison"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold tracking-[-0.03em] text-white" }, comparison.model_name || `${comparison.display_type || "Comparison"} ${String(index2 + 1).padStart(2, "0")}`), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Document how this model handles the same prompt so creators can choose the right tool faster.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveComparison(index2, -1), disabled: index2 === 0, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white disabled:opacity-40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveComparison(index2, 1), disabled: index2 === comparisons.length - 1, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white disabled:opacity-40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeComparison(index2), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-2 text-xs font-semibold text-rose-100" }, "Remove"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-5 xl:grid-cols-[280px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3 xl:sticky xl:top-5 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-[radial-gradient(circle_at_top,rgba(56,189,248,0.16),rgba(2,6,23,0.92))] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.08] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, comparison.display_type || "Comparison"), comparison.provider ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, comparison.provider) : null, comparison.score ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/12 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Score ", comparison.score) : null), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]" }, resolvePreviewUrl(comparison) ? /* @__PURE__ */ React.createElement("img", { src: resolvePreviewUrl(comparison), alt: comparison.model_name || comparison.provider || `Comparison ${index2 + 1}`, className: "h-72 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-72 flex-col items-center justify-center gap-3 px-5 text-center text-sm text-slate-500" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-image" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-slate-200" }, "No comparison image yet"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-500" }, "Upload the generated result so editors can review differences at a glance."))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 sm:grid-cols-2 lg:grid-cols-1" }, /* @__PURE__ */ React.createElement("label", { className: "cursor-pointer rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-center text-sm font-semibold text-sky-100 transition hover:bg-sky-300/18" }, /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "file",
        accept: "image/jpeg,image/png,image/webp",
        className: "hidden",
        disabled: busyIndex === index2 || Boolean(bulkUploadState),
        onChange: (event) => {
          const file = event.target.files?.[0] || null;
          if (file) {
            handleUpload(index2, file);
          }
          event.target.value = "";
        }
      }
    ), busyIndex === index2 ? "Uploading..." : resolvePreviewUrl(comparison) ? "Replace image" : "Upload image"), comparison.image_path ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearMedia(index2), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-slate-200 transition hover:bg-white/[0.08]" }, "Clear image") : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-black/30 px-4 py-3 text-xs leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, "Stored asset"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 break-all" }, comparison.image_path || "No uploaded comparison image yet."), comparison.model_name || comparison.provider ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, comparison.model_name ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, comparison.model_name) : null, comparison.provider ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, comparison.provider) : null) : null)), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2", role: "tablist", "aria-label": `Comparison ${index2 + 1} sections` }, PROMPT_COMPARISON_EDITOR_TABS.map((tab2) => {
      const isActive = tab2.id === activeComparisonTab;
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          key: tab2.id,
          type: "button",
          role: "tab",
          "aria-selected": isActive,
          onClick: () => setComparisonEditorTab(comparisonKey, tab2.id),
          className: [
            "inline-flex items-center gap-2 rounded-2xl border px-4 py-2.5 text-sm font-semibold transition",
            isActive ? "border-sky-300/25 bg-sky-300/12 text-sky-100 ring-1 ring-sky-300/20" : "border-white/10 bg-white/[0.03] text-white/80 hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white"
          ].join(" ")
        },
        /* @__PURE__ */ React.createElement("span", null, tab2.label)
      );
    })), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-5 text-slate-400" }, activeComparisonTabMeta.description)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, comparison.display_type || "Default")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Provider"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, comparison.provider || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Model"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, comparison.model_name || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Visibility"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, comparison.active ? "Visible" : "Hidden")))), activeComparisonTab === "summary" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mt-0 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Type", value: comparison.display_type || "", onChange: (nextValue) => updateComparison(index2, "display_type", String(nextValue || "")), options: PROMPT_COMPARISON_TYPE_OPTIONS, className: "rounded-2xl bg-black/20" }), /* @__PURE__ */ React.createElement(TextField$1, { label: "Score", type: "number", min: "1", max: "10", value: comparison.score, onChange: (event) => updateComparison(index2, "score", event.target.value), placeholder: "1-10" })), /* @__PURE__ */ React.createElement("div", { className: "mt-0 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Provider", value: comparison.provider || "", onChange: (nextValue) => updateComparison(index2, "provider", String(nextValue || "")), options: providerOptions, searchable: true, className: "rounded-2xl bg-black/20" }), /* @__PURE__ */ React.createElement(NovaSelect, { label: "Model", value: comparison.model_name || "", onChange: (nextValue) => updateComparison(index2, "model_name", String(nextValue || "")), options: modelOptions, searchable: true, className: "rounded-2xl bg-black/20" })), /* @__PURE__ */ React.createElement(TextAreaField, { label: "Notes", value: comparison.notes, onChange: (event) => updateComparison(index2, "notes", event.target.value), rows: 5, hint: "How does this provider interpret the prompt overall?" }), /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer items-center justify-between gap-4 rounded-[24px] border px-5 py-4 transition ${comparison.active ? "border-[#f39a24]/35 bg-[#f39a24]/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(comparison.active), onChange: (event) => updateComparison(index2, "active", event.target.checked), className: "sr-only" }), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block text-sm font-semibold tracking-[-0.02em] text-white" }, "Visible on frontend"), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-sm leading-6 text-slate-300" }, "Turn this off to keep the comparison saved but hidden publicly.")), /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-12 min-w-[92px] items-center justify-center rounded-full border px-4 text-sm font-semibold transition ${comparison.active ? "border-[#f39a24] bg-[#f39a24] text-white" : "border-white/10 bg-[#151a29] text-slate-300"}` }, comparison.active ? "Visible" : "Hidden")), /* @__PURE__ */ React.createElement(TextAreaField, { label: "Best for", value: comparison.best_for, onChange: (event) => updateComparison(index2, "best_for", event.target.value), rows: 4, hint: "What type of creator or output is this model the best fit for?" })) : null, activeComparisonTab === "setup" ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextAreaField, { label: "Generation details", value: comparison.settings, onChange: (event) => updateComparison(index2, "settings", event.target.value), rows: 7, hint: "Mention where it was generated, model mode, aspect ratio, or special settings." }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5 text-sm leading-7 text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "What to capture here"), /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Record the setup details you would want when reproducing the result later: provider mode, prompt tweaks, seed or aspect ratio, and any notable generation constraints."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, "Mode"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, "Aspect ratio"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, "Prompt changes"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5" }, "Seed")))) : null, activeComparisonTab === "review" ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextAreaField, { label: "Strengths", value: comparison.strengths, onChange: (event) => updateComparison(index2, "strengths", event.target.value), rows: 7, hint: "What this model consistently does well with the prompt." }), /* @__PURE__ */ React.createElement(TextAreaField, { label: "Weaknesses", value: comparison.weaknesses, onChange: (event) => updateComparison(index2, "weaknesses", event.target.value), rows: 7, hint: "What tends to fail or need correction in post-processing." })) : null)));
  }) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 bg-black/20 px-6 py-8 text-sm text-slate-400" }, "No comparison blocks yet. Add one when the same prompt needs model-specific guidance."), /* @__PURE__ */ React.createElement("div", { className: "flex justify-center" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addComparison, className: "rounded-full border border-amber-300/25 bg-amber-300/12 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-300/18" }, "+ Add AI Comparison")), /* @__PURE__ */ React.createElement(
    "div",
    {
      className: [
        "rounded-[28px] border border-dashed px-6 py-8 transition",
        isBulkDropActive ? "border-sky-300/40 bg-sky-300/10" : "border-white/10 bg-black/20 hover:border-sky-300/25 hover:bg-sky-300/[0.06]"
      ].join(" "),
      onDragOver: (event) => {
        event.preventDefault();
        if (!bulkUploadState) {
          setIsBulkDropActive(true);
        }
      },
      onDragLeave: (event) => {
        event.preventDefault();
        if (event.currentTarget.contains(event.relatedTarget)) return;
        setIsBulkDropActive(false);
      },
      onDrop: (event) => {
        event.preventDefault();
        if (bulkUploadState) return;
        setIsBulkDropActive(false);
        handleBulkUpload(event.dataTransfer?.files);
      }
    },
    /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: bulkFileInputRef,
        type: "file",
        multiple: true,
        accept: "image/jpeg,image/png,image/webp",
        className: "hidden",
        disabled: Boolean(bulkUploadState),
        onChange: (event) => {
          handleBulkUpload(event.target.files);
          event.target.value = "";
        }
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex max-w-3xl flex-col items-center text-center" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-14 w-14 items-center justify-center rounded-[20px] border border-white/10 bg-white/[0.04] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images text-lg" })), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Bulk comparison uploads"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, "Drag and drop multiple images to create comparison blocks"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-7 text-slate-300" }, "Each uploaded image creates a new AI comparison block at the bottom, then runs through the same upload process used by the per-block image picker."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 w-full max-w-md text-left" }, /* @__PURE__ */ React.createElement(
      NovaSelect,
      {
        label: "Type for new blocks",
        value: bulkComparisonType,
        onChange: (nextValue) => setBulkComparisonType(String(nextValue || "")),
        options: PROMPT_COMPARISON_TYPE_OPTIONS,
        searchable: false,
        className: "rounded-2xl bg-black/20"
      }
    ), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-5 text-slate-500" }, "The selected type is applied automatically to every block created by this multi-image upload.")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap items-center justify-center gap-3" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => bulkFileInputRef.current?.click(),
        disabled: Boolean(bulkUploadState),
        className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-300/18 disabled:cursor-not-allowed disabled:opacity-60"
      },
      bulkUploadState ? `Uploading ${bulkUploadState.current} of ${bulkUploadState.total}...` : "Select multiple images"
    ), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, "or drop JPG, PNG, and WebP files here")))
  ), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Provider and model library"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, "Keep reusable provider and model names here so comparison entries stay consistent and easy to scan.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    CodeListEditor,
    {
      title: "Providers",
      description: "Use a short consistent provider name in the dropdown. Add custom ones when a new tool appears.",
      items: providerOptions.map((option) => option.value),
      customItems: customProviders,
      draftValue: draftProvider,
      setDraftValue: setDraftProvider,
      onAdd: addCustomProvider,
      onRemove: removeCustomProvider
    }
  ), /* @__PURE__ */ React.createElement(
    CodeListEditor,
    {
      title: "Models",
      description: "Keep model names standardized so frontend comparisons stay readable and sortable.",
      items: modelOptions.map((option) => option.value),
      customItems: customModels,
      draftValue: draftModel,
      setDraftValue: setDraftModel,
      onAdd: addCustomModel,
      onRemove: removeCustomModel
    }
  ))));
}
function Field$5({ field, form }) {
  const value = form.data[field.name];
  if (field.type === "checkbox") {
    return /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(value), onChange: (event) => form.setData(field.name, event.target.checked) }), field.label);
  }
  if (field.type === "datetime-local") {
    return /* @__PURE__ */ React.createElement(
      DateTimePicker,
      {
        label: field.label,
        value: value || "",
        onChange: (nextValue) => form.setData(field.name, nextValue || ""),
        error: form.errors[field.name],
        clearable: true,
        className: "bg-black/20"
      }
    );
  }
  if (field.type === "textarea") {
    return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, field.label), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: value || "",
        onChange: (event) => form.setData(field.name, event.target.value),
        rows: field.rows || 6,
        className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-7 text-white outline-none"
      }
    ), form.errors[field.name] ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, form.errors[field.name]) : null);
  }
  if (field.type === "select") {
    return /* @__PURE__ */ React.createElement(
      NovaSelect,
      {
        label: field.label,
        value: value ?? "",
        onChange: (nextValue) => form.setData(field.name, nextValue ?? ""),
        options: field.options || [],
        searchable: false,
        className: "rounded-2xl bg-black/20",
        error: form.errors[field.name]
      }
    );
  }
  if (field.type === "multiselect") {
    return /* @__PURE__ */ React.createElement(
      NovaSelect,
      {
        multi: true,
        label: field.label,
        value: value || [],
        onChange: (nextValue) => form.setData(field.name, Array.isArray(nextValue) ? nextValue : []),
        options: field.options || [],
        className: "rounded-2xl bg-black/20",
        error: form.errors[field.name]
      }
    );
  }
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, field.label), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: field.type || "text",
      value: value ?? "",
      onChange: (event) => form.setData(field.name, event.target.value),
      className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none"
    }
  ), form.errors[field.name] ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, form.errors[field.name]) : null);
}
function PromptPreviewDropzone({ form, previewUrl }) {
  const inputRef = reactExports.useRef(null);
  const [dragging, setDragging] = reactExports.useState(false);
  const [localPreviewUrl, setLocalPreviewUrl] = reactExports.useState("");
  const [selectedFileName, setSelectedFileName] = reactExports.useState("");
  const previewSrc = localPreviewUrl || previewUrl || form.data.preview_image || "";
  reactExports.useEffect(() => () => {
    if (localPreviewUrl.startsWith("blob:")) {
      URL.revokeObjectURL(localPreviewUrl);
    }
  }, [localPreviewUrl]);
  const setSelectedFile = (file) => {
    if (localPreviewUrl.startsWith("blob:")) {
      URL.revokeObjectURL(localPreviewUrl);
    }
    if (!file) {
      setLocalPreviewUrl("");
      setSelectedFileName("");
      form.setData("preview_image_file", null);
      form.clearErrors("preview_image_file");
      return;
    }
    const nextPreviewUrl = URL.createObjectURL(file);
    setLocalPreviewUrl(nextPreviewUrl);
    setSelectedFileName(file.name);
    form.setData("preview_image_file", file);
    form.clearErrors("preview_image_file");
  };
  const clearSelection = () => {
    if (localPreviewUrl.startsWith("blob:")) {
      URL.revokeObjectURL(localPreviewUrl);
    }
    setLocalPreviewUrl("");
    setSelectedFileName("");
    form.setData("preview_image_file", null);
    form.clearErrors("preview_image_file");
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };
  return /* @__PURE__ */ React.createElement(
    SectionCard$4,
    {
      eyebrow: "Visual preview",
      title: "Preview image",
      description: "Drag an image here or paste a URL. Uploaded files are converted to WebP and stored on Contabo automatically."
    },
    /* @__PURE__ */ React.createElement(
      "div",
      {
        role: "button",
        tabIndex: 0,
        onClick: () => inputRef.current?.click(),
        onKeyDown: (event) => {
          if (event.key === "Enter" || event.key === " ") {
            event.preventDefault();
            inputRef.current?.click();
          }
        },
        onDragOver: (event) => {
          event.preventDefault();
          setDragging(true);
        },
        onDragEnter: (event) => {
          event.preventDefault();
          setDragging(true);
        },
        onDragLeave: (event) => {
          event.preventDefault();
          setDragging(false);
        },
        onDrop: (event) => {
          event.preventDefault();
          setDragging(false);
          setSelectedFile(event.dataTransfer?.files?.[0] || null);
        },
        className: [
          "w-full min-w-0 rounded-[28px] border border-dashed p-5 outline-none transition",
          dragging ? "border-sky-300/50 bg-sky-400/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Drop a preview image or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, "JPG, PNG, or WEBP. The server re-encodes the final asset to WebP before uploading it to the CDN."), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "JPG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "PNG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "Max 5 MB")))), /* @__PURE__ */ React.createElement("div", { className: "grid w-full max-w-full gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, previewSrc ? /* @__PURE__ */ React.createElement("img", { src: previewSrc, alt: "Prompt preview", className: "h-40 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-40 items-center justify-center px-4 text-center text-sm text-slate-500" }, "No preview image selected")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => inputRef.current?.click(), className: "flex-1 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse"), selectedFileName || localPreviewUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: clearSelection, className: "rounded-full border border-white/10 bg-transparent px-4 py-2.5 text-sm font-semibold text-slate-300 transition hover:bg-white/[0.04]" }, "Clear") : null))),
      /* @__PURE__ */ React.createElement(
        "input",
        {
          ref: inputRef,
          type: "file",
          accept: "image/jpeg,image/png,image/webp",
          className: "hidden",
          onChange: (event) => {
            setSelectedFile(event.target.files?.[0] || null);
            event.target.value = "";
          }
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid min-w-0 gap-3 md:grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,220px)]" }, /* @__PURE__ */ React.createElement(
        TextField$1,
        {
          label: "Preview image URL fallback",
          value: form.data.preview_image || "",
          onChange: (event) => form.setData("preview_image", event.target.value),
          error: form.errors.preview_image,
          placeholder: "Paste a URL or leave empty if you upload a file"
        }
      ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, "Stored value"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 break-all text-slate-400" }, form.data.preview_image_file?.name || form.data.preview_image || previewUrl || "None yet"))),
      form.errors.preview_image_file ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-rose-300" }, form.errors.preview_image_file) : null
    )
  );
}
function PromptEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext }) {
  const form = G$1({ ...record, new_category_name: "", preview_image_file: null, tool_notes: normalizePromptComparisons(record.tool_notes, { preserveEmpty: true }) });
  const categoryField = reactExports.useMemo(() => getField(fields, "category_id"), [fields]);
  const categoryOptions = reactExports.useMemo(() => {
    const options = Array.isArray(categoryField?.options) ? categoryField.options : [];
    const emptyOptions2 = options.filter((option) => String(option?.value ?? "") === "");
    const filledOptions = options.filter((option) => String(option?.value ?? "") !== "").slice().sort((left, right) => String(left?.label ?? "").localeCompare(String(right?.label ?? ""), void 0, { numeric: true, sensitivity: "base" }));
    return [...emptyOptions2, ...filledOptions];
  }, [categoryField]);
  const difficultyField = reactExports.useMemo(() => getField(fields, "difficulty"), [fields]);
  const accessField = reactExports.useMemo(() => getField(fields, "access_level"), [fields]);
  const publishedAtField = reactExports.useMemo(() => getField(fields, "published_at"), [fields]);
  const featuredField = reactExports.useMemo(() => getField(fields, "featured"), [fields]);
  const promptOfWeekField = reactExports.useMemo(() => getField(fields, "prompt_of_week"), [fields]);
  const activeField = reactExports.useMemo(() => getField(fields, "active"), [fields]);
  const seoDescriptionField = reactExports.useMemo(() => getField(fields, "seo_description"), [fields]);
  const documentationField = reactExports.useMemo(() => getField(fields, "documentation"), [fields]);
  const placeholdersField = reactExports.useMemo(() => getField(fields, "placeholders"), [fields]);
  const helperPromptsField = reactExports.useMemo(() => getField(fields, "helper_prompts"), [fields]);
  const promptVariantsField = reactExports.useMemo(() => getField(fields, "prompt_variants"), [fields]);
  const slugTouchedRef = reactExports.useRef(Boolean(String(record.slug || "").trim()));
  const [activeTab, setActiveTab] = reactExports.useState("overview");
  const [jsonImportOpen, setJsonImportOpen] = reactExports.useState(false);
  const [jsonImportValue, setJsonImportValue] = reactExports.useState("");
  const [jsonImportError, setJsonImportError] = reactExports.useState("");
  const [toast, setToast] = reactExports.useState({ id: 0, visible: false, message: "", variant: "success" });
  const previewUrl = form.data.preview_image_url || "";
  const tagCount = String(form.data.tags || "").split(/[,\n]/).map((item) => item.trim()).filter(Boolean).length;
  const promptWordCount = reactExports.useMemo(() => countPlainWords(form.data.prompt), [form.data.prompt]);
  const negativePromptWordCount = reactExports.useMemo(() => countPlainWords(form.data.negative_prompt), [form.data.negative_prompt]);
  const comparisonCount = Array.isArray(form.data.tool_notes) ? form.data.tool_notes.length : 0;
  const tabErrorCounts = reactExports.useMemo(() => promptTabErrorCounts(form.errors), [form.errors]);
  const activeTabMeta = reactExports.useMemo(() => PROMPT_EDITOR_TABS.find((tab2) => tab2.id === activeTab) || PROMPT_EDITOR_TABS[0], [activeTab]);
  const visibleSections = reactExports.useMemo(() => new Set(activeTabMeta.sections), [activeTabMeta]);
  const sectionClassName = (sectionId, className = "") => `${visibleSections.has(sectionId) ? "" : "hidden"} ${className}`.trim();
  const editorLinks = editorContext?.links || {};
  const [heroPreviewObjectUrl, setHeroPreviewObjectUrl] = reactExports.useState("");
  const heroPreviewImage = heroPreviewObjectUrl || previewUrl || form.data.preview_image || "";
  const showToast = (message, variant = "error") => {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant
    });
  };
  reactExports.useEffect(() => {
    if (slugTouchedRef.current) return;
    form.setData("slug", slugifyPromptTitle(form.data.title));
  }, [form, form.data.title]);
  reactExports.useEffect(() => {
    const nextTab = firstPromptErrorTab(form.errors);
    if (!nextTab) return;
    setActiveTab(nextTab);
  }, [form.errors]);
  reactExports.useEffect(() => {
    const previewFile = form.data.preview_image_file;
    if (!(previewFile instanceof File)) {
      setHeroPreviewObjectUrl("");
      return void 0;
    }
    const objectUrl = URL.createObjectURL(previewFile);
    setHeroPreviewObjectUrl(objectUrl);
    return () => {
      URL.revokeObjectURL(objectUrl);
    };
  }, [form.data.preview_image_file]);
  const applyJsonImport = () => {
    try {
      const categoryOptions2 = Array.isArray(categoryField?.options) ? categoryField.options : [];
      const parsed = parsePromptImport(jsonImportValue, categoryOptions2);
      Object.entries(parsed.next).forEach(([key, value]) => {
        form.setData(key, value);
      });
      if (parsed.next.slug != null) {
        slugTouchedRef.current = true;
      }
      setJsonImportError("");
      setJsonImportOpen(false);
    } catch (error) {
      setJsonImportError(error instanceof Error ? error.message : "Could not parse JSON.");
    }
  };
  const submit = (event) => {
    event.preventDefault();
    const advancedJsonFields = [
      { name: "documentation", label: documentationField?.label || "Documentation JSON" },
      { name: "placeholders", label: placeholdersField?.label || "Placeholders JSON" },
      { name: "helper_prompts", label: helperPromptsField?.label || "Helper Prompts JSON" },
      { name: "prompt_variants", label: promptVariantsField?.label || "Prompt Variants JSON" }
    ];
    const parsedJsonFields = {};
    for (const field of advancedJsonFields) {
      form.clearErrors(field.name);
      const value = form.data[field.name];
      if (typeof value !== "string") {
        parsedJsonFields[field.name] = value ?? null;
        continue;
      }
      const trimmed = value.trim();
      if (!trimmed) {
        parsedJsonFields[field.name] = null;
        continue;
      }
      try {
        parsedJsonFields[field.name] = JSON.parse(trimmed);
      } catch {
        const message = `${field.label} must be valid JSON.`;
        form.setError(field.name, message);
        showToast(message, "error");
        setActiveTab("advanced");
        return;
      }
    }
    const payload = normalizePayload(fields, {
      ...form.data,
      ...parsedJsonFields,
      tool_notes: serializePromptComparisons(form.data.tool_notes)
    });
    form.transform(() => payload);
    const submitOptions = {
      preserveScroll: true,
      onError: (errors) => {
        const nextTab = firstPromptErrorTab(errors);
        if (nextTab) {
          setActiveTab(nextTab);
        }
        showToast(firstErrorMessage$1(errors), "error");
      },
      onFinish: () => form.transform((data) => data)
    };
    if (method === "patch") {
      form.patch(submitUrl, submitOptions);
      return;
    }
    form.post(submitUrl, submitOptions);
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-6 pb-16" }, editorLinks.preview ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: editorLinks.preview, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Preview public page")) : null, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] shadow-[0_24px_70px_rgba(2,6,23,0.34)] backdrop-blur" }, heroPreviewImage ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-y-0 right-0 w-full bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.12),transparent_24%),linear-gradient(90deg,rgba(2,6,23,0.98)_0%,rgba(2,6,23,0.94)_34%,rgba(2,6,23,0.7)_100%)]" }), /* @__PURE__ */ React.createElement("img", { src: heroPreviewImage, alt: "", "aria-hidden": "true", className: "absolute inset-y-0 right-0 h-full w-full object-cover opacity-[0.08] blur-[5px]" })) : null, /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-4 border-b border-white/10 px-5 py-3 lg:grid-cols-[140px_minmax(0,1fr)_auto] lg:items-stretch" }, /* @__PURE__ */ React.createElement("div", { className: "lg:min-h-[150px]" }, heroPreviewImage ? /* @__PURE__ */ React.createElement("div", { className: "h-full overflow-hidden rounded-[20px] border border-white/10 bg-black/25 shadow-[0_16px_34px_rgba(2,6,23,0.26)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-full min-h-[150px] overflow-hidden" }, /* @__PURE__ */ React.createElement("img", { src: heroPreviewImage, alt: form.data.title || "Prompt preview", className: "h-full w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.04),rgba(2,6,23,0.48))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 border-t border-white/10 bg-[linear-gradient(180deg,rgba(2,6,23,0.32),rgba(2,6,23,0.78))] px-3 py-2.5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Loaded preview"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs font-semibold text-white" }, "Current prompt image")))) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full min-h-[150px] items-center justify-center rounded-[20px] border border-dashed border-white/10 bg-black/20 px-4 text-center text-xs leading-5 text-slate-400" }, "Upload a prompt preview image in the Media tab to surface it here.")), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 self-center" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white transition hover:bg-white/[0.08]" }, "Back to prompts"), /* @__PURE__ */ React.createElement("span", null, destroyUrl ? "Edit prompt" : "New prompt")), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-300" }, "Keep the prompt editor focused like a production worksheet: identity first, then the actual prompt body, then model comparisons and publishing details in separate tabs.")), /* @__PURE__ */ React.createElement("div", { className: "self-start lg:justify-self-end" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-nowrap items-center gap-2 lg:justify-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "inline-flex items-center gap-2 whitespace-nowrap rounded-2xl border border-white/10 bg-slate-800/90 px-4 py-2 text-sm font-semibold text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] transition hover:bg-slate-700/90" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-file-import text-xs" }), /* @__PURE__ */ React.createElement("span", null, "Import JSON")), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "inline-flex items-center gap-2 whitespace-nowrap rounded-2xl border border-sky-300/25 bg-sky-300/18 px-4 py-2 text-sm font-semibold text-sky-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] transition hover:bg-sky-300/24" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-floppy-disk text-xs" }), /* @__PURE__ */ React.createElement("span", null, form.processing ? "Saving..." : "Save prompt")))))), /* @__PURE__ */ React.createElement(PromptEditorTabs, { activeTab, onChange: setActiveTab, errorCounts: tabErrorCounts }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.14)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Current workspace"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, activeTabMeta.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, activeTabMeta.description)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Prompt words"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, promptWordCount.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Negative words"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, negativePromptWordCount.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Tags"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, tagCount)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Comparisons"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, comparisonCount))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6", role: "tabpanel", id: `prompt-editor-panel-${activeTab}`, "aria-labelledby": `prompt-editor-tab-${activeTab}` }, /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "Identity", title: "Core prompt details", description: "Set the catalog identity first so the prompt is easy to find, sort, and preview.", className: sectionClassName("prompt-identity") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, categoryField ? /* @__PURE__ */ React.createElement(NovaSelect, { label: categoryField.label, value: form.data.category_id ?? "", onChange: (nextValue) => {
    form.setData("category_id", nextValue ?? "");
    if (nextValue) {
      form.setData("new_category_name", "");
    }
  }, options: categoryOptions, searchable: true, searchPlaceholder: "Filter categories...", className: "rounded-2xl bg-black/20", error: form.errors.category_id }) : null, /* @__PURE__ */ React.createElement(TextField$1, { label: "Or enter new category", value: form.data.new_category_name || "", onChange: (event) => form.setData("new_category_name", event.target.value), error: form.errors.new_category_name, placeholder: "New prompt category name" }), difficultyField ? /* @__PURE__ */ React.createElement(NovaSelect, { label: difficultyField.label, value: form.data.difficulty ?? "", onChange: (nextValue) => form.setData("difficulty", nextValue ?? ""), options: difficultyField.options || [], searchable: false, className: "rounded-2xl bg-black/20", error: form.errors.difficulty }) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-4 py-3 text-xs leading-6 text-slate-400" }, "Choose an existing category from the dropdown or type a new category name. When you save, a new prompt category will be created automatically and attached to this prompt."), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, accessField ? /* @__PURE__ */ React.createElement(NovaSelect, { label: accessField.label, value: form.data.access_level ?? "", onChange: (nextValue) => form.setData("access_level", nextValue ?? ""), options: accessField.options || [], searchable: false, className: "rounded-2xl bg-black/20", error: form.errors.access_level }) : null, /* @__PURE__ */ React.createElement(TextField$1, { label: "Aspect ratio", value: form.data.aspect_ratio || "", onChange: (event) => form.setData("aspect_ratio", event.target.value), error: form.errors.aspect_ratio, placeholder: "1:1, 16:9, 3:2" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$1, { label: "Title", value: form.data.title || "", onChange: (event) => form.setData("title", event.target.value), error: form.errors.title, maxLength: 180 }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    slugTouchedRef.current = false;
    form.setData("slug", slugifyPromptTitle(form.data.title));
  }, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Sync")), /* @__PURE__ */ React.createElement("input", { value: form.data.slug || "", onChange: (event) => {
    slugTouchedRef.current = String(event.target.value).trim() !== "";
    form.setData("slug", event.target.value);
  }, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none", maxLength: 180, placeholder: "prompt-template-slug" }), form.errors.slug ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, form.errors.slug) : null)), /* @__PURE__ */ React.createElement(TextAreaField, { label: "Excerpt", value: form.data.excerpt || "", onChange: (event) => form.setData("excerpt", event.target.value), error: form.errors.excerpt, rows: 4, hint: "Short summary shown in the library and preview cards." }), /* @__PURE__ */ React.createElement(TextField$1, { label: "Tags", value: form.data.tags || "", onChange: (event) => form.setData("tags", event.target.value), error: form.errors.tags, placeholder: "wallpaper, cinematic, neon, portrait" })), /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "Prompt body", title: "Prompt instructions", description: "Write the instruction stack, guardrails, and workflow notes without cramming publishing settings into the same view.", className: sectionClassName("prompt-body") }, /* @__PURE__ */ React.createElement(TextAreaField, { label: "Prompt", value: form.data.prompt || "", onChange: (event) => form.setData("prompt", event.target.value), error: form.errors.prompt, rows: 12, hint: "This is the main model instruction used by creators." }), /* @__PURE__ */ React.createElement(TextAreaField, { label: "Negative prompt", value: form.data.negative_prompt || "", onChange: (event) => form.setData("negative_prompt", event.target.value), error: form.errors.negative_prompt, rows: 6, hint: "Optional exclusions, artifacts, or anti-patterns to avoid." }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextAreaField, { label: "Usage notes", value: form.data.usage_notes || "", onChange: (event) => form.setData("usage_notes", event.target.value), error: form.errors.usage_notes, rows: 6, hint: "Explain how to apply the prompt in a practical workflow." }), /* @__PURE__ */ React.createElement(TextAreaField, { label: "Workflow notes", value: form.data.workflow_notes || "", onChange: (event) => form.setData("workflow_notes", event.target.value), error: form.errors.workflow_notes, rows: 6, hint: "Internal editorial notes, camera settings, or prompt variants." }))), /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "Structured docs", title: "Advanced prompt metadata", description: "Use JSON editors for advanced prompt guidance, variables, supporting prompts, and reusable variants. Keep them valid JSON so the public prompt page can render them safely.", className: sectionClassName("prompt-advanced") }, /* @__PURE__ */ React.createElement(TextAreaField, { label: documentationField?.label || "Documentation JSON", value: form.data.documentation || "", onChange: (event) => form.setData("documentation", event.target.value), error: form.errors.documentation, rows: 12, hint: "Object with summary, best_for, how_to_use, required_inputs, workflow, tips, common_mistakes, data_accuracy_notes, and display_notes." }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextAreaField, { label: placeholdersField?.label || "Placeholders JSON", value: form.data.placeholders || "", onChange: (event) => form.setData("placeholders", event.target.value), error: form.errors.placeholders, rows: 12, hint: "Array of variable objects with key, label, description, required, example, default, and type." }), /* @__PURE__ */ React.createElement(TextAreaField, { label: helperPromptsField?.label || "Helper Prompts JSON", value: form.data.helper_prompts || "", onChange: (event) => form.setData("helper_prompts", event.target.value), error: form.errors.helper_prompts, rows: 12, hint: "Array of supporting prompts used for data collection, preparation, validation, or refinement." })), /* @__PURE__ */ React.createElement(TextAreaField, { label: promptVariantsField?.label || "Prompt Variants JSON", value: form.data.prompt_variants || "", onChange: (event) => form.setData("prompt_variants", event.target.value), error: form.errors.prompt_variants, rows: 12, hint: "Array of alternative prompt versions with prompt, negative_prompt, recommended flags, and risk notes." })), /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "Structured blocks", title: "AI model comparisons", description: "Add reusable same-prompt comparison notes without burying provider-specific behavior inside the main prompt body.", className: sectionClassName("prompt-comparisons") }, /* @__PURE__ */ React.createElement(PromptComparisonEditor, { comparisons: Array.isArray(form.data.tool_notes) ? form.data.tool_notes : [], setComparisons: (nextValue) => form.setData("tool_notes", normalizePromptComparisons(nextValue, { preserveEmpty: true })), editorContext })), /* @__PURE__ */ React.createElement("div", { className: sectionClassName("prompt-media") }, /* @__PURE__ */ React.createElement(PromptPreviewDropzone, { form, previewUrl })), /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "Publishing", title: "Release controls", description: "Choose when the prompt becomes visible and how it behaves in the academy.", className: sectionClassName("prompt-publishing") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, publishedAtField ? /* @__PURE__ */ React.createElement(DateTimePicker, { label: publishedAtField.label, value: form.data.published_at || "", onChange: (nextValue) => form.setData("published_at", nextValue || ""), error: form.errors.published_at, clearable: true, className: "bg-black/20" }) : null, /* @__PURE__ */ React.createElement(TextField$1, { label: "SEO title", value: form.data.seo_title || "", onChange: (event) => form.setData("seo_title", event.target.value), error: form.errors.seo_title, maxLength: 180 })), seoDescriptionField ? /* @__PURE__ */ React.createElement(TextAreaField, { label: seoDescriptionField.label, value: form.data.seo_description || "", onChange: (event) => form.setData("seo_description", event.target.value), error: form.errors.seo_description, rows: 4 }) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-3" }, featuredField ? /* @__PURE__ */ React.createElement(ToggleField$1, { label: featuredField.label, checked: Boolean(form.data.featured), onChange: (event) => form.setData("featured", event.target.checked), help: "Highlight this prompt in featured rails.", error: form.errors.featured }) : null, promptOfWeekField ? /* @__PURE__ */ React.createElement(ToggleField$1, { label: promptOfWeekField.label, checked: Boolean(form.data.prompt_of_week), onChange: (event) => form.setData("prompt_of_week", event.target.checked), help: "Promote this prompt as the current weekly pick.", error: form.errors.prompt_of_week }) : null, activeField ? /* @__PURE__ */ React.createElement(ToggleField$1, { label: activeField.label, checked: Boolean(form.data.active), onChange: (event) => form.setData("active", event.target.checked), help: "Keep draft prompts hidden until they are ready.", error: form.errors.active }) : null)), /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "Preview", title: "Public-facing snapshot", description: "Check the prompt card summary, tags, and current image before publishing.", className: sectionClassName("prompt-preview") }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/30" }, previewUrl || form.data.preview_image ? /* @__PURE__ */ React.createElement("img", { src: previewUrl || form.data.preview_image, alt: "Prompt preview", className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-64 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No preview image selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Prompt summary"), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white" }, form.data.title || "Untitled prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, form.data.excerpt || "Add a concise excerpt to give the prompt some context in the library."), /* @__PURE__ */ React.createElement("dl", { className: "mt-4 grid grid-cols-2 gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Difficulty"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.difficulty || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Access"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.access_level || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Aspect"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.aspect_ratio || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Comparisons"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, comparisonCount)))))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6 xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement(SectionCard$4, { eyebrow: "At a glance", title: "Prompt status", description: "A compact summary while you work through the tabs." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Prompt words"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, promptWordCount.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Tags"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, tagCount)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Comparisons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, comparisonCount)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Visibility"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, form.data.active ? "Active" : "Draft"))), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-6 text-slate-500" }, "Uploaded images are converted to WebP and stored on the Contabo S3-backed CDN before the record is saved.")))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save prompt"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this record?")) return;
    At.delete(destroyUrl);
  }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null)), /* @__PURE__ */ React.createElement(
    PromptJsonImportDialog,
    {
      open: jsonImportOpen,
      value: jsonImportValue,
      error: jsonImportError,
      onChange: setJsonImportValue,
      onClose: () => setJsonImportOpen(false),
      onApply: applyJsonImport
    }
  ), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ));
}
function GenericEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext }) {
  const form = G$1(record);
  const editorLinks = editorContext?.links || {};
  const [toast, setToast] = reactExports.useState({ id: 0, visible: false, message: "", variant: "success" });
  const showToast = (message, variant = "error") => {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant
    });
  };
  const submit = (event) => {
    event.preventDefault();
    const payload = normalizePayload(fields, form.data);
    form.transform(() => payload);
    const submitOptions = {
      preserveScroll: true,
      onError: (errors) => showToast(firstErrorMessage$1(errors), "error"),
      onFinish: () => form.transform((data) => data)
    };
    if (method === "patch") {
      form.patch(submitUrl, submitOptions);
      return;
    }
    form.post(submitUrl, submitOptions);
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${title}` }), editorLinks.builder || editorLinks.preview ? /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap gap-3" }, editorLinks.builder ? /* @__PURE__ */ React.createElement(xe, { href: editorLinks.builder, className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-5 py-3 text-sm font-semibold text-amber-100" }, "Open builder") : null, editorLinks.preview ? /* @__PURE__ */ React.createElement(xe, { href: editorLinks.preview, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Preview public page") : null) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-5 rounded-[30px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, fields.map((field) => /* @__PURE__ */ React.createElement(Field$5, { key: field.name, field, form }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this record?")) return;
    At.delete(destroyUrl);
  }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null)), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ));
}
function AcademyCrudForm({ resource, title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext }) {
  if (resource === "courses") {
    return /* @__PURE__ */ React.createElement(
      CourseEditor,
      {
        title,
        subtitle,
        fields,
        record,
        submitUrl,
        indexUrl,
        destroyUrl,
        method,
        editorContext
      }
    );
  }
  if (resource === "lessons") {
    return /* @__PURE__ */ React.createElement(
      LessonEditor,
      {
        title,
        subtitle,
        fields,
        record,
        submitUrl,
        indexUrl,
        destroyUrl,
        method,
        editorContext
      }
    );
  }
  if (resource === "prompts") {
    return /* @__PURE__ */ React.createElement(
      PromptEditor,
      {
        title,
        subtitle,
        fields,
        record,
        submitUrl,
        indexUrl,
        destroyUrl,
        method,
        editorContext
      }
    );
  }
  if (resource === "challenges") {
    return /* @__PURE__ */ React.createElement(
      ChallengeEditor,
      {
        title,
        subtitle,
        fields,
        record,
        submitUrl,
        indexUrl,
        destroyUrl,
        method,
        editorContext
      }
    );
  }
  return /* @__PURE__ */ React.createElement(
    GenericEditor,
    {
      title,
      subtitle,
      fields,
      record,
      submitUrl,
      indexUrl,
      destroyUrl,
      method,
      editorContext
    }
  );
}
const __vite_glob_0_20 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyCrudForm
}, Symbol.toStringTag, { value: "Module" }));
const PROMPT_VIEW_STORAGE_KEY = "skinbase.admin.academy.prompts.view";
const COURSE_VIEW_STORAGE_KEY = "skinbase.admin.academy.courses.view";
const PROMPT_VIEW_OPTIONS = [
  { value: "gallery", label: "Gallery", icon: "fa-images" },
  { value: "grid", label: "Grid", icon: "fa-grid-2" },
  { value: "table", label: "Table", icon: "fa-table-list" }
];
const COURSE_VIEW_OPTIONS = [
  { value: "grid", label: "Grid", icon: "fa-grid-2" },
  { value: "table", label: "Table", icon: "fa-table-list" }
];
function formatDateLabel$1(value) {
  if (!value) return "Recently updated";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Recently updated";
  return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric" }).format(date);
}
function paginationLabel(label) {
  return String(label || "").replace(/&laquo;/g, "Previous").replace(/&raquo;/g, "Next").replace(/<[^>]+>/g, "").trim();
}
function courseStatusMeta(status2) {
  const normalized = String(status2 || "draft");
  if (normalized === "published") {
    return { label: "Published", className: "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" };
  }
  if (normalized === "review") {
    return { label: "Review", className: "border-amber-300/20 bg-amber-300/10 text-amber-100" };
  }
  if (normalized === "archived") {
    return { label: "Archived", className: "border-white/10 bg-white/[0.04] text-slate-300" };
  }
  return { label: "Draft", className: "border-slate-500/20 bg-slate-500/10 text-slate-300" };
}
function courseAccessMeta(accessLevel) {
  const normalized = String(accessLevel || "free");
  if (normalized === "premium") {
    return { label: "Premium", className: "border-[#ffcfbf]/20 bg-[#ffcfbf]/10 text-[#fff0ea]" };
  }
  if (normalized === "mixed") {
    return { label: "Mixed", className: "border-sky-300/20 bg-sky-300/10 text-sky-100" };
  }
  return { label: "Free", className: "border-white/10 bg-white/[0.05] text-slate-200" };
}
function courseSummary(items = [], summary = null) {
  if (summary && typeof summary === "object") {
    return {
      total: Number(summary.total || 0),
      published: Number(summary.published || 0),
      featured: Number(summary.featured || 0),
      drafts: Number(summary.drafts || 0),
      visibleOnPage: Array.isArray(items) ? items.length : 0
    };
  }
  return items.reduce((accumulator, item) => ({
    total: accumulator.total + 1,
    published: accumulator.published + (item.status === "published" ? 1 : 0),
    featured: accumulator.featured + (item.is_featured ? 1 : 0),
    drafts: accumulator.drafts + (item.status === "draft" ? 1 : 0),
    visibleOnPage: accumulator.visibleOnPage + 1
  }), { total: 0, published: 0, featured: 0, drafts: 0, visibleOnPage: 0 });
}
function promptSummary(items = []) {
  return items.reduce((summary, item) => ({
    total: summary.total + 1,
    active: summary.active + (item.active ? 1 : 0),
    featured: summary.featured + (item.featured ? 1 : 0),
    promptOfWeek: summary.promptOfWeek + (item.prompt_of_week ? 1 : 0),
    comparisons: summary.comparisons + Number(item.comparisons_count || 0)
  }), { total: 0, active: 0, featured: 0, promptOfWeek: 0, comparisons: 0 });
}
function PromptFlag({ children, tone = "default" }) {
  const toneClass = tone === "warm" ? "border-[#ffcfbf]/20 bg-[#ffcfbf]/10 text-[#fff0ea]" : tone === "sky" ? "border-sky-300/20 bg-sky-300/10 text-sky-100" : tone === "emerald" ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border-white/10 bg-white/[0.05] text-slate-200";
  return /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${toneClass}` }, children);
}
function CoursePill({ children, tone = "default" }) {
  const toneClass = tone === "warm" ? "border-[#ffcfbf]/20 bg-[#ffcfbf]/10 text-[#fff0ea]" : tone === "sky" ? "border-sky-300/20 bg-sky-300/10 text-sky-100" : tone === "emerald" ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border-white/10 bg-white/[0.05] text-slate-200";
  return /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${toneClass}` }, children);
}
function CourseCover({ item, compact = false }) {
  if (item.cover_image_url) {
    return /* @__PURE__ */ React.createElement("img", { src: item.cover_image_url, alt: item.title, className: `h-full w-full object-cover transition duration-500 ${compact ? "group-hover:scale-[1.04]" : "group-hover:scale-[1.03]"}` });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.18),transparent_28%),radial-gradient(circle_at_bottom_right,rgba(255,207,191,0.18),transparent_24%),linear-gradient(135deg,rgba(15,23,42,0.98),rgba(30,41,59,0.94))] p-6 text-center text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Course cover"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm font-semibold text-white" }, "No cover image attached yet")));
}
function CourseCoverWall({ items = [] }) {
  const images = items.map((item) => item?.cover_image_url).filter(Boolean).slice(0, 4);
  if (!images.length) {
    return /* @__PURE__ */ React.createElement("div", { className: "flex min-h-[320px] items-center justify-center rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(255,207,191,0.18),transparent_26%),linear-gradient(135deg,rgba(12,18,31,0.98),rgba(30,41,59,0.94))] px-8 text-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-500" }, "Course cover wall"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-lg font-semibold text-white" }, "Course artwork will appear here once covers are added.")));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/10 bg-black/20 shadow-[0_18px_45px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/10] overflow-hidden" }, /* @__PURE__ */ React.createElement("img", { src: images[0], alt: "", "aria-hidden": "true", className: "h-full w-full object-cover" }))), images.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3" }, images.slice(1, 4).map((image2, index2) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: `${image2}-${index2}`,
      className: "aspect-square overflow-hidden rounded-[24px] border border-white/10 bg-black/20 shadow-[0_18px_45px_rgba(2,6,23,0.2)]"
    },
    /* @__PURE__ */ React.createElement("img", { src: image2, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover" })
  ))) : null);
}
function CourseStatCard({ label, value, tone = "default" }) {
  const toneClass = tone === "sky" ? "border-sky-300/20 bg-sky-300/10 text-sky-100" : tone === "emerald" ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : tone === "warm" ? "border-[#ffcfbf]/20 bg-[#ffcfbf]/10 text-[#fff0ea]" : "border-white/10 bg-black/20 text-slate-300";
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[24px] border px-5 py-4 ${toneClass}` }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] opacity-70" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, value));
}
function PromptActions({ item }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, item.preview_url ? /* @__PURE__ */ React.createElement(xe, { href: item.preview_url, className: "inline-flex items-center gap-2 rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-4 py-2 text-sm font-semibold text-[#fff0ea]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-eye text-xs" }), "Preview") : null, /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square text-xs" }), "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this prompt?")) return;
    At.delete(item.destroy_url, { preserveScroll: true });
  }, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash text-xs" }), "Delete"));
}
function CourseActions({ item }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: item.builder_url, className: "inline-flex items-center gap-2 rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-4 py-2 text-sm font-semibold text-[#fff0ea]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sitemap text-xs" }), "Builder"), /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square text-xs" }), "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this course?")) return;
    At.delete(item.destroy_url, { preserveScroll: true });
  }, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash text-xs" }), "Delete"));
}
function CourseGridCard({ item }) {
  const status2 = courseStatusMeta(item.status);
  const access = courseAccessMeta(item.access_level);
  return /* @__PURE__ */ React.createElement("article", { className: "group overflow-hidden rounded-[30px] border border-white/[0.08] bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.18))] shadow-[0_18px_60px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-56 overflow-hidden border-b border-white/10" }, /* @__PURE__ */ React.createElement(CourseCover, { item, compact: true }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.02),rgba(2,6,23,0.34))]" })), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(CoursePill, { tone: "warm" }, item.lessons_count || 0, " lessons"), /* @__PURE__ */ React.createElement(CoursePill, { tone: item.is_featured ? "sky" : "default" }, item.is_featured ? "Featured" : "Course"), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${status2.className}` }, status2.label)), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-xl font-semibold tracking-[-0.04em] text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, item.subtitle) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.excerpt || "No excerpt added yet."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, access.label), /* @__PURE__ */ React.createElement("span", null, formatDateLabel$1(item.updated_at))), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement(CourseActions, { item }))));
}
function CourseTable({ items }) {
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/[0.08] bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(2,6,23,0.92))] shadow-[0_24px_80px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/10 text-left" }, /* @__PURE__ */ React.createElement("thead", { className: "bg-white/[0.04] text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Cover"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Course"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Access"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Lessons"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Updated"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/10 text-sm text-slate-200" }, items.map((item) => {
    const status2 = courseStatusMeta(item.status);
    const access = courseAccessMeta(item.access_level);
    return /* @__PURE__ */ React.createElement("tr", { key: item.id, className: "align-top transition hover:bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-20 w-28 overflow-hidden rounded-2xl border border-white/10 bg-black/30" }, /* @__PURE__ */ React.createElement(CourseCover, { item, compact: true }))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-md text-sm leading-6 text-slate-400" }, item.subtitle) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-xl text-sm leading-6 text-slate-400" }, item.excerpt || "No excerpt added yet."))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-3 py-1 text-xs font-semibold ${access.className}` }, access.label)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-3 py-1 text-xs font-semibold ${status2.className}` }, status2.label)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-1 text-white" }, /* @__PURE__ */ React.createElement("p", null, item.lessons_count || 0, " lessons"), /* @__PURE__ */ React.createElement("p", null, item.is_featured ? "Featured" : "Standard"))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, formatDateLabel$1(item.updated_at)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex justify-end gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: item.builder_url, className: "rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-3 py-2 text-xs font-semibold text-[#fff0ea]" }, "Builder"), /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white" }, "Edit"))));
  })))));
}
function CourseSearchBar({ value, onChange, onSubmit, onClear, viewMode, onViewModeChange }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-4 shadow-[0_18px_50px_rgba(2,6,23,0.14)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between" }, /* @__PURE__ */ React.createElement("form", { onSubmit, className: "flex flex-1 flex-col gap-3 sm:flex-row sm:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "relative flex-1 max-w-2xl" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-xs text-slate-500" }), /* @__PURE__ */ React.createElement(
    "input",
    {
      name: "search",
      value,
      onChange: (event) => onChange(event.target.value),
      placeholder: "Search title, slug, subtitle, excerpt, or description…",
      className: "w-full rounded-2xl border border-white/10 bg-black/20 py-3 pl-9 pr-4 text-sm text-white placeholder:text-slate-600 focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10"
    }
  )), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl bg-sky-300/12 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-300/16" }, "Search"), value ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClear, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white/80 transition hover:bg-white/[0.08]" }, "Clear") : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, COURSE_VIEW_OPTIONS.map((option) => {
    const active = option.value === viewMode;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => onViewModeChange(option.value),
        className: `inline-flex items-center gap-2 rounded-full border px-4 py-2.5 text-sm font-semibold transition ${active ? "border-sky-300/25 bg-sky-300/12 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-200 hover:border-white/20 hover:bg-white/[0.07]"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${option.icon} text-xs` }),
      /* @__PURE__ */ React.createElement("span", null, option.label)
    );
  }))));
}
function PromptPreview({ item, compact = false }) {
  if (item.preview_image_url) {
    return /* @__PURE__ */ React.createElement("img", { src: item.preview_image_url, alt: item.title, className: `h-full w-full object-cover transition duration-500 ${compact ? "group-hover:scale-[1.04]" : "group-hover:scale-[1.03]"}` });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.18),transparent_30%),linear-gradient(135deg,rgba(15,23,42,0.98),rgba(30,41,59,0.94))] p-6 text-center text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Prompt preview"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm font-semibold text-white" }, "No image attached yet")));
}
function PromptMeta({ item }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, item.category_name ? /* @__PURE__ */ React.createElement(PromptFlag, { tone: "warm" }, item.category_name) : null, item.difficulty ? /* @__PURE__ */ React.createElement(PromptFlag, null, item.difficulty) : null, item.access_level ? /* @__PURE__ */ React.createElement(PromptFlag, null, item.access_level) : null, item.aspect_ratio ? /* @__PURE__ */ React.createElement(PromptFlag, null, item.aspect_ratio) : null, item.featured ? /* @__PURE__ */ React.createElement(PromptFlag, { tone: "sky" }, "Featured") : null, item.prompt_of_week ? /* @__PURE__ */ React.createElement(PromptFlag, { tone: "emerald" }, "Prompt of week") : null, /* @__PURE__ */ React.createElement(PromptFlag, { tone: item.active ? "sky" : "default" }, item.active ? "Active" : "Draft"));
}
function PromptGalleryCard({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "group overflow-hidden rounded-[30px] border border-white/[0.08] bg-[linear-gradient(135deg,rgba(8,15,28,0.98),rgba(15,23,42,0.92))] shadow-[0_24px_80px_rgba(2,6,23,0.24)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-0 xl:grid-cols-[340px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative min-h-[250px] overflow-hidden border-b border-white/10 xl:min-h-full xl:border-b-0 xl:border-r xl:border-white/10" }, /* @__PURE__ */ React.createElement(PromptPreview, { item }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.04),rgba(2,6,23,0.32))]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(PromptFlag, { tone: "warm" }, item.comparisons_count || 0, " comparisons"), item.slug ? /* @__PURE__ */ React.createElement(PromptFlag, null, item.slug) : null)), /* @__PURE__ */ React.createElement("div", { className: "flex h-full flex-col justify-between p-6 lg:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(PromptMeta, { item }), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-2xl font-semibold tracking-[-0.04em] text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, item.excerpt || "Add an excerpt to make this prompt easier to scan in moderation."), item.tags?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, item.tags.slice(0, 5).map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-slate-300" }, tag))) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-center justify-between gap-4 border-t border-white/10 pt-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Updated"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, formatDateLabel$1(item.updated_at))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Access"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, item.access_level || "free")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-semibold text-white" }, item.active ? "Visible" : "Hidden"))), /* @__PURE__ */ React.createElement(PromptActions, { item })))));
}
function PromptGridCard({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "group overflow-hidden rounded-[28px] border border-white/[0.08] bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(15,23,42,0.18))] shadow-[0_18px_60px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-52 overflow-hidden border-b border-white/10" }, /* @__PURE__ */ React.createElement(PromptPreview, { item, compact: true }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[linear-gradient(180deg,rgba(2,6,23,0.02),rgba(2,6,23,0.34))]" })), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement(PromptMeta, { item }), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-xl font-semibold tracking-[-0.04em] text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.excerpt || "No excerpt added yet."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatDateLabel$1(item.updated_at)), /* @__PURE__ */ React.createElement("span", null, item.comparisons_count || 0, " comparisons")), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement(PromptActions, { item }))));
}
function PromptTable({ items }) {
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/[0.08] bg-[linear-gradient(180deg,rgba(15,23,42,0.92),rgba(2,6,23,0.92))] shadow-[0_24px_80px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/10 text-left" }, /* @__PURE__ */ React.createElement("thead", { className: "bg-white/[0.04] text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Prompt"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Category"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Access"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Signals"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Updated"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/10 text-sm text-slate-200" }, items.map((item) => /* @__PURE__ */ React.createElement("tr", { key: item.id, className: "align-top transition hover:bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-16 w-20 overflow-hidden rounded-2xl border border-white/10 bg-black/30 shrink-0" }, /* @__PURE__ */ React.createElement(PromptPreview, { item, compact: true })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-md text-sm leading-6 text-slate-400" }, item.excerpt || "No excerpt added yet.")))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, item.category_name || "Uncategorized"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, item.access_level || "free"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-1" }, /* @__PURE__ */ React.createElement("p", null, item.comparisons_count || 0, " comparisons"), /* @__PURE__ */ React.createElement("p", null, item.difficulty || "No difficulty"), /* @__PURE__ */ React.createElement("p", null, item.active ? "Active" : "Draft"))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, formatDateLabel$1(item.updated_at)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex justify-end gap-2" }, item.preview_url ? /* @__PURE__ */ React.createElement(xe, { href: item.preview_url, className: "rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-3 py-2 text-xs font-semibold text-[#fff0ea]" }, "Preview") : null, /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold text-white" }, "Edit")))))))));
}
function PromptHeroCollage({ items = [] }) {
  const images = items.map((item) => item?.preview_image_url).filter(Boolean).slice(0, 4);
  if (!images.length) {
    return /* @__PURE__ */ React.createElement("div", { className: "flex min-h-[320px] items-center justify-center rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(255,207,191,0.18),transparent_26%),linear-gradient(135deg,rgba(12,18,31,0.98),rgba(30,41,59,0.94))] px-8 text-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-500" }, "Prompt preview wall"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-lg font-semibold text-white" }, "Preview images will appear here as prompts get covers.")));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/10 bg-black/20 shadow-[0_18px_45px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/10] overflow-hidden" }, /* @__PURE__ */ React.createElement("img", { src: images[0], alt: "", "aria-hidden": "true", className: "h-full w-full object-cover" }))), images.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3" }, images.slice(1, 4).map((image2, index2) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: `${image2}-${index2}`,
      className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 shadow-[0_18px_45px_rgba(2,6,23,0.2)] aspect-square"
    },
    /* @__PURE__ */ React.createElement("img", { src: image2, alt: "", "aria-hidden": "true", className: "h-full w-full object-cover" })
  ))) : null);
}
function CourseIndexContent({ title, subtitle, items, createUrl, filters = {}, summary = {} }) {
  const { url } = X$1();
  const courses = items?.data || [];
  const [viewMode, setViewMode] = reactExports.useState("grid");
  const [searchValue, setSearchValue] = reactExports.useState(filters.search || "");
  reactExports.useEffect(() => {
    setSearchValue(filters.search || "");
  }, [filters.search]);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") return;
    const storedView = window.localStorage.getItem(COURSE_VIEW_STORAGE_KEY);
    if (COURSE_VIEW_OPTIONS.some((option) => option.value === storedView)) {
      setViewMode(storedView);
    }
  }, []);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem(COURSE_VIEW_STORAGE_KEY, viewMode);
  }, [viewMode]);
  const stats = reactExports.useMemo(() => courseSummary(courses, summary), [courses, summary]);
  const currentPath = url.split("?")[0];
  const hasSearch = Boolean(searchValue.trim());
  const meta = items?.meta || {};
  const handleSearch = (event) => {
    event.preventDefault();
    At.get(currentPath, { search: searchValue.trim() || void 0 }, { preserveScroll: true, preserveState: true, replace: true });
  };
  const handleClearSearch = () => {
    setSearchValue("");
    At.get(currentPath, {}, { preserveScroll: true, preserveState: true, replace: true });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[38px] border border-white/[0.08] bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(255,207,191,0.16),transparent_24%),linear-gradient(135deg,rgba(4,9,18,0.98),rgba(15,23,42,0.92))] shadow-[0_28px_90px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 p-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start xl:p-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-[#fff0ea]" }, "Academy moderation"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-300" }, "Course library")), /* @__PURE__ */ React.createElement("h2", { className: "mt-5 max-w-4xl text-4xl font-semibold tracking-[-0.055em] text-white md:text-5xl xl:text-6xl" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, subtitle, " Search courses quickly, switch between grid and table views, and jump into editing with a cleaner visual overview of covers, status, and lesson counts."), /* @__PURE__ */ React.createElement("div", { className: "mt-7 grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(CourseStatCard, { label: "Total", value: stats.total, tone: "sky" }), /* @__PURE__ */ React.createElement(CourseStatCard, { label: "Published", value: stats.published, tone: "emerald" }), /* @__PURE__ */ React.createElement(CourseStatCard, { label: "Featured", value: stats.featured, tone: "warm" }), /* @__PURE__ */ React.createElement(CourseStatCard, { label: "Drafts", value: stats.drafts })), /* @__PURE__ */ React.createElement("div", { className: "mt-7 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "inline-flex items-center gap-2 whitespace-nowrap rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-xs" }), "Create course"), /* @__PURE__ */ React.createElement(xe, { href: "/academy/courses", className: "inline-flex items-center gap-2 whitespace-nowrap rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white/85" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open text-xs" }), "Open public courses"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 whitespace-nowrap rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white/85" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-xs" }), meta.total || courses.length, " courses in view"))), /* @__PURE__ */ React.createElement("div", { className: "xl:pt-2" }, /* @__PURE__ */ React.createElement(CourseCoverWall, { items: courses })))), /* @__PURE__ */ React.createElement(
    CourseSearchBar,
    {
      value: searchValue,
      onChange: setSearchValue,
      onSubmit: handleSearch,
      onClear: handleClearSearch,
      viewMode,
      onViewModeChange: setViewMode
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, meta.total ? /* @__PURE__ */ React.createElement(React.Fragment, null, "Showing ", meta.from || 0, "-", meta.to || 0, " of ", meta.total, " courses", hasSearch ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 text-sky-200" }, "filtered by “", searchValue.trim(), "”") : null) : "Manage Academy courses below. Changes clear Academy cache automatically."), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-xs" }), "Create course"))), courses.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] px-6 py-12 text-center text-slate-400" }, hasSearch ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-lg font-semibold text-white" }, "No courses matched your search."), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleClearSearch, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Clear search")) : /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-lg font-semibold text-white" }, "No courses exist yet."), /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-xs" }), "Create the first course"))) : viewMode === "table" ? /* @__PURE__ */ React.createElement(CourseTable, { items: courses }) : /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2 2xl:grid-cols-3" }, courses.map((item) => /* @__PURE__ */ React.createElement(CourseGridCard, { key: item.id, item }))), /* @__PURE__ */ React.createElement(PaginationLinks, { links: items?.links }));
}
function PaginationLinks({ links = [] }) {
  if (!Array.isArray(links) || links.length <= 3) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex flex-wrap gap-2" }, links.map((link2, index2) => {
    const label = paginationLabel(link2.label);
    const className = link2.active ? "border-sky-300/25 bg-sky-300/12 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-200 hover:border-white/20 hover:bg-white/[0.07]";
    return link2.url ? /* @__PURE__ */ React.createElement(xe, { key: `${label}-${index2}`, href: link2.url, className: `rounded-full border px-4 py-2 text-sm font-semibold transition ${className}`, preserveScroll: true }, label) : /* @__PURE__ */ React.createElement("span", { key: `${label}-${index2}`, className: "rounded-full border border-white/10 bg-black/20 px-4 py-2 text-sm font-semibold text-slate-500" }, label);
  }));
}
function renderCrudCell(column, item) {
  if (column === "active") {
    const active = Boolean(item.active);
    return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] ${active ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border-white/10 bg-white/[0.04] text-slate-300"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${active ? "fa-circle-check" : "fa-circle-minus"} text-[11px]` }), /* @__PURE__ */ React.createElement("span", null, active ? "Active" : "Inactive"));
  }
  if (column === "course_names") {
    const courseNames = Array.isArray(item.course_names) ? item.course_names.filter(Boolean) : [];
    if (courseNames.length === 0) {
      return /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, "Not attached");
    }
    return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, courseNames.map((courseName) => /* @__PURE__ */ React.createElement("span", { key: courseName, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-200" }, courseName)));
  }
  if (column === "course_order") {
    return /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white" }, item.course_order ?? "Not set");
  }
  return /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white" }, String(item[column] ?? ""));
}
function PromptIndexContent({ title, subtitle, items, createUrl }) {
  const promptItems = items?.data || [];
  const summary = promptSummary(promptItems);
  const [viewMode, setViewMode] = reactExports.useState("gallery");
  reactExports.useEffect(() => {
    if (typeof window === "undefined") return;
    const storedView = window.localStorage.getItem(PROMPT_VIEW_STORAGE_KEY);
    if (PROMPT_VIEW_OPTIONS.some((option) => option.value === storedView)) {
      setViewMode(storedView);
    }
  }, []);
  reactExports.useEffect(() => {
    if (typeof window === "undefined") return;
    window.localStorage.setItem(PROMPT_VIEW_STORAGE_KEY, viewMode);
  }, [viewMode]);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[38px] border border-white/[0.08] bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(255,207,191,0.16),transparent_24%),linear-gradient(135deg,rgba(4,9,18,0.98),rgba(15,23,42,0.92))] shadow-[0_28px_90px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 p-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start xl:p-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-[#ffcfbf]/20 bg-[#ffcfbf]/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-[#fff0ea]" }, "Academy moderation"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-300" }, "Prompt library")), /* @__PURE__ */ React.createElement("h2", { className: "mt-5 max-w-4xl text-4xl font-semibold tracking-[-0.055em] text-white md:text-5xl xl:text-6xl" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, subtitle, " Review prompts in a visual-first moderation surface, jump into edits quickly, and switch between gallery, grid, or table depending on the task in front of you."), /* @__PURE__ */ React.createElement("div", { className: "mt-7 grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Visual-first"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, "Curate covers and prompt outputs before opening the form.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Workflow-ready"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, "Switch between gallery, compact cards, and scan-heavy tables.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Comparison-aware"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, "Spot prompts with provider notes and attached result references."))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, PROMPT_VIEW_OPTIONS.map((option) => {
    const active = option.value === viewMode;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => setViewMode(option.value),
        className: `inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-semibold transition ${active ? "border-sky-300/25 bg-sky-300/12 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-200 hover:border-white/20 hover:bg-white/[0.07]"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${option.icon}` }),
      /* @__PURE__ */ React.createElement("span", null, option.label, " view")
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-7 flex flex-nowrap gap-3 overflow-x-auto pb-1" }, /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "inline-flex items-center gap-2 whitespace-nowrap rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-xs" }), "Create prompt"), /* @__PURE__ */ React.createElement(xe, { href: "/academy/prompts", className: "inline-flex items-center gap-2 whitespace-nowrap rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white/85" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open text-xs" }), "Open public library"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 whitespace-nowrap rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white/85" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-xs" }), summary.total, " prompts in view")), /* @__PURE__ */ React.createElement("div", { className: "mt-7 grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Active"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, summary.active)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Featured"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, summary.featured)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Prompt of week"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, summary.promptOfWeek)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Comparisons"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, summary.comparisons)))), /* @__PURE__ */ React.createElement("div", { className: "xl:pt-2" }, /* @__PURE__ */ React.createElement(PromptHeroCollage, { items: promptItems })))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Manage Academy content below. Changes clear Academy cache automatically."), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: "/academy/prompts", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white/85" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open text-xs" }), "View public library"), /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-xs" }), "Create prompt"))), promptItems.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] px-6 py-12 text-center text-slate-400" }, "No prompt templates exist yet.") : viewMode === "table" ? /* @__PURE__ */ React.createElement(PromptTable, { items: promptItems }) : viewMode === "grid" ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2 2xl:grid-cols-3" }, promptItems.map((item) => /* @__PURE__ */ React.createElement(PromptGridCard, { key: item.id, item }))) : /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, promptItems.map((item) => /* @__PURE__ */ React.createElement(PromptGalleryCard, { key: item.id, item }))), /* @__PURE__ */ React.createElement(PaginationLinks, { links: items?.links }));
}
function AcademyCrudIndex({ title, subtitle, items, columns, createUrl }) {
  const flash = X$1().props.flash || {};
  const resource = X$1().props.resource;
  const filters = X$1().props.filters || {};
  const summary = X$1().props.summary || {};
  return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se$1, { title: `Admin · ${title}` }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, resource === "courses" ? /* @__PURE__ */ React.createElement(CourseIndexContent, { title, subtitle, items, createUrl, filters, summary }) : resource === "prompts" ? /* @__PURE__ */ React.createElement(PromptIndexContent, { title, subtitle, items, createUrl }) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Manage Academy content below. Changes clear Academy cache automatically."), /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Create record")), (items?.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] px-6 py-12 text-center text-slate-400" }, "No records exist yet.") : /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, items.data.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-6" }, columns.map((column) => /* @__PURE__ */ React.createElement("div", { key: column }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, column.replaceAll("_", " ")), /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, renderCrudCell(column, item))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, item.builder_url ? /* @__PURE__ */ React.createElement(xe, { href: item.builder_url, className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-4 py-2 text-sm font-semibold text-amber-100" }, "Builder") : null, /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this record?")) return;
    At.delete(item.destroy_url, { preserveScroll: true });
  }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Delete"))))))));
}
const __vite_glob_0_21 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyCrudIndex
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$c({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, value.toLocaleString()));
}
function AcademyDashboard({ stats, links }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Dashboard", subtitle: "Overview of Academy content, challenge activity, and live Academy subscription health." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Dashboard" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$c, { label: "Courses", value: stats.courses }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Lessons", value: stats.lessons }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Prompts", value: stats.prompts }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Prompt Packs", value: stats.packs }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Challenges", value: stats.challenges }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Submissions", value: stats.submissions }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Badges", value: stats.badges }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Active Subscribers", value: stats.active_subscribers || 0 }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Creator Subscribers", value: stats.creator_subscribers }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Pro Subscribers", value: stats.pro_subscribers }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Grace Period", value: stats.grace_period_subscribers || 0 })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Modules"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, Object.entries(links).map(([key, href]) => /* @__PURE__ */ React.createElement(xe, { key, href, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4 text-sm font-semibold text-white transition hover:border-white/15 hover:bg-white/[0.05]" }, key.replaceAll("_", " "))))));
}
const __vite_glob_0_22 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademyDashboard
}, Symbol.toStringTag, { value: "Module" }));
function AcademySubmissions({ submissions }) {
  const flash = X$1().props.flash || {};
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Challenge Submissions", subtitle: "Approve or reject Academy challenge entries." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Academy Challenge Submissions" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, (submissions?.data || []).map((submission) => /* @__PURE__ */ React.createElement("article", { key: submission.id, className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-white/80" }, submission.moderation_status), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, submission.challenge?.title || "Challenge")), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, submission.artwork?.title || "Artwork removed"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, submission.user?.name || "Unknown user", " · ", submission.ai_tool_used || "No tool noted"), submission.prompt_used ? /* @__PURE__ */ React.createElement("pre", { className: "whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, submission.prompt_used) : null, submission.workflow_notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-300" }, submission.workflow_notes) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(submission.approve_url, {}, { preserveScroll: true }), className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(submission.reject_url, {}, { preserveScroll: true }), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Reject")))))));
}
const __vite_glob_0_24 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AcademySubmissions
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$h() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$q(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$h(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed.");
  }
  return payload;
}
function formatDateTime$5(value) {
  if (!value) return "—";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "—";
  return new Intl.DateTimeFormat("en", {
    dateStyle: "medium",
    timeStyle: "short"
  }).format(date);
}
function Badge$3({ children, tone = "slate" }) {
  const tones2 = {
    slate: "border-white/10 bg-white/[0.06] text-slate-200",
    sky: "border-sky-300/20 bg-sky-400/12 text-sky-100",
    emerald: "border-emerald-300/20 bg-emerald-400/12 text-emerald-100",
    amber: "border-amber-300/20 bg-amber-400/12 text-amber-100",
    rose: "border-rose-300/20 bg-rose-400/12 text-rose-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tones2[tone] || tones2.slate}` }, children);
}
function StatCard$b({ label, value, tone = "sky" }) {
  const tones2 = {
    sky: "border-sky-300/15 bg-sky-400/10 text-sky-100",
    amber: "border-amber-300/15 bg-amber-400/10 text-amber-100",
    emerald: "border-emerald-300/15 bg-emerald-400/10 text-emerald-100",
    rose: "border-rose-300/15 bg-rose-400/10 text-rose-100",
    slate: "border-white/10 bg-white/10 text-slate-100"
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${tones2[tone] || tones2.sky}` }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, Number(value || 0).toLocaleString()));
}
function selectTone(record) {
  if (record.last_error_code || record.status === "failed") return "rose";
  if (record.needs_review) return "amber";
  if (record.is_user_edited) return "sky";
  if (record.status === "approved") return "emerald";
  return "slate";
}
function labelForStatus(value) {
  if (!value) return "Unknown";
  return String(value).replaceAll("_", " ");
}
function AiBiographyAdmin() {
  const { props } = X$1();
  const records = props.records || { data: [] };
  const stats = props.stats || {};
  const endpoints = props.endpoints || {};
  const filterOptions = props.filterOptions || {};
  const [filters, setFilters] = React.useState(props.filters || {});
  const [busyKey, setBusyKey] = React.useState("");
  const [notice, setNotice] = React.useState("");
  const [error, setError] = React.useState("");
  React.useEffect(() => {
    setFilters(props.filters || {});
  }, [props.filters]);
  function updateFilter(key, value) {
    setFilters((current) => ({ ...current, [key]: value }));
  }
  function applyFilters(event) {
    event.preventDefault();
    setError("");
    setNotice("");
    At.get(endpoints.index, filters, {
      preserveState: true,
      replace: true,
      preserveScroll: true
    });
  }
  function resetFilters() {
    setError("");
    setNotice("");
    At.get(endpoints.index, {
      q: "",
      status: "all",
      scope: "all",
      tier: "all",
      visibility: "all",
      review: "all"
    }, {
      preserveState: true,
      replace: true,
      preserveScroll: true
    });
  }
  async function performAction(actionKey, url) {
    setBusyKey(actionKey);
    setError("");
    try {
      const payload = await requestJson$q(url);
      setNotice(payload.message || "Action completed.");
      At.reload({
        only: ["records", "stats", "filters"],
        preserveScroll: true
      });
    } catch (requestError) {
      setError(requestError.message || "Action failed.");
    } finally {
      setBusyKey("");
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "AI Biography Review" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.2),transparent_32%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.9))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Moderator surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "AI biography review"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Browse active biographies and historical generations, inspect review flags and failures, and rebuild a creator biography directly from cPad.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 text-xs uppercase tracking-[0.16em] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2" }, "Page ", records.current_page || 1, " / ", records.last_page || 1), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2" }, Number(records.total || 0).toLocaleString(), " records"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$b, { label: "Total records", value: stats.total_records, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Active", value: stats.active_records, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Needs review", value: stats.needs_review, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Hidden active", value: stats.hidden_active, tone: "slate" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Failed", value: stats.failed, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "User edited", value: stats.user_edited_active, tone: "sky" })), /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 grid gap-3 lg:grid-cols-[2fr_repeat(5,minmax(0,1fr))]" }, /* @__PURE__ */ React.createElement("label", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Search creator"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: filters.q || "",
      onChange: (event) => updateFilter("q", event.target.value),
      placeholder: "username, name, or email",
      className: "mt-2 w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-sm text-white outline-none"
    }
  )), ["status", "scope", "tier", "visibility", "review"].map((key) => /* @__PURE__ */ React.createElement("div", { key, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, key.replace("_", " ")), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters[key] || "all",
      onChange: (value) => updateFilter(key, value),
      className: "mt-2",
      options: (filterOptions[key] || []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "lg:col-span-full flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-400/12 px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/18" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-filter text-[10px]" }), "Apply filters"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetFilters, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left text-[10px]" }), "Reset")))), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, notice) : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-4" }, (records.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-300" }, "No AI biography records matched the current filters.") : (records.data || []).map((record) => {
    const rebuildKey = `rebuild-${record.user_id}`;
    const approveKey = `approve-${record.id}`;
    const flagKey = `flag-${record.id}`;
    const visibilityKey = `${record.is_hidden ? "show" : "hide"}-${record.id}`;
    return /* @__PURE__ */ React.createElement("article", { key: record.id, className: "rounded-[28px] border border-white/10 bg-[#08111d] p-5 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Badge$3, { tone: selectTone(record) }, labelForStatus(record.status)), /* @__PURE__ */ React.createElement(Badge$3, { tone: record.is_active ? "emerald" : "slate" }, record.is_active ? "active" : "inactive"), /* @__PURE__ */ React.createElement(Badge$3, { tone: record.is_hidden ? "amber" : "sky" }, record.is_hidden ? "hidden" : "visible"), record.needs_review ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "amber" }, "needs review") : null, record.is_user_edited ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "sky" }, "user edited") : null, record.is_stale ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "rose" }, "stale") : null, record.input_quality_tier ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "slate" }, "tier: ", record.input_quality_tier) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, record.user?.display_name || "Unknown creator"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "@", record.user?.username || "unknown", record.user?.email ? ` • ${record.user.email}` : "", record.generation_reason ? ` • reason: ${labelForStatus(record.generation_reason)}` : "")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, record.user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: record.user.profile_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-[10px]" }), "Open profile") : null, record.user?.gallery_url ? /* @__PURE__ */ React.createElement("a", { href: record.user.gallery_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images text-[10px]" }), "Open gallery") : null, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: busyKey === rebuildKey,
        onClick: () => performAction(rebuildKey, String(endpoints.rebuildPattern || "").replace("__USER__", String(record.user_id))),
        className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/18 disabled:cursor-not-allowed disabled:opacity-60"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate text-[10px]" }),
      busyKey === rebuildKey ? "Rebuilding…" : "Rebuild"
    ))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Prompt"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, record.prompt_version || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Model"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, record.model || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Generated"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, formatDateTime$5(record.generated_at))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last attempted"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, formatDateTime$5(record.last_attempted_at)))), record.last_error_code || record.last_error_reason ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm leading-relaxed text-rose-100" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-100/80" }, "Last error"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, record.last_error_code || "generation_failed", record.last_error_reason ? ` • ${record.last_error_reason}` : "")) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Biography text"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 max-h-[320px] overflow-y-auto whitespace-pre-wrap rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-4 text-sm leading-relaxed text-slate-100" }, record.text || "No biography text stored for this record.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Review actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: busyKey === approveKey,
        onClick: () => performAction(approveKey, String(endpoints.approvePattern || "").replace("__BIOGRAPHY__", String(record.id))),
        className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-emerald-300/20 bg-emerald-400/12 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-50 transition hover:bg-emerald-400/18 disabled:cursor-not-allowed disabled:opacity-60"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check text-[10px]" }),
      busyKey === approveKey ? "Saving…" : "Mark reviewed"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: busyKey === flagKey,
        onClick: () => performAction(flagKey, String(endpoints.flagPattern || "").replace("__BIOGRAPHY__", String(record.id))),
        className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/12 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-amber-50 transition hover:bg-amber-400/18 disabled:cursor-not-allowed disabled:opacity-60"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag text-[10px]" }),
      busyKey === flagKey ? "Saving…" : "Flag for review"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: !record.is_active || busyKey === visibilityKey,
        onClick: () => performAction(visibilityKey, String((record.is_hidden ? endpoints.showPattern : endpoints.hidePattern) || "").replace("__BIOGRAPHY__", String(record.id))),
        className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:cursor-not-allowed disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${record.is_hidden ? "fa-eye" : "fa-eye-slash"} text-[10px]` }),
      busyKey === visibilityKey ? "Saving…" : record.is_hidden ? "Show publicly" : "Hide publicly"
    )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2 text-xs leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Approved:"), " ", formatDateTime$5(record.approved_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Created:"), " ", formatDateTime$5(record.created_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Updated:"), " ", formatDateTime$5(record.updated_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Source hash:"), " ", record.source_hash || "—")))));
  })), records.prev_page_url || records.next_page_url ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, records.prev_page_url ? /* @__PURE__ */ React.createElement(xe, { href: records.prev_page_url, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Previous") : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, "Showing page ", records.current_page || 1, " of ", records.last_page || 1), /* @__PURE__ */ React.createElement("div", null, records.next_page_url ? /* @__PURE__ */ React.createElement(xe, { href: records.next_page_url, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-[10px]" })) : null)) : null);
}
const __vite_glob_0_94 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AiBiographyAdmin
}, Symbol.toStringTag, { value: "Module" }));
function AdminAiBiography() {
  return /* @__PURE__ */ React.createElement(AdminLayout, null, /* @__PURE__ */ React.createElement(AiBiographyAdmin, null));
}
const __vite_glob_0_25 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AdminAiBiography
}, Symbol.toStringTag, { value: "Module" }));
function AdminArtworks({ artworks }) {
  const items = artworks?.data ?? [];
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Artworks", subtitle: "Browse and manage all artworks on the platform" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Artworks" }), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-wider text-slate-600" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Artwork"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Author"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Uploaded"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.04]" }, items.length === 0 && /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 5, className: "px-5 py-12 text-center text-slate-500" }, "No artworks found.")), items.map((artwork) => /* @__PURE__ */ React.createElement("tr", { key: artwork.id, className: "transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, artwork.thumb && /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-10 w-10 rounded-lg object-cover" }), /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, artwork.title || /* @__PURE__ */ React.createElement("span", { className: "italic text-slate-500" }, "Untitled")))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-400" }, artwork.user?.name ?? "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${artwork.status === "published" ? "bg-teal-500/20 text-teal-300" : artwork.status === "pending" ? "bg-amber-500/20 text-amber-300" : "bg-slate-500/20 text-slate-400"}` }, artwork.status ?? "unknown")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-500" }, artwork.created_at ? new Date(artwork.created_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/studio/artworks/${artwork.id}/edit`,
      className: "rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.09]"
    },
    "Edit"
  ))))))), artworks?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", artworks.from, "–", artworks.to, " of ", artworks.total, " artworks"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, artworks.links.map((link2, i) => link2.url ? /* @__PURE__ */ React.createElement(
    "button",
    {
      key: i,
      type: "button",
      onClick: () => At.get(link2.url, {}, { preserveScroll: true }),
      className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`,
      dangerouslySetInnerHTML: { __html: link2.label }
    }
  ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } }))))));
}
const __vite_glob_0_26 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AdminArtworks
}, Symbol.toStringTag, { value: "Module" }));
const EVENT_LABELS = {
  login: "Login",
  register: "Register",
  forgot_password: "Forgot password",
  reset_password: "Reset password"
};
const STATUS_BADGES = {
  success: "border-emerald-400/20 bg-emerald-400/10 text-emerald-200",
  failed: "border-rose-400/20 bg-rose-400/10 text-rose-200"
};
function formatTimestamp(value) {
  if (!value) {
    return "Unknown";
  }
  return new Intl.DateTimeFormat("en-GB", {
    dateStyle: "medium",
    timeStyle: "medium"
  }).format(new Date(value));
}
function formatLabel(value) {
  if (!value) {
    return "Not recorded";
  }
  return value.replaceAll("_", " ").replace(/\b\w/g, (match) => match.toUpperCase());
}
function SummaryCard$5({ label, value, tone = "slate" }) {
  const tones2 = {
    slate: "border-white/[0.07] bg-white/[0.02] text-white",
    rose: "border-rose-400/15 bg-rose-500/10 text-rose-100",
    sky: "border-sky-400/15 bg-sky-500/10 text-sky-100"
  };
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border p-5 ${tones2[tone] ?? tones2.slate}` }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-tight" }, value));
}
function AuthAudit({ logs, filters, eventOptions, statusOptions }) {
  const items = logs?.data ?? [];
  const failedCount = items.filter((entry) => entry.status === "failed").length;
  const uniqueIpCount = new Set(items.map((entry) => entry.ip).filter(Boolean)).size;
  const handleSearch = (event) => {
    event.preventDefault();
    const search2 = event.target.elements.search.value;
    At.get("/moderation/auth-audit", {
      search: search2,
      event: filters.event,
      status: filters.status
    }, {
      preserveState: true,
      preserveScroll: true
    });
  };
  const handleFilterChange = (key, value) => {
    At.get("/moderation/auth-audit", {
      search: filters.search,
      event: key === "event" ? value : filters.event,
      status: key === "status" ? value : filters.status
    }, {
      preserveState: true,
      preserveScroll: true
    });
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Auth Audit", subtitle: "Review login, registration, forgot-password, and reset-password activity with IPs, timestamps, status, and failure reasons." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Auth Audit" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Visible records", value: items.length.toLocaleString(), tone: "slate" }), /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Failures on page", value: failedCount.toLocaleString(), tone: "rose" }), /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Unique IPs on page", value: uniqueIpCount.toLocaleString(), tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-white/[0.07] bg-white/[0.02] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSearch, className: "flex flex-1 flex-col gap-3 md:flex-row" }, /* @__PURE__ */ React.createElement("label", { className: "flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement(
    "input",
    {
      name: "search",
      defaultValue: filters.search,
      placeholder: "Email, username, IP, or failure reason",
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white placeholder:text-slate-600 focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10"
    }
  )), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl bg-rose-500/80 px-5 py-3 text-sm font-semibold text-white transition hover:bg-rose-500" }, "Search")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:min-w-[26rem]" }, /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Event"), /* @__PURE__ */ React.createElement(
    "select",
    {
      value: filters.event,
      onChange: (event) => handleFilterChange("event", event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10"
    },
    eventOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value, className: "bg-slate-950 text-white" }, option.label))
  )), /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement(
    "select",
    {
      value: filters.status,
      onChange: (event) => handleFilterChange("status", event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10"
    },
    statusOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value, className: "bg-slate-950 text-white" }, option.label))
  ))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 overflow-hidden rounded-[28px] border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full min-w-[980px] text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "When"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Event"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Identifier"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "User"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "IP"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Reason"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Details"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.05]" }, items.length === 0 ? /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 8, className: "px-5 py-12 text-center text-slate-500" }, "No auth audit records matched the current filters.")) : items.map((entry) => /* @__PURE__ */ React.createElement("tr", { key: entry.id, className: "align-top transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, formatTimestamp(entry.created_at)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-white" }, EVENT_LABELS[entry.event_type] ?? formatLabel(entry.event_type)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold uppercase tracking-[0.16em] ${STATUS_BADGES[entry.status] ?? "border-white/10 bg-white/[0.04] text-white/70"}` }, entry.status)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, entry.identifier || "Not recorded"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, entry.user ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-medium text-white" }, entry.user.name), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, entry.user.username ? `@${entry.user.username}` : entry.user.email)) : /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Unknown user")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, entry.ip || "Unknown"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, formatLabel(entry.reason)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("details", { className: "group w-72 max-w-full" }, /* @__PURE__ */ React.createElement("summary", { className: "cursor-pointer list-none text-sm font-medium text-sky-200 transition hover:text-sky-100" }, "View payload"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 rounded-2xl border border-white/10 bg-black/20 p-4 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "User agent"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 break-words leading-5 text-slate-300" }, entry.user_agent || "Not recorded")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Metadata"), /* @__PURE__ */ React.createElement("pre", { className: "mt-1 overflow-x-auto whitespace-pre-wrap break-words rounded-xl bg-slate-950/70 p-3 text-[11px] leading-5 text-slate-300" }, JSON.stringify(entry.metadata || {}, null, 2))))))))))), logs?.last_page > 1 ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", logs.from, "–", logs.to, " of ", logs.total, " audit records"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, logs.links.map((link2, index2) => link2.url ? /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${link2.label}-${index2}`,
      type: "button",
      onClick: () => At.get(link2.url, {}, { preserveScroll: true, preserveState: true }),
      className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`,
      dangerouslySetInnerHTML: { __html: link2.label }
    }
  ) : /* @__PURE__ */ React.createElement("span", { key: `${link2.label}-${index2}`, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))) : null));
}
const __vite_glob_0_27 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AuthAudit
}, Symbol.toStringTag, { value: "Module" }));
function formatDateTime$4(value) {
  if (!value) return "—";
  try {
    return new Intl.DateTimeFormat(void 0, {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit"
    }).format(new Date(value));
  } catch {
    return String(value);
  }
}
function StatCard$a({ icon, label, value, tone = "sky" }) {
  const tones2 = {
    sky: "border-sky-400/20 bg-sky-400/10 text-sky-200",
    rose: "border-rose-400/20 bg-rose-400/10 text-rose-200",
    amber: "border-amber-400/20 bg-amber-400/10 text-amber-200",
    emerald: "border-emerald-400/20 bg-emerald-400/10 text-emerald-200"
  };
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border p-5 ${tones2[tone]}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/65" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-bold text-white" }, Number(value || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-black/20 text-lg text-white/80" }, /* @__PURE__ */ React.createElement("i", { className: icon }))));
}
function SectionCard$3({ title, subtitle, actionHref, actionLabel, children }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-3xl border border-white/10 bg-white/[0.04] p-5 shadow-[0_24px_80px_rgba(2,6,23,0.35)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/8 pb-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle) : null), actionHref ? /* @__PURE__ */ React.createElement("a", { href: actionHref, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-200 transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, actionLabel || "Open queue"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-[10px]" })) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, children));
}
function EmptyState$6({ label }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-black/10 px-4 py-6 text-sm text-slate-400" }, label);
}
function DataTable({ columns, rows, emptyLabel }) {
  if (!rows?.length) {
    return /* @__PURE__ */ React.createElement(EmptyState$6, { label: emptyLabel });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/10 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "text-left text-[11px] uppercase tracking-[0.18em] text-slate-500" }, columns.map((column) => /* @__PURE__ */ React.createElement("th", { key: column.key, className: "px-3 py-3 font-semibold" }, column.label)))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/6" }, rows.map((row, index2) => /* @__PURE__ */ React.createElement("tr", { key: row.id || `${index2}-${row.created_at || row.updated_at || "row"}`, className: "align-top" }, columns.map((column) => /* @__PURE__ */ React.createElement("td", { key: column.key, className: "px-3 py-3 text-slate-200/90" }, column.render ? column.render(row) : row[column.key])))))));
}
function DailyActivity({ selectedDate, summary, queues, sections }) {
  const onDateChange = (event) => {
    At.get("/moderation/activity", { date: event.target.value }, { preserveState: true, replace: true });
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Daily Activity", subtitle: "A day-by-day moderation cockpit for reviewing new content, queue movement, and staff actions." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Daily Activity" }), /* @__PURE__ */ React.createElement("div", { className: "rounded-3xl border border-white/10 bg-[linear-gradient(135deg,rgba(244,63,94,0.18),rgba(15,23,42,0.75))] p-6 shadow-[0_30px_120px_rgba(15,23,42,0.5)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.26em] text-rose-200/80" }, "Moderation review"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-bold text-white" }, "Selected day: ", selectedDate), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-200/80" }, "This view pulls together the moderation-adjacent activity for the selected day so admins can triage queues and jump into the right review surface quickly.")), /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-300" }, "Day"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "date",
      value: selectedDate,
      onChange: onDateChange,
      className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none transition focus:border-rose-400/50"
    }
  )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-user-plus", label: "New Users", value: summary.new_users, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-images", label: "New Artworks", value: summary.new_artworks, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-feather-pointed", label: "New Stories", value: summary.new_stories, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-cloud-arrow-up", label: "Upload Events", value: summary.upload_events, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-flag", label: "Report Events", value: summary.report_events, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-fingerprint", label: "Auth Events", value: summary.auth_events, tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Queues right now"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Pending uploads"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.pending_uploads)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Open reports"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.open_reports)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Pending username requests"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.pending_username_requests)))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-5 lg:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Moderation throughput on this day"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Moderated uploads"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.moderated_uploads)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Moderated reports"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.moderated_reports)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Username events"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.username_events))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Uploads", subtitle: "New uploads and same-day moderation decisions.", actionHref: "/moderation/uploads", actionLabel: "Open uploads" }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No upload activity on this day.",
      rows: sections.uploads,
      columns: [
        { key: "title", label: "Upload", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, row.type, " · ", row.status, " · ", row.processing_state)) },
        { key: "moderation_status", label: "Moderation", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, row.moderation_status), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.moderation_note || "No note")) },
        { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) },
        { key: "moderated_at", label: "Moderated", render: (row) => formatDateTime$4(row.moderated_at) }
      ]
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Reports", subtitle: "User reports created or reviewed during the selected day." }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No report activity on this day.",
      rows: sections.reports,
      columns: [
        { key: "reason", label: "Report", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.reason), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, row.status, " · ", row.target_type, " #", row.target_id)) },
        { key: "reporter", label: "Reporter", render: (row) => row.reporter ? `@${row.reporter.username}` : "—" },
        { key: "target", label: "Target", render: (row) => row.target?.title || row.target?.context || "Resolved via moderation target" },
        { key: "last_moderated_at", label: "Reviewed", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, formatDateTime$4(row.last_moderated_at)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.last_moderated_by ? `@${row.last_moderated_by.username}` : "Unassigned")) }
      ]
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Username Requests", subtitle: "Requests created or reviewed on this day.", actionHref: "/moderation/usernames/moderation", actionLabel: "Open usernames" }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No username activity on this day.",
      rows: sections.username_requests,
      columns: [
        { key: "requested_username", label: "Request", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.requested_username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Current: ", row.current_username || row.current_name || "Unknown user")) },
        { key: "status", label: "Status" },
        { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) },
        { key: "reviewed_at", label: "Reviewed", render: (row) => formatDateTime$4(row.reviewed_at) }
      ]
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Auth Audit", subtitle: "Authentication events for the selected day.", actionHref: "/moderation/auth-audit", actionLabel: "Open audit" }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No auth audit events on this day.",
      rows: sections.auth_events,
      columns: [
        { key: "event_type", label: "Event", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.event_type), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.status, " · ", row.ip || "No IP")) },
        { key: "user", label: "User", render: (row) => row.user ? `@${row.user.username || row.user.name}` : row.identifier || "Guest" },
        { key: "reason", label: "Reason", render: (row) => row.reason || "—" },
        { key: "created_at", label: "When", render: (row) => formatDateTime$4(row.created_at) }
      ]
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Users", subtitle: "Accounts created on this day.", actionHref: "/moderation/users", actionLabel: "Open users" }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No new users on this day.",
      rows: sections.users,
      columns: [
        { key: "username", label: "User", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.username ? `@${row.username}` : row.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.email)) },
        { key: "role", label: "Role" },
        { key: "created_at", label: "Joined", render: (row) => formatDateTime$4(row.created_at) }
      ]
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Artworks", subtitle: "Artwork records created on this day.", actionHref: "/moderation/artworks", actionLabel: "Open artworks" }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No artwork activity on this day.",
      rows: sections.artworks,
      columns: [
        { key: "title", label: "Artwork", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.user?.username ? `@${row.user.username}` : "Unknown artist")) },
        { key: "status", label: "Status" },
        { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) }
      ]
    }
  )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Stories", subtitle: "Creator stories created on this day.", actionHref: "/moderation/stories", actionLabel: "Open stories" }, /* @__PURE__ */ React.createElement(
    DataTable,
    {
      emptyLabel: "No story activity on this day.",
      rows: sections.stories,
      columns: [
        { key: "title", label: "Story", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.creator?.username ? `@${row.creator.username}` : "Unknown creator")) },
        { key: "status", label: "Status" },
        { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) }
      ]
    }
  )))));
}
const __vite_glob_0_28 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: DailyActivity
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$9({ icon, label, value, color: color2 = "sky" }) {
  const colors = {
    sky: "from-sky-500/20 to-sky-500/5 border-sky-500/20 text-sky-400",
    rose: "from-rose-500/20 to-rose-500/5 border-rose-500/20 text-rose-400",
    amber: "from-amber-500/20 to-amber-500/5 border-amber-500/20 text-amber-400",
    violet: "from-violet-500/20 to-violet-500/5 border-violet-500/20 text-violet-400"
  };
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border bg-gradient-to-br p-6 ${colors[color2]}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-wider text-slate-400" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-3xl font-bold text-white" }, value.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: `flex h-12 w-12 items-center justify-center rounded-xl bg-white/5` }, /* @__PURE__ */ React.createElement("i", { className: `${icon} text-xl ${colors[color2].split(" ").at(-1)}` }))));
}
function Dashboard({ stats }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Dashboard", subtitle: "Overview of your Skinbase platform" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin Dashboard" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-users", label: "Total Users", value: stats.total_users, color: "sky" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-user-plus", label: "New Today", value: stats.new_users_today, color: "violet" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-shield-halved", label: "Staff Members", value: stats.staff_count, color: "rose" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-user-shield", label: "Moderators", value: stats.moderator_count, color: "amber" })), /* @__PURE__ */ React.createElement("div", { className: "mt-10" }, /* @__PURE__ */ React.createElement("h2", { className: "mb-4 text-sm font-semibold uppercase tracking-wider text-slate-500" }, "Quick Actions"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 lg:grid-cols-3" }, [
    { label: "Daily Activity", href: "/moderation/activity", icon: "fa-solid fa-calendar-day", desc: "Review everything created or moderated on a selected day" },
    { label: "Manage Users", href: "/moderation/users", icon: "fa-solid fa-users", desc: "Search, promote or demote users" },
    { label: "Staff Roles", href: "/moderation/users?role=admin", icon: "fa-solid fa-shield-halved", desc: "View all admins, managers and editorial staff" },
    { label: "Username Queue", href: "/moderation/usernames/moderation", icon: "fa-solid fa-id-badge", desc: "Review pending username requests" },
    { label: "Upload Queue", href: "/moderation/uploads", icon: "fa-solid fa-cloud-arrow-up", desc: "Moderate pending artwork submissions" },
    { label: "Stories", href: "/moderation/stories", icon: "fa-solid fa-feather-pointed", desc: "Browse all creator stories" },
    { label: "Artworks", href: "/moderation/artworks", icon: "fa-solid fa-images", desc: "Browse all uploaded artworks" },
    { label: "Enhance Jobs", href: "/moderation/enhance", icon: "fa-solid fa-up-right-and-down-left-from-center", desc: "Inspect queued, failed, and completed image enhance jobs" },
    { label: "Featured Artworks", href: "/moderation/artworks/featured", icon: "fa-solid fa-star", desc: "Curate the homepage featured artwork lineup" },
    { label: "AI Biography", href: "/moderation/ai-biography", icon: "fa-solid fa-wand-magic-sparkles", desc: "Review generated creator biographies and moderation flags" }
  ].map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.href,
      href: item.href,
      className: "group flex items-start gap-4 rounded-2xl border border-white/[0.07] bg-white/[0.03] p-5 transition hover:border-white/15 hover:bg-white/[0.06]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-rose-500/10" }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} text-rose-400` })),
    /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white group-hover:text-rose-300 transition" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-500" }, item.desc))
  )))));
}
const __vite_glob_0_29 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: Dashboard
}, Symbol.toStringTag, { value: "Module" }));
const variantStyles = {
  accent: { checked: "#E07A21", ring: "rgba(224,122,33,0.45)" },
  emerald: { checked: "#10b981", ring: "rgba(16,185,129,0.45)" },
  sky: { checked: "#0ea5e9", ring: "rgba(14,165,233,0.45)" }
};
const Checkbox = reactExports.forwardRef(function Checkbox2({ label, hint, error, size = 18, variant = "accent", id, className = "", checked, disabled, onChange, ...rest }, ref2) {
  const dim = typeof size === "number" ? `${size}px` : size;
  const numSize = typeof size === "number" ? size : parseInt(size, 10);
  const inputId = id ?? (label ? `cb-${label.toLowerCase().replace(/\s+/g, "-")}` : void 0);
  const colors = variantStyles[variant] ?? variantStyles.accent;
  const tickInset = Math.round(numSize * 0.18);
  const strokeWidth = Math.max(1.5, numSize * 0.1);
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1" }, /* @__PURE__ */ React.createElement(
    "label",
    {
      className: [
        "inline-flex items-start gap-2.5 select-none",
        disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "checkbox",
        id: inputId,
        ref: ref2,
        checked,
        disabled,
        onChange,
        className: "sr-only",
        "aria-invalid": !!error,
        ...rest
      }
    ),
    /* @__PURE__ */ React.createElement(
      "span",
      {
        "aria-hidden": "true",
        style: {
          width: dim,
          height: dim,
          minWidth: dim,
          minHeight: dim,
          aspectRatio: "1 / 1",
          marginTop: label ? "1px" : void 0,
          backgroundColor: checked ? colors.checked : "rgba(255,255,255,0.06)",
          borderColor: checked ? colors.checked : "rgba(255,255,255,0.25)",
          boxShadow: checked ? `0 0 0 0px ${colors.ring}` : void 0,
          transition: "background-color 150ms, border-color 150ms"
        },
        className: [
          "shrink-0 inline-flex items-center justify-center",
          "rounded-md border",
          className
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement(
        "svg",
        {
          viewBox: "0 0 12 12",
          fill: "none",
          style: {
            width: numSize - tickInset * 2,
            height: numSize - tickInset * 2,
            opacity: checked ? 1 : 0,
            transition: "opacity 100ms"
          },
          "aria-hidden": "true"
        },
        /* @__PURE__ */ React.createElement(
          "path",
          {
            d: "M1.5 6l3 3 6-6",
            stroke: "white",
            strokeWidth,
            strokeLinecap: "round",
            strokeLinejoin: "round"
          }
        )
      )
    ),
    (label || hint) && /* @__PURE__ */ React.createElement("span", { className: "flex flex-col gap-0.5" }, label && /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/90 leading-snug" }, label), hint && /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, hint))
  ), error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400", style: { paddingLeft: `calc(${dim} + 0.625rem)` } }, error));
});
const FILTER_OPTIONS$1 = [
  { value: "all", label: "All rows" },
  { value: "winner", label: "Winner" },
  { value: "active", label: "Active" },
  { value: "eligible", label: "Eligible" },
  { value: "attention", label: "Needs attention" },
  { value: "ineligible", label: "Ineligible" },
  { value: "expired", label: "Expired" },
  { value: "inactive", label: "Inactive" }
];
const SORT_OPTIONS$2 = [
  { value: "priority", label: "Priority" },
  { value: "featured_at", label: "Featured Since" },
  { value: "expires_at", label: "Expires" },
  { value: "score_30d", label: "Medal Score (30d)" }
];
const PRIORITY_PRESETS = [60, 100, 180, 260, 340];
const PAGE_SIZE$1 = 24;
function cn(...values) {
  return values.filter(Boolean).join(" ");
}
function getCsrfToken$g() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$p(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$g(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.errors?.artwork_id?.[0] || payload?.errors?.is_active?.[0] || payload?.errors?.force_hero?.[0] || "Request failed.");
  }
  return payload;
}
function isoToLocalInput$3(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 6e4);
  return local.toISOString().slice(0, 16);
}
function localInputToIso$1(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return date.toISOString();
}
function formatDateTime$3(value) {
  if (!value) return "—";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "—";
  return new Intl.DateTimeFormat("en", {
    dateStyle: "medium",
    timeStyle: "short"
  }).format(date);
}
function formatShortDate$3(value) {
  if (!value) return "No expiry";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "No expiry";
  return new Intl.DateTimeFormat("en", {
    month: "short",
    day: "numeric"
  }).format(date);
}
function formatRelativeExpiry(value) {
  if (!value) return "No expiry";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "No expiry";
  const now = /* @__PURE__ */ new Date();
  const diffInDays = Math.ceil((date.getTime() - now.getTime()) / 864e5);
  if (diffInDays < 0) return `${Math.abs(diffInDays)}d overdue`;
  if (diffInDays === 0) return "Due today";
  if (diffInDays === 1) return "Due tomorrow";
  return `${diffInDays}d left`;
}
function formatOwner(entry) {
  if (!entry?.artwork?.owner) return "Unknown artist";
  if (entry.artwork.owner.type === "group") return `${entry.artwork.owner.display_name || "Unknown"} · Group publisher`;
  return `${entry.artwork.owner.display_name || "Unknown"} · @${entry.artwork.owner.username || ""}`;
}
function compareWinnerOrder(left, right) {
  if (Boolean(left?.is_force_hero) !== Boolean(right?.is_force_hero)) {
    return Boolean(right?.is_force_hero) - Boolean(left?.is_force_hero);
  }
  const priorityDiff = Number(right?.priority || 0) - Number(left?.priority || 0);
  if (priorityDiff !== 0) return priorityDiff;
  const scoreDiff = Number(right?.medals?.score_30d || 0) - Number(left?.medals?.score_30d || 0);
  if (scoreDiff !== 0) return scoreDiff;
  const featuredDiff = (new Date(right?.featured_at || 0).getTime() || 0) - (new Date(left?.featured_at || 0).getTime() || 0);
  if (featuredDiff !== 0) return featuredDiff;
  const publishedDiff = (new Date(right?.artwork?.published_at || 0).getTime() || 0) - (new Date(left?.artwork?.published_at || 0).getTime() || 0);
  if (publishedDiff !== 0) return publishedDiff;
  return Number(right?.id || 0) - Number(left?.id || 0);
}
function compareEntries(left, right, sortKey, direction) {
  const dir = direction === "asc" ? 1 : -1;
  const value = (entry) => {
    switch (sortKey) {
      case "featured_at":
        return new Date(entry.featured_at || 0).getTime() || 0;
      case "expires_at":
        return new Date(entry.expires_at || 0).getTime() || 0;
      case "score_30d":
        return Number(entry.medals?.score_30d || 0);
      default:
        return Number(entry.priority || 0);
    }
  };
  const leftValue = value(left);
  const rightValue = value(right);
  if (leftValue !== rightValue) {
    return (leftValue > rightValue ? 1 : -1) * dir;
  }
  return compareWinnerOrder(left, right);
}
function buildEntrySummary(entry) {
  if (entry?.is_force_hero) {
    return "Force Hero is enabled, so this row overrides the normal homepage winner order until editors switch it off.";
  }
  if (entry?.is_winner && entry?.winner_reason) {
    return entry.winner_reason;
  }
  if (!entry?.is_active) {
    return "Inactive rows stay visible for planning and editing, but they cannot win the homepage slot.";
  }
  if (entry?.is_expired) {
    return "This featured slot has expired and is excluded from the live homepage rotation.";
  }
  if (!entry?.eligibility?.is_eligible) {
    const reasons = Array.isArray(entry?.eligibility?.reasons) && entry.eligibility.reasons.length > 0 ? entry.eligibility.reasons.join(", ") : "Eligibility checks failed.";
    return `Currently blocked from winning: ${reasons}`;
  }
  return "Eligible and in the active selection pool. Priority leads first, then medal score, featured time, and publish date.";
}
function Badge$2({ label, tone = "slate" }) {
  const toneClasses2 = {
    slate: "border-white/10 bg-white/[0.07] text-slate-100",
    sky: "border-sky-300/20 bg-sky-400/15 text-sky-100",
    emerald: "border-emerald-300/20 bg-emerald-400/15 text-emerald-100",
    amber: "border-amber-300/20 bg-amber-400/15 text-amber-100",
    rose: "border-rose-300/20 bg-rose-400/15 text-rose-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: cn("inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em]", toneClasses2[tone] || toneClasses2.slate) }, label);
}
function Field$4({ label, help, children }) {
  return /* @__PURE__ */ React.createElement("label", { className: "block space-y-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, label), children, help ? /* @__PURE__ */ React.createElement("span", { className: "block text-xs leading-relaxed text-slate-400" }, help) : null);
}
function NoticeBanner({ notice }) {
  if (!notice?.message) return null;
  const toneClasses2 = {
    success: "border-emerald-300/20 bg-emerald-400/10 text-emerald-50",
    error: "border-rose-300/20 bg-rose-400/10 text-rose-50",
    info: "border-sky-300/20 bg-sky-400/10 text-sky-50"
  };
  return /* @__PURE__ */ React.createElement("div", { className: cn("rounded-[22px] border px-4 py-3 text-sm leading-6 shadow-[0_10px_30px_rgba(2,6,23,0.18)]", toneClasses2[notice.tone] || toneClasses2.info) }, notice.message);
}
function StatCard$8({ label, value, detail, tone = "sky" }) {
  const toneClasses2 = {
    sky: "border-sky-300/15 bg-sky-400/10 text-sky-100",
    amber: "border-amber-300/15 bg-amber-400/10 text-amber-100",
    emerald: "border-emerald-300/15 bg-emerald-400/10 text-emerald-100",
    rose: "border-rose-300/15 bg-rose-400/10 text-rose-100"
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: cn("inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em]", toneClasses2[tone] || toneClasses2.sky) }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] text-white" }, value), detail ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-400" }, detail) : null);
}
function MetricTile({ label, value, hint }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, value), hint ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, hint) : null);
}
function DockButton({ label, detail, tone = "sky", onClick }) {
  const toneClasses2 = {
    sky: "border-sky-300/25 bg-sky-400/12 text-sky-50",
    amber: "border-amber-300/25 bg-amber-400/12 text-amber-50",
    slate: "border-white/10 bg-white/[0.05] text-slate-100"
  };
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick,
      className: cn("flex min-w-0 flex-1 flex-col rounded-[20px] border px-4 py-3 text-left shadow-[0_14px_30px_rgba(2,6,23,0.24)] backdrop-blur-sm", toneClasses2[tone] || toneClasses2.sky)
    },
    /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] opacity-80" }, label),
    /* @__PURE__ */ React.createElement("span", { className: "mt-1 truncate text-sm font-semibold" }, detail)
  );
}
function FilterChip({ label, value, active, onClick, count }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onClick(value),
      className: cn(
        "inline-flex items-center gap-2 rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] transition",
        active ? "border-sky-300/40 bg-sky-400/15 text-sky-50 shadow-[0_10px_30px_rgba(56,189,248,0.16)]" : "border-white/10 bg-white/[0.03] text-slate-300 hover:border-white/20 hover:bg-white/[0.06]"
      )
    },
    /* @__PURE__ */ React.createElement("span", null, label),
    /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-black/20 px-2 py-0.5 text-[10px] text-slate-200" }, count)
  );
}
function emptyForm() {
  return {
    artwork_id: "",
    priority: 100,
    featured_at: isoToLocalInput$3((/* @__PURE__ */ new Date()).toISOString()),
    expires_at: "",
    is_active: true
  };
}
function mapEntryToCandidate(entry) {
  if (!entry) return null;
  return {
    ...entry.artwork,
    medals: entry.medals,
    eligibility: entry.eligibility,
    existing_feature_count: entry.duplicate_count,
    already_featured: entry.duplicate_count > 0
  };
}
function FeaturedArtworksAdmin() {
  const { props } = X$1();
  const composerRef = React.useRef(null);
  const rosterRef = React.useRef(null);
  const loadMoreRef = React.useRef(null);
  const endpoints = props.endpoints || {};
  const capabilities = props.capabilities || {};
  const seo = props.seo || {};
  const [entries, setEntries] = React.useState(Array.isArray(props.entries) ? props.entries : []);
  const [winner, setWinner] = React.useState(props.winner || null);
  const [stats, setStats] = React.useState(props.stats || {});
  const [notice, setNotice] = React.useState(null);
  const [busy, setBusy] = React.useState("");
  const [filter2, setFilter] = React.useState("all");
  const [sortKey, setSortKey] = React.useState("priority");
  const [sortDirection, setSortDirection] = React.useState("desc");
  const [listQuery, setListQuery] = React.useState("");
  const deferredListQuery = React.useDeferredValue(listQuery);
  const [searchQuery, setSearchQuery] = React.useState("");
  const [searchResults, setSearchResults] = React.useState([]);
  const [selectedArtwork, setSelectedArtwork] = React.useState(null);
  const [editingId, setEditingId] = React.useState(null);
  const [form, setForm] = React.useState(emptyForm());
  const [visibleCount, setVisibleCount] = React.useState(PAGE_SIZE$1);
  React.useEffect(() => {
    setEntries(Array.isArray(props.entries) ? props.entries : []);
    setWinner(props.winner || null);
    setStats(props.stats || {});
  }, [props.entries, props.stats, props.winner]);
  React.useEffect(() => {
    setVisibleCount(PAGE_SIZE$1);
  }, [deferredListQuery, filter2, sortDirection, sortKey]);
  function scrollToSection(ref2) {
    ref2.current?.scrollIntoView({ behavior: "smooth", block: "start" });
  }
  function scrollToTop() {
    if (typeof window !== "undefined") {
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  }
  function syncPayload(payload) {
    setEntries(Array.isArray(payload.entries) ? payload.entries : []);
    setWinner(payload.winner || null);
    setStats(payload.stats || {});
    if (payload.message) {
      setNotice({ tone: "success", message: payload.message });
    }
  }
  function resetEditor() {
    setEditingId(null);
    setSelectedArtwork(null);
    setSearchResults([]);
    setSearchQuery("");
    setForm(emptyForm());
  }
  async function handleArtworkSearch(event) {
    event.preventDefault();
    if (!searchQuery.trim()) {
      setSearchResults([]);
      return;
    }
    setBusy("search");
    setNotice(null);
    try {
      const url = `${endpoints.search}?q=${encodeURIComponent(searchQuery.trim())}`;
      const payload = await requestJson$p(url, { method: "GET" });
      const results = Array.isArray(payload.results) ? payload.results : [];
      setSearchResults(results);
      if (results.length === 0) {
        setNotice({ tone: "info", message: "No artworks matched that search." });
      }
    } catch (error) {
      setNotice({ tone: "error", message: error.message || "Artwork search failed." });
    } finally {
      setBusy("");
    }
  }
  function chooseArtwork(artwork) {
    setSelectedArtwork(artwork);
    setForm((current) => ({
      ...current,
      artwork_id: artwork.id
    }));
  }
  function editEntry(entry) {
    setEditingId(entry.id);
    setSelectedArtwork(mapEntryToCandidate(entry));
    setSearchResults([]);
    setSearchQuery("");
    setForm({
      artwork_id: entry.artwork_id,
      priority: entry.priority,
      featured_at: isoToLocalInput$3(entry.featured_at),
      expires_at: isoToLocalInput$3(entry.expires_at),
      is_active: Boolean(entry.is_active)
    });
    scrollToSection(composerRef);
  }
  async function handleSubmit(event) {
    event.preventDefault();
    if (!editingId && !form.artwork_id) {
      setNotice({ tone: "error", message: "Select an artwork first." });
      return;
    }
    setBusy("submit");
    setNotice(null);
    try {
      const payload = await requestJson$p(
        editingId ? endpoints.updatePattern.replace("__FEATURE__", String(editingId)) : endpoints.store,
        {
          method: editingId ? "PATCH" : "POST",
          body: {
            artwork_id: Number(form.artwork_id),
            priority: Number(form.priority || 0),
            featured_at: localInputToIso$1(form.featured_at),
            expires_at: localInputToIso$1(form.expires_at),
            is_active: Boolean(form.is_active)
          }
        }
      );
      syncPayload(payload);
      resetEditor();
    } catch (error) {
      setNotice({ tone: "error", message: error.message || "Failed to save this featured entry." });
    } finally {
      setBusy("");
    }
  }
  async function handleToggle(entry) {
    setBusy(`toggle-${entry.id}`);
    setNotice(null);
    try {
      const payload = await requestJson$p(endpoints.togglePattern.replace("__FEATURE__", String(entry.id)), {
        method: "PATCH"
      });
      syncPayload(payload);
    } catch (error) {
      setNotice({ tone: "error", message: error.message || "Failed to change active state." });
    } finally {
      setBusy("");
    }
  }
  async function handleDelete(entry) {
    if (typeof window !== "undefined" && !window.confirm(`Delete featured entry #${entry.id}?`)) {
      return;
    }
    setBusy(`delete-${entry.id}`);
    setNotice(null);
    try {
      const payload = await requestJson$p(endpoints.destroyPattern.replace("__FEATURE__", String(entry.id)), {
        method: "DELETE"
      });
      syncPayload(payload);
      if (editingId === entry.id) {
        resetEditor();
      }
    } catch (error) {
      setNotice({ tone: "error", message: error.message || "Failed to delete this featured entry." });
    } finally {
      setBusy("");
    }
  }
  async function handleForceHero(entry) {
    setBusy(`force-${entry.id}`);
    setNotice(null);
    try {
      const payload = await requestJson$p(endpoints.forceHeroPattern.replace("__FEATURE__", String(entry.id)), {
        method: "PATCH"
      });
      syncPayload(payload);
    } catch (error) {
      setNotice({ tone: "error", message: error.message || "Failed to change force hero state." });
    } finally {
      setBusy("");
    }
  }
  const duplicateSelection = !editingId && selectedArtwork?.already_featured;
  const suggestedPriority = winner ? Number(winner.priority || 0) + 20 : 120;
  const filterCounts = React.useMemo(() => ({
    all: entries.length,
    winner: entries.filter((entry) => Boolean(entry.is_winner)).length,
    active: entries.filter((entry) => Boolean(entry.is_active)).length,
    eligible: entries.filter((entry) => Boolean(entry.eligibility?.is_eligible)).length,
    attention: entries.filter((entry) => Boolean(entry.is_active) && (Boolean(entry.is_expired) || !entry.eligibility?.is_eligible)).length,
    ineligible: entries.filter((entry) => !entry.eligibility?.is_eligible).length,
    expired: entries.filter((entry) => Boolean(entry.is_expired)).length,
    inactive: entries.filter((entry) => !entry.is_active).length
  }), [entries]);
  const activeForceHeroEntry = React.useMemo(() => entries.find((entry) => Boolean(entry.is_force_hero)) || null, [entries]);
  const soonExpiringEntries = React.useMemo(() => {
    const now = Date.now();
    const cutoff = now + 7 * 864e5;
    return entries.filter((entry) => {
      if (!entry.expires_at || entry.is_expired) return false;
      const expiresAt = new Date(entry.expires_at).getTime();
      return !Number.isNaN(expiresAt) && expiresAt >= now && expiresAt <= cutoff;
    }).sort((left, right) => (new Date(left.expires_at).getTime() || 0) - (new Date(right.expires_at).getTime() || 0));
  }, [entries]);
  const naturalFallback = React.useMemo(() => {
    return [...entries].filter((entry) => Boolean(entry.is_active) && !Boolean(entry.is_expired) && Boolean(entry.eligibility?.is_eligible) && !Boolean(entry.is_winner)).sort(compareWinnerOrder)[0] || null;
  }, [entries]);
  const attentionEntries = React.useMemo(() => {
    return [...entries].filter((entry) => Boolean(entry.is_active) && (Boolean(entry.is_expired) || !entry.eligibility?.is_eligible)).sort(compareWinnerOrder).slice(0, 3);
  }, [entries]);
  const selectedArtworkSignals = React.useMemo(() => {
    if (!selectedArtwork) return [];
    const signals = [];
    const eligibilityReasons = Array.isArray(selectedArtwork.eligibility?.reasons) ? selectedArtwork.eligibility.reasons : [];
    signals.push({
      label: selectedArtwork.eligibility?.is_eligible ? "Ready for rotation now" : "Needs editorial attention",
      tone: selectedArtwork.eligibility?.is_eligible ? "emerald" : "rose",
      detail: selectedArtwork.eligibility?.is_eligible ? "Current eligibility checks pass." : eligibilityReasons.join(", ") || "Eligibility checks are failing."
    });
    if (winner) {
      const priorityGap = Number(form.priority || 0) - Number(winner.priority || 0);
      signals.push({
        label: priorityGap >= 0 ? "Priority matches or exceeds current winner" : "Lower priority than current winner",
        tone: priorityGap >= 0 ? "sky" : "amber",
        detail: `Current winner priority: ${winner.priority}. Proposed priority: ${Number(form.priority || 0)}.`
      });
    }
    if (selectedArtwork.already_featured) {
      signals.push({
        label: "Existing featured row found",
        tone: "amber",
        detail: `This artwork already appears in ${selectedArtwork.existing_feature_count || 1} featured row${selectedArtwork.existing_feature_count === 1 ? "" : "s"}.`
      });
    }
    return signals;
  }, [form.priority, selectedArtwork, winner]);
  const filteredEntries = React.useMemo(() => {
    const query = deferredListQuery.trim().toLowerCase();
    return [...entries].filter((entry) => {
      if (filter2 === "active") return Boolean(entry.is_active);
      if (filter2 === "inactive") return !entry.is_active;
      if (filter2 === "expired") return Boolean(entry.is_expired);
      if (filter2 === "winner") return Boolean(entry.is_winner);
      if (filter2 === "eligible") return Boolean(entry.eligibility?.is_eligible);
      if (filter2 === "ineligible") return !entry.eligibility?.is_eligible;
      if (filter2 === "attention") return Boolean(entry.is_active) && (Boolean(entry.is_expired) || !entry.eligibility?.is_eligible);
      return true;
    }).filter((entry) => {
      if (!query) return true;
      const haystack = [
        entry.artwork?.title,
        entry.artwork?.owner?.display_name,
        entry.artwork?.owner?.username,
        entry.artwork?.id,
        entry.id
      ].join(" ").toLowerCase();
      return haystack.includes(query);
    }).sort((left, right) => compareEntries(left, right, sortKey, sortDirection));
  }, [deferredListQuery, entries, filter2, sortDirection, sortKey]);
  const visibleEntries = React.useMemo(() => filteredEntries.slice(0, visibleCount), [filteredEntries, visibleCount]);
  const hasMoreEntries = visibleEntries.length < filteredEntries.length;
  React.useEffect(() => {
    if (!hasMoreEntries || typeof IntersectionObserver === "undefined" || !loadMoreRef.current) {
      return void 0;
    }
    const observer = new IntersectionObserver((observerEntries) => {
      if (observerEntries.some((observerEntry) => observerEntry.isIntersecting)) {
        setVisibleCount((current) => Math.min(current + PAGE_SIZE$1, filteredEntries.length));
      }
    }, { rootMargin: "320px 0px" });
    observer.observe(loadMoreRef.current);
    return () => observer.disconnect();
  }, [filteredEntries.length, hasMoreEntries, visibleCount]);
  function loadMoreEntries() {
    setVisibleCount((current) => Math.min(current + PAGE_SIZE$1, filteredEntries.length));
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, seo.title || "Featured Artworks"), seo.description ? /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description }) : null, seo.robots ? /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots }) : null, seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[#07111c] pb-28 text-white xl:pb-0" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex w-full max-w-none flex-col gap-8 px-4 py-8 sm:px-6 lg:px-8 2xl:px-10" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_35%),radial-gradient(circle_at_bottom_right,_rgba(245,158,11,0.14),_transparent_35%),linear-gradient(180deg,_rgba(6,14,25,0.92),_rgba(8,18,32,0.96))] p-8 shadow-[0_28px_90px_rgba(2,6,23,0.45)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-8 xl:flex-row xl:items-start xl:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Featured Artworks"), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold tracking-[-0.06em] text-white sm:text-5xl" }, "Curate the homepage with live winner context, not guesswork."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-7 text-slate-300 sm:text-base" }, "This workspace now behaves like an editorial command center: current winner visibility, natural fallback awareness, faster filters, and a cleaner composer for new or existing featured rows."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => scrollToSection(composerRef), className: "rounded-full bg-white px-5 py-3 text-sm font-semibold text-slate-950 transition hover:bg-slate-100" }, "Add or edit featured row"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        React.startTransition(() => setFilter("attention"));
        scrollToSection(rosterRef);
      },
      className: "rounded-full border border-white/10 px-5 py-3 text-sm font-semibold text-slate-100 transition hover:border-white/20 hover:bg-white/[0.06]"
    },
    "Review attention items"
  ), winner?.artwork?.canonical_url ? /* @__PURE__ */ React.createElement("a", { href: winner.artwork.canonical_url, target: "_blank", rel: "noreferrer", className: "rounded-full border border-amber-300/20 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:border-amber-300/40 hover:bg-amber-400/10" }, "Open current winner") : null)), /* @__PURE__ */ React.createElement("div", { className: "grid w-full max-w-2xl gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement(StatCard$8, { label: "Active pool", value: stats.active || 0, detail: "Rows currently allowed to compete for the homepage slot.", tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$8, { label: "Eligible now", value: stats.eligible || 0, detail: "Rows that can win without any manual override.", tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$8, { label: "Force Hero", value: activeForceHeroEntry ? "On" : "Off", detail: activeForceHeroEntry ? `${activeForceHeroEntry.artwork?.title || "Selected artwork"} is overriding the normal order.` : "Normal winner logic is in control.", tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$8, { label: "Expiring soon", value: soonExpiringEntries.length, detail: soonExpiringEntries[0] ? `${soonExpiringEntries[0].artwork?.title || "Next row"} is the nearest expiry.` : "No featured rows expire in the next 7 days.", tone: soonExpiringEntries.length > 0 ? "rose" : "sky" })))), /* @__PURE__ */ React.createElement(NoticeBanner, { notice }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[1.3fr_0.7fr]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.28)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Current Homepage Hero"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-3xl font-semibold tracking-[-0.05em] text-white" }, winner ? winner.artwork?.title : "No eligible featured artwork"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-7 text-slate-300" }, winner?.selection_reason || "There is no active, non-expired, eligible featured artwork right now.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, winner ? /* @__PURE__ */ React.createElement(Badge$2, { label: "Winner", tone: "amber" }) : /* @__PURE__ */ React.createElement(Badge$2, { label: "No winner", tone: "rose" }), winner?.is_force_hero ? /* @__PURE__ */ React.createElement(Badge$2, { label: "Force Hero", tone: "amber" }) : /* @__PURE__ */ React.createElement(Badge$2, { label: "Normal logic", tone: "sky" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 lg:grid-cols-[240px_1fr]" }, /* @__PURE__ */ React.createElement("a", { href: winner?.artwork?.canonical_url || "#", className: "overflow-hidden rounded-[26px] border border-white/10 bg-[#09121f]", target: "_blank", rel: "noreferrer" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: winner?.artwork?.thumbnail?.url,
      alt: winner?.artwork?.title || "Winner preview",
      className: "h-full min-h-[220px] w-full object-cover"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(MetricTile, { label: "Artist", value: winner?.artwork?.owner?.display_name || "Unknown", hint: winner?.artwork?.owner?.type === "group" ? "Group publisher" : `@${winner?.artwork?.owner?.username || ""}` }), /* @__PURE__ */ React.createElement(MetricTile, { label: "Priority", value: winner?.priority ?? "—", hint: "Primary tie-breaker in hero selection." }), /* @__PURE__ */ React.createElement(MetricTile, { label: "Medal score", value: winner?.medals?.score_30d || 0, hint: "Last 30 days." }), /* @__PURE__ */ React.createElement(MetricTile, { label: "Featured Since", value: formatDateTime$3(winner?.featured_at), hint: "Used after priority and medal score." }))), winner?.is_force_hero ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[22px] border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-50" }, "Force Hero is active. This row bypasses the normal ranking until editors disable the override from the roster below.") : null), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.28)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Editorial Radar"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Know what happens next before you touch a row."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-400" }, "Natural fallback"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, naturalFallback?.artwork?.title || "No fallback candidate"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm leading-6 text-slate-400" }, naturalFallback ? `${formatOwner(naturalFallback)} · Priority ${naturalFallback.priority} · Medal ${naturalFallback.medals?.score_30d || 0}` : "All remaining rows are either inactive, expired, or ineligible.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-400" }, "Needs attention"), attentionEntries.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-300" }, "No active rows are currently blocked by expiry or eligibility rules.") : /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, attentionEntries.map((entry) => /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      key: entry.id,
      onClick: () => {
        React.startTransition(() => {
          setFilter("attention");
          setListQuery(String(entry.artwork?.id || entry.artwork_id || entry.id));
        });
        scrollToSection(rosterRef);
      },
      className: "block w-full rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-left transition hover:border-white/20 hover:bg-white/[0.05]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, entry.artwork?.title || `Featured row #${entry.id}`),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, buildEntrySummary(entry))
  )))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-400" }, "Next expiry checkpoint"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, soonExpiringEntries[0]?.artwork?.title || "Nothing expiring soon"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm leading-6 text-slate-400" }, soonExpiringEntries[0] ? `${formatRelativeExpiry(soonExpiringEntries[0].expires_at)} · ${formatDateTime$3(soonExpiringEntries[0].expires_at)}` : "No featured rows expire in the next 7 days."))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[1.25fr_0.75fr]" }, /* @__PURE__ */ React.createElement("section", { ref: rosterRef, className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.28)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Featured Pool"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Every featured row, with enough context to act quickly."), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Showing ", visibleEntries.length, " of ", filteredEntries.length, " matching rows. ", entries.length, " rows in the full pool.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-[minmax(0,1fr)_220px_124px] lg:w-[720px]" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: listQuery,
      onChange: (event) => setListQuery(event.target.value),
      placeholder: "Filter by title, artist, row ID, or artwork ID",
      className: "rounded-2xl border border-white/10 bg-[#08111d] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/40"
    }
  ), /* @__PURE__ */ React.createElement(NovaSelect, { value: sortKey, onChange: (value) => setSortKey(value), searchable: false, options: SORT_OPTIONS$2 }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setSortDirection((current) => current === "desc" ? "asc" : "desc"), className: "rounded-2xl border border-white/10 px-4 py-3 text-sm font-semibold text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, sortDirection === "desc" ? "Desc" : "Asc"))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, FILTER_OPTIONS$1.map((option) => /* @__PURE__ */ React.createElement(
    FilterChip,
    {
      key: option.value,
      label: option.label,
      value: option.value,
      active: filter2 === option.value,
      onClick: (nextValue) => React.startTransition(() => setFilter(nextValue)),
      count: filterCounts[option.value] ?? 0
    }
  )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, filteredEntries.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-dashed border-white/10 bg-black/20 px-6 py-12 text-center text-sm leading-6 text-slate-400" }, "No featured entries match the current search and filter combination.") : visibleEntries.map((entry) => /* @__PURE__ */ React.createElement("article", { key: entry.id, className: "rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 xl:flex-row xl:items-start xl:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 gap-4" }, /* @__PURE__ */ React.createElement("a", { href: entry.artwork?.canonical_url || "#", target: "_blank", rel: "noreferrer", className: "h-28 w-28 shrink-0 overflow-hidden rounded-[22px] border border-white/10 bg-[#08111d]" }, /* @__PURE__ */ React.createElement("img", { src: entry.artwork?.thumbnail?.url, alt: entry.artwork?.title || "Artwork preview", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold tracking-[-0.03em] text-white" }, entry.artwork?.title || "Missing artwork"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-400" }, "Artwork #", entry.artwork?.id || entry.artwork_id), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "Row #", entry.id)), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-300" }, formatOwner(entry)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-slate-400" }, buildEntrySummary(entry)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, (entry.status_badges || []).map((badge, index2) => /* @__PURE__ */ React.createElement(Badge$2, { key: `${entry.id}-${badge.label}-${index2}`, label: badge.label, tone: badge.tone }))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:w-[420px] xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(MetricTile, { label: "Priority", value: entry.priority, hint: "Higher wins first" }), /* @__PURE__ */ React.createElement(MetricTile, { label: "Medal score", value: entry.medals?.score_30d || 0, hint: "Last 30d" }), /* @__PURE__ */ React.createElement(MetricTile, { label: "Featured", value: formatShortDate$3(entry.featured_at), hint: formatDateTime$3(entry.featured_at) }), /* @__PURE__ */ React.createElement(MetricTile, { label: "Expires", value: formatRelativeExpiry(entry.expires_at), hint: formatDateTime$3(entry.expires_at) }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-col gap-4 border-t border-white/10 pt-4 xl:flex-row xl:items-center xl:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm leading-6 text-slate-400" }, "Visibility: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, entry.artwork?.visibility || "—"), /* @__PURE__ */ React.createElement("span", { className: "mx-2 text-slate-600" }, "•"), "Published: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, entry.artwork?.published_at ? "Yes" : "No")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 xl:justify-end" }, /* @__PURE__ */ React.createElement("a", { href: entry.artwork?.canonical_url || "#", target: "_blank", rel: "noreferrer", className: "rounded-full border border-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, "Open artwork"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => editEntry(entry), className: "rounded-full border border-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, "Edit row"), capabilities.forceHeroEnabled ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleForceHero(entry), disabled: busy === `force-${entry.id}`, className: cn("rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition disabled:cursor-not-allowed disabled:opacity-60", entry.is_force_hero ? "border-amber-300/25 text-amber-100 hover:border-amber-300/40 hover:bg-amber-400/10" : "border-amber-300/15 text-amber-50 hover:border-amber-300/30 hover:bg-amber-400/5") }, busy === `force-${entry.id}` ? "Saving…" : entry.is_force_hero ? "Disable Force Hero" : "Force Hero") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleToggle(entry), disabled: busy === `toggle-${entry.id}`, className: "rounded-full border border-sky-300/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-400/10 disabled:cursor-not-allowed disabled:opacity-60" }, busy === `toggle-${entry.id}` ? "Saving…" : entry.is_active ? "Deactivate" : "Activate"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleDelete(entry), disabled: busy === `delete-${entry.id}`, className: "rounded-full border border-rose-300/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-rose-100 transition hover:border-rose-300/40 hover:bg-rose-400/10 disabled:cursor-not-allowed disabled:opacity-60" }, busy === `delete-${entry.id}` ? "Deleting…" : "Delete"))))), hasMoreEntries ? /* @__PURE__ */ React.createElement("div", { ref: loadMoreRef, className: "rounded-[24px] border border-dashed border-white/10 bg-black/20 px-5 py-6 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, "Loading more rows as you reach the bottom."), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: loadMoreEntries,
      className: "mt-4 rounded-full border border-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-100 transition hover:border-white/20 hover:bg-white/5"
    },
    "Load 24 more"
  )) : filteredEntries.length > PAGE_SIZE$1 ? /* @__PURE__ */ React.createElement("div", { className: "text-center text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "All matching rows loaded") : null)), /* @__PURE__ */ React.createElement("section", { ref: composerRef, className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.28)] backdrop-blur-sm xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Editorial Composer"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, editingId ? `Edit featured row #${editingId}` : "Build a new featured row"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Search, inspect readiness, choose timing, and ship the change without leaving the page context.")), editingId ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetEditor, className: "rounded-full border border-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-200 transition hover:border-white/20 hover:bg-white/5" }, "Cancel edit") : null), !editingId ? /* @__PURE__ */ React.createElement("form", { onSubmit: handleArtworkSearch, className: "mt-6 space-y-4 rounded-[26px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement(Field$4, { label: "Artwork selector", help: "Search by artwork ID, title, slug, artist, or group, then lock one result into the composer." }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: searchQuery,
      onChange: (event) => setSearchQuery(event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-[#08111d] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/40",
      placeholder: "Try an artwork ID, title, or creator"
    }
  ), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "search", className: "rounded-2xl bg-sky-400 px-4 py-3 text-sm font-semibold text-slate-950 transition hover:bg-sky-300 disabled:cursor-not-allowed disabled:opacity-60" }, busy === "search" ? "Searching…" : "Search"))), searchResults.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Search results"), searchResults.map((artwork) => /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      key: artwork.id,
      onClick: () => chooseArtwork(artwork),
      className: cn("grid gap-4 rounded-[22px] border p-3 text-left transition sm:grid-cols-[88px_1fr]", selectedArtwork?.id === artwork.id ? "border-sky-300/40 bg-sky-400/10 shadow-[0_12px_30px_rgba(56,189,248,0.15)]" : "border-white/10 bg-white/[0.02] hover:border-white/20 hover:bg-white/[0.04]")
    },
    /* @__PURE__ */ React.createElement("img", { src: artwork.thumbnail?.url, alt: artwork.title, className: "h-24 w-full rounded-2xl object-cover" }),
    /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-400" }, "#", artwork.id), artwork.already_featured ? /* @__PURE__ */ React.createElement(Badge$2, { label: "Already Featured", tone: "amber" }) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, artwork.owner?.display_name || "Unknown", " · Medal Score (30d): ", artwork.medals?.score_30d || 0), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (artwork.eligibility?.is_eligible ? [{ label: "Eligible", tone: "emerald" }] : [{ label: "Not eligible", tone: "rose" }]).concat(
      (artwork.eligibility?.reasons || []).map((reason) => ({
        label: reason,
        tone: reason === "Missing preview" ? "rose" : "slate"
      }))
    ).slice(0, 4).map((badge) => /* @__PURE__ */ React.createElement(Badge$2, { key: `${artwork.id}-${badge.label}`, label: badge.label, tone: badge.tone }))))
  ))) : null) : null, selectedArtwork ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-[108px_1fr]" }, /* @__PURE__ */ React.createElement("img", { src: selectedArtwork.thumbnail?.url, alt: selectedArtwork.title || "Artwork preview", className: "h-28 w-full rounded-2xl object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-400" }, "Selected Artwork"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, selectedArtwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm leading-6 text-slate-400" }, "#", selectedArtwork.id, " · ", selectedArtwork.owner?.display_name || "Unknown", " · Medal Score (30d): ", selectedArtwork.medals?.score_30d || 0)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (selectedArtwork.eligibility?.is_eligible ? [{ label: "Currently eligible", tone: "emerald" }] : [{ label: "Currently ineligible", tone: "rose" }]).concat(
    (selectedArtwork.eligibility?.reasons || []).map((reason) => ({
      label: reason,
      tone: reason === "Missing preview" ? "rose" : "slate"
    }))
  ).map((badge) => /* @__PURE__ */ React.createElement(Badge$2, { key: `selected-${badge.label}`, label: badge.label, tone: badge.tone }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, selectedArtwork.canonical_url ? /* @__PURE__ */ React.createElement("a", { href: selectedArtwork.canonical_url, target: "_blank", rel: "noreferrer", className: "rounded-full border border-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, "Open artwork") : null, selectedArtwork.already_featured ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        React.startTransition(() => {
          setFilter("all");
          setListQuery(String(selectedArtwork?.id || ""));
        });
        scrollToSection(rosterRef);
      },
      className: "rounded-full border border-amber-300/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-amber-50 transition hover:border-amber-300/40 hover:bg-amber-400/10"
    },
    "Find existing row"
  ) : null))), selectedArtworkSignals.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, selectedArtworkSignals.map((signal) => /* @__PURE__ */ React.createElement("div", { key: signal.label, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement(Badge$2, { label: signal.label, tone: signal.tone })), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-300" }, signal.detail)))) : null) : null, duplicateSelection ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-100" }, "This artwork already has a featured entry. Edit the existing row instead of creating a duplicate.", /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        React.startTransition(() => {
          setFilter("all");
          setListQuery(String(selectedArtwork?.id || ""));
        });
        scrollToSection(rosterRef);
      },
      className: "rounded-full border border-amber-300/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-amber-50 transition hover:border-amber-300/40 hover:bg-amber-400/10"
    },
    "Find existing row"
  ))) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit, className: "mt-6 space-y-5" }, /* @__PURE__ */ React.createElement(Field$4, { label: "Priority", help: "Higher priority always wins before medal score is considered." }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "number",
      min: "0",
      value: form.priority,
      onChange: (event) => setForm((current) => ({ ...current, priority: event.target.value })),
      className: "w-full rounded-2xl border border-white/10 bg-[#08111d] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/40"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, PRIORITY_PRESETS.map((preset) => /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      key: preset,
      onClick: () => setForm((current) => ({ ...current, priority: preset })),
      className: cn("rounded-full border px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] transition", Number(form.priority) === preset ? "border-sky-300/40 bg-sky-400/10 text-sky-100" : "border-white/10 text-slate-300 hover:border-white/20 hover:bg-white/[0.05]")
    },
    preset
  )), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setForm((current) => ({ ...current, priority: suggestedPriority })),
      className: "rounded-full border border-emerald-300/20 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-emerald-100 transition hover:border-emerald-300/40 hover:bg-emerald-400/10"
    },
    "Winner + 20"
  ), winner ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setForm((current) => ({ ...current, priority: Number(winner.priority || 0) })),
      className: "rounded-full border border-white/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300 transition hover:border-white/20 hover:bg-white/[0.05]"
    },
    "Match winner"
  ) : null))), /* @__PURE__ */ React.createElement(Field$4, { label: "Active", help: "Inactive rows stay visible in admin but cannot win the homepage hero." }, /* @__PURE__ */ React.createElement("label", { className: "flex h-[52px] items-center gap-3 rounded-2xl border border-white/10 bg-[#08111d] px-4 py-3 text-sm text-slate-100" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: Boolean(form.is_active),
      onChange: (event) => setForm((current) => ({ ...current, is_active: event.target.checked }))
    }
  ), /* @__PURE__ */ React.createElement("span", null, form.is_active ? "Active on save" : "Inactive on save"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$4, { label: "Featured Since" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.featured_at, onChange: (nextValue) => setForm((current) => ({ ...current, featured_at: nextValue })), placeholder: "Featured since", clearable: true, className: "bg-[#08111d]" })), /* @__PURE__ */ React.createElement(Field$4, { label: "Expires" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.expires_at, onChange: (nextValue) => setForm((current) => ({ ...current, expires_at: nextValue })), placeholder: "Expiry date", clearable: true, className: "bg-[#08111d]" }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: busy === "submit" || !editingId && !selectedArtwork || duplicateSelection,
      className: "rounded-2xl bg-white px-5 py-3 text-sm font-semibold text-slate-950 transition hover:bg-slate-100 disabled:cursor-not-allowed disabled:opacity-60"
    },
    busy === "submit" ? "Saving…" : editingId ? "Save Changes" : "Create Featured Entry"
  ), editingId ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetEditor, className: "rounded-2xl border border-white/10 px-5 py-3 text-sm font-semibold text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, "Reset composer") : null)))))), /* @__PURE__ */ React.createElement("div", { className: "fixed inset-x-4 bottom-4 z-30 xl:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-3 rounded-[26px] border border-white/10 bg-[#08111d]/95 p-3 shadow-[0_24px_70px_rgba(2,6,23,0.42)] backdrop-blur-xl" }, /* @__PURE__ */ React.createElement(
    DockButton,
    {
      label: "Winner",
      detail: winner?.artwork?.title || "No live winner",
      tone: "sky",
      onClick: scrollToTop
    }
  ), /* @__PURE__ */ React.createElement(
    DockButton,
    {
      label: "Attention",
      detail: `${filterCounts.attention || 0} row${(filterCounts.attention || 0) === 1 ? "" : "s"}`,
      tone: "amber",
      onClick: () => {
        React.startTransition(() => setFilter("attention"));
        scrollToSection(rosterRef);
      }
    }
  ), /* @__PURE__ */ React.createElement(
    DockButton,
    {
      label: "Composer",
      detail: editingId ? `Editing #${editingId}` : "Add featured row",
      tone: "slate",
      onClick: () => scrollToSection(composerRef)
    }
  )))));
}
const __vite_glob_0_50 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: FeaturedArtworksAdmin
}, Symbol.toStringTag, { value: "Module" }));
function AdminFeaturedArtworks() {
  return /* @__PURE__ */ React.createElement(AdminLayout, null, /* @__PURE__ */ React.createElement(FeaturedArtworksAdmin, null));
}
const __vite_glob_0_30 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AdminFeaturedArtworks
}, Symbol.toStringTag, { value: "Module" }));
const HOMEPAGE_ANNOUNCEMENT_STORAGE_KEY = "skinbase:hidden_homepage_announcements";
const PRESETS = {
  nova_aurora: {
    shell: "border-cyan-300/15 bg-[radial-gradient(circle_at_top_left,rgba(34,211,238,0.26),transparent_30%),radial-gradient(circle_at_80%_20%,rgba(168,85,247,0.22),transparent_28%),linear-gradient(135deg,rgba(6,12,24,0.96),rgba(10,17,34,0.9))] text-white",
    glow: "from-cyan-400/25 via-fuchsia-400/10 to-transparent",
    badge: "border-cyan-200/20 bg-cyan-300/10 text-cyan-100",
    primary: "border-cyan-300/30 bg-cyan-300/15 text-cyan-50 hover:bg-cyan-300/22",
    secondary: "border-white/12 bg-white/[0.05] text-white/85 hover:bg-white/[0.1]",
    prose: "prose-invert prose-a:text-cyan-200 prose-strong:text-white"
  },
  deep_space: {
    shell: "border-indigo-300/15 bg-[radial-gradient(circle_at_top,rgba(59,130,246,0.18),transparent_34%),linear-gradient(145deg,rgba(5,10,20,0.98),rgba(11,18,36,0.94))] text-white",
    glow: "from-indigo-400/20 via-sky-400/12 to-transparent",
    badge: "border-indigo-200/20 bg-indigo-300/10 text-indigo-100",
    primary: "border-indigo-300/30 bg-indigo-300/15 text-indigo-50 hover:bg-indigo-300/22",
    secondary: "border-white/12 bg-white/[0.05] text-white/85 hover:bg-white/[0.1]",
    prose: "prose-invert prose-a:text-indigo-200 prose-strong:text-white"
  },
  sunrise: {
    shell: "border-amber-300/20 bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.28),transparent_28%),linear-gradient(145deg,rgba(44,15,18,0.95),rgba(17,9,24,0.96))] text-white",
    glow: "from-amber-300/25 via-rose-300/10 to-transparent",
    badge: "border-amber-100/20 bg-amber-300/15 text-amber-50",
    primary: "border-amber-300/35 bg-amber-300/18 text-amber-50 hover:bg-amber-300/24",
    secondary: "border-white/12 bg-white/[0.05] text-white/85 hover:bg-white/[0.1]",
    prose: "prose-invert prose-a:text-amber-100 prose-strong:text-white"
  },
  ocean_glow: {
    shell: "border-sky-300/15 bg-[radial-gradient(circle_at_top_right,rgba(56,189,248,0.24),transparent_28%),linear-gradient(135deg,rgba(3,20,38,0.98),rgba(8,27,45,0.92))] text-white",
    glow: "from-sky-400/24 via-emerald-300/10 to-transparent",
    badge: "border-sky-200/20 bg-sky-300/10 text-sky-100",
    primary: "border-sky-300/30 bg-sky-300/15 text-sky-50 hover:bg-sky-300/22",
    secondary: "border-white/12 bg-white/[0.05] text-white/85 hover:bg-white/[0.1]",
    prose: "prose-invert prose-a:text-sky-200 prose-strong:text-white"
  },
  spring_vibes: {
    shell: "border-emerald-300/18 bg-[radial-gradient(circle_at_top_left,rgba(74,222,128,0.2),transparent_28%),linear-gradient(145deg,rgba(8,24,22,0.98),rgba(14,28,38,0.92))] text-white",
    glow: "from-emerald-300/24 via-lime-200/8 to-transparent",
    badge: "border-emerald-200/20 bg-emerald-300/10 text-emerald-100",
    primary: "border-emerald-300/30 bg-emerald-300/15 text-emerald-50 hover:bg-emerald-300/22",
    secondary: "border-white/12 bg-white/[0.05] text-white/85 hover:bg-white/[0.1]",
    prose: "prose-invert prose-a:text-emerald-200 prose-strong:text-white"
  },
  fantasy_realms: {
    shell: "border-fuchsia-300/18 bg-[radial-gradient(circle_at_15%_10%,rgba(232,121,249,0.2),transparent_26%),linear-gradient(145deg,rgba(23,8,35,0.97),rgba(12,16,36,0.93))] text-white",
    glow: "from-fuchsia-300/24 via-violet-300/10 to-transparent",
    badge: "border-fuchsia-200/20 bg-fuchsia-300/10 text-fuchsia-100",
    primary: "border-fuchsia-300/30 bg-fuchsia-300/15 text-fuchsia-50 hover:bg-fuchsia-300/22",
    secondary: "border-white/12 bg-white/[0.05] text-white/85 hover:bg-white/[0.1]",
    prose: "prose-invert prose-a:text-fuchsia-200 prose-strong:text-white"
  },
  minimal_light: {
    shell: "border-slate-300/35 bg-[linear-gradient(140deg,rgba(255,255,255,0.96),rgba(240,247,255,0.92))] text-slate-900",
    glow: "from-sky-200/50 via-transparent to-transparent",
    badge: "border-slate-300/60 bg-white/70 text-slate-700",
    primary: "border-slate-900/10 bg-slate-900 text-white hover:bg-slate-800",
    secondary: "border-slate-300/60 bg-white text-slate-700 hover:bg-slate-50",
    prose: "prose prose-slate prose-a:text-sky-700 prose-strong:text-slate-900"
  },
  dark_glass: {
    shell: "border-white/12 bg-[linear-gradient(145deg,rgba(12,16,24,0.82),rgba(6,10,18,0.76))] text-white backdrop-blur-xl",
    glow: "from-white/10 via-white/0 to-transparent",
    badge: "border-white/12 bg-white/[0.06] text-white/90",
    primary: "border-white/18 bg-white/[0.09] text-white hover:bg-white/[0.14]",
    secondary: "border-white/12 bg-black/20 text-white/80 hover:bg-white/[0.08]",
    prose: "prose-invert prose-a:text-slate-200 prose-strong:text-white"
  }
};
function cx$9(...parts) {
  return parts.filter(Boolean).join(" ");
}
function readHiddenAnnouncements() {
  if (typeof window === "undefined") return {};
  try {
    const raw = window.localStorage.getItem(HOMEPAGE_ANNOUNCEMENT_STORAGE_KEY);
    const parsed = raw ? JSON.parse(raw) : {};
    return parsed && typeof parsed === "object" ? parsed : {};
  } catch {
    return {};
  }
}
function writeHiddenAnnouncements(payload) {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(HOMEPAGE_ANNOUNCEMENT_STORAGE_KEY, JSON.stringify(payload));
}
function HomepageAnnouncement({ announcement, mode = "live" }) {
  const [hidden, setHidden] = React.useState(false);
  const isLiveMode = mode === "live";
  const isPreviewMode = mode === "preview";
  React.useEffect(() => {
    if (!isLiveMode || !announcement?.id) {
      setHidden(false);
      return;
    }
    const hiddenAnnouncements = readHiddenAnnouncements();
    setHidden(Number(hiddenAnnouncements[String(announcement.id)] || 0) === Number(announcement.dismiss_version || 1));
  }, [announcement, isLiveMode]);
  if (!announcement) {
    return null;
  }
  const preset = PRESETS[announcement.gradient_preset] || PRESETS.nova_aurora;
  const overlayOpacity = Math.max(0, Math.min(100, Number(announcement.overlay_opacity ?? 55)));
  const dismiss = () => {
    if (!isLiveMode || !announcement?.id) return;
    const next = {
      ...readHiddenAnnouncements(),
      [String(announcement.id)]: Number(announcement.dismiss_version || 1)
    };
    writeHiddenAnnouncements(next);
    setHidden(true);
  };
  const restore = () => {
    if (!isLiveMode || !announcement?.id) return;
    const next = readHiddenAnnouncements();
    delete next[String(announcement.id)];
    writeHiddenAnnouncements(next);
    setHidden(false);
  };
  if (hidden && isLiveMode) {
    return /* @__PURE__ */ React.createElement("section", { className: "px-4 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: restore,
        className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-sm font-semibold text-white/90 transition hover:border-white/20 hover:bg-white/[0.1]"
      },
      /* @__PURE__ */ React.createElement("span", { "aria-hidden": "true" }, "✨"),
      /* @__PURE__ */ React.createElement("span", null, "Show Skinbase announcement")
    )));
  }
  return /* @__PURE__ */ React.createElement("section", { className: "px-4 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl" }, /* @__PURE__ */ React.createElement("div", { className: cx$9("relative overflow-hidden rounded-[2rem] border shadow-[0_28px_90px_rgba(0,0,0,0.35)]", preset.shell) }, announcement.background_image_url ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0" }, /* @__PURE__ */ React.createElement("img", { src: announcement.background_image_url, alt: "", className: "h-full w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-slate-950", style: { opacity: overlayOpacity / 100 } })) : null, /* @__PURE__ */ React.createElement("div", { className: cx$9("pointer-events-none absolute inset-0 bg-gradient-to-br", preset.glow) }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),transparent_22%,rgba(2,6,23,0.15)_100%)]" }), announcement.is_dismissible && isLiveMode ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: dismiss,
      className: "absolute right-5 top-5 z-10 inline-flex items-center gap-2 rounded-full border border-white/10 bg-black/30 px-3 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-white/70 transition hover:border-white/20 hover:bg-black/45 hover:text-white sm:right-6 sm:top-6 lg:right-8 lg:top-8",
      "aria-label": "Dismiss homepage announcement"
    },
    /* @__PURE__ */ React.createElement("svg", { "aria-hidden": "true", viewBox: "0 0 16 16", className: "h-3.5 w-3.5", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M3.5 3.5 12.5 12.5" }), /* @__PURE__ */ React.createElement("path", { d: "M12.5 3.5 3.5 12.5" })),
    "Dismiss"
  ) : null, /* @__PURE__ */ React.createElement("div", { className: cx$9(
    "relative px-6 py-7 sm:px-8 lg:px-10 lg:py-10",
    isPreviewMode ? "flex min-h-[42rem] flex-col gap-8" : "grid gap-8 lg:grid-cols-[minmax(0,1.25fr)_auto] lg:items-end"
  ) }, /* @__PURE__ */ React.createElement("div", { className: cx$9(isPreviewMode ? "w-full flex-1" : "max-w-3xl") }, announcement.badge_text ? /* @__PURE__ */ React.createElement("div", { className: cx$9("inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em]", preset.badge) }, announcement.badge_text) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] sm:text-4xl lg:text-[3.15rem]" }, announcement.title), announcement.subtitle ? /* @__PURE__ */ React.createElement("p", { className: cx$9("mt-3 text-base leading-7 text-current/80 sm:text-lg", isPreviewMode ? "w-full max-w-none" : "max-w-2xl") }, announcement.subtitle) : null, announcement.content_html ? /* @__PURE__ */ React.createElement(
    "div",
    {
      className: cx$9(
        "mt-5 text-sm leading-7 sm:text-base",
        "[&_p]:my-0 [&_p+p]:mt-6 [&_ul]:my-5 [&_ol]:my-5 [&_li+li]:mt-1.5 [&_blockquote]:my-5 [&_h2]:mb-3 [&_h2]:mt-7 [&_h3]:mb-2 [&_h3]:mt-6",
        preset.prose,
        isPreviewMode ? "w-full max-w-none" : "max-w-2xl"
      ),
      dangerouslySetInnerHTML: { __html: announcement.content_html }
    }
  ) : null), /* @__PURE__ */ React.createElement("div", { className: cx$9(
    isPreviewMode ? "mt-auto flex w-full flex-col gap-4 border-t border-white/10 pt-5" : "flex flex-col items-start gap-3 lg:items-end"
  ) }, /* @__PURE__ */ React.createElement("div", { className: cx$9("flex flex-wrap gap-3", isPreviewMode ? "w-full" : "lg:justify-end") }, announcement.primary_link ? /* @__PURE__ */ React.createElement("a", { href: announcement.primary_link.url, className: cx$9("inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition", isPreviewMode ? "min-w-[11rem]" : "", preset.primary) }, announcement.primary_link.label) : null, announcement.secondary_link ? /* @__PURE__ */ React.createElement("a", { href: announcement.secondary_link.url, className: cx$9("inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition", isPreviewMode ? "min-w-[11rem]" : "", preset.secondary) }, announcement.secondary_link.label) : null))))));
}
function ToolbarButton$1({ onClick, active, disabled, title, children }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick,
      disabled,
      title,
      className: [
        "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors",
        "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400",
        active ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200",
        disabled ? "pointer-events-none opacity-30" : ""
      ].join(" ")
    },
    children
  );
}
function Divider() {
  return /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-5 w-px bg-white/10" });
}
function Toolbar({ editor }) {
  if (!editor) return null;
  const addLink = reactExports.useCallback(() => {
    const previous2 = editor.getAttributes("link").href;
    const url = window.prompt("URL", previous2 ?? "https://");
    if (url === null) return;
    if (url === "") {
      editor.chain().focus().extendMarkRange("link").unsetLink().run();
      return;
    }
    editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
  }, [editor]);
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-0.5 border-b border-white/[0.06] px-2.5 py-2" }, /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold"), title: "Bold" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6zm0 8h9a4 4 0 014 4 4 4 0 01-4 4H6z" }))), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic"), title: "Italic" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: editor.isActive("heading", { level: 2 }), title: "Heading 2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H2")), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: editor.isActive("heading", { level: 3 }), title: "Heading 3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H3")), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList"), title: "Bullet list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "6", x2: "20", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "18", x2: "20", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "6", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "12", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "18", r: "1", fill: "currentColor" }))), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList"), title: "Numbered list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("text", { x: "3", y: "8", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "1"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "14", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "2"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "20", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "3"))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().toggleBlockquote().run(), active: editor.isActive("blockquote"), title: "Quote" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.24 11 15.14c0 .94-.36 1.84-1.001 2.503A3.34 3.34 0 017.559 18.6a3.77 3.77 0 01-2.976-.879zm10.4 0C13.953 16.227 13.4 15 13.4 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.986.169 3.395 1.729 3.395 3.629 0 .94-.36 1.84-1.001 2.503a3.34 3.34 0 01-2.44.957 3.77 3.77 0 01-2.976-.879z" }))), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: addLink, active: editor.isActive("link"), title: "Link" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" }))), /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-0.5" }, /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo(), title: "Undo" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "1 4 1 10 7 10" }), /* @__PURE__ */ React.createElement("path", { d: "M3.51 15a9 9 0 102.13-9.36L1 10" }))), /* @__PURE__ */ React.createElement(ToolbarButton$1, { onClick: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo(), title: "Redo" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "23 4 23 10 17 10" }), /* @__PURE__ */ React.createElement("path", { d: "M20.49 15a9 9 0 11-2.13-9.36L23 10" })))));
}
function HomepageAnnouncementEditor({
  content: content2 = "",
  onChange,
  placeholder = "Write the announcement message…",
  error,
  minHeight = 14
}) {
  const editor = useEditor({
    extensions: [
      index_default$2.configure({
        link: false,
        heading: { levels: [2, 3] },
        code: false,
        codeBlock: false,
        horizontalRule: false
      }),
      index_default$3.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: "text-sky-300 underline hover:text-sky-200",
          rel: "noopener noreferrer nofollow"
        }
      }),
      index_default$4.configure({ placeholder })
    ],
    immediatelyRender: false,
    content: content2,
    editorProps: {
      attributes: {
        class: [
          "prose prose-invert prose-sm max-w-none",
          "focus:outline-none",
          "px-4 py-3",
          "prose-headings:text-white prose-headings:font-bold",
          "prose-p:text-zinc-200 prose-p:leading-relaxed",
          "prose-a:text-sky-300 prose-a:no-underline hover:prose-a:text-sky-200",
          "prose-blockquote:border-l-sky-500/50 prose-blockquote:text-zinc-400",
          "prose-ul:text-zinc-200 prose-ol:text-zinc-200"
        ].join(" "),
        style: `min-height: ${minHeight}rem`
      }
    },
    onUpdate: ({ editor: currentEditor }) => {
      onChange?.(currentEditor.getHTML());
    }
  });
  reactExports.useEffect(() => {
    if (editor && content2 !== editor.getHTML()) {
      editor.commands.setContent(content2 || "", false);
      onChange?.(content2 || "");
    }
  }, [content2, editor, onChange]);
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1.5" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: [
        "overflow-hidden rounded-[28px] border bg-black/20 transition-colors",
        error ? "border-red-500/60 focus-within:border-red-500/70 focus-within:ring-2 focus-within:ring-red-500/30" : "border-white/12 hover:border-white/20 focus-within:border-sky-500/50 focus-within:ring-2 focus-within:ring-sky-500/20"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(Toolbar, { editor }),
    /* @__PURE__ */ React.createElement(EditorContent, { editor })
  ), error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error) : null);
}
const BACKGROUND_IMAGE_ACCEPT = "image/jpeg,image/jpg,image/png,image/webp";
const BACKGROUND_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
const FORM_TABS = [
  { id: "overview", label: "Overview", description: "Identity, status, and schedule." },
  { id: "content", label: "Content", description: "Message body and CTA links." },
  { id: "design", label: "Design", description: "Visual treatment and background media." },
  { id: "behavior", label: "Behavior", description: "Dismiss rules and placement." }
];
const FIELD_TAB_MAP = {
  title: "overview",
  badge_text: "overview",
  subtitle: "overview",
  type: "overview",
  status: "overview",
  priority: "overview",
  is_active: "overview",
  starts_at: "overview",
  ends_at: "overview",
  content_html: "content",
  primary_link_label: "content",
  primary_link_type: "content",
  primary_link_url: "content",
  primary_link_target_id: "content",
  secondary_link_label: "content",
  secondary_link_type: "content",
  secondary_link_url: "content",
  secondary_link_target_id: "content",
  gradient_preset: "design",
  theme_preset: "design",
  overlay_opacity: "design",
  background_image: "design",
  background_image_file: "design",
  remove_background_image: "design",
  dismiss_version: "behavior",
  placement: "behavior",
  is_dismissible: "behavior"
};
function isIntegerLike(value) {
  if (typeof value === "number") return Number.isInteger(value);
  if (typeof value !== "string") return false;
  const normalized = value.trim();
  return normalized !== "" && /^-?\d+$/.test(normalized);
}
function isSafeClientUrl(value) {
  const normalized = String(value || "").trim();
  if (!normalized) return true;
  return normalized.startsWith("/") || normalized.startsWith("https://");
}
function firstErrorMessage(errors) {
  const firstKey = Object.keys(errors || {})[0];
  if (!firstKey) return null;
  const value = errors[firstKey];
  return Array.isArray(value) ? value[0] : value;
}
function getCsrfToken$f() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function FieldError$1({ error }) {
  if (!error) return null;
  return /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, error);
}
function resolveTabFromErrors(errors) {
  const firstKey = Object.keys(errors || {})[0];
  return FIELD_TAB_MAP[firstKey] || "overview";
}
function Section$1({ title, description, children }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, description) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, children));
}
function TextField({ label, value, onChange, error, ...rest }) {
  return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("input", { value, onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", ...rest }), /* @__PURE__ */ React.createElement(FieldError$1, { error }));
}
function ToggleField({ label, checked, onChange, help }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, label), help ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-6 text-slate-400" }, help) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked, onChange, "aria-label": label, variant: "sky", size: 20 })));
}
function SelectField({ label, value, onChange, options, error }) {
  return /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label,
      value,
      onChange,
      options: options || [],
      error,
      searchable: false,
      className: "rounded-2xl bg-black/20"
    }
  );
}
function DateTimeField({ label, value, onChange, error }) {
  return /* @__PURE__ */ React.createElement(
    DateTimePicker,
    {
      label,
      value,
      onChange,
      error,
      clearable: true,
      className: "rounded-2xl bg-black/20"
    }
  );
}
function BackgroundImageDropzone({ previewUrl, storedValue, selectedFileName, error, onSelect }) {
  const inputRef = React.useRef(null);
  const [dragging, setDragging] = React.useState(false);
  const handleFile = React.useCallback((file) => {
    onSelect?.(file || null);
  }, [onSelect]);
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", null, "Upload background image"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => inputRef.current?.click(),
      className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]"
    },
    "Browse"
  )), /* @__PURE__ */ React.createElement(
    "div",
    {
      role: "button",
      tabIndex: 0,
      onClick: () => inputRef.current?.click(),
      onKeyDown: (event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          inputRef.current?.click();
        }
      },
      onDragOver: (event) => {
        event.preventDefault();
        setDragging(true);
      },
      onDragEnter: (event) => {
        event.preventDefault();
        setDragging(true);
      },
      onDragLeave: (event) => {
        event.preventDefault();
        setDragging(false);
      },
      onDrop: (event) => {
        event.preventDefault();
        setDragging(false);
        handleFile(event.dataTransfer?.files?.[0] || null);
      },
      className: [
        "rounded-[28px] border border-dashed px-5 py-5 transition outline-none",
        dragging ? "border-sky-300/50 bg-sky-400/12" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-cloud-arrow-up" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Drop image here or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, "JPG, PNG, or WEBP. Maximum 5 MB. The selected image is previewed here and on the card preview."), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "JPG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "PNG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "Max 5 MB")))), /* @__PURE__ */ React.createElement("div", { className: "h-28 w-full overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 lg:w-44" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "Background preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center px-4 text-center text-sm text-slate-500" }, "No background image selected"))),
    selectedFileName ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 truncate rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs text-slate-300" }, "Selected file: ", /* @__PURE__ */ React.createElement("span", { className: "text-white" }, selectedFileName)) : null,
    !selectedFileName && storedValue ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 truncate rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs text-slate-400" }, "Stored path: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, storedValue)) : null,
    error ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null,
    /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: inputRef,
        type: "file",
        accept: BACKGROUND_IMAGE_ACCEPT,
        className: "hidden",
        onChange: (event) => {
          handleFile(event.target.files?.[0] || null);
          event.target.value = "";
        }
      }
    )
  ));
}
function LinkFields({ title, prefix, form, options }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 rounded-[28px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold uppercase tracking-[0.18em] text-white/75" }, title), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField, { label: "Label", value: form.data[`${prefix}_link_label`], onChange: (event) => form.setData(`${prefix}_link_label`, event.target.value), error: form.errors[`${prefix}_link_label`], maxLength: 80 }), /* @__PURE__ */ React.createElement(SelectField, { label: "Link type", value: form.data[`${prefix}_link_type`], onChange: (nextValue) => form.setData(`${prefix}_link_type`, nextValue), options: options.linkTypes, error: form.errors[`${prefix}_link_type`] })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField, { label: "Fallback URL", value: form.data[`${prefix}_link_url`], onChange: (event) => form.setData(`${prefix}_link_url`, event.target.value), error: form.errors[`${prefix}_link_url`], placeholder: "/explore or https://example.com", maxLength: 2048 }), /* @__PURE__ */ React.createElement(TextField, { label: "Target ID", value: form.data[`${prefix}_link_target_id`], onChange: (event) => form.setData(`${prefix}_link_target_id`, event.target.value), error: form.errors[`${prefix}_link_target_id`], placeholder: "Optional entity id", inputMode: "numeric" })));
}
function HomepageAnnouncementForm({ announcement, previewAnnouncement, options, submitUrl, previewUrl, indexUrl, destroyUrl }) {
  const { props } = X$1();
  const isEditing = Boolean(announcement?.id);
  const flash = props.flash ?? {};
  const [activeTab, setActiveTab] = React.useState("overview");
  const [preview, setPreview] = React.useState(previewAnnouncement || null);
  const [previewBusy, setPreviewBusy] = React.useState(false);
  const [previewError, setPreviewError] = React.useState("");
  const [backgroundImageError, setBackgroundImageError] = React.useState("");
  const [backgroundPreviewUrl, setBackgroundPreviewUrl] = React.useState(announcement?.background_image_url || "");
  const [toast, setToast] = React.useState({ id: 0, visible: false, message: "", variant: "success" });
  const form = G$1({
    ...announcement,
    background_image_file: null
  });
  const showToast = React.useCallback((message, variant = "success") => {
    setToast({
      id: Date.now(),
      visible: true,
      message,
      variant
    });
  }, []);
  React.useEffect(() => {
    return () => {
      if (backgroundPreviewUrl?.startsWith?.("blob:")) {
        URL.revokeObjectURL(backgroundPreviewUrl);
      }
    };
  }, [backgroundPreviewUrl]);
  const previewWithLocalImage = React.useMemo(() => {
    if (!preview) return null;
    if (!backgroundPreviewUrl) return preview;
    return { ...preview, background_image_url: backgroundPreviewUrl };
  }, [backgroundPreviewUrl, preview]);
  const validateForm = React.useCallback((statusOverride = null) => {
    const data = { ...form.data, status: statusOverride || form.data.status };
    const errors = [];
    if (!String(data.title || "").trim()) {
      errors.push("Title is required.");
    }
    if (!String(data.type || "").trim()) {
      errors.push("Type is required.");
    }
    if (!String(data.status || "").trim()) {
      errors.push("Status is required.");
    }
    if (!String(data.placement || "").trim()) {
      errors.push("Placement is required.");
    }
    if (!isIntegerLike(data.priority)) {
      errors.push("Priority must be a whole number.");
    }
    if (!isIntegerLike(data.dismiss_version) || Number(data.dismiss_version) < 1) {
      errors.push("Dismiss version must be a whole number greater than or equal to 1.");
    }
    if (String(data.overlay_opacity || "").trim() !== "" && (!isIntegerLike(data.overlay_opacity) || Number(data.overlay_opacity) < 0 || Number(data.overlay_opacity) > 100)) {
      errors.push("Overlay opacity must be a whole number between 0 and 100.");
    }
    if (data.starts_at && Number.isNaN(Date.parse(data.starts_at))) {
      errors.push("Starts at must be a valid date and time.");
    }
    if (data.ends_at && Number.isNaN(Date.parse(data.ends_at))) {
      errors.push("Ends at must be a valid date and time.");
    }
    if (data.starts_at && data.ends_at && Date.parse(data.ends_at) < Date.parse(data.starts_at)) {
      errors.push("Ends at must be after or equal to starts at.");
    }
    for (const prefix of ["primary", "secondary"]) {
      const type2 = String(data[`${prefix}_link_type`] || "none");
      const label = String(data[`${prefix}_link_label`] || "").trim();
      const url = String(data[`${prefix}_link_url`] || "").trim();
      const targetId = data[`${prefix}_link_target_id`];
      if (type2 !== "none" && !label) {
        errors.push(`${prefix === "primary" ? "Primary" : "Secondary"} CTA label is required when that link is enabled.`);
      }
      if (url && !isSafeClientUrl(url)) {
        errors.push(`${prefix === "primary" ? "Primary" : "Secondary"} CTA URL must start with / or https://.`);
      }
      if (type2 === "custom_url" && !url) {
        errors.push(`${prefix === "primary" ? "Primary" : "Secondary"} custom CTA requires a URL.`);
      }
      if (!["none", "custom_url", "explore", "upload"].includes(type2) && !url) {
        if (String(targetId || "").trim() === "") {
          errors.push(`${prefix === "primary" ? "Primary" : "Secondary"} CTA requires a target id or fallback URL.`);
        } else if (!isIntegerLike(targetId) || Number(targetId) < 1) {
          errors.push(`${prefix === "primary" ? "Primary" : "Secondary"} target id must be a whole number greater than or equal to 1.`);
        }
      }
    }
    return errors;
  }, [form.data]);
  const applyBackgroundFile = React.useCallback((file) => {
    setBackgroundImageError("");
    if (!file) {
      form.setData("background_image_file", null);
      return;
    }
    const fileType = String(file.type || "").toLowerCase();
    const allowedTypes = ["image/jpeg", "image/jpg", "image/png", "image/webp"];
    if (!allowedTypes.includes(fileType)) {
      setBackgroundImageError("Use a JPG, PNG, or WEBP image for the announcement background.");
      return;
    }
    if (file.size > BACKGROUND_IMAGE_MAX_BYTES) {
      setBackgroundImageError("Background images must be 5 MB or smaller.");
      return;
    }
    form.setData("background_image_file", file);
    form.setData("remove_background_image", false);
    if (backgroundPreviewUrl?.startsWith?.("blob:")) {
      URL.revokeObjectURL(backgroundPreviewUrl);
    }
    setBackgroundPreviewUrl(URL.createObjectURL(file));
  }, [backgroundPreviewUrl, form]);
  const submit = (statusOverride = null) => {
    const validationErrors = validateForm(statusOverride);
    if (validationErrors.length > 0) {
      showToast(validationErrors[0], "error");
      return;
    }
    form.transform((data) => {
      const payload = { ...data, status: statusOverride || data.status };
      if (isEditing) payload._method = "patch";
      return payload;
    });
    form.post(submitUrl, {
      forceFormData: true,
      preserveScroll: true,
      onError: (errors) => {
        setActiveTab(resolveTabFromErrors(errors));
        const message = firstErrorMessage(errors) || "Please correct the form and try again.";
        showToast(message, "error");
      },
      onSuccess: () => {
        showToast(isEditing ? "Homepage announcement updated." : "Homepage announcement created.", "success");
      },
      onFinish: () => form.transform((data) => data)
    });
  };
  const runPreview = async () => {
    const validationErrors = validateForm();
    if (validationErrors.length > 0) {
      const message = validationErrors[0];
      setPreviewError(message);
      showToast(message, "error");
      return;
    }
    setPreviewBusy(true);
    setPreviewError("");
    try {
      const formData = new FormData();
      const payload = form.data;
      Object.entries(payload).forEach(([key, value]) => {
        if (value === null || value === void 0 || key === "id") return;
        if (value instanceof File) {
          formData.append(key, value);
          return;
        }
        formData.append(key, String(value));
      });
      const response = await fetch(previewUrl, {
        method: "POST",
        credentials: "same-origin",
        headers: {
          "X-CSRF-TOKEN": getCsrfToken$f(),
          "X-Requested-With": "XMLHttpRequest",
          Accept: "application/json"
        },
        body: formData
      });
      const body2 = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(body2?.message || "Preview failed.");
      }
      setPreview(body2.announcement || null);
    } catch (error) {
      const message = error.message || "Preview failed.";
      setPreviewError(message);
      showToast(message, "error");
    } finally {
      setPreviewBusy(false);
    }
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: isEditing ? "Edit Homepage Announcement" : "Create Homepage Announcement", subtitle: "Compose, schedule, preview, and publish a premium homepage announcement card." }, /* @__PURE__ */ React.createElement(Se$1, { title: isEditing ? "Admin · Edit Homepage Announcement" : "Admin · Create Homepage Announcement" }), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, /* @__PURE__ */ React.createElement("div", { className: "sticky top-4 z-30 mb-6 rounded-[28px] border border-white/10 bg-slate-950/85 px-4 py-4 shadow-[0_20px_60px_rgba(0,0,0,0.35)] backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("svg", { "aria-hidden": "true", viewBox: "0 0 16 16", className: "h-3.5 w-3.5", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10.5 3.5 6 8l4.5 4.5" })), "Back to announcements"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => submit("draft"), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Save draft"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => submit("published"), className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Publish"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => submit("archived"), className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-4 py-2 text-sm font-semibold text-amber-100" }, "Archive"), destroyUrl ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        if (!window.confirm("Delete this homepage announcement?")) return;
        form.delete(destroyUrl, { preserveScroll: true });
      },
      className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100"
    },
    "Delete"
  ) : null))), /* @__PURE__ */ React.createElement("div", { className: "grid items-start gap-6 xl:grid-cols-[minmax(0,1fr)_26rem] 2xl:grid-cols-[minmax(0,1fr)_28rem]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "sticky top-[6.75rem] z-20 rounded-[28px] border border-white/10 bg-slate-950/80 p-2 backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, FORM_TABS.map((tab2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: tab2.id,
      type: "button",
      onClick: () => setActiveTab(tab2.id),
      className: [
        "rounded-2xl px-4 py-3 text-sm font-semibold transition",
        activeTab === tab2.id ? "bg-sky-300/14 text-sky-100 ring-1 ring-sky-300/25" : "text-slate-300 hover:bg-white/[0.04] hover:text-white"
      ].join(" ")
    },
    tab2.label
  ))), /* @__PURE__ */ React.createElement("p", { className: "px-2 pt-3 text-sm text-slate-400" }, FORM_TABS.find((tab2) => tab2.id === activeTab)?.description)), activeTab === "overview" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Section$1, { title: "Basic", description: "Core identity, status, and visibility controls." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField, { label: "Title", value: form.data.title, onChange: (event) => form.setData("title", event.target.value), error: form.errors.title, maxLength: 180 }), /* @__PURE__ */ React.createElement(TextField, { label: "Badge text", value: form.data.badge_text, onChange: (event) => form.setData("badge_text", event.target.value), error: form.errors.badge_text, maxLength: 100 })), /* @__PURE__ */ React.createElement(TextField, { label: "Subtitle", value: form.data.subtitle, onChange: (event) => form.setData("subtitle", event.target.value), error: form.errors.subtitle, maxLength: 255 }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(SelectField, { label: "Type", value: form.data.type, onChange: (nextValue) => form.setData("type", nextValue), options: options.types, error: form.errors.type }), /* @__PURE__ */ React.createElement(SelectField, { label: "Status", value: form.data.status, onChange: (nextValue) => form.setData("status", nextValue), options: options.statuses, error: form.errors.status }), /* @__PURE__ */ React.createElement(TextField, { label: "Priority", value: form.data.priority, onChange: (event) => form.setData("priority", event.target.value), error: form.errors.priority, inputMode: "numeric" })), /* @__PURE__ */ React.createElement(ToggleField, { label: "Announcement is active", checked: Boolean(form.data.is_active), onChange: (event) => form.setData("is_active", event.target.checked), help: "Inactive announcements never surface even when published." })), /* @__PURE__ */ React.createElement(Section$1, { title: "Schedule", description: "Keep launch cards time-bound and predictable." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimeField, { label: "Starts at", value: form.data.starts_at, onChange: (nextValue) => form.setData("starts_at", nextValue), error: form.errors.starts_at }), /* @__PURE__ */ React.createElement(DateTimeField, { label: "Ends at", value: form.data.ends_at, onChange: (nextValue) => form.setData("ends_at", nextValue), error: form.errors.ends_at })))) : null, activeTab === "content" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Section$1, { title: "Content", description: "Only sanitized HTML is stored and rendered on the homepage." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Announcement message"), /* @__PURE__ */ React.createElement(
    HomepageAnnouncementEditor,
    {
      content: form.data.content_html || "",
      onChange: (nextValue) => form.setData("content_html", nextValue),
      placeholder: "Write the launch message with headings, lists, links, quotes, and highlighted copy.",
      error: form.errors.content_html,
      minHeight: 14
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-xs leading-6 text-slate-400" }, "Supported formatting matches the homepage sanitizer: paragraphs, bold, italic, links, lists, H2, H3, and blockquotes."))), /* @__PURE__ */ React.createElement(Section$1, { title: "Links", description: "Use entity targets when you know the id, or provide a fallback URL for a stable manual route." }, /* @__PURE__ */ React.createElement(LinkFields, { title: "Primary CTA", prefix: "primary", form, options }), /* @__PURE__ */ React.createElement(LinkFields, { title: "Secondary CTA", prefix: "secondary", form, options }))) : null, activeTab === "design" ? /* @__PURE__ */ React.createElement(Section$1, { title: "Design", description: "Choose a launch-ready gradient, optional background image, and glass intensity." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(SelectField, { label: "Gradient preset", value: form.data.gradient_preset, onChange: (nextValue) => form.setData("gradient_preset", nextValue), options: options.gradients, error: form.errors.gradient_preset }), /* @__PURE__ */ React.createElement(SelectField, { label: "Theme preset", value: form.data.theme_preset, onChange: (nextValue) => form.setData("theme_preset", nextValue), options: options.themes, error: form.errors.theme_preset })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField, { label: "Overlay opacity", value: form.data.overlay_opacity, onChange: (event) => form.setData("overlay_opacity", event.target.value), error: form.errors.overlay_opacity, inputMode: "numeric" }), /* @__PURE__ */ React.createElement("div", { className: "hidden md:block" })), /* @__PURE__ */ React.createElement(TextField, { label: "Background image path or URL", value: form.data.background_image, onChange: (event) => form.setData("background_image", event.target.value), error: form.errors.background_image, placeholder: "/storage/homepage-announcements/... or https://..." }), /* @__PURE__ */ React.createElement(
    BackgroundImageDropzone,
    {
      previewUrl: backgroundPreviewUrl,
      storedValue: form.data.background_image,
      selectedFileName: form.data.background_image_file?.name || "",
      error: backgroundImageError || form.errors.background_image_file,
      onSelect: applyBackgroundFile
    }
  ), /* @__PURE__ */ React.createElement(ToggleField, { label: "Remove stored background image", checked: Boolean(form.data.remove_background_image), onChange: (event) => {
    form.setData("remove_background_image", event.target.checked);
    if (event.target.checked) {
      setBackgroundImageError("");
      form.setData("background_image_file", null);
      if (backgroundPreviewUrl?.startsWith?.("blob:")) {
        URL.revokeObjectURL(backgroundPreviewUrl);
      }
      setBackgroundPreviewUrl("");
    }
  }, help: "Turn this on to clear the saved background image on the next save." })) : null, activeTab === "behavior" ? /* @__PURE__ */ React.createElement(Section$1, { title: "Behavior", description: "Dismiss controls let you force a fresh surface when the message materially changes." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField, { label: "Dismiss version", value: form.data.dismiss_version, onChange: (event) => form.setData("dismiss_version", event.target.value), error: form.errors.dismiss_version, inputMode: "numeric" }), /* @__PURE__ */ React.createElement(SelectField, { label: "Placement", value: form.data.placement, onChange: (nextValue) => form.setData("placement", nextValue), options: options.placements, error: form.errors.placement })), /* @__PURE__ */ React.createElement(ToggleField, { label: "Users can dismiss this card", checked: Boolean(form.data.is_dismissible), onChange: (event) => form.setData("is_dismissible", event.target.checked), help: "When disabled, the card remains visible and no restore pill is shown." })) : null), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6 xl:sticky xl:top-[7.5rem] xl:self-start" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Section$1, { title: "Preview", description: "Refresh the preview to render the sanitized content and resolved CTA payload exactly as the homepage card sees it." }, /* @__PURE__ */ React.createElement("div", { className: "-mx-6 -mt-6 mb-5 border-b border-white/10 bg-slate-950/92 px-6 py-4 backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: runPreview, disabled: previewBusy, className: "rounded-full border border-sky-300/20 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:bg-sky-300/18 disabled:opacity-60" }, previewBusy ? "Refreshing preview…" : "Refresh preview"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => submit(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Save changes")), previewError ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-rose-300" }, previewError) : null), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/10 bg-black/20 py-2" }, /* @__PURE__ */ React.createElement(HomepageAnnouncement, { announcement: previewWithLocalImage, mode: "preview" })))))));
}
const __vite_glob_0_31 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: HomepageAnnouncementForm
}, Symbol.toStringTag, { value: "Module" }));
function formatDateRange(startsAt, endsAt) {
  const formatter = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
  const start = startsAt ? formatter.format(new Date(startsAt)) : "Now";
  const end = endsAt ? formatter.format(new Date(endsAt)) : "Open ended";
  return `${start} → ${end}`;
}
function StatusBadge$1({ status: status2, active }) {
  const tone = status2 === "published" ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : status2 === "archived" ? "border-amber-300/20 bg-amber-300/10 text-amber-100" : "border-slate-300/15 bg-slate-300/10 text-slate-200";
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-2 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${tone}` }, /* @__PURE__ */ React.createElement("span", { className: `h-2 w-2 rounded-full ${active ? "bg-emerald-300" : "bg-slate-500"}` }), status2);
}
function HomepageAnnouncementsIndex({ announcements, createUrl }) {
  const { props } = X$1();
  const flash = props.flash ?? {};
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Homepage Announcements", subtitle: "Schedule launch cards, homepage notices, and editorial announcements below the featured artwork hero." }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Homepage Announcements" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl text-sm leading-6 text-slate-400" }, "Only the highest-priority published announcement that is active and inside its visibility window appears on the homepage."), /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "rounded-full border border-sky-300/20 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-300/18" }, "Create announcement")), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, (announcements?.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] px-6 py-10 text-center text-slate-400" }, "No homepage announcements exist yet.") : announcements.data.map((announcement) => /* @__PURE__ */ React.createElement("article", { key: announcement.id, className: "overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 border-b border-white/8 px-6 py-6 lg:grid-cols-[minmax(0,1.2fr)_auto] lg:items-start" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(StatusBadge$1, { status: announcement.status, active: announcement.is_active }), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white/70" }, announcement.type), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white/70" }, "Priority ", announcement.priority), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white/70" }, "Dismiss v", announcement.dismiss_version)), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-2xl font-semibold tracking-[-0.04em] text-white" }, announcement.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, formatDateRange(announcement.starts_at, announcement.ends_at)), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, announcement.placement.replaceAll("_", " "))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement(xe, { href: announcement.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Edit"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        if (!window.confirm("Delete this homepage announcement?")) return;
        At.delete(announcement.destroy_url, { preserveScroll: true });
      },
      className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100 transition hover:bg-rose-300/16"
    },
    "Delete"
  ))), /* @__PURE__ */ React.createElement("div", { className: "bg-black/10 py-2" }, /* @__PURE__ */ React.createElement(HomepageAnnouncement, { announcement: announcement.preview, mode: "preview" }))))), announcements?.last_page > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", announcements.from, "–", announcements.to, " of ", announcements.total, " announcements"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, announcements.links.map((link2, index2) => link2.url ? /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${link2.label}-${index2}`,
      type: "button",
      onClick: () => At.get(link2.url, {}, { preserveScroll: true }),
      className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-sky-300/15 text-sky-100" : "bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-white"}`,
      dangerouslySetInnerHTML: { __html: link2.label }
    }
  ) : /* @__PURE__ */ React.createElement("span", { key: `${link2.label}-${index2}`, className: "rounded-lg px-3 py-1.5 text-xs text-slate-600", dangerouslySetInnerHTML: { __html: link2.label } })))) : null);
}
const __vite_glob_0_32 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: HomepageAnnouncementsIndex
}, Symbol.toStringTag, { value: "Module" }));
const SETTING_GROUPS = [
  {
    label: "Platform",
    items: [
      { key: "site_name", label: "Site Name", type: "text", description: "The public name of the platform" },
      { key: "site_description", label: "Site Description", type: "textarea", description: "Short tagline shown in meta tags" },
      { key: "maintenance_mode", label: "Maintenance Mode", type: "toggle", description: "Put the site into maintenance mode" }
    ]
  },
  {
    label: "Registration",
    items: [
      { key: "registration_open", label: "Open Registration", type: "toggle", description: "Allow new users to register" },
      { key: "require_invite", label: "Require Invite", type: "toggle", description: "New users must have an invite code" }
    ]
  }
];
function AdminSettings({ settings = {} }) {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Settings", subtitle: "Platform-wide configuration" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Settings" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-8 max-w-2xl" }, SETTING_GROUPS.map((group) => /* @__PURE__ */ React.createElement("div", { key: group.label, className: "rounded-2xl border border-white/[0.07] bg-white/[0.02] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "mb-5 text-sm font-bold uppercase tracking-wider text-slate-500" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, group.items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "flex items-start justify-between gap-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-500" }, item.description)), item.type === "toggle" ? /* @__PURE__ */ React.createElement("div", { className: "flex h-6 w-11 flex-shrink-0 cursor-not-allowed items-center rounded-full border border-white/10 bg-white/[0.06] px-1 opacity-60" }, /* @__PURE__ */ React.createElement("span", { className: "h-4 w-4 rounded-full bg-slate-600" })) : item.type === "textarea" ? /* @__PURE__ */ React.createElement(
    "textarea",
    {
      defaultValue: settings[item.key] ?? "",
      rows: 2,
      readOnly: true,
      className: "w-64 cursor-not-allowed resize-none rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white/60"
    }
  ) : /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      defaultValue: settings[item.key] ?? "",
      readOnly: true,
      className: "w-64 cursor-not-allowed rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white/60"
    }
  )))))), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-600" }, "Full settings management via config files and environment variables.")));
}
const __vite_glob_0_33 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AdminSettings
}, Symbol.toStringTag, { value: "Module" }));
function AdminStories({ stories }) {
  const items = stories?.data ?? [];
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Stories", subtitle: "Review all stories submitted by creators" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Stories" }), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-wider text-slate-600" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Title"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Author"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Published"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.04]" }, items.length === 0 && /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 5, className: "px-5 py-12 text-center text-slate-500" }, "No stories found.")), items.map((story) => /* @__PURE__ */ React.createElement("tr", { key: story.id, className: "transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 font-medium text-white" }, story.title || /* @__PURE__ */ React.createElement("span", { className: "italic text-slate-500" }, "Untitled")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-400" }, story.creator?.name ?? "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${story.status === "published" ? "bg-teal-500/20 text-teal-300" : story.status === "pending_review" ? "bg-amber-500/20 text-amber-300" : "bg-slate-500/20 text-slate-400"}` }, story.status?.replace("_", " ") ?? "draft")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-500" }, story.published_at ? new Date(story.published_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/studio/stories/${story.id}/edit`,
      className: "rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.09]"
    },
    "Edit"
  ))))))), stories?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", stories.from, "–", stories.to, " of ", stories.total, " stories"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, stories.links.map((link2, i) => link2.url ? /* @__PURE__ */ React.createElement(
    "button",
    {
      key: i,
      type: "button",
      onClick: () => At.get(link2.url, {}, { preserveScroll: true }),
      className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`,
      dangerouslySetInnerHTML: { __html: link2.label }
    }
  ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } }))))));
}
const __vite_glob_0_34 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AdminStories
}, Symbol.toStringTag, { value: "Module" }));
function AdminUploadQueue() {
  const [items, setItems] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [error, setError] = reactExports.useState("");
  const [notes, setNotes] = reactExports.useState({});
  const loadPending = async () => {
    setLoading(true);
    setError("");
    try {
      const response = await window.axios.get("/api/admin/uploads/pending");
      setItems(Array.isArray(response?.data?.data) ? response.data.data : []);
    } catch (loadError) {
      setError(loadError?.response?.data?.message || "Failed to load moderation queue.");
    } finally {
      setLoading(false);
    }
  };
  reactExports.useEffect(() => {
    loadPending();
  }, []);
  const moderate = async (id, action) => {
    try {
      const payload = { note: String(notes[id] || "") };
      await window.axios.post(`/api/admin/uploads/${id}/${action}`, payload);
      setItems((prev) => prev.filter((item) => item.id !== id));
    } catch (moderateError) {
      setError(moderateError?.response?.data?.message || `Failed to ${action} upload.`);
    }
  };
  return /* @__PURE__ */ React.createElement("section", { "aria-label": "Moderation queue", className: "mx-auto w-full max-w-5xl rounded-2xl border border-white/10 bg-slate-900/60 p-4 md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Pending Upload Moderation"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: loadPending, className: "rounded-lg border border-white/20 px-3 py-1 text-xs text-white" }, "Refresh")), loading ? /* @__PURE__ */ React.createElement("p", { role: "status", className: "text-sm text-white/70" }, "Loading…") : null, error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "mb-3 text-sm text-rose-200" }, error) : null, !loading && items.length === 0 ? /* @__PURE__ */ React.createElement("p", { role: "status", className: "text-sm text-white/60" }, "No pending uploads.") : null, /* @__PURE__ */ React.createElement("ul", { className: "space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("li", { key: item.id, "aria-label": `Pending upload ${item.id}`, className: "rounded-xl border border-white/10 bg-white/5 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-medium text-white" }, item.title || "(untitled upload)"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-white/65" }, item.type, " · ", item.id), item.preview_path ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-white/55" }, "Preview: ", item.preview_path) : null), /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-sm space-y-2" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      "aria-label": `Moderation note for ${item.id}`,
      value: notes[item.id] || "",
      onChange: (event) => setNotes((prev) => ({ ...prev, [item.id]: event.target.value })),
      placeholder: "Moderation note",
      className: "w-full rounded-lg border border-white/15 bg-white/10 px-3 py-2 text-xs text-white"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": `Approve upload ${item.id}`,
      onClick: () => moderate(item.id, "approve"),
      className: "rounded-lg bg-emerald-500 px-3 py-2 text-xs font-semibold text-black"
    },
    "Approve"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": `Reject upload ${item.id}`,
      onClick: () => moderate(item.id, "reject"),
      className: "rounded-lg bg-rose-500 px-3 py-2 text-xs font-semibold text-white"
    },
    "Reject"
  ))))))));
}
function UploadQueuePage() {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Upload Queue", subtitle: "Review and moderate pending artwork submissions" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Upload Queue" }), /* @__PURE__ */ React.createElement(AdminUploadQueue, null));
}
const __vite_glob_0_35 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: UploadQueuePage
}, Symbol.toStringTag, { value: "Module" }));
function AdminUsernameQueue() {
  const [items, setItems] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [error, setError] = reactExports.useState("");
  const [notes, setNotes] = reactExports.useState({});
  const loadPending = async () => {
    setLoading(true);
    setError("");
    try {
      const response = await window.axios.get("/api/admin/usernames/pending");
      setItems(Array.isArray(response?.data?.data) ? response.data.data : []);
    } catch (loadError) {
      setError(loadError?.response?.data?.message || "Failed to load username moderation queue.");
    } finally {
      setLoading(false);
    }
  };
  reactExports.useEffect(() => {
    loadPending();
  }, []);
  const moderate = async (id, action) => {
    try {
      const payload = { note: String(notes[id] || "") };
      await window.axios.post(`/api/admin/usernames/${id}/${action}`, payload);
      setItems((prev) => prev.filter((item) => item.id !== id));
    } catch (moderateError) {
      setError(moderateError?.response?.data?.message || `Failed to ${action} username request.`);
    }
  };
  return /* @__PURE__ */ React.createElement("section", { "aria-label": "Username moderation queue", className: "mx-auto w-full max-w-5xl rounded-2xl border border-white/10 bg-slate-900/60 p-4 md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Pending Username Approvals"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: loadPending, className: "rounded-lg border border-white/20 px-3 py-1 text-xs text-white" }, "Refresh")), loading ? /* @__PURE__ */ React.createElement("p", { role: "status", className: "text-sm text-white/70" }, "Loading…") : null, error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "mb-3 text-sm text-rose-200" }, error) : null, !loading && items.length === 0 ? /* @__PURE__ */ React.createElement("p", { role: "status", className: "text-sm text-white/60" }, "No pending username requests.") : null, /* @__PURE__ */ React.createElement("ul", { className: "space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("li", { key: item.id, className: "rounded-xl border border-white/10 bg-white/5 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-medium text-white" }, item.requested_username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-white/65" }, "Request #", item.id, " · ", item.context), item.similar_to ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-amber-200" }, "Similar to reserved: ", item.similar_to) : null), /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-sm space-y-2" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      "aria-label": `Moderation note for request ${item.id}`,
      value: notes[item.id] || "",
      onChange: (event) => setNotes((prev) => ({ ...prev, [item.id]: event.target.value })),
      placeholder: "Review note",
      className: "w-full rounded-lg border border-white/15 bg-white/10 px-3 py-2 text-xs text-white"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => moderate(item.id, "approve"),
      className: "rounded-lg bg-emerald-500 px-3 py-2 text-xs font-semibold text-black"
    },
    "Approve"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => moderate(item.id, "reject"),
      className: "rounded-lg bg-rose-500 px-3 py-2 text-xs font-semibold text-white"
    },
    "Reject"
  ))))))));
}
function UsernameQueuePage() {
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Username Queue", subtitle: "Review and approve pending username change requests" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Username Queue" }), /* @__PURE__ */ React.createElement(AdminUsernameQueue, null));
}
const __vite_glob_0_36 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: UsernameQueuePage
}, Symbol.toStringTag, { value: "Module" }));
const ROLE_BADGE = {
  user: "bg-slate-500/20 text-slate-300",
  creator: "bg-sky-500/20 text-sky-300",
  moderator: "bg-violet-500/20 text-violet-300",
  editorial: "bg-teal-500/20 text-teal-300",
  manager: "bg-amber-500/20 text-amber-300",
  admin: "bg-rose-500/20 text-rose-300"
};
function RoleBadge({ role }) {
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${ROLE_BADGE[role] ?? "bg-slate-500/20 text-slate-300"}` }, role);
}
function RoleDropdown({ user, roles, currentUserIsAdmin }) {
  const [open, setOpen] = reactExports.useState(false);
  const [pending, setPending] = reactExports.useState(false);
  const handleSelect = (newRole) => {
    if (newRole === user.role) {
      setOpen(false);
      return;
    }
    setPending(true);
    At.patch(`/admin/users/${user.id}/role`, { role: newRole }, {
      preserveScroll: true,
      onFinish: () => {
        setPending(false);
        setOpen(false);
      }
    });
  };
  const availableRoles = currentUserIsAdmin ? roles : roles.filter((r) => r.value !== "admin");
  return /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setOpen(!open),
      disabled: pending,
      className: "flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.09] disabled:opacity-50"
    },
    pending ? /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner animate-spin" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square" }),
    "Change role"
  ), open && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-10", onClick: () => setOpen(false) }), /* @__PURE__ */ React.createElement("div", { className: "absolute right-0 z-20 mt-1 w-44 rounded-xl border border-white/10 bg-[rgba(12,16,26,0.98)] shadow-2xl backdrop-blur-xl" }, availableRoles.map((r) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: r.value,
      type: "button",
      onClick: () => handleSelect(r.value),
      className: `flex w-full items-center gap-2.5 px-3 py-2.5 text-left text-sm transition hover:bg-white/[0.06] first:rounded-t-xl last:rounded-b-xl ${r.value === user.role ? "text-white/90" : "text-white/60"}`
    },
    /* @__PURE__ */ React.createElement("span", { className: `h-2 w-2 rounded-full ${r.value === user.role ? "bg-rose-400" : "bg-white/20"}` }),
    r.label,
    r.value === user.role && /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check ml-auto text-xs text-rose-400" })
  )))));
}
function UsersIndex({ users, filters, roles }) {
  const { props } = X$1();
  const currentUserIsAdmin = Boolean(props.auth?.user?.is_admin);
  const flash = props.flash ?? {};
  const handleSearch = (e) => {
    e.preventDefault();
    const search2 = e.target.elements.search.value;
    At.get("/moderation/users", { search: search2, role: filters.role }, { preserveState: true });
  };
  const handleRoleFilter = (role) => {
    At.get("/moderation/users", { search: filters.search, role }, { preserveState: true });
  };
  return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Users", subtitle: "Search, view and manage user roles" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Admin · Users" }), flash.success && /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-xl border border-teal-500/20 bg-teal-500/10 px-4 py-3 text-sm text-teal-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-check mr-2" }), flash.success), flash.error && /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-xl border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-exclamation mr-2" }), flash.error), /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSearch, className: "flex flex-1 items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "relative flex-1 max-w-sm" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass absolute left-3.5 top-1/2 -translate-y-1/2 text-xs text-slate-500" }), /* @__PURE__ */ React.createElement(
    "input",
    {
      name: "search",
      defaultValue: filters.search,
      placeholder: "Search name, username or email…",
      className: "w-full rounded-xl border border-white/10 bg-white/[0.04] py-2.5 pl-9 pr-4 text-sm text-white placeholder:text-slate-600 focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10"
    }
  )), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-xl bg-rose-500/80 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-rose-500" }, "Search")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, [{ value: "all", label: "All" }, ...roles].map((r) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: r.value,
      type: "button",
      onClick: () => handleRoleFilter(r.value === "all" ? "" : r.value),
      className: `rounded-full px-3 py-1 text-xs font-semibold transition ${filters.role === r.value || r.value === "all" && !filters.role ? "bg-rose-500/20 text-rose-300" : "bg-white/[0.05] text-slate-400 hover:bg-white/[0.09]"}`
    },
    r.label
  )))), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-wider text-slate-600" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "User"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Email"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Role"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Joined"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.04]" }, users.data.length === 0 && /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 5, className: "px-5 py-12 text-center text-slate-500" }, "No users found.")), users.data.map((user) => /* @__PURE__ */ React.createElement("tr", { key: user.id, className: "group transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-slate-700 text-xs font-bold text-white uppercase" }, user.name?.[0] ?? "?"), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-medium text-white" }, user.name), user.username && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "@", user.username)))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-400" }, user.email), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement(RoleBadge, { role: user.role ?? "user" })), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-500" }, new Date(user.created_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement(RoleDropdown, { user, roles, currentUserIsAdmin }))))))), users.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", users.from, "–", users.to, " of ", users.total, " users"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, users.links.map((link2, i) => link2.url ? /* @__PURE__ */ React.createElement(
    "button",
    {
      key: i,
      type: "button",
      onClick: () => At.get(link2.url, {}, { preserveScroll: true }),
      className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`,
      dangerouslySetInnerHTML: { __html: link2.label }
    }
  ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } }))))));
}
const __vite_glob_0_37 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: UsersIndex
}, Symbol.toStringTag, { value: "Module" }));
function SimilarArtworksHeader({ artwork }) {
  if (!artwork) return null;
  const title = artwork.title || "Artwork";
  const artworkUrl = artwork.url || "#";
  const authorName = artwork.author_name || "Artist";
  const authorHref = artwork.author_profile_url || (artwork.author_username ? `/@${artwork.author_username}` : null);
  const browseHref = artwork.browse_url || (artwork.content_type_slug ? `/${artwork.content_type_slug}` : "/explore");
  const thumbUrl = artwork.thumb_lg || artwork.thumb_md || null;
  const thumbSrcSet = artwork.thumb_srcset || void 0;
  const tags = Array.isArray(artwork.tag_slugs) ? artwork.tag_slugs.filter(Boolean) : [];
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[34px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_28%),linear-gradient(145deg,rgba(8,17,29,0.96),rgba(11,20,34,0.94))] shadow-[0_28px_80px_rgba(2,6,23,0.34)]" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(249,115,22,0.12),transparent_24%),radial-gradient(circle_at_bottom_left,rgba(59,130,246,0.12),transparent_30%)]" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-6 p-5 md:p-7 xl:grid-cols-[280px_minmax(0,1fr)] xl:items-center" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artworkUrl,
      className: "group relative overflow-hidden rounded-[28px] border border-white/10 bg-[#08111d] shadow-[0_18px_40px_rgba(2,6,23,0.28)]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "aspect-[5/4] overflow-hidden" }, thumbUrl ? /* @__PURE__ */ React.createElement(
      "img",
      {
        src: thumbUrl,
        srcSet: thumbSrcSet,
        sizes: "(min-width: 1280px) 280px, (min-width: 768px) 40vw, 100vw",
        alt: title,
        className: "h-full w-full object-cover transition-transform duration-700 group-hover:scale-[1.03]"
      }
    ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center bg-white/[0.04] text-sm text-slate-500" }, "Preview unavailable")),
    /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-slate-950/55 via-transparent to-transparent" })
  ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200" }, /* @__PURE__ */ React.createElement("span", { className: "h-2 w-2 rounded-full bg-sky-300 shadow-[0_0_12px_rgba(125,211,252,0.85)]" }), "Visual discovery"), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 max-w-4xl text-3xl font-semibold leading-tight tracking-[-0.04em] text-white md:text-4xl xl:text-5xl" }, "Artworks similar to", " ", /* @__PURE__ */ React.createElement("a", { href: artworkUrl, className: "underline decoration-white/15 underline-offset-4 transition hover:decoration-sky-300" }, title)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-slate-300" }, "Browse visually related artworks, compare style cues, and jump back into the original piece whenever you need context."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2.5 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-1.5" }, artwork.author_avatar ? /* @__PURE__ */ React.createElement(
    "img",
    {
      src: artwork.author_avatar,
      alt: authorName,
      className: "h-5 w-5 rounded-full object-cover ring-1 ring-white/15"
    }
  ) : null, authorHref ? /* @__PURE__ */ React.createElement("a", { href: authorHref, className: "font-medium text-white/85 transition hover:text-white" }, authorName) : /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white/85" }, authorName)), artwork.category_name ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-medium text-slate-300" }, artwork.category_name) : null, artwork.content_type_name ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1.5 text-xs font-medium text-amber-100" }, artwork.content_type_name) : null), tags.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, tags.map((tagSlug) => /* @__PURE__ */ React.createElement(
    "span",
    {
      key: tagSlug,
      className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-xs font-medium text-slate-300 transition hover:border-sky-300/30 hover:bg-sky-400/10 hover:text-white"
    },
    "#",
    tagSlug
  ))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artworkUrl,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.06] px-4 py-2.5 text-sm font-semibold text-white/85 transition hover:bg-white/[0.1] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: "2", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M10 19l-7-7m0 0l7-7m-7 7h18" })),
    "Back to artwork"
  ), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: browseHref,
      className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 hover:text-white"
    },
    "Browse ",
    artwork.content_type_name || "artworks"
  )))));
}
const __vite_glob_0_38 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: SimilarArtworksHeader
}, Symbol.toStringTag, { value: "Module" }));
const FALLBACK_MD = "https://files.skinbase.org/default/missing_md.webp";
const FALLBACK_LG = "https://files.skinbase.org/default/missing_lg.webp";
function ArtworkHero({ artwork, presentMd, presentLg, presentXl, mediaWidth = null, mediaHeight = null, mediaKey = "cover", onOpenViewer, hasPrev, hasNext, onPrev, onNext }) {
  const [isLoaded, setIsLoaded] = reactExports.useState(false);
  const [mainImageMode, setMainImageMode] = reactExports.useState("primary");
  const [previewImageMode, setPreviewImageMode] = reactExports.useState("primary");
  const [showBackdrop, setShowBackdrop] = reactExports.useState(true);
  const mdSource = presentMd?.url || artwork?.thumbs?.md?.url || null;
  const lgSource = presentLg?.url || artwork?.thumbs?.lg?.url || null;
  const xlSource = presentXl?.url || artwork?.thumbs?.xl?.url || null;
  const hasRealArtworkImage = Boolean(mdSource || lgSource || xlSource);
  const blurBackdropSrc = mdSource || lgSource || xlSource || null;
  const primaryMainSrc = lgSource || xlSource || mdSource || FALLBACK_LG;
  const primaryPreviewSrc = mdSource || lgSource || xlSource || FALLBACK_MD;
  const srcSet = [
    mdSource ? `${mdSource} 640w` : null,
    lgSource ? `${lgSource} 1280w` : null,
    xlSource ? `${xlSource} 1920w` : null
  ].filter(Boolean).join(", ");
  const resolvedMainSrc = mainImageMode === "fallback" ? FALLBACK_LG : mainImageMode === "hidden" ? null : primaryMainSrc;
  const resolvedPreviewSrc = previewImageMode === "fallback" ? FALLBACK_MD : previewImageMode === "hidden" ? null : primaryPreviewSrc;
  const dbWidth = Number(mediaWidth ?? artwork?.width);
  const dbHeight = Number(mediaHeight ?? artwork?.height);
  const hasDbDims = dbWidth > 0 && dbHeight > 0;
  const [naturalDims, setNaturalDims] = reactExports.useState(
    hasDbDims ? { w: dbWidth, h: dbHeight } : null
  );
  reactExports.useEffect(() => {
    setIsLoaded(false);
    setMainImageMode("primary");
    setPreviewImageMode("primary");
    setShowBackdrop(true);
    if (hasDbDims) {
      setNaturalDims({ w: dbWidth, h: dbHeight });
      return;
    }
    setNaturalDims(null);
  }, [mediaKey, hasDbDims, dbWidth, dbHeight]);
  reactExports.useEffect(() => {
    if (naturalDims || !xlSource) return;
    const img = new Image();
    img.onload = () => {
      if (img.naturalWidth > 0 && img.naturalHeight > 0) {
        setNaturalDims({ w: img.naturalWidth, h: img.naturalHeight });
      }
    };
    img.onerror = null;
    img.src = xlSource;
  }, [xlSource, naturalDims]);
  const aspectRatio = naturalDims ? `${naturalDims.w} / ${naturalDims.h}` : "16 / 9";
  return /* @__PURE__ */ React.createElement("figure", { className: "relative w-full overflow-hidden rounded-[2rem] border border-white/10 bg-gradient-to-b from-nova-950 via-nova-900 to-nova-900 p-2 shadow-[0_35px_90px_-35px_rgba(15,23,36,0.9)] sm:p-4" }, blurBackdropSrc && showBackdrop && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: blurBackdropSrc,
      alt: "",
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-0 h-full w-full scale-110 object-cover opacity-30 blur-3xl",
      loading: "eager",
      decoding: "async",
      fetchPriority: "high",
      onError: (event) => {
        event.currentTarget.onerror = null;
        setShowBackdrop(false);
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-b from-nova-950/55 via-nova-900/40 to-nova-950/70" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 backdrop-blur-sm" })), /* @__PURE__ */ React.createElement("div", { className: "relative mx-auto flex w-full max-w-[1400px] items-center gap-2 sm:gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "hidden w-12 shrink-0 justify-center sm:flex" }, hasPrev && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Previous artwork",
      onClick: () => onPrev?.(),
      className: "flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white/70 ring-1 ring-white/15 shadow-lg transition-colors duration-150 hover:bg-white/20 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-accent"
    },
    /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2.5 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 19l-7-7 7-7" }))
  )), /* @__PURE__ */ React.createElement("div", { className: "relative min-w-0 flex-1" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: `relative mx-auto w-full max-h-[70vh] overflow-hidden transition-[max-width] duration-300 ${onOpenViewer ? "cursor-zoom-in" : ""}`,
      style: { aspectRatio, maxWidth: naturalDims ? `${naturalDims.w}px` : void 0 },
      onClick: onOpenViewer,
      role: onOpenViewer ? "button" : void 0,
      "aria-label": onOpenViewer ? "Open artwork lightbox" : void 0,
      tabIndex: onOpenViewer ? 0 : void 0,
      onKeyDown: onOpenViewer ? (e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          onOpenViewer();
        }
      } : void 0
    },
    resolvedPreviewSrc ? /* @__PURE__ */ React.createElement(
      "img",
      {
        src: resolvedPreviewSrc,
        alt: artwork?.title ?? "Artwork",
        className: "absolute inset-0 h-full w-full object-contain rounded-xl",
        loading: "eager",
        decoding: "async",
        fetchPriority: "high",
        onError: (event) => {
          event.currentTarget.onerror = null;
          if (previewImageMode === "primary") {
            setPreviewImageMode("fallback");
            return;
          }
          setPreviewImageMode("hidden");
        }
      }
    ) : null,
    resolvedMainSrc ? /* @__PURE__ */ React.createElement(
      "img",
      {
        src: resolvedMainSrc,
        srcSet: mainImageMode === "primary" && srcSet !== "" ? srcSet : void 0,
        sizes: mainImageMode === "primary" && srcSet !== "" ? "(min-width: 1536px) 1400px, (min-width: 1024px) 92vw, 100vw" : void 0,
        alt: artwork?.title ?? "Artwork",
        className: `absolute inset-0 h-full w-full object-contain transition-opacity duration-500 ${isLoaded ? "opacity-100" : "opacity-0"}`,
        loading: "eager",
        decoding: "async",
        fetchPriority: "high",
        onLoad: () => setIsLoaded(true),
        onError: (event) => {
          event.currentTarget.onerror = null;
          if (mainImageMode === "primary") {
            setMainImageMode("fallback");
            setIsLoaded(false);
            return;
          }
          setMainImageMode("hidden");
          setIsLoaded(true);
        }
      }
    ) : null,
    onOpenViewer && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        "aria-label": "View fullscreen",
        onClick: (e) => {
          e.stopPropagation();
          onOpenViewer();
        },
        className: "absolute bottom-3 right-3 flex h-9 w-9 items-center justify-center rounded-full bg-black/50 text-white/80 shadow-lg ring-1 ring-white/15 backdrop-blur-sm opacity-0 transition-opacity duration-150 hover:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:opacity-100 [div:hover_&]:opacity-100"
      },
      /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", className: "h-4 w-4", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5v-4m0 4h-4m4 0l-5-5" }))
    )
  ), hasRealArtworkImage && /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-8 -bottom-5 h-10 rounded-full bg-accent/25 blur-2xl" })), /* @__PURE__ */ React.createElement("div", { className: "hidden w-12 shrink-0 justify-center sm:flex" }, hasNext && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Next artwork",
      onClick: () => onNext?.(),
      className: "flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white/70 ring-1 ring-white/15 shadow-lg transition-colors duration-150 hover:bg-white/20 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-accent"
    },
    /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2.5 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 5l7 7-7 7" }))
  ))));
}
function ArtworkMediaStrip({ items = [], selectedId = null, onSelect }) {
  if (!Array.isArray(items) || items.length <= 1) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[1.75rem] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-4 shadow-[0_18px_60px_rgba(2,8,23,0.24)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/45" }, "Gallery"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white/60" }, "Switch between the default cover and additional archive screenshots.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] text-white/65" }, items.length, " views")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 overflow-x-auto pb-1" }, items.map((item) => {
    const active = item.id === selectedId;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: item.id,
        type: "button",
        onClick: () => onSelect?.(item.id),
        "aria-pressed": active,
        className: [
          "group shrink-0 rounded-2xl border p-2 text-left transition-all",
          active ? "border-sky-300/45 bg-sky-400/12 shadow-[0_0_0_1px_rgba(56,189,248,0.18)]" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "h-20 w-28 overflow-hidden rounded-xl bg-black/30 ring-1 ring-white/10 sm:h-24 sm:w-36" }, item.thumbUrl ? /* @__PURE__ */ React.createElement(
        "img",
        {
          src: item.thumbUrl,
          alt: item.label,
          className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]",
          loading: "lazy",
          decoding: "async"
        }
      ) : /* @__PURE__ */ React.createElement("div", { className: "grid h-full w-full place-items-center text-white/30" }, /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" })))),
      /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center justify-between gap-2 px-1" }, /* @__PURE__ */ React.createElement("span", { className: "truncate text-xs font-medium text-white/80" }, item.label), /* @__PURE__ */ React.createElement("span", { className: [
        "rounded-full px-2 py-0.5 text-[10px]",
        active ? "bg-sky-300/20 text-sky-100" : "bg-white/10 text-white/45"
      ].join(" ") }, active ? "Showing" : "View"))
    );
  })));
}
function Separator() {
  return /* @__PURE__ */ React.createElement(
    "svg",
    {
      className: "h-3 w-3 flex-shrink-0 text-white/15",
      fill: "none",
      viewBox: "0 0 24 24",
      stroke: "currentColor",
      strokeWidth: 2,
      "aria-hidden": "true"
    },
    /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 5l7 7-7 7" })
  );
}
function Crumb({ href, children, current = false }) {
  const base = "text-xs leading-none truncate max-w-[180px] sm:max-w-[260px]";
  if (current) {
    return /* @__PURE__ */ React.createElement(
      "span",
      {
        className: `${base} text-white/55`,
        "aria-current": "page"
      },
      children
    );
  }
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href,
      className: `${base} text-white/55 hover:text-white/80 transition-colors duration-150`
    },
    children
  );
}
function ArtworkBreadcrumbs({ artwork }) {
  if (!artwork) return null;
  const firstCategory = artwork.categories?.[0] ?? null;
  const contentTypeSlug = firstCategory?.content_type_slug || null;
  const contentTypeName = contentTypeSlug ? contentTypeSlug.charAt(0).toUpperCase() + contentTypeSlug.slice(1) : null;
  const categorySlug = firstCategory?.slug || null;
  const categoryName = firstCategory?.name || null;
  const categoryUrl = contentTypeSlug && categorySlug ? `/${contentTypeSlug}/${categorySlug}` : null;
  return /* @__PURE__ */ React.createElement("nav", { "aria-label": "Breadcrumb", className: "mt-1.5 mb-0" }, /* @__PURE__ */ React.createElement("ol", { className: "flex flex-wrap items-center gap-x-1 gap-y-1" }, /* @__PURE__ */ React.createElement("li", { className: "flex items-center gap-x-1.5" }, /* @__PURE__ */ React.createElement(Crumb, { href: "/" }, "Home")), contentTypeSlug && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("li", { className: "flex items-center" }, /* @__PURE__ */ React.createElement(Separator, null)), /* @__PURE__ */ React.createElement("li", { className: "flex items-center gap-x-1.5" }, /* @__PURE__ */ React.createElement(Crumb, { href: `/${contentTypeSlug}` }, contentTypeName))), categoryUrl && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("li", { className: "flex items-center" }, /* @__PURE__ */ React.createElement(Separator, null)), /* @__PURE__ */ React.createElement("li", { className: "flex items-center gap-x-1.5" }, /* @__PURE__ */ React.createElement(Crumb, { href: categoryUrl }, categoryName)))));
}
function toneClasses$2(tone) {
  switch (tone) {
    case "featured":
      return "border-amber-300/30 bg-amber-400/12 text-amber-50 hover:border-amber-300/45 hover:bg-amber-400/18";
    case "community":
      return "border-sky-300/25 bg-sky-300/10 text-sky-100 hover:border-sky-300/40 hover:bg-sky-300/15";
    case "curated":
      return "border-emerald-300/25 bg-emerald-400/10 text-emerald-100 hover:border-emerald-300/40 hover:bg-emerald-400/15";
    case "emerald":
      return "border-emerald-300/25 bg-emerald-400/10 text-emerald-100 hover:border-emerald-300/40 hover:bg-emerald-400/15";
    case "amber":
      return "border-amber-300/30 bg-amber-400/12 text-amber-50 hover:border-amber-300/45 hover:bg-amber-400/18";
    case "violet":
      return "border-violet-300/25 bg-violet-400/10 text-violet-100 hover:border-violet-300/40 hover:bg-violet-400/15";
    case "rose":
      return "border-rose-300/25 bg-rose-400/10 text-rose-100 hover:border-rose-300/40 hover:bg-rose-400/15";
    case "sky":
      return "border-sky-300/25 bg-sky-300/10 text-sky-100 hover:border-sky-300/40 hover:bg-sky-300/15";
    default:
      return "border-white/10 bg-white/[0.04] text-white hover:border-white/20 hover:bg-white/[0.07]";
  }
}
function WorldParticipationBadge({ items = [] }) {
  const badges = Array.isArray(items) ? items : [];
  if (badges.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "World participation"), badges.map((item) => {
    const label = item?.badge_label || item?.world_title || "World participation";
    const badgeClassName = `inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm font-medium transition ${toneClasses$2(item?.tone)}`;
    if (item?.world_url) {
      return /* @__PURE__ */ React.createElement("a", { key: `${item.world_id}-${item.status || item.tone || "world"}`, href: item.world_url, className: badgeClassName }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-[11px]" }), /* @__PURE__ */ React.createElement("span", null, label));
    }
    return /* @__PURE__ */ React.createElement("span", { key: `${item.world_id}-${item.status || item.tone || "world"}`, className: badgeClassName }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-[11px]" }), /* @__PURE__ */ React.createElement("span", null, label));
  }));
}
function ArtworkMeta({ artwork }) {
  const publisher = artwork?.publisher || null;
  const credits = artwork?.credits || {};
  const contributors = Array.isArray(credits?.contributors) ? credits.contributors : [];
  const worldParticipation = Array.isArray(artwork?.world_participation) ? artwork.world_participation : [];
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold tracking-tight text-white sm:text-3xl" }, artwork?.title), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3 text-sm text-slate-300" }, publisher?.type === "group" ? /* @__PURE__ */ React.createElement("a", { href: publisher.profile_url, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Published by"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold" }, publisher.name)) : null, contributors.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Contributors")), contributors.map((item) => {
    const label = item.name || item.username;
    return /* @__PURE__ */ React.createElement("span", { key: item.id || label, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white" }, item.profile_url ? /* @__PURE__ */ React.createElement("a", { href: item.profile_url, className: "font-semibold text-white hover:text-sky-200" }, label) : /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, label), item.credit_role ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-400" }, item.credit_role) : null, item.is_primary ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/30 bg-emerald-400/12 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Lead support") : null);
  })) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement(ArtworkBreadcrumbs, { artwork })), /* @__PURE__ */ React.createElement(WorldParticipationBadge, { items: worldParticipation }));
}
const sizeClass = {
  sm: "max-w-sm",
  md: "max-w-md",
  lg: "max-w-lg",
  xl: "max-w-xl",
  "2xl": "max-w-2xl",
  full: "max-w-full h-full rounded-none"
};
function Modal({
  open,
  onClose,
  title,
  footer: footer2,
  size = "md",
  closeOnBackdrop = true,
  variant = "default",
  children,
  className = ""
}) {
  const panelRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prev;
    };
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return;
    const handleKey = (e) => {
      if (e.key === "Escape") onClose?.();
    };
    window.addEventListener("keydown", handleKey);
    const firstFocusable = panelRef.current?.querySelector(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    firstFocusable?.focus();
    return () => window.removeEventListener("keydown", handleKey);
  }, [open, onClose]);
  if (!open) return null;
  const borderClass = variant === "danger" ? "border-red-500/30" : "border-white/10";
  const sClass = sizeClass[size] ?? sizeClass.md;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        role: "dialog",
        "aria-modal": "true",
        "aria-label": title,
        className: "fixed inset-0 z-[200] flex items-center justify-center p-4"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          className: "absolute inset-0 bg-black/70 backdrop-blur-sm",
          onClick: closeOnBackdrop ? onClose : void 0,
          "aria-hidden": "true"
        }
      ),
      /* @__PURE__ */ React.createElement(
        "div",
        {
          ref: panelRef,
          className: [
            "relative w-full bg-nova-900 rounded-2xl border shadow-2xl",
            "flex flex-col max-h-[90vh]",
            borderClass,
            sClass,
            className
          ].join(" ")
        },
        title && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between px-6 py-4 border-b border-white/10 shrink-0" }, /* @__PURE__ */ React.createElement("h2", { className: "text-base font-bold text-white" }, title), /* @__PURE__ */ React.createElement(
          "button",
          {
            onClick: onClose,
            className: "w-8 h-8 flex items-center justify-center rounded-lg text-slate-400 hover:text-white hover:bg-white/8 transition-all",
            "aria-label": "Close dialog"
          },
          /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 14 14", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M1 1l12 12M13 1L1 13", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }))
        )),
        /* @__PURE__ */ React.createElement("div", { className: "flex-1 overflow-y-auto nova-scrollbar px-6 py-5" }, children),
        footer2 && /* @__PURE__ */ React.createElement("div", { className: "shrink-0 px-6 py-4 border-t border-white/10 flex items-center justify-end gap-2" }, footer2)
      )
    ),
    document.body
  );
}
const variantClasses = {
  primary: "bg-sky-600   hover:bg-sky-500   text-white       shadow-lg shadow-sky-600/20   focus-visible:ring-sky-500/50",
  accent: "bg-accent    hover:bg-accent/90 text-white       shadow-lg shadow-accent/25    focus-visible:ring-accent/50",
  secondary: "bg-white/8   hover:bg-white/14  text-white       border border-white/15        focus-visible:ring-white/30",
  ghost: "bg-transparent hover:bg-white/8 text-slate-300  hover:text-white              focus-visible:ring-white/20",
  danger: "bg-red-600   hover:bg-red-700   text-white       shadow-lg shadow-red-600/20   focus-visible:ring-red-500/50",
  success: "bg-emerald-600 hover:bg-emerald-500 text-white  shadow-lg shadow-emerald-600/20 focus-visible:ring-emerald-500/50"
};
const sizeClasses = {
  xs: "px-2.5 py-1   text-xs  rounded-lg  gap-1.5",
  sm: "px-3.5 py-1.5 text-sm  rounded-xl  gap-2",
  md: "px-5   py-2.5 text-sm  rounded-xl  gap-2",
  lg: "px-6   py-3   text-base rounded-xl  gap-2.5"
};
const iconOnlySizeClasses = {
  xs: "w-7  h-7  rounded-lg",
  sm: "w-8  h-8  rounded-lg",
  md: "w-10 h-10 rounded-xl",
  lg: "w-12 h-12 rounded-xl"
};
function Button$1({
  variant = "primary",
  size = "md",
  loading = false,
  iconOnly = false,
  leftIcon,
  rightIcon,
  disabled,
  className = "",
  children,
  type: type2 = "button",
  ...rest
}) {
  const isDisabled = disabled || loading;
  const base = [
    "inline-flex items-center justify-center font-semibold transition-all duration-150",
    "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-0",
    "disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none",
    variantClasses[variant] ?? variantClasses.primary,
    iconOnly ? iconOnlySizeClasses[size] ?? iconOnlySizeClasses.md : sizeClasses[size] ?? sizeClasses.md,
    className
  ].join(" ");
  return /* @__PURE__ */ React.createElement("button", { type: type2, disabled: isDisabled, className: base, ...rest }, loading ? /* @__PURE__ */ React.createElement(
    "svg",
    {
      className: "animate-spin shrink-0",
      style: { width: "1em", height: "1em" },
      viewBox: "0 0 24 24",
      fill: "none",
      "aria-hidden": "true"
    },
    /* @__PURE__ */ React.createElement("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }),
    /* @__PURE__ */ React.createElement("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8v8H4z" })
  ) : leftIcon ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0" }, leftIcon) : null, !iconOnly && children && /* @__PURE__ */ React.createElement("span", null, children), iconOnly && !loading && children, rightIcon && !loading && /* @__PURE__ */ React.createElement("span", { className: "shrink-0" }, rightIcon));
}
const MEDALS = [
  { key: "gold", label: "Gold", emoji: "🥇", weight: 5 },
  { key: "silver", label: "Silver", emoji: "🥈", weight: 3 },
  { key: "bronze", label: "Bronze", emoji: "🥉", weight: 1 }
];
function getMedalMeta(medalKey) {
  return MEDALS.find((medal) => medal.key === medalKey) ?? null;
}
function getMedalWeight(medalKey) {
  return getMedalMeta(medalKey)?.weight ?? 0;
}
function buildConfirmationContent(pendingConfirmation) {
  if (!pendingConfirmation) {
    return null;
  }
  const nextMedal = getMedalMeta(pendingConfirmation.medal);
  const previousMedal = getMedalMeta(pendingConfirmation.previousMedal);
  if (pendingConfirmation.action === "remove") {
    return {
      title: `Remove ${nextMedal?.label ?? "medal"} medal?`,
      summary: `This will remove your ${nextMedal?.label ?? ""} medal from this artwork.`,
      details: "Your contribution to the medal score will be removed immediately after confirmation.",
      confirmLabel: "Remove medal",
      confirmVariant: "danger",
      modalVariant: "danger"
    };
  }
  return {
    title: `Change medal to ${nextMedal?.label ?? "selected medal"}?`,
    summary: `You already awarded ${previousMedal?.label ?? "a medal"} to this artwork.`,
    details: `Confirm to switch your medal from ${previousMedal?.label ?? "the current medal"} to ${nextMedal?.label ?? "the selected medal"}.`,
    confirmLabel: `Change to ${nextMedal?.label ?? "selected medal"}`,
    confirmVariant: "accent",
    modalVariant: "default"
  };
}
function describeMedalError(message) {
  const normalized = String(message || "").trim();
  const lower = normalized.toLowerCase();
  if (lower.includes("verify your email")) {
    return {
      title: "Email verification required",
      summary: "Medals are limited to verified accounts to reduce abuse and low-quality vote spam.",
      details: "Open your account email, use the verification link, then reload this page and try again."
    };
  }
  if (lower.includes("at least") && lower.includes("hours old")) {
    return {
      title: "Account is too new",
      summary: normalized,
      details: "This cooldown is there to stop throwaway accounts from mass-awarding artworks immediately after signup."
    };
  }
  if (lower.includes("your own artwork")) {
    return {
      title: "Own artwork cannot be medaled",
      summary: "Creators cannot add medals to their own work.",
      details: "Only other community members can award medals so the score stays community-driven."
    };
  }
  if (lower.includes("not published yet")) {
    return {
      title: "Artwork is not published yet",
      summary: "This artwork has not reached a public, medal-eligible state yet.",
      details: "Medals are only available after the artwork is published and visible publicly."
    };
  }
  if (lower.includes("not eligible for medals")) {
    return {
      title: "Artwork is not eligible for medals",
      summary: "This artwork is currently blocked from medal voting.",
      details: "That usually means it is private, unapproved, or otherwise not available for public medal activity."
    };
  }
  if (lower.includes("no longer available")) {
    return {
      title: "Artwork is unavailable",
      summary: "This artwork can no longer receive medals.",
      details: "The artwork may have been removed or is no longer publicly available."
    };
  }
  if (lower.includes("disabled")) {
    return {
      title: "Medals are temporarily unavailable",
      summary: normalized,
      details: "This is a site-wide setting, not a problem with your account."
    };
  }
  return {
    title: "Unable to add medal",
    summary: normalized || "The medal request could not be completed.",
    details: "Check that you are signed in with an eligible account and that the artwork is publicly medal-eligible."
  };
}
function ArtworkAwards({ artwork, initialAwards = null, isAuthenticated = false }) {
  const artworkId = artwork?.id;
  const isOwnArtwork = Boolean(artwork?.viewer?.id && artwork?.user?.id && artwork.viewer.id === artwork.user.id);
  const [awards, setAwards] = reactExports.useState({
    gold: initialAwards?.gold ?? 0,
    silver: initialAwards?.silver ?? 0,
    bronze: initialAwards?.bronze ?? 0,
    score: initialAwards?.score ?? 0
  });
  const [viewerAward, setViewerAward] = reactExports.useState(initialAwards?.current_user_medal ?? initialAwards?.viewer_award ?? null);
  const [loading, setLoading] = reactExports.useState(null);
  const [error, setError] = reactExports.useState(null);
  const [pendingConfirmation, setPendingConfirmation] = reactExports.useState(null);
  const errorDetails = error ? describeMedalError(error) : null;
  const confirmationContent = buildConfirmationContent(pendingConfirmation);
  const csrfToken2 = typeof document !== "undefined" ? document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") : null;
  const apiFetch2 = reactExports.useCallback(async (method, body2 = null) => {
    const res = await fetch(`/api/artworks/${artworkId}/medal`, {
      method,
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken2 || "",
        "Accept": "application/json"
      },
      credentials: "same-origin",
      body: body2 ? JSON.stringify(body2) : void 0
    });
    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      throw new Error(data?.message || data?.errors?.medal?.[0] || "Request failed");
    }
    return res.json();
  }, [artworkId, csrfToken2]);
  const applyServerResponse = reactExports.useCallback((data) => {
    const payload = data?.medals || data?.awards || null;
    if (payload) {
      setAwards({
        gold: payload.gold ?? 0,
        silver: payload.silver ?? 0,
        bronze: payload.bronze ?? 0,
        score: payload.score ?? 0
      });
    }
    setViewerAward(data?.current_user_medal ?? data?.viewer_award ?? null);
  }, []);
  const handleMedalAction = reactExports.useCallback(async ({ action, medal, previousMedal = null }) => {
    if (!isAuthenticated || isOwnArtwork) return;
    if (loading) return;
    setError(null);
    const prevAwards = { ...awards };
    const prevViewer = viewerAward;
    if (action === "remove") {
      setAwards((a) => ({
        ...a,
        [medal]: Math.max(0, a[medal] - 1),
        score: Math.max(0, a.score - getMedalWeight(medal))
      }));
      setViewerAward(null);
      setLoading(medal);
      try {
        const data = await apiFetch2("DELETE");
        applyServerResponse(data);
      } catch (e) {
        setAwards(prevAwards);
        setViewerAward(prevViewer);
        setError(e.message);
      } finally {
        setLoading(null);
      }
      return;
    }
    if (action === "change" && previousMedal) {
      setAwards((a) => ({
        ...a,
        [previousMedal]: Math.max(0, a[previousMedal] - 1),
        [medal]: a[medal] + 1,
        score: a.score - getMedalWeight(previousMedal) + getMedalWeight(medal)
      }));
      setViewerAward(medal);
      setLoading(medal);
      try {
        const data = await apiFetch2("POST", { medal_type: medal });
        applyServerResponse(data);
      } catch (e) {
        setAwards(prevAwards);
        setViewerAward(prevViewer);
        setError(e.message);
      } finally {
        setLoading(null);
      }
      return;
    }
    setAwards((a) => ({
      ...a,
      [medal]: a[medal] + 1,
      score: a.score + getMedalWeight(medal)
    }));
    setViewerAward(medal);
    setLoading(medal);
    try {
      const data = await apiFetch2("POST", { medal_type: medal });
      applyServerResponse(data);
    } catch (e) {
      setAwards(prevAwards);
      setViewerAward(prevViewer);
      setError(e.message);
    } finally {
      setLoading(null);
    }
  }, [isAuthenticated, isOwnArtwork, loading, awards, viewerAward, apiFetch2, applyServerResponse]);
  const handleMedalClick = reactExports.useCallback((medal) => {
    if (!isAuthenticated || isOwnArtwork) return;
    if (loading) return;
    setError(null);
    if (viewerAward === medal) {
      setPendingConfirmation({ action: "remove", medal, previousMedal: medal });
      return;
    }
    if (viewerAward) {
      setPendingConfirmation({ action: "change", medal, previousMedal: viewerAward });
      return;
    }
    void handleMedalAction({ action: "add", medal });
  }, [isAuthenticated, isOwnArtwork, loading, viewerAward, handleMedalAction]);
  const closeConfirmation = reactExports.useCallback(() => {
    if (loading) return;
    setPendingConfirmation(null);
  }, [loading]);
  const confirmPendingAction = reactExports.useCallback(async () => {
    if (!pendingConfirmation || loading) return;
    const action = pendingConfirmation;
    setPendingConfirmation(null);
    await handleMedalAction(action);
  }, [pendingConfirmation, loading, handleMedalAction]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xs font-semibold uppercase tracking-wider text-white/30" }, "Medals"), errorDetails && /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-xl border border-red-400/20 bg-red-500/10 px-4 py-3 text-left" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-red-300/90" }, errorDetails.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-red-200" }, errorDetails.summary), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-5 text-red-100/75" }, errorDetails.details)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-col gap-3 sm:flex-row" }, MEDALS.map(({ key, label, emoji }) => {
    const isActive = viewerAward === key;
    const isPending = loading === key;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key,
        type: "button",
        disabled: !isAuthenticated || isOwnArtwork || loading !== null,
        onClick: () => handleMedalClick(key),
        title: !isAuthenticated ? "Sign in to medal" : isOwnArtwork ? "You cannot medal your own artwork" : isActive ? `Remove ${label} medal` : viewerAward ? `Change medal to ${label}` : `Give ${label} medal`,
        className: [
          "inline-flex min-h-11 flex-1 flex-col items-center justify-center gap-1 rounded-lg border px-3 py-2 text-sm transition-all",
          isActive ? "border-accent/40 bg-accent/10 font-semibold text-accent shadow-lg shadow-accent/10" : "border-white/[0.08] bg-white/[0.03] text-white/70 hover:bg-white/[0.06] hover:border-white/[0.12]",
          (!isAuthenticated || isOwnArtwork || loading !== null) && "cursor-not-allowed opacity-60"
        ].filter(Boolean).join(" ")
      },
      /* @__PURE__ */ React.createElement("span", { className: "text-xl leading-none", "aria-hidden": "true" }, isPending ? "…" : emoji),
      /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium leading-none" }, label),
      /* @__PURE__ */ React.createElement("span", { className: "text-xs text-soft tabular-nums" }, awards[key])
    );
  })), awards.score > 0 && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-right text-xs text-soft" }, "Score: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, awards.score)), !isAuthenticated && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-center text-xs text-soft" }, /* @__PURE__ */ React.createElement("a", { href: "/login", className: "text-accent underline hover:no-underline" }, "Sign in"), " to medal this artwork"), isAuthenticated && isOwnArtwork && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-center text-xs text-soft" }, "You cannot medal your own artwork.")), /* @__PURE__ */ React.createElement(
    Modal,
    {
      open: Boolean(confirmationContent),
      onClose: closeConfirmation,
      title: confirmationContent?.title,
      size: "sm",
      variant: confirmationContent?.modalVariant,
      footer: confirmationContent ? /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-2" }, /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "sm", onClick: closeConfirmation, disabled: loading !== null }, "Cancel"), /* @__PURE__ */ React.createElement(Button$1, { variant: confirmationContent.confirmVariant, size: "sm", onClick: confirmPendingAction, loading: loading !== null }, confirmationContent.confirmLabel)) : null
    },
    confirmationContent ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-200" }, confirmationContent.summary), /* @__PURE__ */ React.createElement("p", { className: "text-xs leading-5 text-slate-400" }, confirmationContent.details)) : null
  ));
}
function ArtworkTags({ artwork }) {
  const [expanded, setExpanded] = reactExports.useState(false);
  const tags = reactExports.useMemo(() => {
    const seen = /* @__PURE__ */ new Set();
    const contentTypeSeen = /* @__PURE__ */ new Set();
    const categoryPills = [];
    for (const category of artwork?.categories || []) {
      const ctSlug = category.content_type_slug;
      if (ctSlug && !contentTypeSeen.has(ctSlug)) {
        contentTypeSeen.add(ctSlug);
        const ctName = ctSlug.charAt(0).toUpperCase() + ctSlug.slice(1);
        categoryPills.push({
          key: `ct-${ctSlug}`,
          label: ctName,
          href: `/${ctSlug}`,
          isCategory: true
        });
      }
      if (category.parent && !seen.has(category.parent.id)) {
        seen.add(category.parent.id);
        categoryPills.push({
          key: `cat-${category.parent.id}`,
          label: category.parent.name,
          href: category.parent.url || `/${category.parent.content_type_slug}/${category.parent.slug}`,
          isCategory: true
        });
      }
      if (!seen.has(category.id)) {
        seen.add(category.id);
        categoryPills.push({
          key: `cat-${category.id}`,
          label: category.name,
          href: category.url || `/${category.content_type_slug}/${category.slug}`,
          isCategory: true
        });
      }
    }
    const artworkTags = (artwork?.tags || []).map((tag) => ({
      key: `tag-${tag.id || tag.slug}`,
      label: tag.name,
      href: `/tag/${tag.slug || ""}`,
      isCategory: false
    }));
    return [...categoryPills, ...artworkTags];
  }, [artwork]);
  if (tags.length === 0) return null;
  const visible = expanded ? tags : tags.slice(0, 12);
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "mb-4 text-xs font-semibold uppercase tracking-widest text-accent/70" }, "Tags & Categories"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, visible.map((tag, idx) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: tag.key,
      href: tag.href,
      className: [
        "inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-all duration-200",
        tag.isCategory ? "border-accent/30 bg-accent/10 text-accent hover:border-accent/50 hover:bg-accent/20" : "border-white/[0.08] bg-white/[0.03] text-white/60 hover:border-white/[0.15] hover:bg-white/[0.06] hover:text-white/80"
      ].join(" ")
    },
    tag.label
  )), tags.length > 12 && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      className: "inline-flex items-center rounded-full border border-dashed border-white/[0.1] px-3 py-1.5 text-xs text-white/40 transition hover:border-white/20 hover:text-white/60",
      onClick: () => setExpanded((value) => !value)
    },
    expanded ? "Show less" : `+${tags.length - 12} more`
  )));
}
const COLLAPSE_AT = 560;
function stripTags(value) {
  return String(value || "").replace(/<\/?(?:html|head|body|title|meta|link|script|style)[^>]*>/gi, "").replace(/<[^>]*>/g, "").trim();
}
function sanitizeDescriptionHtml(value) {
  const html2 = String(value || "").trim();
  if (!html2) {
    return "";
  }
  if (/<\/?(?:html|head|body|title|meta|link|script|style)\b/i.test(html2)) {
    return "";
  }
  return html2;
}
function ArtworkDescription({ artwork }) {
  const [expanded, setExpanded] = reactExports.useState(false);
  const content2 = (artwork?.description || "").trim();
  const contentHtml = sanitizeDescriptionHtml(artwork?.description_html || "");
  const collapsed = content2.length > COLLAPSE_AT && !expanded;
  const fallbackText = contentHtml ? stripTags(contentHtml) : content2;
  if (content2.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: [
        "max-w-[720px] overflow-hidden transition-[max-height] duration-300",
        collapsed ? "max-h-[11.5rem]" : "max-h-[100rem]"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "prose prose-invert max-w-none text-sm leading-7 prose-p:my-3 prose-p:text-white/50 prose-a:text-accent prose-a:no-underline hover:prose-a:underline prose-strong:text-white/80 prose-em:text-white/70 prose-code:text-white/80",
        suppressHydrationWarning: true,
        dangerouslySetInnerHTML: { __html: contentHtml || escapeHtml(fallbackText) }
      }
    )
  ), content2.length > COLLAPSE_AT && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      className: "mt-3 text-sm font-medium text-accent transition-colors hover:text-accent/80",
      onClick: () => setExpanded((value) => !value)
    },
    expanded ? "Show less" : "Show more"
  ));
}
function escapeHtml(value) {
  return String(value || "").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
}
function EvolutionArtworkCard({ card }) {
  if (!card) return null;
  const shouldBlur = Boolean(card?.maturity?.should_blur);
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: card.url,
      className: "group block overflow-hidden rounded-[26px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.03))] transition hover:border-white/20 hover:bg-white/[0.07]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[1.08/1] overflow-hidden bg-slate-950" }, card.thumbnail ? /* @__PURE__ */ React.createElement(
      "img",
      {
        src: card.thumbnail,
        alt: card.title,
        className: `h-full w-full object-cover transition duration-500 group-hover:scale-[1.03] ${shouldBlur ? "scale-[1.03] blur-xl" : ""}`
      }
    ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-3xl" })), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 inline-flex items-center gap-2 rounded-full border border-white/10 bg-black/45 px-3 py-1.5 text-[10px] font-semibold uppercase tracking-[0.18em] text-white backdrop-blur-md" }, /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-sky-300" }), card.role_label), shouldBlur ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 bg-[linear-gradient(180deg,rgba(15,23,42,0),rgba(15,23,42,0.9))] px-4 py-4 text-sm text-white/85" }, "Mature artwork preview is softened for your current viewer settings.") : null),
    /* @__PURE__ */ React.createElement("div", { className: "space-y-2 px-4 py-4 sm:px-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, card.content_type ? /* @__PURE__ */ React.createElement("span", null, card.content_type) : null, card.category ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, card.category) : null), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold tracking-[-0.02em] text-white" }, card.title), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, card.publisher), card.year ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, card.year) : null))
  );
}
function ComparisonModal({ item, open, onClose }) {
  if (!item) return null;
  return /* @__PURE__ */ React.createElement(Modal, { open, onClose, title: item.compare?.title || "Compare versions", size: "full" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, item.heading), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, item.relation_label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-7 text-slate-300" }, item.summary)), item.years_apart_label ? /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-clock", "aria-hidden": "true" }), item.years_apart_label) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-2" }, [item.before, item.after].map((card) => /* @__PURE__ */ React.createElement("div", { key: `${item.id}-${card.id}`, className: "overflow-hidden rounded-[28px] border border-white/10 bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, card.role_label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-base font-semibold text-white" }, card.title)), /* @__PURE__ */ React.createElement("a", { href: card.url, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-medium text-white transition hover:bg-white/[0.08]" }, "Open", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500", "aria-hidden": "true" }))), /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[4/3] overflow-hidden bg-slate-950" }, card.image_lg ? /* @__PURE__ */ React.createElement(
    "img",
    {
      src: card.image_lg,
      alt: card.title,
      className: `h-full w-full object-cover ${card?.maturity?.should_blur ? "scale-[1.03] blur-xl" : ""}`
    }
  ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-4xl" }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 px-5 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, card.publisher), card.year ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, card.year) : null, card.category ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, card.category) : null)))), item.note ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-sky-300/20 bg-sky-300/10 px-5 py-4 text-sm leading-7 text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/80" }, "Creator note"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap" }, item.note)) : null));
}
function EvolutionStoryBlock({ item, onCompare }) {
  if (!item) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[30px] border border-white/[0.08] bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_34%),linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.025))] p-5 shadow-[0_22px_55px_rgba(2,6,23,0.26)] backdrop-blur-xl sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, item.heading), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-[28px] font-semibold tracking-[-0.04em] text-white" }, item.relation_label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-200/90" }, item.summary)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 lg:justify-end" }, item.years_apart_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-clock", "aria-hidden": "true" }), item.years_apart_label) : null, item.compare?.available ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onCompare(item),
      className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-300/18"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-up-right-and-down-left-from-center", "aria-hidden": "true" }),
    "Compare side by side"
  ) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(EvolutionArtworkCard, { card: item.before }), /* @__PURE__ */ React.createElement(EvolutionArtworkCard, { card: item.after })), item.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4 text-sm leading-7 text-slate-200/90" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Creator note"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap" }, item.note)) : null);
}
function EvolutionUpdates({ updates, onCompare }) {
  if (!updates?.length) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/[0.08] bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-5 shadow-[0_22px_55px_rgba(0,0,0,0.18)] backdrop-blur-xl sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/55" }, "Updated Versions"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "This piece has later evolutions")), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Follow how the creator revisited the idea over time.")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, updates.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, item.heading), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.02em] text-white" }, item.after?.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, item.summary)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, item.years_apart_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-clock", "aria-hidden": "true" }), item.years_apart_label) : null, item.compare?.available ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onCompare(item),
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
    },
    "Compare"
  ) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(EvolutionArtworkCard, { card: item.before }), /* @__PURE__ */ React.createElement(EvolutionArtworkCard, { card: item.after })), item.note ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, item.note) : null))));
}
function ArtworkEvolutionPanel({ evolution }) {
  const [compareItem, setCompareItem] = reactExports.useState(null);
  if (!evolution?.primary && !evolution?.updates?.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, evolution.primary ? /* @__PURE__ */ React.createElement(EvolutionStoryBlock, { item: evolution.primary, onCompare: setCompareItem }) : null, evolution.updates?.length ? /* @__PURE__ */ React.createElement(EvolutionUpdates, { updates: evolution.updates, onCompare: setCompareItem }) : null), /* @__PURE__ */ React.createElement(ComparisonModal, { item: compareItem, open: Boolean(compareItem), onClose: () => setCompareItem(null) }));
}
function ok$1() {
}
function unreachable() {
}
function stringify$1(values, options) {
  const settings = {};
  const input = values[values.length - 1] === "" ? [...values, ""] : values;
  return input.join(
    (settings.padRight ? " " : "") + "," + (settings.padLeft === false ? "" : " ")
  ).trim();
}
const nameRe = /^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u;
const nameReJsx = /^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u;
const emptyOptions$2 = {};
function name(name2, options) {
  const settings = emptyOptions$2;
  const re2 = settings.jsx ? nameReJsx : nameRe;
  return re2.test(name2);
}
const re = /[ \t\n\f\r]/g;
function whitespace(thing) {
  return typeof thing === "object" ? thing.type === "text" ? empty$1(thing.value) : false : empty$1(thing);
}
function empty$1(value) {
  return value.replace(re, "") === "";
}
class Schema {
  /**
   * @param {SchemaType['property']} property
   *   Property.
   * @param {SchemaType['normal']} normal
   *   Normal.
   * @param {Space | undefined} [space]
   *   Space.
   * @returns
   *   Schema.
   */
  constructor(property, normal, space2) {
    this.normal = normal;
    this.property = property;
    if (space2) {
      this.space = space2;
    }
  }
}
Schema.prototype.normal = {};
Schema.prototype.property = {};
Schema.prototype.space = void 0;
function merge(definitions, space2) {
  const property = {};
  const normal = {};
  for (const definition2 of definitions) {
    Object.assign(property, definition2.property);
    Object.assign(normal, definition2.normal);
  }
  return new Schema(property, normal, space2);
}
function normalize(value) {
  return value.toLowerCase();
}
class Info {
  /**
   * @param {string} property
   *   Property.
   * @param {string} attribute
   *   Attribute.
   * @returns
   *   Info.
   */
  constructor(property, attribute) {
    this.attribute = attribute;
    this.property = property;
  }
}
Info.prototype.attribute = "";
Info.prototype.booleanish = false;
Info.prototype.boolean = false;
Info.prototype.commaOrSpaceSeparated = false;
Info.prototype.commaSeparated = false;
Info.prototype.defined = false;
Info.prototype.mustUseProperty = false;
Info.prototype.number = false;
Info.prototype.overloadedBoolean = false;
Info.prototype.property = "";
Info.prototype.spaceSeparated = false;
Info.prototype.space = void 0;
let powers = 0;
const boolean = increment();
const booleanish = increment();
const overloadedBoolean = increment();
const number$3 = increment();
const spaceSeparated = increment();
const commaSeparated = increment();
const commaOrSpaceSeparated = increment();
function increment() {
  return 2 ** ++powers;
}
const types = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  boolean,
  booleanish,
  commaOrSpaceSeparated,
  commaSeparated,
  number: number$3,
  overloadedBoolean,
  spaceSeparated
}, Symbol.toStringTag, { value: "Module" }));
const checks = (
  /** @type {ReadonlyArray<keyof typeof types>} */
  Object.keys(types)
);
class DefinedInfo extends Info {
  /**
   * @constructor
   * @param {string} property
   *   Property.
   * @param {string} attribute
   *   Attribute.
   * @param {number | null | undefined} [mask]
   *   Mask.
   * @param {Space | undefined} [space]
   *   Space.
   * @returns
   *   Info.
   */
  constructor(property, attribute, mask, space2) {
    let index2 = -1;
    super(property, attribute);
    mark(this, "space", space2);
    if (typeof mask === "number") {
      while (++index2 < checks.length) {
        const check = checks[index2];
        mark(this, checks[index2], (mask & types[check]) === types[check]);
      }
    }
  }
}
DefinedInfo.prototype.defined = true;
function mark(values, key, value) {
  if (value) {
    values[key] = value;
  }
}
function create(definition2) {
  const properties = {};
  const normals = {};
  for (const [property, value] of Object.entries(definition2.properties)) {
    const info = new DefinedInfo(
      property,
      definition2.transform(definition2.attributes || {}, property),
      value,
      definition2.space
    );
    if (definition2.mustUseProperty && definition2.mustUseProperty.includes(property)) {
      info.mustUseProperty = true;
    }
    properties[property] = info;
    normals[normalize(property)] = property;
    normals[normalize(info.attribute)] = property;
  }
  return new Schema(properties, normals, definition2.space);
}
const aria = create({
  properties: {
    ariaActiveDescendant: null,
    ariaAtomic: booleanish,
    ariaAutoComplete: null,
    ariaBusy: booleanish,
    ariaChecked: booleanish,
    ariaColCount: number$3,
    ariaColIndex: number$3,
    ariaColSpan: number$3,
    ariaControls: spaceSeparated,
    ariaCurrent: null,
    ariaDescribedBy: spaceSeparated,
    ariaDetails: null,
    ariaDisabled: booleanish,
    ariaDropEffect: spaceSeparated,
    ariaErrorMessage: null,
    ariaExpanded: booleanish,
    ariaFlowTo: spaceSeparated,
    ariaGrabbed: booleanish,
    ariaHasPopup: null,
    ariaHidden: booleanish,
    ariaInvalid: null,
    ariaKeyShortcuts: null,
    ariaLabel: null,
    ariaLabelledBy: spaceSeparated,
    ariaLevel: number$3,
    ariaLive: null,
    ariaModal: booleanish,
    ariaMultiLine: booleanish,
    ariaMultiSelectable: booleanish,
    ariaOrientation: null,
    ariaOwns: spaceSeparated,
    ariaPlaceholder: null,
    ariaPosInSet: number$3,
    ariaPressed: booleanish,
    ariaReadOnly: booleanish,
    ariaRelevant: null,
    ariaRequired: booleanish,
    ariaRoleDescription: spaceSeparated,
    ariaRowCount: number$3,
    ariaRowIndex: number$3,
    ariaRowSpan: number$3,
    ariaSelected: booleanish,
    ariaSetSize: number$3,
    ariaSort: null,
    ariaValueMax: number$3,
    ariaValueMin: number$3,
    ariaValueNow: number$3,
    ariaValueText: null,
    role: null
  },
  transform(_2, property) {
    return property === "role" ? property : "aria-" + property.slice(4).toLowerCase();
  }
});
function caseSensitiveTransform(attributes, attribute) {
  return attribute in attributes ? attributes[attribute] : attribute;
}
function caseInsensitiveTransform(attributes, property) {
  return caseSensitiveTransform(attributes, property.toLowerCase());
}
const html$2 = create({
  attributes: {
    acceptcharset: "accept-charset",
    classname: "class",
    htmlfor: "for",
    httpequiv: "http-equiv"
  },
  mustUseProperty: ["checked", "multiple", "muted", "selected"],
  properties: {
    // Standard Properties.
    abbr: null,
    accept: commaSeparated,
    acceptCharset: spaceSeparated,
    accessKey: spaceSeparated,
    action: null,
    allow: null,
    allowFullScreen: boolean,
    allowPaymentRequest: boolean,
    allowUserMedia: boolean,
    alt: null,
    as: null,
    async: boolean,
    autoCapitalize: null,
    autoComplete: spaceSeparated,
    autoFocus: boolean,
    autoPlay: boolean,
    blocking: spaceSeparated,
    capture: null,
    charSet: null,
    checked: boolean,
    cite: null,
    className: spaceSeparated,
    cols: number$3,
    colSpan: null,
    content: null,
    contentEditable: booleanish,
    controls: boolean,
    controlsList: spaceSeparated,
    coords: number$3 | commaSeparated,
    crossOrigin: null,
    data: null,
    dateTime: null,
    decoding: null,
    default: boolean,
    defer: boolean,
    dir: null,
    dirName: null,
    disabled: boolean,
    download: overloadedBoolean,
    draggable: booleanish,
    encType: null,
    enterKeyHint: null,
    fetchPriority: null,
    form: null,
    formAction: null,
    formEncType: null,
    formMethod: null,
    formNoValidate: boolean,
    formTarget: null,
    headers: spaceSeparated,
    height: number$3,
    hidden: overloadedBoolean,
    high: number$3,
    href: null,
    hrefLang: null,
    htmlFor: spaceSeparated,
    httpEquiv: spaceSeparated,
    id: null,
    imageSizes: null,
    imageSrcSet: null,
    inert: boolean,
    inputMode: null,
    integrity: null,
    is: null,
    isMap: boolean,
    itemId: null,
    itemProp: spaceSeparated,
    itemRef: spaceSeparated,
    itemScope: boolean,
    itemType: spaceSeparated,
    kind: null,
    label: null,
    lang: null,
    language: null,
    list: null,
    loading: null,
    loop: boolean,
    low: number$3,
    manifest: null,
    max: null,
    maxLength: number$3,
    media: null,
    method: null,
    min: null,
    minLength: number$3,
    multiple: boolean,
    muted: boolean,
    name: null,
    nonce: null,
    noModule: boolean,
    noValidate: boolean,
    onAbort: null,
    onAfterPrint: null,
    onAuxClick: null,
    onBeforeMatch: null,
    onBeforePrint: null,
    onBeforeToggle: null,
    onBeforeUnload: null,
    onBlur: null,
    onCancel: null,
    onCanPlay: null,
    onCanPlayThrough: null,
    onChange: null,
    onClick: null,
    onClose: null,
    onContextLost: null,
    onContextMenu: null,
    onContextRestored: null,
    onCopy: null,
    onCueChange: null,
    onCut: null,
    onDblClick: null,
    onDrag: null,
    onDragEnd: null,
    onDragEnter: null,
    onDragExit: null,
    onDragLeave: null,
    onDragOver: null,
    onDragStart: null,
    onDrop: null,
    onDurationChange: null,
    onEmptied: null,
    onEnded: null,
    onError: null,
    onFocus: null,
    onFormData: null,
    onHashChange: null,
    onInput: null,
    onInvalid: null,
    onKeyDown: null,
    onKeyPress: null,
    onKeyUp: null,
    onLanguageChange: null,
    onLoad: null,
    onLoadedData: null,
    onLoadedMetadata: null,
    onLoadEnd: null,
    onLoadStart: null,
    onMessage: null,
    onMessageError: null,
    onMouseDown: null,
    onMouseEnter: null,
    onMouseLeave: null,
    onMouseMove: null,
    onMouseOut: null,
    onMouseOver: null,
    onMouseUp: null,
    onOffline: null,
    onOnline: null,
    onPageHide: null,
    onPageShow: null,
    onPaste: null,
    onPause: null,
    onPlay: null,
    onPlaying: null,
    onPopState: null,
    onProgress: null,
    onRateChange: null,
    onRejectionHandled: null,
    onReset: null,
    onResize: null,
    onScroll: null,
    onScrollEnd: null,
    onSecurityPolicyViolation: null,
    onSeeked: null,
    onSeeking: null,
    onSelect: null,
    onSlotChange: null,
    onStalled: null,
    onStorage: null,
    onSubmit: null,
    onSuspend: null,
    onTimeUpdate: null,
    onToggle: null,
    onUnhandledRejection: null,
    onUnload: null,
    onVolumeChange: null,
    onWaiting: null,
    onWheel: null,
    open: boolean,
    optimum: number$3,
    pattern: null,
    ping: spaceSeparated,
    placeholder: null,
    playsInline: boolean,
    popover: null,
    popoverTarget: null,
    popoverTargetAction: null,
    poster: null,
    preload: null,
    readOnly: boolean,
    referrerPolicy: null,
    rel: spaceSeparated,
    required: boolean,
    reversed: boolean,
    rows: number$3,
    rowSpan: number$3,
    sandbox: spaceSeparated,
    scope: null,
    scoped: boolean,
    seamless: boolean,
    selected: boolean,
    shadowRootClonable: boolean,
    shadowRootDelegatesFocus: boolean,
    shadowRootMode: null,
    shape: null,
    size: number$3,
    sizes: null,
    slot: null,
    span: number$3,
    spellCheck: booleanish,
    src: null,
    srcDoc: null,
    srcLang: null,
    srcSet: null,
    start: number$3,
    step: null,
    style: null,
    tabIndex: number$3,
    target: null,
    title: null,
    translate: null,
    type: null,
    typeMustMatch: boolean,
    useMap: null,
    value: booleanish,
    width: number$3,
    wrap: null,
    writingSuggestions: null,
    // Legacy.
    // See: https://html.spec.whatwg.org/#other-elements,-attributes-and-apis
    align: null,
    // Several. Use CSS `text-align` instead,
    aLink: null,
    // `<body>`. Use CSS `a:active {color}` instead
    archive: spaceSeparated,
    // `<object>`. List of URIs to archives
    axis: null,
    // `<td>` and `<th>`. Use `scope` on `<th>`
    background: null,
    // `<body>`. Use CSS `background-image` instead
    bgColor: null,
    // `<body>` and table elements. Use CSS `background-color` instead
    border: number$3,
    // `<table>`. Use CSS `border-width` instead,
    borderColor: null,
    // `<table>`. Use CSS `border-color` instead,
    bottomMargin: number$3,
    // `<body>`
    cellPadding: null,
    // `<table>`
    cellSpacing: null,
    // `<table>`
    char: null,
    // Several table elements. When `align=char`, sets the character to align on
    charOff: null,
    // Several table elements. When `char`, offsets the alignment
    classId: null,
    // `<object>`
    clear: null,
    // `<br>`. Use CSS `clear` instead
    code: null,
    // `<object>`
    codeBase: null,
    // `<object>`
    codeType: null,
    // `<object>`
    color: null,
    // `<font>` and `<hr>`. Use CSS instead
    compact: boolean,
    // Lists. Use CSS to reduce space between items instead
    declare: boolean,
    // `<object>`
    event: null,
    // `<script>`
    face: null,
    // `<font>`. Use CSS instead
    frame: null,
    // `<table>`
    frameBorder: null,
    // `<iframe>`. Use CSS `border` instead
    hSpace: number$3,
    // `<img>` and `<object>`
    leftMargin: number$3,
    // `<body>`
    link: null,
    // `<body>`. Use CSS `a:link {color: *}` instead
    longDesc: null,
    // `<frame>`, `<iframe>`, and `<img>`. Use an `<a>`
    lowSrc: null,
    // `<img>`. Use a `<picture>`
    marginHeight: number$3,
    // `<body>`
    marginWidth: number$3,
    // `<body>`
    noResize: boolean,
    // `<frame>`
    noHref: boolean,
    // `<area>`. Use no href instead of an explicit `nohref`
    noShade: boolean,
    // `<hr>`. Use background-color and height instead of borders
    noWrap: boolean,
    // `<td>` and `<th>`
    object: null,
    // `<applet>`
    profile: null,
    // `<head>`
    prompt: null,
    // `<isindex>`
    rev: null,
    // `<link>`
    rightMargin: number$3,
    // `<body>`
    rules: null,
    // `<table>`
    scheme: null,
    // `<meta>`
    scrolling: booleanish,
    // `<frame>`. Use overflow in the child context
    standby: null,
    // `<object>`
    summary: null,
    // `<table>`
    text: null,
    // `<body>`. Use CSS `color` instead
    topMargin: number$3,
    // `<body>`
    valueType: null,
    // `<param>`
    version: null,
    // `<html>`. Use a doctype.
    vAlign: null,
    // Several. Use CSS `vertical-align` instead
    vLink: null,
    // `<body>`. Use CSS `a:visited {color}` instead
    vSpace: number$3,
    // `<img>` and `<object>`
    // Non-standard Properties.
    allowTransparency: null,
    autoCorrect: null,
    autoSave: null,
    disablePictureInPicture: boolean,
    disableRemotePlayback: boolean,
    prefix: null,
    property: null,
    results: number$3,
    security: null,
    unselectable: null
  },
  space: "html",
  transform: caseInsensitiveTransform
});
const svg$1 = create({
  attributes: {
    accentHeight: "accent-height",
    alignmentBaseline: "alignment-baseline",
    arabicForm: "arabic-form",
    baselineShift: "baseline-shift",
    capHeight: "cap-height",
    className: "class",
    clipPath: "clip-path",
    clipRule: "clip-rule",
    colorInterpolation: "color-interpolation",
    colorInterpolationFilters: "color-interpolation-filters",
    colorProfile: "color-profile",
    colorRendering: "color-rendering",
    crossOrigin: "crossorigin",
    dataType: "datatype",
    dominantBaseline: "dominant-baseline",
    enableBackground: "enable-background",
    fillOpacity: "fill-opacity",
    fillRule: "fill-rule",
    floodColor: "flood-color",
    floodOpacity: "flood-opacity",
    fontFamily: "font-family",
    fontSize: "font-size",
    fontSizeAdjust: "font-size-adjust",
    fontStretch: "font-stretch",
    fontStyle: "font-style",
    fontVariant: "font-variant",
    fontWeight: "font-weight",
    glyphName: "glyph-name",
    glyphOrientationHorizontal: "glyph-orientation-horizontal",
    glyphOrientationVertical: "glyph-orientation-vertical",
    hrefLang: "hreflang",
    horizAdvX: "horiz-adv-x",
    horizOriginX: "horiz-origin-x",
    horizOriginY: "horiz-origin-y",
    imageRendering: "image-rendering",
    letterSpacing: "letter-spacing",
    lightingColor: "lighting-color",
    markerEnd: "marker-end",
    markerMid: "marker-mid",
    markerStart: "marker-start",
    navDown: "nav-down",
    navDownLeft: "nav-down-left",
    navDownRight: "nav-down-right",
    navLeft: "nav-left",
    navNext: "nav-next",
    navPrev: "nav-prev",
    navRight: "nav-right",
    navUp: "nav-up",
    navUpLeft: "nav-up-left",
    navUpRight: "nav-up-right",
    onAbort: "onabort",
    onActivate: "onactivate",
    onAfterPrint: "onafterprint",
    onBeforePrint: "onbeforeprint",
    onBegin: "onbegin",
    onCancel: "oncancel",
    onCanPlay: "oncanplay",
    onCanPlayThrough: "oncanplaythrough",
    onChange: "onchange",
    onClick: "onclick",
    onClose: "onclose",
    onCopy: "oncopy",
    onCueChange: "oncuechange",
    onCut: "oncut",
    onDblClick: "ondblclick",
    onDrag: "ondrag",
    onDragEnd: "ondragend",
    onDragEnter: "ondragenter",
    onDragExit: "ondragexit",
    onDragLeave: "ondragleave",
    onDragOver: "ondragover",
    onDragStart: "ondragstart",
    onDrop: "ondrop",
    onDurationChange: "ondurationchange",
    onEmptied: "onemptied",
    onEnd: "onend",
    onEnded: "onended",
    onError: "onerror",
    onFocus: "onfocus",
    onFocusIn: "onfocusin",
    onFocusOut: "onfocusout",
    onHashChange: "onhashchange",
    onInput: "oninput",
    onInvalid: "oninvalid",
    onKeyDown: "onkeydown",
    onKeyPress: "onkeypress",
    onKeyUp: "onkeyup",
    onLoad: "onload",
    onLoadedData: "onloadeddata",
    onLoadedMetadata: "onloadedmetadata",
    onLoadStart: "onloadstart",
    onMessage: "onmessage",
    onMouseDown: "onmousedown",
    onMouseEnter: "onmouseenter",
    onMouseLeave: "onmouseleave",
    onMouseMove: "onmousemove",
    onMouseOut: "onmouseout",
    onMouseOver: "onmouseover",
    onMouseUp: "onmouseup",
    onMouseWheel: "onmousewheel",
    onOffline: "onoffline",
    onOnline: "ononline",
    onPageHide: "onpagehide",
    onPageShow: "onpageshow",
    onPaste: "onpaste",
    onPause: "onpause",
    onPlay: "onplay",
    onPlaying: "onplaying",
    onPopState: "onpopstate",
    onProgress: "onprogress",
    onRateChange: "onratechange",
    onRepeat: "onrepeat",
    onReset: "onreset",
    onResize: "onresize",
    onScroll: "onscroll",
    onSeeked: "onseeked",
    onSeeking: "onseeking",
    onSelect: "onselect",
    onShow: "onshow",
    onStalled: "onstalled",
    onStorage: "onstorage",
    onSubmit: "onsubmit",
    onSuspend: "onsuspend",
    onTimeUpdate: "ontimeupdate",
    onToggle: "ontoggle",
    onUnload: "onunload",
    onVolumeChange: "onvolumechange",
    onWaiting: "onwaiting",
    onZoom: "onzoom",
    overlinePosition: "overline-position",
    overlineThickness: "overline-thickness",
    paintOrder: "paint-order",
    panose1: "panose-1",
    pointerEvents: "pointer-events",
    referrerPolicy: "referrerpolicy",
    renderingIntent: "rendering-intent",
    shapeRendering: "shape-rendering",
    stopColor: "stop-color",
    stopOpacity: "stop-opacity",
    strikethroughPosition: "strikethrough-position",
    strikethroughThickness: "strikethrough-thickness",
    strokeDashArray: "stroke-dasharray",
    strokeDashOffset: "stroke-dashoffset",
    strokeLineCap: "stroke-linecap",
    strokeLineJoin: "stroke-linejoin",
    strokeMiterLimit: "stroke-miterlimit",
    strokeOpacity: "stroke-opacity",
    strokeWidth: "stroke-width",
    tabIndex: "tabindex",
    textAnchor: "text-anchor",
    textDecoration: "text-decoration",
    textRendering: "text-rendering",
    transformOrigin: "transform-origin",
    typeOf: "typeof",
    underlinePosition: "underline-position",
    underlineThickness: "underline-thickness",
    unicodeBidi: "unicode-bidi",
    unicodeRange: "unicode-range",
    unitsPerEm: "units-per-em",
    vAlphabetic: "v-alphabetic",
    vHanging: "v-hanging",
    vIdeographic: "v-ideographic",
    vMathematical: "v-mathematical",
    vectorEffect: "vector-effect",
    vertAdvY: "vert-adv-y",
    vertOriginX: "vert-origin-x",
    vertOriginY: "vert-origin-y",
    wordSpacing: "word-spacing",
    writingMode: "writing-mode",
    xHeight: "x-height",
    // These were camelcased in Tiny. Now lowercased in SVG 2
    playbackOrder: "playbackorder",
    timelineBegin: "timelinebegin"
  },
  properties: {
    about: commaOrSpaceSeparated,
    accentHeight: number$3,
    accumulate: null,
    additive: null,
    alignmentBaseline: null,
    alphabetic: number$3,
    amplitude: number$3,
    arabicForm: null,
    ascent: number$3,
    attributeName: null,
    attributeType: null,
    azimuth: number$3,
    bandwidth: null,
    baselineShift: null,
    baseFrequency: null,
    baseProfile: null,
    bbox: null,
    begin: null,
    bias: number$3,
    by: null,
    calcMode: null,
    capHeight: number$3,
    className: spaceSeparated,
    clip: null,
    clipPath: null,
    clipPathUnits: null,
    clipRule: null,
    color: null,
    colorInterpolation: null,
    colorInterpolationFilters: null,
    colorProfile: null,
    colorRendering: null,
    content: null,
    contentScriptType: null,
    contentStyleType: null,
    crossOrigin: null,
    cursor: null,
    cx: null,
    cy: null,
    d: null,
    dataType: null,
    defaultAction: null,
    descent: number$3,
    diffuseConstant: number$3,
    direction: null,
    display: null,
    dur: null,
    divisor: number$3,
    dominantBaseline: null,
    download: boolean,
    dx: null,
    dy: null,
    edgeMode: null,
    editable: null,
    elevation: number$3,
    enableBackground: null,
    end: null,
    event: null,
    exponent: number$3,
    externalResourcesRequired: null,
    fill: null,
    fillOpacity: number$3,
    fillRule: null,
    filter: null,
    filterRes: null,
    filterUnits: null,
    floodColor: null,
    floodOpacity: null,
    focusable: null,
    focusHighlight: null,
    fontFamily: null,
    fontSize: null,
    fontSizeAdjust: null,
    fontStretch: null,
    fontStyle: null,
    fontVariant: null,
    fontWeight: null,
    format: null,
    fr: null,
    from: null,
    fx: null,
    fy: null,
    g1: commaSeparated,
    g2: commaSeparated,
    glyphName: commaSeparated,
    glyphOrientationHorizontal: null,
    glyphOrientationVertical: null,
    glyphRef: null,
    gradientTransform: null,
    gradientUnits: null,
    handler: null,
    hanging: number$3,
    hatchContentUnits: null,
    hatchUnits: null,
    height: null,
    href: null,
    hrefLang: null,
    horizAdvX: number$3,
    horizOriginX: number$3,
    horizOriginY: number$3,
    id: null,
    ideographic: number$3,
    imageRendering: null,
    initialVisibility: null,
    in: null,
    in2: null,
    intercept: number$3,
    k: number$3,
    k1: number$3,
    k2: number$3,
    k3: number$3,
    k4: number$3,
    kernelMatrix: commaOrSpaceSeparated,
    kernelUnitLength: null,
    keyPoints: null,
    // SEMI_COLON_SEPARATED
    keySplines: null,
    // SEMI_COLON_SEPARATED
    keyTimes: null,
    // SEMI_COLON_SEPARATED
    kerning: null,
    lang: null,
    lengthAdjust: null,
    letterSpacing: null,
    lightingColor: null,
    limitingConeAngle: number$3,
    local: null,
    markerEnd: null,
    markerMid: null,
    markerStart: null,
    markerHeight: null,
    markerUnits: null,
    markerWidth: null,
    mask: null,
    maskContentUnits: null,
    maskUnits: null,
    mathematical: null,
    max: null,
    media: null,
    mediaCharacterEncoding: null,
    mediaContentEncodings: null,
    mediaSize: number$3,
    mediaTime: null,
    method: null,
    min: null,
    mode: null,
    name: null,
    navDown: null,
    navDownLeft: null,
    navDownRight: null,
    navLeft: null,
    navNext: null,
    navPrev: null,
    navRight: null,
    navUp: null,
    navUpLeft: null,
    navUpRight: null,
    numOctaves: null,
    observer: null,
    offset: null,
    onAbort: null,
    onActivate: null,
    onAfterPrint: null,
    onBeforePrint: null,
    onBegin: null,
    onCancel: null,
    onCanPlay: null,
    onCanPlayThrough: null,
    onChange: null,
    onClick: null,
    onClose: null,
    onCopy: null,
    onCueChange: null,
    onCut: null,
    onDblClick: null,
    onDrag: null,
    onDragEnd: null,
    onDragEnter: null,
    onDragExit: null,
    onDragLeave: null,
    onDragOver: null,
    onDragStart: null,
    onDrop: null,
    onDurationChange: null,
    onEmptied: null,
    onEnd: null,
    onEnded: null,
    onError: null,
    onFocus: null,
    onFocusIn: null,
    onFocusOut: null,
    onHashChange: null,
    onInput: null,
    onInvalid: null,
    onKeyDown: null,
    onKeyPress: null,
    onKeyUp: null,
    onLoad: null,
    onLoadedData: null,
    onLoadedMetadata: null,
    onLoadStart: null,
    onMessage: null,
    onMouseDown: null,
    onMouseEnter: null,
    onMouseLeave: null,
    onMouseMove: null,
    onMouseOut: null,
    onMouseOver: null,
    onMouseUp: null,
    onMouseWheel: null,
    onOffline: null,
    onOnline: null,
    onPageHide: null,
    onPageShow: null,
    onPaste: null,
    onPause: null,
    onPlay: null,
    onPlaying: null,
    onPopState: null,
    onProgress: null,
    onRateChange: null,
    onRepeat: null,
    onReset: null,
    onResize: null,
    onScroll: null,
    onSeeked: null,
    onSeeking: null,
    onSelect: null,
    onShow: null,
    onStalled: null,
    onStorage: null,
    onSubmit: null,
    onSuspend: null,
    onTimeUpdate: null,
    onToggle: null,
    onUnload: null,
    onVolumeChange: null,
    onWaiting: null,
    onZoom: null,
    opacity: null,
    operator: null,
    order: null,
    orient: null,
    orientation: null,
    origin: null,
    overflow: null,
    overlay: null,
    overlinePosition: number$3,
    overlineThickness: number$3,
    paintOrder: null,
    panose1: null,
    path: null,
    pathLength: number$3,
    patternContentUnits: null,
    patternTransform: null,
    patternUnits: null,
    phase: null,
    ping: spaceSeparated,
    pitch: null,
    playbackOrder: null,
    pointerEvents: null,
    points: null,
    pointsAtX: number$3,
    pointsAtY: number$3,
    pointsAtZ: number$3,
    preserveAlpha: null,
    preserveAspectRatio: null,
    primitiveUnits: null,
    propagate: null,
    property: commaOrSpaceSeparated,
    r: null,
    radius: null,
    referrerPolicy: null,
    refX: null,
    refY: null,
    rel: commaOrSpaceSeparated,
    rev: commaOrSpaceSeparated,
    renderingIntent: null,
    repeatCount: null,
    repeatDur: null,
    requiredExtensions: commaOrSpaceSeparated,
    requiredFeatures: commaOrSpaceSeparated,
    requiredFonts: commaOrSpaceSeparated,
    requiredFormats: commaOrSpaceSeparated,
    resource: null,
    restart: null,
    result: null,
    rotate: null,
    rx: null,
    ry: null,
    scale: null,
    seed: null,
    shapeRendering: null,
    side: null,
    slope: null,
    snapshotTime: null,
    specularConstant: number$3,
    specularExponent: number$3,
    spreadMethod: null,
    spacing: null,
    startOffset: null,
    stdDeviation: null,
    stemh: null,
    stemv: null,
    stitchTiles: null,
    stopColor: null,
    stopOpacity: null,
    strikethroughPosition: number$3,
    strikethroughThickness: number$3,
    string: null,
    stroke: null,
    strokeDashArray: commaOrSpaceSeparated,
    strokeDashOffset: null,
    strokeLineCap: null,
    strokeLineJoin: null,
    strokeMiterLimit: number$3,
    strokeOpacity: number$3,
    strokeWidth: null,
    style: null,
    surfaceScale: number$3,
    syncBehavior: null,
    syncBehaviorDefault: null,
    syncMaster: null,
    syncTolerance: null,
    syncToleranceDefault: null,
    systemLanguage: commaOrSpaceSeparated,
    tabIndex: number$3,
    tableValues: null,
    target: null,
    targetX: number$3,
    targetY: number$3,
    textAnchor: null,
    textDecoration: null,
    textRendering: null,
    textLength: null,
    timelineBegin: null,
    title: null,
    transformBehavior: null,
    type: null,
    typeOf: commaOrSpaceSeparated,
    to: null,
    transform: null,
    transformOrigin: null,
    u1: null,
    u2: null,
    underlinePosition: number$3,
    underlineThickness: number$3,
    unicode: null,
    unicodeBidi: null,
    unicodeRange: null,
    unitsPerEm: number$3,
    values: null,
    vAlphabetic: number$3,
    vMathematical: number$3,
    vectorEffect: null,
    vHanging: number$3,
    vIdeographic: number$3,
    version: null,
    vertAdvY: number$3,
    vertOriginX: number$3,
    vertOriginY: number$3,
    viewBox: null,
    viewTarget: null,
    visibility: null,
    width: null,
    widths: null,
    wordSpacing: null,
    writingMode: null,
    x: null,
    x1: null,
    x2: null,
    xChannelSelector: null,
    xHeight: number$3,
    y: null,
    y1: null,
    y2: null,
    yChannelSelector: null,
    z: null,
    zoomAndPan: null
  },
  space: "svg",
  transform: caseSensitiveTransform
});
const xlink = create({
  properties: {
    xLinkActuate: null,
    xLinkArcRole: null,
    xLinkHref: null,
    xLinkRole: null,
    xLinkShow: null,
    xLinkTitle: null,
    xLinkType: null
  },
  space: "xlink",
  transform(_2, property) {
    return "xlink:" + property.slice(5).toLowerCase();
  }
});
const xmlns = create({
  attributes: { xmlnsxlink: "xmlns:xlink" },
  properties: { xmlnsXLink: null, xmlns: null },
  space: "xmlns",
  transform: caseInsensitiveTransform
});
const xml = create({
  properties: { xmlBase: null, xmlLang: null, xmlSpace: null },
  space: "xml",
  transform(_2, property) {
    return "xml:" + property.slice(3).toLowerCase();
  }
});
const hastToReact = {
  classId: "classID",
  dataType: "datatype",
  itemId: "itemID",
  strokeDashArray: "strokeDasharray",
  strokeDashOffset: "strokeDashoffset",
  strokeLineCap: "strokeLinecap",
  strokeLineJoin: "strokeLinejoin",
  strokeMiterLimit: "strokeMiterlimit",
  typeOf: "typeof",
  xLinkActuate: "xlinkActuate",
  xLinkArcRole: "xlinkArcrole",
  xLinkHref: "xlinkHref",
  xLinkRole: "xlinkRole",
  xLinkShow: "xlinkShow",
  xLinkTitle: "xlinkTitle",
  xLinkType: "xlinkType",
  xmlnsXLink: "xmlnsXlink"
};
const cap$1 = /[A-Z]/g;
const dash = /-[a-z]/g;
const valid = /^data[-\w.:]+$/i;
function find(schema, value) {
  const normal = normalize(value);
  let property = value;
  let Type = Info;
  if (normal in schema.normal) {
    return schema.property[schema.normal[normal]];
  }
  if (normal.length > 4 && normal.slice(0, 4) === "data" && valid.test(value)) {
    if (value.charAt(4) === "-") {
      const rest = value.slice(5).replace(dash, camelcase);
      property = "data" + rest.charAt(0).toUpperCase() + rest.slice(1);
    } else {
      const rest = value.slice(4);
      if (!dash.test(rest)) {
        let dashes = rest.replace(cap$1, kebab);
        if (dashes.charAt(0) !== "-") {
          dashes = "-" + dashes;
        }
        value = "data" + dashes;
      }
    }
    Type = DefinedInfo;
  }
  return new Type(property, value);
}
function kebab($0) {
  return "-" + $0.toLowerCase();
}
function camelcase($0) {
  return $0.charAt(1).toUpperCase();
}
const html$1 = merge([aria, html$2, xlink, xmlns, xml], "html");
const svg = merge([aria, svg$1, xlink, xmlns, xml], "svg");
function stringify(values) {
  return values.join(" ").trim();
}
var cjs$2 = {};
var cjs$1;
var hasRequiredCjs$2;
function requireCjs$2() {
  if (hasRequiredCjs$2) return cjs$1;
  hasRequiredCjs$2 = 1;
  var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g;
  var NEWLINE_REGEX = /\n/g;
  var WHITESPACE_REGEX = /^\s*/;
  var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/;
  var COLON_REGEX = /^:\s*/;
  var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/;
  var SEMICOLON_REGEX = /^[;\s]*/;
  var TRIM_REGEX = /^\s+|\s+$/g;
  var NEWLINE = "\n";
  var FORWARD_SLASH = "/";
  var ASTERISK = "*";
  var EMPTY_STRING = "";
  var TYPE_COMMENT = "comment";
  var TYPE_DECLARATION = "declaration";
  function index2(style, options) {
    if (typeof style !== "string") {
      throw new TypeError("First argument must be a string");
    }
    if (!style) return [];
    options = options || {};
    var lineno = 1;
    var column = 1;
    function updatePosition(str) {
      var lines = str.match(NEWLINE_REGEX);
      if (lines) lineno += lines.length;
      var i = str.lastIndexOf(NEWLINE);
      column = ~i ? str.length - i : column + str.length;
    }
    function position2() {
      var start = { line: lineno, column };
      return function(node2) {
        node2.position = new Position(start);
        whitespace2();
        return node2;
      };
    }
    function Position(start) {
      this.start = start;
      this.end = { line: lineno, column };
      this.source = options.source;
    }
    Position.prototype.content = style;
    function error(msg) {
      var err = new Error(
        options.source + ":" + lineno + ":" + column + ": " + msg
      );
      err.reason = msg;
      err.filename = options.source;
      err.line = lineno;
      err.column = column;
      err.source = style;
      if (options.silent) ;
      else {
        throw err;
      }
    }
    function match(re2) {
      var m2 = re2.exec(style);
      if (!m2) return;
      var str = m2[0];
      updatePosition(str);
      style = style.slice(str.length);
      return m2;
    }
    function whitespace2() {
      match(WHITESPACE_REGEX);
    }
    function comments(rules) {
      var c;
      rules = rules || [];
      while (c = comment()) {
        if (c !== false) {
          rules.push(c);
        }
      }
      return rules;
    }
    function comment() {
      var pos = position2();
      if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;
      var i = 2;
      while (EMPTY_STRING != style.charAt(i) && (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))) {
        ++i;
      }
      i += 2;
      if (EMPTY_STRING === style.charAt(i - 1)) {
        return error("End of comment missing");
      }
      var str = style.slice(2, i - 2);
      column += 2;
      updatePosition(str);
      style = style.slice(i);
      column += 2;
      return pos({
        type: TYPE_COMMENT,
        comment: str
      });
    }
    function declaration() {
      var pos = position2();
      var prop = match(PROPERTY_REGEX);
      if (!prop) return;
      comment();
      if (!match(COLON_REGEX)) return error("property missing ':'");
      var val = match(VALUE_REGEX);
      var ret = pos({
        type: TYPE_DECLARATION,
        property: trim2(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),
        value: val ? trim2(val[0].replace(COMMENT_REGEX, EMPTY_STRING)) : EMPTY_STRING
      });
      match(SEMICOLON_REGEX);
      return ret;
    }
    function declarations() {
      var decls = [];
      comments(decls);
      var decl;
      while (decl = declaration()) {
        if (decl !== false) {
          decls.push(decl);
          comments(decls);
        }
      }
      return decls;
    }
    whitespace2();
    return declarations();
  }
  function trim2(str) {
    return str ? str.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING;
  }
  cjs$1 = index2;
  return cjs$1;
}
var hasRequiredCjs$1;
function requireCjs$1() {
  if (hasRequiredCjs$1) return cjs$2;
  hasRequiredCjs$1 = 1;
  var __importDefault = cjs$2 && cjs$2.__importDefault || function(mod) {
    return mod && mod.__esModule ? mod : { "default": mod };
  };
  Object.defineProperty(cjs$2, "__esModule", { value: true });
  cjs$2.default = StyleToObject;
  const inline_style_parser_1 = __importDefault(requireCjs$2());
  function StyleToObject(style, iterator2) {
    let styleObject = null;
    if (!style || typeof style !== "string") {
      return styleObject;
    }
    const declarations = (0, inline_style_parser_1.default)(style);
    const hasIterator = typeof iterator2 === "function";
    declarations.forEach((declaration) => {
      if (declaration.type !== "declaration") {
        return;
      }
      const { property, value } = declaration;
      if (hasIterator) {
        iterator2(property, value, declaration);
      } else if (value) {
        styleObject = styleObject || {};
        styleObject[property] = value;
      }
    });
    return styleObject;
  }
  return cjs$2;
}
var utilities = {};
var hasRequiredUtilities;
function requireUtilities() {
  if (hasRequiredUtilities) return utilities;
  hasRequiredUtilities = 1;
  Object.defineProperty(utilities, "__esModule", { value: true });
  utilities.camelCase = void 0;
  var CUSTOM_PROPERTY_REGEX = /^--[a-zA-Z0-9_-]+$/;
  var HYPHEN_REGEX = /-([a-z])/g;
  var NO_HYPHEN_REGEX = /^[^-]+$/;
  var VENDOR_PREFIX_REGEX = /^-(webkit|moz|ms|o|khtml)-/;
  var MS_VENDOR_PREFIX_REGEX = /^-(ms)-/;
  var skipCamelCase = function(property) {
    return !property || NO_HYPHEN_REGEX.test(property) || CUSTOM_PROPERTY_REGEX.test(property);
  };
  var capitalize = function(match, character) {
    return character.toUpperCase();
  };
  var trimHyphen = function(match, prefix) {
    return "".concat(prefix, "-");
  };
  var camelCase = function(property, options) {
    if (options === void 0) {
      options = {};
    }
    if (skipCamelCase(property)) {
      return property;
    }
    property = property.toLowerCase();
    if (options.reactCompat) {
      property = property.replace(MS_VENDOR_PREFIX_REGEX, trimHyphen);
    } else {
      property = property.replace(VENDOR_PREFIX_REGEX, trimHyphen);
    }
    return property.replace(HYPHEN_REGEX, capitalize);
  };
  utilities.camelCase = camelCase;
  return utilities;
}
var cjs;
var hasRequiredCjs;
function requireCjs() {
  if (hasRequiredCjs) return cjs;
  hasRequiredCjs = 1;
  var __importDefault = cjs && cjs.__importDefault || function(mod) {
    return mod && mod.__esModule ? mod : { "default": mod };
  };
  var style_to_object_1 = __importDefault(requireCjs$1());
  var utilities_1 = requireUtilities();
  function StyleToJS(style, options) {
    var output = {};
    if (!style || typeof style !== "string") {
      return output;
    }
    (0, style_to_object_1.default)(style, function(property, value) {
      if (property && value) {
        output[(0, utilities_1.camelCase)(property, options)] = value;
      }
    });
    return output;
  }
  StyleToJS.default = StyleToJS;
  cjs = StyleToJS;
  return cjs;
}
var cjsExports = requireCjs();
const styleToJs = /* @__PURE__ */ getDefaultExportFromCjs(cjsExports);
const pointEnd = point$2("end");
const pointStart = point$2("start");
function point$2(type2) {
  return point2;
  function point2(node2) {
    const point3 = node2 && node2.position && node2.position[type2] || {};
    if (typeof point3.line === "number" && point3.line > 0 && typeof point3.column === "number" && point3.column > 0) {
      return {
        line: point3.line,
        column: point3.column,
        offset: typeof point3.offset === "number" && point3.offset > -1 ? point3.offset : void 0
      };
    }
  }
}
function position$1(node2) {
  const start = pointStart(node2);
  const end = pointEnd(node2);
  if (start && end) {
    return { start, end };
  }
}
function stringifyPosition(value) {
  if (!value || typeof value !== "object") {
    return "";
  }
  if ("position" in value || "type" in value) {
    return position(value.position);
  }
  if ("start" in value || "end" in value) {
    return position(value);
  }
  if ("line" in value || "column" in value) {
    return point$1(value);
  }
  return "";
}
function point$1(point2) {
  return index(point2 && point2.line) + ":" + index(point2 && point2.column);
}
function position(pos) {
  return point$1(pos && pos.start) + "-" + point$1(pos && pos.end);
}
function index(value) {
  return value && typeof value === "number" ? value : 1;
}
class VFileMessage extends Error {
  /**
   * Create a message for `reason`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {Options | null | undefined} [options]
   * @returns
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | Options | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns
   *   Instance of `VFileMessage`.
   */
  // eslint-disable-next-line complexity
  constructor(causeOrReason, optionsOrParentOrPlace, origin2) {
    super();
    if (typeof optionsOrParentOrPlace === "string") {
      origin2 = optionsOrParentOrPlace;
      optionsOrParentOrPlace = void 0;
    }
    let reason = "";
    let options = {};
    let legacyCause = false;
    if (optionsOrParentOrPlace) {
      if ("line" in optionsOrParentOrPlace && "column" in optionsOrParentOrPlace) {
        options = { place: optionsOrParentOrPlace };
      } else if ("start" in optionsOrParentOrPlace && "end" in optionsOrParentOrPlace) {
        options = { place: optionsOrParentOrPlace };
      } else if ("type" in optionsOrParentOrPlace) {
        options = {
          ancestors: [optionsOrParentOrPlace],
          place: optionsOrParentOrPlace.position
        };
      } else {
        options = { ...optionsOrParentOrPlace };
      }
    }
    if (typeof causeOrReason === "string") {
      reason = causeOrReason;
    } else if (!options.cause && causeOrReason) {
      legacyCause = true;
      reason = causeOrReason.message;
      options.cause = causeOrReason;
    }
    if (!options.ruleId && !options.source && typeof origin2 === "string") {
      const index2 = origin2.indexOf(":");
      if (index2 === -1) {
        options.ruleId = origin2;
      } else {
        options.source = origin2.slice(0, index2);
        options.ruleId = origin2.slice(index2 + 1);
      }
    }
    if (!options.place && options.ancestors && options.ancestors) {
      const parent = options.ancestors[options.ancestors.length - 1];
      if (parent) {
        options.place = parent.position;
      }
    }
    const start = options.place && "start" in options.place ? options.place.start : options.place;
    this.ancestors = options.ancestors || void 0;
    this.cause = options.cause || void 0;
    this.column = start ? start.column : void 0;
    this.fatal = void 0;
    this.file = "";
    this.message = reason;
    this.line = start ? start.line : void 0;
    this.name = stringifyPosition(options.place) || "1:1";
    this.place = options.place || void 0;
    this.reason = this.message;
    this.ruleId = options.ruleId || void 0;
    this.source = options.source || void 0;
    this.stack = legacyCause && options.cause && typeof options.cause.stack === "string" ? options.cause.stack : "";
    this.actual = void 0;
    this.expected = void 0;
    this.note = void 0;
    this.url = void 0;
  }
}
VFileMessage.prototype.file = "";
VFileMessage.prototype.name = "";
VFileMessage.prototype.reason = "";
VFileMessage.prototype.message = "";
VFileMessage.prototype.stack = "";
VFileMessage.prototype.column = void 0;
VFileMessage.prototype.line = void 0;
VFileMessage.prototype.ancestors = void 0;
VFileMessage.prototype.cause = void 0;
VFileMessage.prototype.fatal = void 0;
VFileMessage.prototype.place = void 0;
VFileMessage.prototype.ruleId = void 0;
VFileMessage.prototype.source = void 0;
const own$4 = {}.hasOwnProperty;
const emptyMap = /* @__PURE__ */ new Map();
const cap = /[A-Z]/g;
const tableElements = /* @__PURE__ */ new Set(["table", "tbody", "thead", "tfoot", "tr"]);
const tableCellElement = /* @__PURE__ */ new Set(["td", "th"]);
const docs = "https://github.com/syntax-tree/hast-util-to-jsx-runtime";
function toJsxRuntime(tree, options) {
  if (!options || options.Fragment === void 0) {
    throw new TypeError("Expected `Fragment` in options");
  }
  const filePath = options.filePath || void 0;
  let create2;
  if (options.development) {
    if (typeof options.jsxDEV !== "function") {
      throw new TypeError(
        "Expected `jsxDEV` in options when `development: true`"
      );
    }
    create2 = developmentCreate(filePath, options.jsxDEV);
  } else {
    if (typeof options.jsx !== "function") {
      throw new TypeError("Expected `jsx` in production options");
    }
    if (typeof options.jsxs !== "function") {
      throw new TypeError("Expected `jsxs` in production options");
    }
    create2 = productionCreate(filePath, options.jsx, options.jsxs);
  }
  const state = {
    Fragment: options.Fragment,
    ancestors: [],
    components: options.components || {},
    create: create2,
    elementAttributeNameCase: options.elementAttributeNameCase || "react",
    evaluater: options.createEvaluater ? options.createEvaluater() : void 0,
    filePath,
    ignoreInvalidStyle: options.ignoreInvalidStyle || false,
    passKeys: options.passKeys !== false,
    passNode: options.passNode || false,
    schema: options.space === "svg" ? svg : html$1,
    stylePropertyNameCase: options.stylePropertyNameCase || "dom",
    tableCellAlignToStyle: options.tableCellAlignToStyle !== false
  };
  const result = one$1(state, tree, void 0);
  if (result && typeof result !== "string") {
    return result;
  }
  return state.create(
    tree,
    state.Fragment,
    { children: result || void 0 },
    void 0
  );
}
function one$1(state, node2, key) {
  if (node2.type === "element") {
    return element(state, node2, key);
  }
  if (node2.type === "mdxFlowExpression" || node2.type === "mdxTextExpression") {
    return mdxExpression(state, node2);
  }
  if (node2.type === "mdxJsxFlowElement" || node2.type === "mdxJsxTextElement") {
    return mdxJsxElement(state, node2, key);
  }
  if (node2.type === "mdxjsEsm") {
    return mdxEsm(state, node2);
  }
  if (node2.type === "root") {
    return root$1(state, node2, key);
  }
  if (node2.type === "text") {
    return text$3(state, node2);
  }
}
function element(state, node2, key) {
  const parentSchema = state.schema;
  let schema = parentSchema;
  if (node2.tagName.toLowerCase() === "svg" && parentSchema.space === "html") {
    schema = svg;
    state.schema = schema;
  }
  state.ancestors.push(node2);
  const type2 = findComponentFromName(state, node2.tagName, false);
  const props = createElementProps(state, node2);
  let children = createChildren(state, node2);
  if (tableElements.has(node2.tagName)) {
    children = children.filter(function(child) {
      return typeof child === "string" ? !whitespace(child) : true;
    });
  }
  addNode(state, props, type2, node2);
  addChildren(props, children);
  state.ancestors.pop();
  state.schema = parentSchema;
  return state.create(node2, type2, props, key);
}
function mdxExpression(state, node2) {
  if (node2.data && node2.data.estree && state.evaluater) {
    const program = node2.data.estree;
    const expression = program.body[0];
    ok$1(expression.type === "ExpressionStatement");
    return (
      /** @type {Child | undefined} */
      state.evaluater.evaluateExpression(expression.expression)
    );
  }
  crashEstree(state, node2.position);
}
function mdxEsm(state, node2) {
  if (node2.data && node2.data.estree && state.evaluater) {
    return (
      /** @type {Child | undefined} */
      state.evaluater.evaluateProgram(node2.data.estree)
    );
  }
  crashEstree(state, node2.position);
}
function mdxJsxElement(state, node2, key) {
  const parentSchema = state.schema;
  let schema = parentSchema;
  if (node2.name === "svg" && parentSchema.space === "html") {
    schema = svg;
    state.schema = schema;
  }
  state.ancestors.push(node2);
  const type2 = node2.name === null ? state.Fragment : findComponentFromName(state, node2.name, true);
  const props = createJsxElementProps(state, node2);
  const children = createChildren(state, node2);
  addNode(state, props, type2, node2);
  addChildren(props, children);
  state.ancestors.pop();
  state.schema = parentSchema;
  return state.create(node2, type2, props, key);
}
function root$1(state, node2, key) {
  const props = {};
  addChildren(props, createChildren(state, node2));
  return state.create(node2, state.Fragment, props, key);
}
function text$3(_2, node2) {
  return node2.value;
}
function addNode(state, props, type2, node2) {
  if (typeof type2 !== "string" && type2 !== state.Fragment && state.passNode) {
    props.node = node2;
  }
}
function addChildren(props, children) {
  if (children.length > 0) {
    const value = children.length > 1 ? children : children[0];
    if (value) {
      props.children = value;
    }
  }
}
function productionCreate(_2, jsx, jsxs) {
  return create2;
  function create2(_3, type2, props, key) {
    const isStaticChildren = Array.isArray(props.children);
    const fn = isStaticChildren ? jsxs : jsx;
    return key ? fn(type2, props, key) : fn(type2, props);
  }
}
function developmentCreate(filePath, jsxDEV) {
  return create2;
  function create2(node2, type2, props, key) {
    const isStaticChildren = Array.isArray(props.children);
    const point2 = pointStart(node2);
    return jsxDEV(
      type2,
      props,
      key,
      isStaticChildren,
      {
        columnNumber: point2 ? point2.column - 1 : void 0,
        fileName: filePath,
        lineNumber: point2 ? point2.line : void 0
      },
      void 0
    );
  }
}
function createElementProps(state, node2) {
  const props = {};
  let alignValue;
  let prop;
  for (prop in node2.properties) {
    if (prop !== "children" && own$4.call(node2.properties, prop)) {
      const result = createProperty(state, prop, node2.properties[prop]);
      if (result) {
        const [key, value] = result;
        if (state.tableCellAlignToStyle && key === "align" && typeof value === "string" && tableCellElement.has(node2.tagName)) {
          alignValue = value;
        } else {
          props[key] = value;
        }
      }
    }
  }
  if (alignValue) {
    const style = (
      /** @type {Style} */
      props.style || (props.style = {})
    );
    style[state.stylePropertyNameCase === "css" ? "text-align" : "textAlign"] = alignValue;
  }
  return props;
}
function createJsxElementProps(state, node2) {
  const props = {};
  for (const attribute of node2.attributes) {
    if (attribute.type === "mdxJsxExpressionAttribute") {
      if (attribute.data && attribute.data.estree && state.evaluater) {
        const program = attribute.data.estree;
        const expression = program.body[0];
        ok$1(expression.type === "ExpressionStatement");
        const objectExpression = expression.expression;
        ok$1(objectExpression.type === "ObjectExpression");
        const property = objectExpression.properties[0];
        ok$1(property.type === "SpreadElement");
        Object.assign(
          props,
          state.evaluater.evaluateExpression(property.argument)
        );
      } else {
        crashEstree(state, node2.position);
      }
    } else {
      const name2 = attribute.name;
      let value;
      if (attribute.value && typeof attribute.value === "object") {
        if (attribute.value.data && attribute.value.data.estree && state.evaluater) {
          const program = attribute.value.data.estree;
          const expression = program.body[0];
          ok$1(expression.type === "ExpressionStatement");
          value = state.evaluater.evaluateExpression(expression.expression);
        } else {
          crashEstree(state, node2.position);
        }
      } else {
        value = attribute.value === null ? true : attribute.value;
      }
      props[name2] = /** @type {Props[keyof Props]} */
      value;
    }
  }
  return props;
}
function createChildren(state, node2) {
  const children = [];
  let index2 = -1;
  const countsByName = state.passKeys ? /* @__PURE__ */ new Map() : emptyMap;
  while (++index2 < node2.children.length) {
    const child = node2.children[index2];
    let key;
    if (state.passKeys) {
      const name2 = child.type === "element" ? child.tagName : child.type === "mdxJsxFlowElement" || child.type === "mdxJsxTextElement" ? child.name : void 0;
      if (name2) {
        const count = countsByName.get(name2) || 0;
        key = name2 + "-" + count;
        countsByName.set(name2, count + 1);
      }
    }
    const result = one$1(state, child, key);
    if (result !== void 0) children.push(result);
  }
  return children;
}
function createProperty(state, prop, value) {
  const info = find(state.schema, prop);
  if (value === null || value === void 0 || typeof value === "number" && Number.isNaN(value)) {
    return;
  }
  if (Array.isArray(value)) {
    value = info.commaSeparated ? stringify$1(value) : stringify(value);
  }
  if (info.property === "style") {
    let styleObject = typeof value === "object" ? value : parseStyle(state, String(value));
    if (state.stylePropertyNameCase === "css") {
      styleObject = transformStylesToCssCasing(styleObject);
    }
    return ["style", styleObject];
  }
  return [
    state.elementAttributeNameCase === "react" && info.space ? hastToReact[info.property] || info.property : info.attribute,
    value
  ];
}
function parseStyle(state, value) {
  try {
    return styleToJs(value, { reactCompat: true });
  } catch (error) {
    if (state.ignoreInvalidStyle) {
      return {};
    }
    const cause = (
      /** @type {Error} */
      error
    );
    const message = new VFileMessage("Cannot parse `style` attribute", {
      ancestors: state.ancestors,
      cause,
      ruleId: "style",
      source: "hast-util-to-jsx-runtime"
    });
    message.file = state.filePath || void 0;
    message.url = docs + "#cannot-parse-style-attribute";
    throw message;
  }
}
function findComponentFromName(state, name$1, allowExpression) {
  let result;
  if (!allowExpression) {
    result = { type: "Literal", value: name$1 };
  } else if (name$1.includes(".")) {
    const identifiers = name$1.split(".");
    let index2 = -1;
    let node2;
    while (++index2 < identifiers.length) {
      const prop = name(identifiers[index2]) ? { type: "Identifier", name: identifiers[index2] } : { type: "Literal", value: identifiers[index2] };
      node2 = node2 ? {
        type: "MemberExpression",
        object: node2,
        property: prop,
        computed: Boolean(index2 && prop.type === "Literal"),
        optional: false
      } : prop;
    }
    result = node2;
  } else {
    result = name(name$1) && !/^[a-z]/.test(name$1) ? { type: "Identifier", name: name$1 } : { type: "Literal", value: name$1 };
  }
  if (result.type === "Literal") {
    const name2 = (
      /** @type {string | number} */
      result.value
    );
    return own$4.call(state.components, name2) ? state.components[name2] : name2;
  }
  if (state.evaluater) {
    return state.evaluater.evaluateExpression(result);
  }
  crashEstree(state);
}
function crashEstree(state, place) {
  const message = new VFileMessage(
    "Cannot handle MDX estrees without `createEvaluater`",
    {
      ancestors: state.ancestors,
      place,
      ruleId: "mdx-estree",
      source: "hast-util-to-jsx-runtime"
    }
  );
  message.file = state.filePath || void 0;
  message.url = docs + "#cannot-handle-mdx-estrees-without-createevaluater";
  throw message;
}
function transformStylesToCssCasing(domCasing) {
  const cssCasing = {};
  let from;
  for (from in domCasing) {
    if (own$4.call(domCasing, from)) {
      cssCasing[transformStyleToCssCasing(from)] = domCasing[from];
    }
  }
  return cssCasing;
}
function transformStyleToCssCasing(from) {
  let to = from.replace(cap, toDash);
  if (to.slice(0, 3) === "ms-") to = "-" + to;
  return to;
}
function toDash($0) {
  return "-" + $0.toLowerCase();
}
const urlAttributes = {
  action: ["form"],
  cite: ["blockquote", "del", "ins", "q"],
  data: ["object"],
  formAction: ["button", "input"],
  href: ["a", "area", "base", "link"],
  icon: ["menuitem"],
  itemId: null,
  manifest: ["html"],
  ping: ["a", "area"],
  poster: ["video"],
  src: [
    "audio",
    "embed",
    "iframe",
    "img",
    "input",
    "script",
    "source",
    "track",
    "video"
  ]
};
const emptyOptions$1 = {};
function toString$1(value, options) {
  const settings = emptyOptions$1;
  const includeImageAlt = typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true;
  const includeHtml = typeof settings.includeHtml === "boolean" ? settings.includeHtml : true;
  return one(value, includeImageAlt, includeHtml);
}
function one(value, includeImageAlt, includeHtml) {
  if (node(value)) {
    if ("value" in value) {
      return value.type === "html" && !includeHtml ? "" : value.value;
    }
    if (includeImageAlt && "alt" in value && value.alt) {
      return value.alt;
    }
    if ("children" in value) {
      return all2(value.children, includeImageAlt, includeHtml);
    }
  }
  if (Array.isArray(value)) {
    return all2(value, includeImageAlt, includeHtml);
  }
  return "";
}
function all2(values, includeImageAlt, includeHtml) {
  const result = [];
  let index2 = -1;
  while (++index2 < values.length) {
    result[index2] = one(values[index2], includeImageAlt, includeHtml);
  }
  return result.join("");
}
function node(value) {
  return Boolean(value && typeof value === "object");
}
const characterEntities = {
  AElig: "Æ",
  AMP: "&",
  Aacute: "Á",
  Abreve: "Ă",
  Acirc: "Â",
  Acy: "А",
  Afr: "𝔄",
  Agrave: "À",
  Alpha: "Α",
  Amacr: "Ā",
  And: "⩓",
  Aogon: "Ą",
  Aopf: "𝔸",
  ApplyFunction: "⁡",
  Aring: "Å",
  Ascr: "𝒜",
  Assign: "≔",
  Atilde: "Ã",
  Auml: "Ä",
  Backslash: "∖",
  Barv: "⫧",
  Barwed: "⌆",
  Bcy: "Б",
  Because: "∵",
  Bernoullis: "ℬ",
  Beta: "Β",
  Bfr: "𝔅",
  Bopf: "𝔹",
  Breve: "˘",
  Bscr: "ℬ",
  Bumpeq: "≎",
  CHcy: "Ч",
  COPY: "©",
  Cacute: "Ć",
  Cap: "⋒",
  CapitalDifferentialD: "ⅅ",
  Cayleys: "ℭ",
  Ccaron: "Č",
  Ccedil: "Ç",
  Ccirc: "Ĉ",
  Cconint: "∰",
  Cdot: "Ċ",
  Cedilla: "¸",
  CenterDot: "·",
  Cfr: "ℭ",
  Chi: "Χ",
  CircleDot: "⊙",
  CircleMinus: "⊖",
  CirclePlus: "⊕",
  CircleTimes: "⊗",
  ClockwiseContourIntegral: "∲",
  CloseCurlyDoubleQuote: "”",
  CloseCurlyQuote: "’",
  Colon: "∷",
  Colone: "⩴",
  Congruent: "≡",
  Conint: "∯",
  ContourIntegral: "∮",
  Copf: "ℂ",
  Coproduct: "∐",
  CounterClockwiseContourIntegral: "∳",
  Cross: "⨯",
  Cscr: "𝒞",
  Cup: "⋓",
  CupCap: "≍",
  DD: "ⅅ",
  DDotrahd: "⤑",
  DJcy: "Ђ",
  DScy: "Ѕ",
  DZcy: "Џ",
  Dagger: "‡",
  Darr: "↡",
  Dashv: "⫤",
  Dcaron: "Ď",
  Dcy: "Д",
  Del: "∇",
  Delta: "Δ",
  Dfr: "𝔇",
  DiacriticalAcute: "´",
  DiacriticalDot: "˙",
  DiacriticalDoubleAcute: "˝",
  DiacriticalGrave: "`",
  DiacriticalTilde: "˜",
  Diamond: "⋄",
  DifferentialD: "ⅆ",
  Dopf: "𝔻",
  Dot: "¨",
  DotDot: "⃜",
  DotEqual: "≐",
  DoubleContourIntegral: "∯",
  DoubleDot: "¨",
  DoubleDownArrow: "⇓",
  DoubleLeftArrow: "⇐",
  DoubleLeftRightArrow: "⇔",
  DoubleLeftTee: "⫤",
  DoubleLongLeftArrow: "⟸",
  DoubleLongLeftRightArrow: "⟺",
  DoubleLongRightArrow: "⟹",
  DoubleRightArrow: "⇒",
  DoubleRightTee: "⊨",
  DoubleUpArrow: "⇑",
  DoubleUpDownArrow: "⇕",
  DoubleVerticalBar: "∥",
  DownArrow: "↓",
  DownArrowBar: "⤓",
  DownArrowUpArrow: "⇵",
  DownBreve: "̑",
  DownLeftRightVector: "⥐",
  DownLeftTeeVector: "⥞",
  DownLeftVector: "↽",
  DownLeftVectorBar: "⥖",
  DownRightTeeVector: "⥟",
  DownRightVector: "⇁",
  DownRightVectorBar: "⥗",
  DownTee: "⊤",
  DownTeeArrow: "↧",
  Downarrow: "⇓",
  Dscr: "𝒟",
  Dstrok: "Đ",
  ENG: "Ŋ",
  ETH: "Ð",
  Eacute: "É",
  Ecaron: "Ě",
  Ecirc: "Ê",
  Ecy: "Э",
  Edot: "Ė",
  Efr: "𝔈",
  Egrave: "È",
  Element: "∈",
  Emacr: "Ē",
  EmptySmallSquare: "◻",
  EmptyVerySmallSquare: "▫",
  Eogon: "Ę",
  Eopf: "𝔼",
  Epsilon: "Ε",
  Equal: "⩵",
  EqualTilde: "≂",
  Equilibrium: "⇌",
  Escr: "ℰ",
  Esim: "⩳",
  Eta: "Η",
  Euml: "Ë",
  Exists: "∃",
  ExponentialE: "ⅇ",
  Fcy: "Ф",
  Ffr: "𝔉",
  FilledSmallSquare: "◼",
  FilledVerySmallSquare: "▪",
  Fopf: "𝔽",
  ForAll: "∀",
  Fouriertrf: "ℱ",
  Fscr: "ℱ",
  GJcy: "Ѓ",
  GT: ">",
  Gamma: "Γ",
  Gammad: "Ϝ",
  Gbreve: "Ğ",
  Gcedil: "Ģ",
  Gcirc: "Ĝ",
  Gcy: "Г",
  Gdot: "Ġ",
  Gfr: "𝔊",
  Gg: "⋙",
  Gopf: "𝔾",
  GreaterEqual: "≥",
  GreaterEqualLess: "⋛",
  GreaterFullEqual: "≧",
  GreaterGreater: "⪢",
  GreaterLess: "≷",
  GreaterSlantEqual: "⩾",
  GreaterTilde: "≳",
  Gscr: "𝒢",
  Gt: "≫",
  HARDcy: "Ъ",
  Hacek: "ˇ",
  Hat: "^",
  Hcirc: "Ĥ",
  Hfr: "ℌ",
  HilbertSpace: "ℋ",
  Hopf: "ℍ",
  HorizontalLine: "─",
  Hscr: "ℋ",
  Hstrok: "Ħ",
  HumpDownHump: "≎",
  HumpEqual: "≏",
  IEcy: "Е",
  IJlig: "Ĳ",
  IOcy: "Ё",
  Iacute: "Í",
  Icirc: "Î",
  Icy: "И",
  Idot: "İ",
  Ifr: "ℑ",
  Igrave: "Ì",
  Im: "ℑ",
  Imacr: "Ī",
  ImaginaryI: "ⅈ",
  Implies: "⇒",
  Int: "∬",
  Integral: "∫",
  Intersection: "⋂",
  InvisibleComma: "⁣",
  InvisibleTimes: "⁢",
  Iogon: "Į",
  Iopf: "𝕀",
  Iota: "Ι",
  Iscr: "ℐ",
  Itilde: "Ĩ",
  Iukcy: "І",
  Iuml: "Ï",
  Jcirc: "Ĵ",
  Jcy: "Й",
  Jfr: "𝔍",
  Jopf: "𝕁",
  Jscr: "𝒥",
  Jsercy: "Ј",
  Jukcy: "Є",
  KHcy: "Х",
  KJcy: "Ќ",
  Kappa: "Κ",
  Kcedil: "Ķ",
  Kcy: "К",
  Kfr: "𝔎",
  Kopf: "𝕂",
  Kscr: "𝒦",
  LJcy: "Љ",
  LT: "<",
  Lacute: "Ĺ",
  Lambda: "Λ",
  Lang: "⟪",
  Laplacetrf: "ℒ",
  Larr: "↞",
  Lcaron: "Ľ",
  Lcedil: "Ļ",
  Lcy: "Л",
  LeftAngleBracket: "⟨",
  LeftArrow: "←",
  LeftArrowBar: "⇤",
  LeftArrowRightArrow: "⇆",
  LeftCeiling: "⌈",
  LeftDoubleBracket: "⟦",
  LeftDownTeeVector: "⥡",
  LeftDownVector: "⇃",
  LeftDownVectorBar: "⥙",
  LeftFloor: "⌊",
  LeftRightArrow: "↔",
  LeftRightVector: "⥎",
  LeftTee: "⊣",
  LeftTeeArrow: "↤",
  LeftTeeVector: "⥚",
  LeftTriangle: "⊲",
  LeftTriangleBar: "⧏",
  LeftTriangleEqual: "⊴",
  LeftUpDownVector: "⥑",
  LeftUpTeeVector: "⥠",
  LeftUpVector: "↿",
  LeftUpVectorBar: "⥘",
  LeftVector: "↼",
  LeftVectorBar: "⥒",
  Leftarrow: "⇐",
  Leftrightarrow: "⇔",
  LessEqualGreater: "⋚",
  LessFullEqual: "≦",
  LessGreater: "≶",
  LessLess: "⪡",
  LessSlantEqual: "⩽",
  LessTilde: "≲",
  Lfr: "𝔏",
  Ll: "⋘",
  Lleftarrow: "⇚",
  Lmidot: "Ŀ",
  LongLeftArrow: "⟵",
  LongLeftRightArrow: "⟷",
  LongRightArrow: "⟶",
  Longleftarrow: "⟸",
  Longleftrightarrow: "⟺",
  Longrightarrow: "⟹",
  Lopf: "𝕃",
  LowerLeftArrow: "↙",
  LowerRightArrow: "↘",
  Lscr: "ℒ",
  Lsh: "↰",
  Lstrok: "Ł",
  Lt: "≪",
  Map: "⤅",
  Mcy: "М",
  MediumSpace: " ",
  Mellintrf: "ℳ",
  Mfr: "𝔐",
  MinusPlus: "∓",
  Mopf: "𝕄",
  Mscr: "ℳ",
  Mu: "Μ",
  NJcy: "Њ",
  Nacute: "Ń",
  Ncaron: "Ň",
  Ncedil: "Ņ",
  Ncy: "Н",
  NegativeMediumSpace: "​",
  NegativeThickSpace: "​",
  NegativeThinSpace: "​",
  NegativeVeryThinSpace: "​",
  NestedGreaterGreater: "≫",
  NestedLessLess: "≪",
  NewLine: "\n",
  Nfr: "𝔑",
  NoBreak: "⁠",
  NonBreakingSpace: " ",
  Nopf: "ℕ",
  Not: "⫬",
  NotCongruent: "≢",
  NotCupCap: "≭",
  NotDoubleVerticalBar: "∦",
  NotElement: "∉",
  NotEqual: "≠",
  NotEqualTilde: "≂̸",
  NotExists: "∄",
  NotGreater: "≯",
  NotGreaterEqual: "≱",
  NotGreaterFullEqual: "≧̸",
  NotGreaterGreater: "≫̸",
  NotGreaterLess: "≹",
  NotGreaterSlantEqual: "⩾̸",
  NotGreaterTilde: "≵",
  NotHumpDownHump: "≎̸",
  NotHumpEqual: "≏̸",
  NotLeftTriangle: "⋪",
  NotLeftTriangleBar: "⧏̸",
  NotLeftTriangleEqual: "⋬",
  NotLess: "≮",
  NotLessEqual: "≰",
  NotLessGreater: "≸",
  NotLessLess: "≪̸",
  NotLessSlantEqual: "⩽̸",
  NotLessTilde: "≴",
  NotNestedGreaterGreater: "⪢̸",
  NotNestedLessLess: "⪡̸",
  NotPrecedes: "⊀",
  NotPrecedesEqual: "⪯̸",
  NotPrecedesSlantEqual: "⋠",
  NotReverseElement: "∌",
  NotRightTriangle: "⋫",
  NotRightTriangleBar: "⧐̸",
  NotRightTriangleEqual: "⋭",
  NotSquareSubset: "⊏̸",
  NotSquareSubsetEqual: "⋢",
  NotSquareSuperset: "⊐̸",
  NotSquareSupersetEqual: "⋣",
  NotSubset: "⊂⃒",
  NotSubsetEqual: "⊈",
  NotSucceeds: "⊁",
  NotSucceedsEqual: "⪰̸",
  NotSucceedsSlantEqual: "⋡",
  NotSucceedsTilde: "≿̸",
  NotSuperset: "⊃⃒",
  NotSupersetEqual: "⊉",
  NotTilde: "≁",
  NotTildeEqual: "≄",
  NotTildeFullEqual: "≇",
  NotTildeTilde: "≉",
  NotVerticalBar: "∤",
  Nscr: "𝒩",
  Ntilde: "Ñ",
  Nu: "Ν",
  OElig: "Œ",
  Oacute: "Ó",
  Ocirc: "Ô",
  Ocy: "О",
  Odblac: "Ő",
  Ofr: "𝔒",
  Ograve: "Ò",
  Omacr: "Ō",
  Omega: "Ω",
  Omicron: "Ο",
  Oopf: "𝕆",
  OpenCurlyDoubleQuote: "“",
  OpenCurlyQuote: "‘",
  Or: "⩔",
  Oscr: "𝒪",
  Oslash: "Ø",
  Otilde: "Õ",
  Otimes: "⨷",
  Ouml: "Ö",
  OverBar: "‾",
  OverBrace: "⏞",
  OverBracket: "⎴",
  OverParenthesis: "⏜",
  PartialD: "∂",
  Pcy: "П",
  Pfr: "𝔓",
  Phi: "Φ",
  Pi: "Π",
  PlusMinus: "±",
  Poincareplane: "ℌ",
  Popf: "ℙ",
  Pr: "⪻",
  Precedes: "≺",
  PrecedesEqual: "⪯",
  PrecedesSlantEqual: "≼",
  PrecedesTilde: "≾",
  Prime: "″",
  Product: "∏",
  Proportion: "∷",
  Proportional: "∝",
  Pscr: "𝒫",
  Psi: "Ψ",
  QUOT: '"',
  Qfr: "𝔔",
  Qopf: "ℚ",
  Qscr: "𝒬",
  RBarr: "⤐",
  REG: "®",
  Racute: "Ŕ",
  Rang: "⟫",
  Rarr: "↠",
  Rarrtl: "⤖",
  Rcaron: "Ř",
  Rcedil: "Ŗ",
  Rcy: "Р",
  Re: "ℜ",
  ReverseElement: "∋",
  ReverseEquilibrium: "⇋",
  ReverseUpEquilibrium: "⥯",
  Rfr: "ℜ",
  Rho: "Ρ",
  RightAngleBracket: "⟩",
  RightArrow: "→",
  RightArrowBar: "⇥",
  RightArrowLeftArrow: "⇄",
  RightCeiling: "⌉",
  RightDoubleBracket: "⟧",
  RightDownTeeVector: "⥝",
  RightDownVector: "⇂",
  RightDownVectorBar: "⥕",
  RightFloor: "⌋",
  RightTee: "⊢",
  RightTeeArrow: "↦",
  RightTeeVector: "⥛",
  RightTriangle: "⊳",
  RightTriangleBar: "⧐",
  RightTriangleEqual: "⊵",
  RightUpDownVector: "⥏",
  RightUpTeeVector: "⥜",
  RightUpVector: "↾",
  RightUpVectorBar: "⥔",
  RightVector: "⇀",
  RightVectorBar: "⥓",
  Rightarrow: "⇒",
  Ropf: "ℝ",
  RoundImplies: "⥰",
  Rrightarrow: "⇛",
  Rscr: "ℛ",
  Rsh: "↱",
  RuleDelayed: "⧴",
  SHCHcy: "Щ",
  SHcy: "Ш",
  SOFTcy: "Ь",
  Sacute: "Ś",
  Sc: "⪼",
  Scaron: "Š",
  Scedil: "Ş",
  Scirc: "Ŝ",
  Scy: "С",
  Sfr: "𝔖",
  ShortDownArrow: "↓",
  ShortLeftArrow: "←",
  ShortRightArrow: "→",
  ShortUpArrow: "↑",
  Sigma: "Σ",
  SmallCircle: "∘",
  Sopf: "𝕊",
  Sqrt: "√",
  Square: "□",
  SquareIntersection: "⊓",
  SquareSubset: "⊏",
  SquareSubsetEqual: "⊑",
  SquareSuperset: "⊐",
  SquareSupersetEqual: "⊒",
  SquareUnion: "⊔",
  Sscr: "𝒮",
  Star: "⋆",
  Sub: "⋐",
  Subset: "⋐",
  SubsetEqual: "⊆",
  Succeeds: "≻",
  SucceedsEqual: "⪰",
  SucceedsSlantEqual: "≽",
  SucceedsTilde: "≿",
  SuchThat: "∋",
  Sum: "∑",
  Sup: "⋑",
  Superset: "⊃",
  SupersetEqual: "⊇",
  Supset: "⋑",
  THORN: "Þ",
  TRADE: "™",
  TSHcy: "Ћ",
  TScy: "Ц",
  Tab: "	",
  Tau: "Τ",
  Tcaron: "Ť",
  Tcedil: "Ţ",
  Tcy: "Т",
  Tfr: "𝔗",
  Therefore: "∴",
  Theta: "Θ",
  ThickSpace: "  ",
  ThinSpace: " ",
  Tilde: "∼",
  TildeEqual: "≃",
  TildeFullEqual: "≅",
  TildeTilde: "≈",
  Topf: "𝕋",
  TripleDot: "⃛",
  Tscr: "𝒯",
  Tstrok: "Ŧ",
  Uacute: "Ú",
  Uarr: "↟",
  Uarrocir: "⥉",
  Ubrcy: "Ў",
  Ubreve: "Ŭ",
  Ucirc: "Û",
  Ucy: "У",
  Udblac: "Ű",
  Ufr: "𝔘",
  Ugrave: "Ù",
  Umacr: "Ū",
  UnderBar: "_",
  UnderBrace: "⏟",
  UnderBracket: "⎵",
  UnderParenthesis: "⏝",
  Union: "⋃",
  UnionPlus: "⊎",
  Uogon: "Ų",
  Uopf: "𝕌",
  UpArrow: "↑",
  UpArrowBar: "⤒",
  UpArrowDownArrow: "⇅",
  UpDownArrow: "↕",
  UpEquilibrium: "⥮",
  UpTee: "⊥",
  UpTeeArrow: "↥",
  Uparrow: "⇑",
  Updownarrow: "⇕",
  UpperLeftArrow: "↖",
  UpperRightArrow: "↗",
  Upsi: "ϒ",
  Upsilon: "Υ",
  Uring: "Ů",
  Uscr: "𝒰",
  Utilde: "Ũ",
  Uuml: "Ü",
  VDash: "⊫",
  Vbar: "⫫",
  Vcy: "В",
  Vdash: "⊩",
  Vdashl: "⫦",
  Vee: "⋁",
  Verbar: "‖",
  Vert: "‖",
  VerticalBar: "∣",
  VerticalLine: "|",
  VerticalSeparator: "❘",
  VerticalTilde: "≀",
  VeryThinSpace: " ",
  Vfr: "𝔙",
  Vopf: "𝕍",
  Vscr: "𝒱",
  Vvdash: "⊪",
  Wcirc: "Ŵ",
  Wedge: "⋀",
  Wfr: "𝔚",
  Wopf: "𝕎",
  Wscr: "𝒲",
  Xfr: "𝔛",
  Xi: "Ξ",
  Xopf: "𝕏",
  Xscr: "𝒳",
  YAcy: "Я",
  YIcy: "Ї",
  YUcy: "Ю",
  Yacute: "Ý",
  Ycirc: "Ŷ",
  Ycy: "Ы",
  Yfr: "𝔜",
  Yopf: "𝕐",
  Yscr: "𝒴",
  Yuml: "Ÿ",
  ZHcy: "Ж",
  Zacute: "Ź",
  Zcaron: "Ž",
  Zcy: "З",
  Zdot: "Ż",
  ZeroWidthSpace: "​",
  Zeta: "Ζ",
  Zfr: "ℨ",
  Zopf: "ℤ",
  Zscr: "𝒵",
  aacute: "á",
  abreve: "ă",
  ac: "∾",
  acE: "∾̳",
  acd: "∿",
  acirc: "â",
  acute: "´",
  acy: "а",
  aelig: "æ",
  af: "⁡",
  afr: "𝔞",
  agrave: "à",
  alefsym: "ℵ",
  aleph: "ℵ",
  alpha: "α",
  amacr: "ā",
  amalg: "⨿",
  amp: "&",
  and: "∧",
  andand: "⩕",
  andd: "⩜",
  andslope: "⩘",
  andv: "⩚",
  ang: "∠",
  ange: "⦤",
  angle: "∠",
  angmsd: "∡",
  angmsdaa: "⦨",
  angmsdab: "⦩",
  angmsdac: "⦪",
  angmsdad: "⦫",
  angmsdae: "⦬",
  angmsdaf: "⦭",
  angmsdag: "⦮",
  angmsdah: "⦯",
  angrt: "∟",
  angrtvb: "⊾",
  angrtvbd: "⦝",
  angsph: "∢",
  angst: "Å",
  angzarr: "⍼",
  aogon: "ą",
  aopf: "𝕒",
  ap: "≈",
  apE: "⩰",
  apacir: "⩯",
  ape: "≊",
  apid: "≋",
  apos: "'",
  approx: "≈",
  approxeq: "≊",
  aring: "å",
  ascr: "𝒶",
  ast: "*",
  asymp: "≈",
  asympeq: "≍",
  atilde: "ã",
  auml: "ä",
  awconint: "∳",
  awint: "⨑",
  bNot: "⫭",
  backcong: "≌",
  backepsilon: "϶",
  backprime: "‵",
  backsim: "∽",
  backsimeq: "⋍",
  barvee: "⊽",
  barwed: "⌅",
  barwedge: "⌅",
  bbrk: "⎵",
  bbrktbrk: "⎶",
  bcong: "≌",
  bcy: "б",
  bdquo: "„",
  becaus: "∵",
  because: "∵",
  bemptyv: "⦰",
  bepsi: "϶",
  bernou: "ℬ",
  beta: "β",
  beth: "ℶ",
  between: "≬",
  bfr: "𝔟",
  bigcap: "⋂",
  bigcirc: "◯",
  bigcup: "⋃",
  bigodot: "⨀",
  bigoplus: "⨁",
  bigotimes: "⨂",
  bigsqcup: "⨆",
  bigstar: "★",
  bigtriangledown: "▽",
  bigtriangleup: "△",
  biguplus: "⨄",
  bigvee: "⋁",
  bigwedge: "⋀",
  bkarow: "⤍",
  blacklozenge: "⧫",
  blacksquare: "▪",
  blacktriangle: "▴",
  blacktriangledown: "▾",
  blacktriangleleft: "◂",
  blacktriangleright: "▸",
  blank: "␣",
  blk12: "▒",
  blk14: "░",
  blk34: "▓",
  block: "█",
  bne: "=⃥",
  bnequiv: "≡⃥",
  bnot: "⌐",
  bopf: "𝕓",
  bot: "⊥",
  bottom: "⊥",
  bowtie: "⋈",
  boxDL: "╗",
  boxDR: "╔",
  boxDl: "╖",
  boxDr: "╓",
  boxH: "═",
  boxHD: "╦",
  boxHU: "╩",
  boxHd: "╤",
  boxHu: "╧",
  boxUL: "╝",
  boxUR: "╚",
  boxUl: "╜",
  boxUr: "╙",
  boxV: "║",
  boxVH: "╬",
  boxVL: "╣",
  boxVR: "╠",
  boxVh: "╫",
  boxVl: "╢",
  boxVr: "╟",
  boxbox: "⧉",
  boxdL: "╕",
  boxdR: "╒",
  boxdl: "┐",
  boxdr: "┌",
  boxh: "─",
  boxhD: "╥",
  boxhU: "╨",
  boxhd: "┬",
  boxhu: "┴",
  boxminus: "⊟",
  boxplus: "⊞",
  boxtimes: "⊠",
  boxuL: "╛",
  boxuR: "╘",
  boxul: "┘",
  boxur: "└",
  boxv: "│",
  boxvH: "╪",
  boxvL: "╡",
  boxvR: "╞",
  boxvh: "┼",
  boxvl: "┤",
  boxvr: "├",
  bprime: "‵",
  breve: "˘",
  brvbar: "¦",
  bscr: "𝒷",
  bsemi: "⁏",
  bsim: "∽",
  bsime: "⋍",
  bsol: "\\",
  bsolb: "⧅",
  bsolhsub: "⟈",
  bull: "•",
  bullet: "•",
  bump: "≎",
  bumpE: "⪮",
  bumpe: "≏",
  bumpeq: "≏",
  cacute: "ć",
  cap: "∩",
  capand: "⩄",
  capbrcup: "⩉",
  capcap: "⩋",
  capcup: "⩇",
  capdot: "⩀",
  caps: "∩︀",
  caret: "⁁",
  caron: "ˇ",
  ccaps: "⩍",
  ccaron: "č",
  ccedil: "ç",
  ccirc: "ĉ",
  ccups: "⩌",
  ccupssm: "⩐",
  cdot: "ċ",
  cedil: "¸",
  cemptyv: "⦲",
  cent: "¢",
  centerdot: "·",
  cfr: "𝔠",
  chcy: "ч",
  check: "✓",
  checkmark: "✓",
  chi: "χ",
  cir: "○",
  cirE: "⧃",
  circ: "ˆ",
  circeq: "≗",
  circlearrowleft: "↺",
  circlearrowright: "↻",
  circledR: "®",
  circledS: "Ⓢ",
  circledast: "⊛",
  circledcirc: "⊚",
  circleddash: "⊝",
  cire: "≗",
  cirfnint: "⨐",
  cirmid: "⫯",
  cirscir: "⧂",
  clubs: "♣",
  clubsuit: "♣",
  colon: ":",
  colone: "≔",
  coloneq: "≔",
  comma: ",",
  commat: "@",
  comp: "∁",
  compfn: "∘",
  complement: "∁",
  complexes: "ℂ",
  cong: "≅",
  congdot: "⩭",
  conint: "∮",
  copf: "𝕔",
  coprod: "∐",
  copy: "©",
  copysr: "℗",
  crarr: "↵",
  cross: "✗",
  cscr: "𝒸",
  csub: "⫏",
  csube: "⫑",
  csup: "⫐",
  csupe: "⫒",
  ctdot: "⋯",
  cudarrl: "⤸",
  cudarrr: "⤵",
  cuepr: "⋞",
  cuesc: "⋟",
  cularr: "↶",
  cularrp: "⤽",
  cup: "∪",
  cupbrcap: "⩈",
  cupcap: "⩆",
  cupcup: "⩊",
  cupdot: "⊍",
  cupor: "⩅",
  cups: "∪︀",
  curarr: "↷",
  curarrm: "⤼",
  curlyeqprec: "⋞",
  curlyeqsucc: "⋟",
  curlyvee: "⋎",
  curlywedge: "⋏",
  curren: "¤",
  curvearrowleft: "↶",
  curvearrowright: "↷",
  cuvee: "⋎",
  cuwed: "⋏",
  cwconint: "∲",
  cwint: "∱",
  cylcty: "⌭",
  dArr: "⇓",
  dHar: "⥥",
  dagger: "†",
  daleth: "ℸ",
  darr: "↓",
  dash: "‐",
  dashv: "⊣",
  dbkarow: "⤏",
  dblac: "˝",
  dcaron: "ď",
  dcy: "д",
  dd: "ⅆ",
  ddagger: "‡",
  ddarr: "⇊",
  ddotseq: "⩷",
  deg: "°",
  delta: "δ",
  demptyv: "⦱",
  dfisht: "⥿",
  dfr: "𝔡",
  dharl: "⇃",
  dharr: "⇂",
  diam: "⋄",
  diamond: "⋄",
  diamondsuit: "♦",
  diams: "♦",
  die: "¨",
  digamma: "ϝ",
  disin: "⋲",
  div: "÷",
  divide: "÷",
  divideontimes: "⋇",
  divonx: "⋇",
  djcy: "ђ",
  dlcorn: "⌞",
  dlcrop: "⌍",
  dollar: "$",
  dopf: "𝕕",
  dot: "˙",
  doteq: "≐",
  doteqdot: "≑",
  dotminus: "∸",
  dotplus: "∔",
  dotsquare: "⊡",
  doublebarwedge: "⌆",
  downarrow: "↓",
  downdownarrows: "⇊",
  downharpoonleft: "⇃",
  downharpoonright: "⇂",
  drbkarow: "⤐",
  drcorn: "⌟",
  drcrop: "⌌",
  dscr: "𝒹",
  dscy: "ѕ",
  dsol: "⧶",
  dstrok: "đ",
  dtdot: "⋱",
  dtri: "▿",
  dtrif: "▾",
  duarr: "⇵",
  duhar: "⥯",
  dwangle: "⦦",
  dzcy: "џ",
  dzigrarr: "⟿",
  eDDot: "⩷",
  eDot: "≑",
  eacute: "é",
  easter: "⩮",
  ecaron: "ě",
  ecir: "≖",
  ecirc: "ê",
  ecolon: "≕",
  ecy: "э",
  edot: "ė",
  ee: "ⅇ",
  efDot: "≒",
  efr: "𝔢",
  eg: "⪚",
  egrave: "è",
  egs: "⪖",
  egsdot: "⪘",
  el: "⪙",
  elinters: "⏧",
  ell: "ℓ",
  els: "⪕",
  elsdot: "⪗",
  emacr: "ē",
  empty: "∅",
  emptyset: "∅",
  emptyv: "∅",
  emsp13: " ",
  emsp14: " ",
  emsp: " ",
  eng: "ŋ",
  ensp: " ",
  eogon: "ę",
  eopf: "𝕖",
  epar: "⋕",
  eparsl: "⧣",
  eplus: "⩱",
  epsi: "ε",
  epsilon: "ε",
  epsiv: "ϵ",
  eqcirc: "≖",
  eqcolon: "≕",
  eqsim: "≂",
  eqslantgtr: "⪖",
  eqslantless: "⪕",
  equals: "=",
  equest: "≟",
  equiv: "≡",
  equivDD: "⩸",
  eqvparsl: "⧥",
  erDot: "≓",
  erarr: "⥱",
  escr: "ℯ",
  esdot: "≐",
  esim: "≂",
  eta: "η",
  eth: "ð",
  euml: "ë",
  euro: "€",
  excl: "!",
  exist: "∃",
  expectation: "ℰ",
  exponentiale: "ⅇ",
  fallingdotseq: "≒",
  fcy: "ф",
  female: "♀",
  ffilig: "ﬃ",
  fflig: "ﬀ",
  ffllig: "ﬄ",
  ffr: "𝔣",
  filig: "ﬁ",
  fjlig: "fj",
  flat: "♭",
  fllig: "ﬂ",
  fltns: "▱",
  fnof: "ƒ",
  fopf: "𝕗",
  forall: "∀",
  fork: "⋔",
  forkv: "⫙",
  fpartint: "⨍",
  frac12: "½",
  frac13: "⅓",
  frac14: "¼",
  frac15: "⅕",
  frac16: "⅙",
  frac18: "⅛",
  frac23: "⅔",
  frac25: "⅖",
  frac34: "¾",
  frac35: "⅗",
  frac38: "⅜",
  frac45: "⅘",
  frac56: "⅚",
  frac58: "⅝",
  frac78: "⅞",
  frasl: "⁄",
  frown: "⌢",
  fscr: "𝒻",
  gE: "≧",
  gEl: "⪌",
  gacute: "ǵ",
  gamma: "γ",
  gammad: "ϝ",
  gap: "⪆",
  gbreve: "ğ",
  gcirc: "ĝ",
  gcy: "г",
  gdot: "ġ",
  ge: "≥",
  gel: "⋛",
  geq: "≥",
  geqq: "≧",
  geqslant: "⩾",
  ges: "⩾",
  gescc: "⪩",
  gesdot: "⪀",
  gesdoto: "⪂",
  gesdotol: "⪄",
  gesl: "⋛︀",
  gesles: "⪔",
  gfr: "𝔤",
  gg: "≫",
  ggg: "⋙",
  gimel: "ℷ",
  gjcy: "ѓ",
  gl: "≷",
  glE: "⪒",
  gla: "⪥",
  glj: "⪤",
  gnE: "≩",
  gnap: "⪊",
  gnapprox: "⪊",
  gne: "⪈",
  gneq: "⪈",
  gneqq: "≩",
  gnsim: "⋧",
  gopf: "𝕘",
  grave: "`",
  gscr: "ℊ",
  gsim: "≳",
  gsime: "⪎",
  gsiml: "⪐",
  gt: ">",
  gtcc: "⪧",
  gtcir: "⩺",
  gtdot: "⋗",
  gtlPar: "⦕",
  gtquest: "⩼",
  gtrapprox: "⪆",
  gtrarr: "⥸",
  gtrdot: "⋗",
  gtreqless: "⋛",
  gtreqqless: "⪌",
  gtrless: "≷",
  gtrsim: "≳",
  gvertneqq: "≩︀",
  gvnE: "≩︀",
  hArr: "⇔",
  hairsp: " ",
  half: "½",
  hamilt: "ℋ",
  hardcy: "ъ",
  harr: "↔",
  harrcir: "⥈",
  harrw: "↭",
  hbar: "ℏ",
  hcirc: "ĥ",
  hearts: "♥",
  heartsuit: "♥",
  hellip: "…",
  hercon: "⊹",
  hfr: "𝔥",
  hksearow: "⤥",
  hkswarow: "⤦",
  hoarr: "⇿",
  homtht: "∻",
  hookleftarrow: "↩",
  hookrightarrow: "↪",
  hopf: "𝕙",
  horbar: "―",
  hscr: "𝒽",
  hslash: "ℏ",
  hstrok: "ħ",
  hybull: "⁃",
  hyphen: "‐",
  iacute: "í",
  ic: "⁣",
  icirc: "î",
  icy: "и",
  iecy: "е",
  iexcl: "¡",
  iff: "⇔",
  ifr: "𝔦",
  igrave: "ì",
  ii: "ⅈ",
  iiiint: "⨌",
  iiint: "∭",
  iinfin: "⧜",
  iiota: "℩",
  ijlig: "ĳ",
  imacr: "ī",
  image: "ℑ",
  imagline: "ℐ",
  imagpart: "ℑ",
  imath: "ı",
  imof: "⊷",
  imped: "Ƶ",
  in: "∈",
  incare: "℅",
  infin: "∞",
  infintie: "⧝",
  inodot: "ı",
  int: "∫",
  intcal: "⊺",
  integers: "ℤ",
  intercal: "⊺",
  intlarhk: "⨗",
  intprod: "⨼",
  iocy: "ё",
  iogon: "į",
  iopf: "𝕚",
  iota: "ι",
  iprod: "⨼",
  iquest: "¿",
  iscr: "𝒾",
  isin: "∈",
  isinE: "⋹",
  isindot: "⋵",
  isins: "⋴",
  isinsv: "⋳",
  isinv: "∈",
  it: "⁢",
  itilde: "ĩ",
  iukcy: "і",
  iuml: "ï",
  jcirc: "ĵ",
  jcy: "й",
  jfr: "𝔧",
  jmath: "ȷ",
  jopf: "𝕛",
  jscr: "𝒿",
  jsercy: "ј",
  jukcy: "є",
  kappa: "κ",
  kappav: "ϰ",
  kcedil: "ķ",
  kcy: "к",
  kfr: "𝔨",
  kgreen: "ĸ",
  khcy: "х",
  kjcy: "ќ",
  kopf: "𝕜",
  kscr: "𝓀",
  lAarr: "⇚",
  lArr: "⇐",
  lAtail: "⤛",
  lBarr: "⤎",
  lE: "≦",
  lEg: "⪋",
  lHar: "⥢",
  lacute: "ĺ",
  laemptyv: "⦴",
  lagran: "ℒ",
  lambda: "λ",
  lang: "⟨",
  langd: "⦑",
  langle: "⟨",
  lap: "⪅",
  laquo: "«",
  larr: "←",
  larrb: "⇤",
  larrbfs: "⤟",
  larrfs: "⤝",
  larrhk: "↩",
  larrlp: "↫",
  larrpl: "⤹",
  larrsim: "⥳",
  larrtl: "↢",
  lat: "⪫",
  latail: "⤙",
  late: "⪭",
  lates: "⪭︀",
  lbarr: "⤌",
  lbbrk: "❲",
  lbrace: "{",
  lbrack: "[",
  lbrke: "⦋",
  lbrksld: "⦏",
  lbrkslu: "⦍",
  lcaron: "ľ",
  lcedil: "ļ",
  lceil: "⌈",
  lcub: "{",
  lcy: "л",
  ldca: "⤶",
  ldquo: "“",
  ldquor: "„",
  ldrdhar: "⥧",
  ldrushar: "⥋",
  ldsh: "↲",
  le: "≤",
  leftarrow: "←",
  leftarrowtail: "↢",
  leftharpoondown: "↽",
  leftharpoonup: "↼",
  leftleftarrows: "⇇",
  leftrightarrow: "↔",
  leftrightarrows: "⇆",
  leftrightharpoons: "⇋",
  leftrightsquigarrow: "↭",
  leftthreetimes: "⋋",
  leg: "⋚",
  leq: "≤",
  leqq: "≦",
  leqslant: "⩽",
  les: "⩽",
  lescc: "⪨",
  lesdot: "⩿",
  lesdoto: "⪁",
  lesdotor: "⪃",
  lesg: "⋚︀",
  lesges: "⪓",
  lessapprox: "⪅",
  lessdot: "⋖",
  lesseqgtr: "⋚",
  lesseqqgtr: "⪋",
  lessgtr: "≶",
  lesssim: "≲",
  lfisht: "⥼",
  lfloor: "⌊",
  lfr: "𝔩",
  lg: "≶",
  lgE: "⪑",
  lhard: "↽",
  lharu: "↼",
  lharul: "⥪",
  lhblk: "▄",
  ljcy: "љ",
  ll: "≪",
  llarr: "⇇",
  llcorner: "⌞",
  llhard: "⥫",
  lltri: "◺",
  lmidot: "ŀ",
  lmoust: "⎰",
  lmoustache: "⎰",
  lnE: "≨",
  lnap: "⪉",
  lnapprox: "⪉",
  lne: "⪇",
  lneq: "⪇",
  lneqq: "≨",
  lnsim: "⋦",
  loang: "⟬",
  loarr: "⇽",
  lobrk: "⟦",
  longleftarrow: "⟵",
  longleftrightarrow: "⟷",
  longmapsto: "⟼",
  longrightarrow: "⟶",
  looparrowleft: "↫",
  looparrowright: "↬",
  lopar: "⦅",
  lopf: "𝕝",
  loplus: "⨭",
  lotimes: "⨴",
  lowast: "∗",
  lowbar: "_",
  loz: "◊",
  lozenge: "◊",
  lozf: "⧫",
  lpar: "(",
  lparlt: "⦓",
  lrarr: "⇆",
  lrcorner: "⌟",
  lrhar: "⇋",
  lrhard: "⥭",
  lrm: "‎",
  lrtri: "⊿",
  lsaquo: "‹",
  lscr: "𝓁",
  lsh: "↰",
  lsim: "≲",
  lsime: "⪍",
  lsimg: "⪏",
  lsqb: "[",
  lsquo: "‘",
  lsquor: "‚",
  lstrok: "ł",
  lt: "<",
  ltcc: "⪦",
  ltcir: "⩹",
  ltdot: "⋖",
  lthree: "⋋",
  ltimes: "⋉",
  ltlarr: "⥶",
  ltquest: "⩻",
  ltrPar: "⦖",
  ltri: "◃",
  ltrie: "⊴",
  ltrif: "◂",
  lurdshar: "⥊",
  luruhar: "⥦",
  lvertneqq: "≨︀",
  lvnE: "≨︀",
  mDDot: "∺",
  macr: "¯",
  male: "♂",
  malt: "✠",
  maltese: "✠",
  map: "↦",
  mapsto: "↦",
  mapstodown: "↧",
  mapstoleft: "↤",
  mapstoup: "↥",
  marker: "▮",
  mcomma: "⨩",
  mcy: "м",
  mdash: "—",
  measuredangle: "∡",
  mfr: "𝔪",
  mho: "℧",
  micro: "µ",
  mid: "∣",
  midast: "*",
  midcir: "⫰",
  middot: "·",
  minus: "−",
  minusb: "⊟",
  minusd: "∸",
  minusdu: "⨪",
  mlcp: "⫛",
  mldr: "…",
  mnplus: "∓",
  models: "⊧",
  mopf: "𝕞",
  mp: "∓",
  mscr: "𝓂",
  mstpos: "∾",
  mu: "μ",
  multimap: "⊸",
  mumap: "⊸",
  nGg: "⋙̸",
  nGt: "≫⃒",
  nGtv: "≫̸",
  nLeftarrow: "⇍",
  nLeftrightarrow: "⇎",
  nLl: "⋘̸",
  nLt: "≪⃒",
  nLtv: "≪̸",
  nRightarrow: "⇏",
  nVDash: "⊯",
  nVdash: "⊮",
  nabla: "∇",
  nacute: "ń",
  nang: "∠⃒",
  nap: "≉",
  napE: "⩰̸",
  napid: "≋̸",
  napos: "ŉ",
  napprox: "≉",
  natur: "♮",
  natural: "♮",
  naturals: "ℕ",
  nbsp: " ",
  nbump: "≎̸",
  nbumpe: "≏̸",
  ncap: "⩃",
  ncaron: "ň",
  ncedil: "ņ",
  ncong: "≇",
  ncongdot: "⩭̸",
  ncup: "⩂",
  ncy: "н",
  ndash: "–",
  ne: "≠",
  neArr: "⇗",
  nearhk: "⤤",
  nearr: "↗",
  nearrow: "↗",
  nedot: "≐̸",
  nequiv: "≢",
  nesear: "⤨",
  nesim: "≂̸",
  nexist: "∄",
  nexists: "∄",
  nfr: "𝔫",
  ngE: "≧̸",
  nge: "≱",
  ngeq: "≱",
  ngeqq: "≧̸",
  ngeqslant: "⩾̸",
  nges: "⩾̸",
  ngsim: "≵",
  ngt: "≯",
  ngtr: "≯",
  nhArr: "⇎",
  nharr: "↮",
  nhpar: "⫲",
  ni: "∋",
  nis: "⋼",
  nisd: "⋺",
  niv: "∋",
  njcy: "њ",
  nlArr: "⇍",
  nlE: "≦̸",
  nlarr: "↚",
  nldr: "‥",
  nle: "≰",
  nleftarrow: "↚",
  nleftrightarrow: "↮",
  nleq: "≰",
  nleqq: "≦̸",
  nleqslant: "⩽̸",
  nles: "⩽̸",
  nless: "≮",
  nlsim: "≴",
  nlt: "≮",
  nltri: "⋪",
  nltrie: "⋬",
  nmid: "∤",
  nopf: "𝕟",
  not: "¬",
  notin: "∉",
  notinE: "⋹̸",
  notindot: "⋵̸",
  notinva: "∉",
  notinvb: "⋷",
  notinvc: "⋶",
  notni: "∌",
  notniva: "∌",
  notnivb: "⋾",
  notnivc: "⋽",
  npar: "∦",
  nparallel: "∦",
  nparsl: "⫽⃥",
  npart: "∂̸",
  npolint: "⨔",
  npr: "⊀",
  nprcue: "⋠",
  npre: "⪯̸",
  nprec: "⊀",
  npreceq: "⪯̸",
  nrArr: "⇏",
  nrarr: "↛",
  nrarrc: "⤳̸",
  nrarrw: "↝̸",
  nrightarrow: "↛",
  nrtri: "⋫",
  nrtrie: "⋭",
  nsc: "⊁",
  nsccue: "⋡",
  nsce: "⪰̸",
  nscr: "𝓃",
  nshortmid: "∤",
  nshortparallel: "∦",
  nsim: "≁",
  nsime: "≄",
  nsimeq: "≄",
  nsmid: "∤",
  nspar: "∦",
  nsqsube: "⋢",
  nsqsupe: "⋣",
  nsub: "⊄",
  nsubE: "⫅̸",
  nsube: "⊈",
  nsubset: "⊂⃒",
  nsubseteq: "⊈",
  nsubseteqq: "⫅̸",
  nsucc: "⊁",
  nsucceq: "⪰̸",
  nsup: "⊅",
  nsupE: "⫆̸",
  nsupe: "⊉",
  nsupset: "⊃⃒",
  nsupseteq: "⊉",
  nsupseteqq: "⫆̸",
  ntgl: "≹",
  ntilde: "ñ",
  ntlg: "≸",
  ntriangleleft: "⋪",
  ntrianglelefteq: "⋬",
  ntriangleright: "⋫",
  ntrianglerighteq: "⋭",
  nu: "ν",
  num: "#",
  numero: "№",
  numsp: " ",
  nvDash: "⊭",
  nvHarr: "⤄",
  nvap: "≍⃒",
  nvdash: "⊬",
  nvge: "≥⃒",
  nvgt: ">⃒",
  nvinfin: "⧞",
  nvlArr: "⤂",
  nvle: "≤⃒",
  nvlt: "<⃒",
  nvltrie: "⊴⃒",
  nvrArr: "⤃",
  nvrtrie: "⊵⃒",
  nvsim: "∼⃒",
  nwArr: "⇖",
  nwarhk: "⤣",
  nwarr: "↖",
  nwarrow: "↖",
  nwnear: "⤧",
  oS: "Ⓢ",
  oacute: "ó",
  oast: "⊛",
  ocir: "⊚",
  ocirc: "ô",
  ocy: "о",
  odash: "⊝",
  odblac: "ő",
  odiv: "⨸",
  odot: "⊙",
  odsold: "⦼",
  oelig: "œ",
  ofcir: "⦿",
  ofr: "𝔬",
  ogon: "˛",
  ograve: "ò",
  ogt: "⧁",
  ohbar: "⦵",
  ohm: "Ω",
  oint: "∮",
  olarr: "↺",
  olcir: "⦾",
  olcross: "⦻",
  oline: "‾",
  olt: "⧀",
  omacr: "ō",
  omega: "ω",
  omicron: "ο",
  omid: "⦶",
  ominus: "⊖",
  oopf: "𝕠",
  opar: "⦷",
  operp: "⦹",
  oplus: "⊕",
  or: "∨",
  orarr: "↻",
  ord: "⩝",
  order: "ℴ",
  orderof: "ℴ",
  ordf: "ª",
  ordm: "º",
  origof: "⊶",
  oror: "⩖",
  orslope: "⩗",
  orv: "⩛",
  oscr: "ℴ",
  oslash: "ø",
  osol: "⊘",
  otilde: "õ",
  otimes: "⊗",
  otimesas: "⨶",
  ouml: "ö",
  ovbar: "⌽",
  par: "∥",
  para: "¶",
  parallel: "∥",
  parsim: "⫳",
  parsl: "⫽",
  part: "∂",
  pcy: "п",
  percnt: "%",
  period: ".",
  permil: "‰",
  perp: "⊥",
  pertenk: "‱",
  pfr: "𝔭",
  phi: "φ",
  phiv: "ϕ",
  phmmat: "ℳ",
  phone: "☎",
  pi: "π",
  pitchfork: "⋔",
  piv: "ϖ",
  planck: "ℏ",
  planckh: "ℎ",
  plankv: "ℏ",
  plus: "+",
  plusacir: "⨣",
  plusb: "⊞",
  pluscir: "⨢",
  plusdo: "∔",
  plusdu: "⨥",
  pluse: "⩲",
  plusmn: "±",
  plussim: "⨦",
  plustwo: "⨧",
  pm: "±",
  pointint: "⨕",
  popf: "𝕡",
  pound: "£",
  pr: "≺",
  prE: "⪳",
  prap: "⪷",
  prcue: "≼",
  pre: "⪯",
  prec: "≺",
  precapprox: "⪷",
  preccurlyeq: "≼",
  preceq: "⪯",
  precnapprox: "⪹",
  precneqq: "⪵",
  precnsim: "⋨",
  precsim: "≾",
  prime: "′",
  primes: "ℙ",
  prnE: "⪵",
  prnap: "⪹",
  prnsim: "⋨",
  prod: "∏",
  profalar: "⌮",
  profline: "⌒",
  profsurf: "⌓",
  prop: "∝",
  propto: "∝",
  prsim: "≾",
  prurel: "⊰",
  pscr: "𝓅",
  psi: "ψ",
  puncsp: " ",
  qfr: "𝔮",
  qint: "⨌",
  qopf: "𝕢",
  qprime: "⁗",
  qscr: "𝓆",
  quaternions: "ℍ",
  quatint: "⨖",
  quest: "?",
  questeq: "≟",
  quot: '"',
  rAarr: "⇛",
  rArr: "⇒",
  rAtail: "⤜",
  rBarr: "⤏",
  rHar: "⥤",
  race: "∽̱",
  racute: "ŕ",
  radic: "√",
  raemptyv: "⦳",
  rang: "⟩",
  rangd: "⦒",
  range: "⦥",
  rangle: "⟩",
  raquo: "»",
  rarr: "→",
  rarrap: "⥵",
  rarrb: "⇥",
  rarrbfs: "⤠",
  rarrc: "⤳",
  rarrfs: "⤞",
  rarrhk: "↪",
  rarrlp: "↬",
  rarrpl: "⥅",
  rarrsim: "⥴",
  rarrtl: "↣",
  rarrw: "↝",
  ratail: "⤚",
  ratio: "∶",
  rationals: "ℚ",
  rbarr: "⤍",
  rbbrk: "❳",
  rbrace: "}",
  rbrack: "]",
  rbrke: "⦌",
  rbrksld: "⦎",
  rbrkslu: "⦐",
  rcaron: "ř",
  rcedil: "ŗ",
  rceil: "⌉",
  rcub: "}",
  rcy: "р",
  rdca: "⤷",
  rdldhar: "⥩",
  rdquo: "”",
  rdquor: "”",
  rdsh: "↳",
  real: "ℜ",
  realine: "ℛ",
  realpart: "ℜ",
  reals: "ℝ",
  rect: "▭",
  reg: "®",
  rfisht: "⥽",
  rfloor: "⌋",
  rfr: "𝔯",
  rhard: "⇁",
  rharu: "⇀",
  rharul: "⥬",
  rho: "ρ",
  rhov: "ϱ",
  rightarrow: "→",
  rightarrowtail: "↣",
  rightharpoondown: "⇁",
  rightharpoonup: "⇀",
  rightleftarrows: "⇄",
  rightleftharpoons: "⇌",
  rightrightarrows: "⇉",
  rightsquigarrow: "↝",
  rightthreetimes: "⋌",
  ring: "˚",
  risingdotseq: "≓",
  rlarr: "⇄",
  rlhar: "⇌",
  rlm: "‏",
  rmoust: "⎱",
  rmoustache: "⎱",
  rnmid: "⫮",
  roang: "⟭",
  roarr: "⇾",
  robrk: "⟧",
  ropar: "⦆",
  ropf: "𝕣",
  roplus: "⨮",
  rotimes: "⨵",
  rpar: ")",
  rpargt: "⦔",
  rppolint: "⨒",
  rrarr: "⇉",
  rsaquo: "›",
  rscr: "𝓇",
  rsh: "↱",
  rsqb: "]",
  rsquo: "’",
  rsquor: "’",
  rthree: "⋌",
  rtimes: "⋊",
  rtri: "▹",
  rtrie: "⊵",
  rtrif: "▸",
  rtriltri: "⧎",
  ruluhar: "⥨",
  rx: "℞",
  sacute: "ś",
  sbquo: "‚",
  sc: "≻",
  scE: "⪴",
  scap: "⪸",
  scaron: "š",
  sccue: "≽",
  sce: "⪰",
  scedil: "ş",
  scirc: "ŝ",
  scnE: "⪶",
  scnap: "⪺",
  scnsim: "⋩",
  scpolint: "⨓",
  scsim: "≿",
  scy: "с",
  sdot: "⋅",
  sdotb: "⊡",
  sdote: "⩦",
  seArr: "⇘",
  searhk: "⤥",
  searr: "↘",
  searrow: "↘",
  sect: "§",
  semi: ";",
  seswar: "⤩",
  setminus: "∖",
  setmn: "∖",
  sext: "✶",
  sfr: "𝔰",
  sfrown: "⌢",
  sharp: "♯",
  shchcy: "щ",
  shcy: "ш",
  shortmid: "∣",
  shortparallel: "∥",
  shy: "­",
  sigma: "σ",
  sigmaf: "ς",
  sigmav: "ς",
  sim: "∼",
  simdot: "⩪",
  sime: "≃",
  simeq: "≃",
  simg: "⪞",
  simgE: "⪠",
  siml: "⪝",
  simlE: "⪟",
  simne: "≆",
  simplus: "⨤",
  simrarr: "⥲",
  slarr: "←",
  smallsetminus: "∖",
  smashp: "⨳",
  smeparsl: "⧤",
  smid: "∣",
  smile: "⌣",
  smt: "⪪",
  smte: "⪬",
  smtes: "⪬︀",
  softcy: "ь",
  sol: "/",
  solb: "⧄",
  solbar: "⌿",
  sopf: "𝕤",
  spades: "♠",
  spadesuit: "♠",
  spar: "∥",
  sqcap: "⊓",
  sqcaps: "⊓︀",
  sqcup: "⊔",
  sqcups: "⊔︀",
  sqsub: "⊏",
  sqsube: "⊑",
  sqsubset: "⊏",
  sqsubseteq: "⊑",
  sqsup: "⊐",
  sqsupe: "⊒",
  sqsupset: "⊐",
  sqsupseteq: "⊒",
  squ: "□",
  square: "□",
  squarf: "▪",
  squf: "▪",
  srarr: "→",
  sscr: "𝓈",
  ssetmn: "∖",
  ssmile: "⌣",
  sstarf: "⋆",
  star: "☆",
  starf: "★",
  straightepsilon: "ϵ",
  straightphi: "ϕ",
  strns: "¯",
  sub: "⊂",
  subE: "⫅",
  subdot: "⪽",
  sube: "⊆",
  subedot: "⫃",
  submult: "⫁",
  subnE: "⫋",
  subne: "⊊",
  subplus: "⪿",
  subrarr: "⥹",
  subset: "⊂",
  subseteq: "⊆",
  subseteqq: "⫅",
  subsetneq: "⊊",
  subsetneqq: "⫋",
  subsim: "⫇",
  subsub: "⫕",
  subsup: "⫓",
  succ: "≻",
  succapprox: "⪸",
  succcurlyeq: "≽",
  succeq: "⪰",
  succnapprox: "⪺",
  succneqq: "⪶",
  succnsim: "⋩",
  succsim: "≿",
  sum: "∑",
  sung: "♪",
  sup1: "¹",
  sup2: "²",
  sup3: "³",
  sup: "⊃",
  supE: "⫆",
  supdot: "⪾",
  supdsub: "⫘",
  supe: "⊇",
  supedot: "⫄",
  suphsol: "⟉",
  suphsub: "⫗",
  suplarr: "⥻",
  supmult: "⫂",
  supnE: "⫌",
  supne: "⊋",
  supplus: "⫀",
  supset: "⊃",
  supseteq: "⊇",
  supseteqq: "⫆",
  supsetneq: "⊋",
  supsetneqq: "⫌",
  supsim: "⫈",
  supsub: "⫔",
  supsup: "⫖",
  swArr: "⇙",
  swarhk: "⤦",
  swarr: "↙",
  swarrow: "↙",
  swnwar: "⤪",
  szlig: "ß",
  target: "⌖",
  tau: "τ",
  tbrk: "⎴",
  tcaron: "ť",
  tcedil: "ţ",
  tcy: "т",
  tdot: "⃛",
  telrec: "⌕",
  tfr: "𝔱",
  there4: "∴",
  therefore: "∴",
  theta: "θ",
  thetasym: "ϑ",
  thetav: "ϑ",
  thickapprox: "≈",
  thicksim: "∼",
  thinsp: " ",
  thkap: "≈",
  thksim: "∼",
  thorn: "þ",
  tilde: "˜",
  times: "×",
  timesb: "⊠",
  timesbar: "⨱",
  timesd: "⨰",
  tint: "∭",
  toea: "⤨",
  top: "⊤",
  topbot: "⌶",
  topcir: "⫱",
  topf: "𝕥",
  topfork: "⫚",
  tosa: "⤩",
  tprime: "‴",
  trade: "™",
  triangle: "▵",
  triangledown: "▿",
  triangleleft: "◃",
  trianglelefteq: "⊴",
  triangleq: "≜",
  triangleright: "▹",
  trianglerighteq: "⊵",
  tridot: "◬",
  trie: "≜",
  triminus: "⨺",
  triplus: "⨹",
  trisb: "⧍",
  tritime: "⨻",
  trpezium: "⏢",
  tscr: "𝓉",
  tscy: "ц",
  tshcy: "ћ",
  tstrok: "ŧ",
  twixt: "≬",
  twoheadleftarrow: "↞",
  twoheadrightarrow: "↠",
  uArr: "⇑",
  uHar: "⥣",
  uacute: "ú",
  uarr: "↑",
  ubrcy: "ў",
  ubreve: "ŭ",
  ucirc: "û",
  ucy: "у",
  udarr: "⇅",
  udblac: "ű",
  udhar: "⥮",
  ufisht: "⥾",
  ufr: "𝔲",
  ugrave: "ù",
  uharl: "↿",
  uharr: "↾",
  uhblk: "▀",
  ulcorn: "⌜",
  ulcorner: "⌜",
  ulcrop: "⌏",
  ultri: "◸",
  umacr: "ū",
  uml: "¨",
  uogon: "ų",
  uopf: "𝕦",
  uparrow: "↑",
  updownarrow: "↕",
  upharpoonleft: "↿",
  upharpoonright: "↾",
  uplus: "⊎",
  upsi: "υ",
  upsih: "ϒ",
  upsilon: "υ",
  upuparrows: "⇈",
  urcorn: "⌝",
  urcorner: "⌝",
  urcrop: "⌎",
  uring: "ů",
  urtri: "◹",
  uscr: "𝓊",
  utdot: "⋰",
  utilde: "ũ",
  utri: "▵",
  utrif: "▴",
  uuarr: "⇈",
  uuml: "ü",
  uwangle: "⦧",
  vArr: "⇕",
  vBar: "⫨",
  vBarv: "⫩",
  vDash: "⊨",
  vangrt: "⦜",
  varepsilon: "ϵ",
  varkappa: "ϰ",
  varnothing: "∅",
  varphi: "ϕ",
  varpi: "ϖ",
  varpropto: "∝",
  varr: "↕",
  varrho: "ϱ",
  varsigma: "ς",
  varsubsetneq: "⊊︀",
  varsubsetneqq: "⫋︀",
  varsupsetneq: "⊋︀",
  varsupsetneqq: "⫌︀",
  vartheta: "ϑ",
  vartriangleleft: "⊲",
  vartriangleright: "⊳",
  vcy: "в",
  vdash: "⊢",
  vee: "∨",
  veebar: "⊻",
  veeeq: "≚",
  vellip: "⋮",
  verbar: "|",
  vert: "|",
  vfr: "𝔳",
  vltri: "⊲",
  vnsub: "⊂⃒",
  vnsup: "⊃⃒",
  vopf: "𝕧",
  vprop: "∝",
  vrtri: "⊳",
  vscr: "𝓋",
  vsubnE: "⫋︀",
  vsubne: "⊊︀",
  vsupnE: "⫌︀",
  vsupne: "⊋︀",
  vzigzag: "⦚",
  wcirc: "ŵ",
  wedbar: "⩟",
  wedge: "∧",
  wedgeq: "≙",
  weierp: "℘",
  wfr: "𝔴",
  wopf: "𝕨",
  wp: "℘",
  wr: "≀",
  wreath: "≀",
  wscr: "𝓌",
  xcap: "⋂",
  xcirc: "◯",
  xcup: "⋃",
  xdtri: "▽",
  xfr: "𝔵",
  xhArr: "⟺",
  xharr: "⟷",
  xi: "ξ",
  xlArr: "⟸",
  xlarr: "⟵",
  xmap: "⟼",
  xnis: "⋻",
  xodot: "⨀",
  xopf: "𝕩",
  xoplus: "⨁",
  xotime: "⨂",
  xrArr: "⟹",
  xrarr: "⟶",
  xscr: "𝓍",
  xsqcup: "⨆",
  xuplus: "⨄",
  xutri: "△",
  xvee: "⋁",
  xwedge: "⋀",
  yacute: "ý",
  yacy: "я",
  ycirc: "ŷ",
  ycy: "ы",
  yen: "¥",
  yfr: "𝔶",
  yicy: "ї",
  yopf: "𝕪",
  yscr: "𝓎",
  yucy: "ю",
  yuml: "ÿ",
  zacute: "ź",
  zcaron: "ž",
  zcy: "з",
  zdot: "ż",
  zeetrf: "ℨ",
  zeta: "ζ",
  zfr: "𝔷",
  zhcy: "ж",
  zigrarr: "⇝",
  zopf: "𝕫",
  zscr: "𝓏",
  zwj: "‍",
  zwnj: "‌"
};
const own$3 = {}.hasOwnProperty;
function decodeNamedCharacterReference(value) {
  return own$3.call(characterEntities, value) ? characterEntities[value] : false;
}
function splice(list2, start, remove, items) {
  const end = list2.length;
  let chunkStart = 0;
  let parameters;
  if (start < 0) {
    start = -start > end ? 0 : end + start;
  } else {
    start = start > end ? end : start;
  }
  remove = remove > 0 ? remove : 0;
  if (items.length < 1e4) {
    parameters = Array.from(items);
    parameters.unshift(start, remove);
    list2.splice(...parameters);
  } else {
    if (remove) list2.splice(start, remove);
    while (chunkStart < items.length) {
      parameters = items.slice(chunkStart, chunkStart + 1e4);
      parameters.unshift(start, 0);
      list2.splice(...parameters);
      chunkStart += 1e4;
      start += 1e4;
    }
  }
}
function push(list2, items) {
  if (list2.length > 0) {
    splice(list2, list2.length, 0, items);
    return list2;
  }
  return items;
}
const hasOwnProperty = {}.hasOwnProperty;
function combineExtensions(extensions) {
  const all3 = {};
  let index2 = -1;
  while (++index2 < extensions.length) {
    syntaxExtension(all3, extensions[index2]);
  }
  return all3;
}
function syntaxExtension(all3, extension2) {
  let hook;
  for (hook in extension2) {
    const maybe = hasOwnProperty.call(all3, hook) ? all3[hook] : void 0;
    const left = maybe || (all3[hook] = {});
    const right = extension2[hook];
    let code2;
    if (right) {
      for (code2 in right) {
        if (!hasOwnProperty.call(left, code2)) left[code2] = [];
        const value = right[code2];
        constructs(
          // @ts-expect-error Looks like a list.
          left[code2],
          Array.isArray(value) ? value : value ? [value] : []
        );
      }
    }
  }
}
function constructs(existing, list2) {
  let index2 = -1;
  const before = [];
  while (++index2 < list2.length) {
    (list2[index2].add === "after" ? existing : before).push(list2[index2]);
  }
  splice(existing, 0, 0, before);
}
function decodeNumericCharacterReference(value, base) {
  const code2 = Number.parseInt(value, base);
  if (
    // C0 except for HT, LF, FF, CR, space.
    code2 < 9 || code2 === 11 || code2 > 13 && code2 < 32 || // Control character (DEL) of C0, and C1 controls.
    code2 > 126 && code2 < 160 || // Lone high surrogates and low surrogates.
    code2 > 55295 && code2 < 57344 || // Noncharacters.
    code2 > 64975 && code2 < 65008 || /* eslint-disable no-bitwise */
    (code2 & 65535) === 65535 || (code2 & 65535) === 65534 || /* eslint-enable no-bitwise */
    // Out of range
    code2 > 1114111
  ) {
    return "�";
  }
  return String.fromCodePoint(code2);
}
function normalizeIdentifier(value) {
  return value.replace(/[\t\n\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase();
}
const asciiAlpha = regexCheck(/[A-Za-z]/);
const asciiAlphanumeric = regexCheck(/[\dA-Za-z]/);
const asciiAtext = regexCheck(/[#-'*+\--9=?A-Z^-~]/);
function asciiControl(code2) {
  return (
    // Special whitespace codes (which have negative values), C0 and Control
    // character DEL
    code2 !== null && (code2 < 32 || code2 === 127)
  );
}
const asciiDigit = regexCheck(/\d/);
const asciiHexDigit = regexCheck(/[\dA-Fa-f]/);
const asciiPunctuation = regexCheck(/[!-/:-@[-`{-~]/);
function markdownLineEnding(code2) {
  return code2 !== null && code2 < -2;
}
function markdownLineEndingOrSpace(code2) {
  return code2 !== null && (code2 < 0 || code2 === 32);
}
function markdownSpace(code2) {
  return code2 === -2 || code2 === -1 || code2 === 32;
}
const unicodePunctuation = regexCheck(new RegExp("\\p{P}|\\p{S}", "u"));
const unicodeWhitespace = regexCheck(/\s/);
function regexCheck(regex) {
  return check;
  function check(code2) {
    return code2 !== null && code2 > -1 && regex.test(String.fromCharCode(code2));
  }
}
function normalizeUri(value) {
  const result = [];
  let index2 = -1;
  let start = 0;
  let skip = 0;
  while (++index2 < value.length) {
    const code2 = value.charCodeAt(index2);
    let replace = "";
    if (code2 === 37 && asciiAlphanumeric(value.charCodeAt(index2 + 1)) && asciiAlphanumeric(value.charCodeAt(index2 + 2))) {
      skip = 2;
    } else if (code2 < 128) {
      if (!/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(code2))) {
        replace = String.fromCharCode(code2);
      }
    } else if (code2 > 55295 && code2 < 57344) {
      const next = value.charCodeAt(index2 + 1);
      if (code2 < 56320 && next > 56319 && next < 57344) {
        replace = String.fromCharCode(code2, next);
        skip = 1;
      } else {
        replace = "�";
      }
    } else {
      replace = String.fromCharCode(code2);
    }
    if (replace) {
      result.push(value.slice(start, index2), encodeURIComponent(replace));
      start = index2 + skip + 1;
      replace = "";
    }
    if (skip) {
      index2 += skip;
      skip = 0;
    }
  }
  return result.join("") + value.slice(start);
}
function factorySpace(effects, ok2, type2, max2) {
  const limit = max2 ? max2 - 1 : Number.POSITIVE_INFINITY;
  let size = 0;
  return start;
  function start(code2) {
    if (markdownSpace(code2)) {
      effects.enter(type2);
      return prefix(code2);
    }
    return ok2(code2);
  }
  function prefix(code2) {
    if (markdownSpace(code2) && size++ < limit) {
      effects.consume(code2);
      return prefix;
    }
    effects.exit(type2);
    return ok2(code2);
  }
}
const content$1 = {
  tokenize: initializeContent
};
function initializeContent(effects) {
  const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial);
  let previous2;
  return contentStart;
  function afterContentStartConstruct(code2) {
    if (code2 === null) {
      effects.consume(code2);
      return;
    }
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return factorySpace(effects, contentStart, "linePrefix");
  }
  function paragraphInitial(code2) {
    effects.enter("paragraph");
    return lineStart(code2);
  }
  function lineStart(code2) {
    const token = effects.enter("chunkText", {
      contentType: "text",
      previous: previous2
    });
    if (previous2) {
      previous2.next = token;
    }
    previous2 = token;
    return data(code2);
  }
  function data(code2) {
    if (code2 === null) {
      effects.exit("chunkText");
      effects.exit("paragraph");
      effects.consume(code2);
      return;
    }
    if (markdownLineEnding(code2)) {
      effects.consume(code2);
      effects.exit("chunkText");
      return lineStart;
    }
    effects.consume(code2);
    return data;
  }
}
const document$2 = {
  tokenize: initializeDocument
};
const containerConstruct = {
  tokenize: tokenizeContainer
};
function initializeDocument(effects) {
  const self2 = this;
  const stack = [];
  let continued = 0;
  let childFlow;
  let childToken;
  let lineStartOffset;
  return start;
  function start(code2) {
    if (continued < stack.length) {
      const item = stack[continued];
      self2.containerState = item[1];
      return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code2);
    }
    return checkNewContainers(code2);
  }
  function documentContinue(code2) {
    continued++;
    if (self2.containerState._closeFlow) {
      self2.containerState._closeFlow = void 0;
      if (childFlow) {
        closeFlow();
      }
      const indexBeforeExits = self2.events.length;
      let indexBeforeFlow = indexBeforeExits;
      let point2;
      while (indexBeforeFlow--) {
        if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === "chunkFlow") {
          point2 = self2.events[indexBeforeFlow][1].end;
          break;
        }
      }
      exitContainers(continued);
      let index2 = indexBeforeExits;
      while (index2 < self2.events.length) {
        self2.events[index2][1].end = {
          ...point2
        };
        index2++;
      }
      splice(self2.events, indexBeforeFlow + 1, 0, self2.events.slice(indexBeforeExits));
      self2.events.length = index2;
      return checkNewContainers(code2);
    }
    return start(code2);
  }
  function checkNewContainers(code2) {
    if (continued === stack.length) {
      if (!childFlow) {
        return documentContinued(code2);
      }
      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
        return flowStart(code2);
      }
      self2.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);
    }
    self2.containerState = {};
    return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code2);
  }
  function thereIsANewContainer(code2) {
    if (childFlow) closeFlow();
    exitContainers(continued);
    return documentContinued(code2);
  }
  function thereIsNoNewContainer(code2) {
    self2.parser.lazy[self2.now().line] = continued !== stack.length;
    lineStartOffset = self2.now().offset;
    return flowStart(code2);
  }
  function documentContinued(code2) {
    self2.containerState = {};
    return effects.attempt(containerConstruct, containerContinue, flowStart)(code2);
  }
  function containerContinue(code2) {
    continued++;
    stack.push([self2.currentConstruct, self2.containerState]);
    return documentContinued(code2);
  }
  function flowStart(code2) {
    if (code2 === null) {
      if (childFlow) closeFlow();
      exitContainers(0);
      effects.consume(code2);
      return;
    }
    childFlow = childFlow || self2.parser.flow(self2.now());
    effects.enter("chunkFlow", {
      _tokenizer: childFlow,
      contentType: "flow",
      previous: childToken
    });
    return flowContinue(code2);
  }
  function flowContinue(code2) {
    if (code2 === null) {
      writeToChild(effects.exit("chunkFlow"), true);
      exitContainers(0);
      effects.consume(code2);
      return;
    }
    if (markdownLineEnding(code2)) {
      effects.consume(code2);
      writeToChild(effects.exit("chunkFlow"));
      continued = 0;
      self2.interrupt = void 0;
      return start;
    }
    effects.consume(code2);
    return flowContinue;
  }
  function writeToChild(token, endOfFile) {
    const stream2 = self2.sliceStream(token);
    if (endOfFile) stream2.push(null);
    token.previous = childToken;
    if (childToken) childToken.next = token;
    childToken = token;
    childFlow.defineSkip(token.start);
    childFlow.write(stream2);
    if (self2.parser.lazy[token.start.line]) {
      let index2 = childFlow.events.length;
      while (index2--) {
        if (
          // The token starts before the line ending…
          childFlow.events[index2][1].start.offset < lineStartOffset && // …and either is not ended yet…
          (!childFlow.events[index2][1].end || // …or ends after it.
          childFlow.events[index2][1].end.offset > lineStartOffset)
        ) {
          return;
        }
      }
      const indexBeforeExits = self2.events.length;
      let indexBeforeFlow = indexBeforeExits;
      let seen;
      let point2;
      while (indexBeforeFlow--) {
        if (self2.events[indexBeforeFlow][0] === "exit" && self2.events[indexBeforeFlow][1].type === "chunkFlow") {
          if (seen) {
            point2 = self2.events[indexBeforeFlow][1].end;
            break;
          }
          seen = true;
        }
      }
      exitContainers(continued);
      index2 = indexBeforeExits;
      while (index2 < self2.events.length) {
        self2.events[index2][1].end = {
          ...point2
        };
        index2++;
      }
      splice(self2.events, indexBeforeFlow + 1, 0, self2.events.slice(indexBeforeExits));
      self2.events.length = index2;
    }
  }
  function exitContainers(size) {
    let index2 = stack.length;
    while (index2-- > size) {
      const entry = stack[index2];
      self2.containerState = entry[1];
      entry[0].exit.call(self2, effects);
    }
    stack.length = size;
  }
  function closeFlow() {
    childFlow.write([null]);
    childToken = void 0;
    childFlow = void 0;
    self2.containerState._closeFlow = void 0;
  }
}
function tokenizeContainer(effects, ok2, nok) {
  return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok2, nok), "linePrefix", this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4);
}
function classifyCharacter(code2) {
  if (code2 === null || markdownLineEndingOrSpace(code2) || unicodeWhitespace(code2)) {
    return 1;
  }
  if (unicodePunctuation(code2)) {
    return 2;
  }
}
function resolveAll(constructs2, events, context) {
  const called = [];
  let index2 = -1;
  while (++index2 < constructs2.length) {
    const resolve = constructs2[index2].resolveAll;
    if (resolve && !called.includes(resolve)) {
      events = resolve(events, context);
      called.push(resolve);
    }
  }
  return events;
}
const attention = {
  name: "attention",
  resolveAll: resolveAllAttention,
  tokenize: tokenizeAttention
};
function resolveAllAttention(events, context) {
  let index2 = -1;
  let open;
  let group;
  let text2;
  let openingSequence;
  let closingSequence;
  let use;
  let nextEvents;
  let offset;
  while (++index2 < events.length) {
    if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
      open = index2;
      while (open--) {
        if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open && // If the markers are the same:
        context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
          if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
            continue;
          }
          use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
          const start = {
            ...events[open][1].end
          };
          const end = {
            ...events[index2][1].start
          };
          movePoint(start, -use);
          movePoint(end, use);
          openingSequence = {
            type: use > 1 ? "strongSequence" : "emphasisSequence",
            start,
            end: {
              ...events[open][1].end
            }
          };
          closingSequence = {
            type: use > 1 ? "strongSequence" : "emphasisSequence",
            start: {
              ...events[index2][1].start
            },
            end
          };
          text2 = {
            type: use > 1 ? "strongText" : "emphasisText",
            start: {
              ...events[open][1].end
            },
            end: {
              ...events[index2][1].start
            }
          };
          group = {
            type: use > 1 ? "strong" : "emphasis",
            start: {
              ...openingSequence.start
            },
            end: {
              ...closingSequence.end
            }
          };
          events[open][1].end = {
            ...openingSequence.start
          };
          events[index2][1].start = {
            ...closingSequence.end
          };
          nextEvents = [];
          if (events[open][1].end.offset - events[open][1].start.offset) {
            nextEvents = push(nextEvents, [["enter", events[open][1], context], ["exit", events[open][1], context]]);
          }
          nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text2, context]]);
          nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context));
          nextEvents = push(nextEvents, [["exit", text2, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
          if (events[index2][1].end.offset - events[index2][1].start.offset) {
            offset = 2;
            nextEvents = push(nextEvents, [["enter", events[index2][1], context], ["exit", events[index2][1], context]]);
          } else {
            offset = 0;
          }
          splice(events, open - 1, index2 - open + 3, nextEvents);
          index2 = open + nextEvents.length - offset - 2;
          break;
        }
      }
    }
  }
  index2 = -1;
  while (++index2 < events.length) {
    if (events[index2][1].type === "attentionSequence") {
      events[index2][1].type = "data";
    }
  }
  return events;
}
function tokenizeAttention(effects, ok2) {
  const attentionMarkers2 = this.parser.constructs.attentionMarkers.null;
  const previous2 = this.previous;
  const before = classifyCharacter(previous2);
  let marker;
  return start;
  function start(code2) {
    marker = code2;
    effects.enter("attentionSequence");
    return inside(code2);
  }
  function inside(code2) {
    if (code2 === marker) {
      effects.consume(code2);
      return inside;
    }
    const token = effects.exit("attentionSequence");
    const after = classifyCharacter(code2);
    const open = !after || after === 2 && before || attentionMarkers2.includes(code2);
    const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
    token._open = Boolean(marker === 42 ? open : open && (before || !close));
    token._close = Boolean(marker === 42 ? close : close && (after || !open));
    return ok2(code2);
  }
}
function movePoint(point2, offset) {
  point2.column += offset;
  point2.offset += offset;
  point2._bufferIndex += offset;
}
const autolink = {
  name: "autolink",
  tokenize: tokenizeAutolink
};
function tokenizeAutolink(effects, ok2, nok) {
  let size = 0;
  return start;
  function start(code2) {
    effects.enter("autolink");
    effects.enter("autolinkMarker");
    effects.consume(code2);
    effects.exit("autolinkMarker");
    effects.enter("autolinkProtocol");
    return open;
  }
  function open(code2) {
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      return schemeOrEmailAtext;
    }
    if (code2 === 64) {
      return nok(code2);
    }
    return emailAtext(code2);
  }
  function schemeOrEmailAtext(code2) {
    if (code2 === 43 || code2 === 45 || code2 === 46 || asciiAlphanumeric(code2)) {
      size = 1;
      return schemeInsideOrEmailAtext(code2);
    }
    return emailAtext(code2);
  }
  function schemeInsideOrEmailAtext(code2) {
    if (code2 === 58) {
      effects.consume(code2);
      size = 0;
      return urlInside;
    }
    if ((code2 === 43 || code2 === 45 || code2 === 46 || asciiAlphanumeric(code2)) && size++ < 32) {
      effects.consume(code2);
      return schemeInsideOrEmailAtext;
    }
    size = 0;
    return emailAtext(code2);
  }
  function urlInside(code2) {
    if (code2 === 62) {
      effects.exit("autolinkProtocol");
      effects.enter("autolinkMarker");
      effects.consume(code2);
      effects.exit("autolinkMarker");
      effects.exit("autolink");
      return ok2;
    }
    if (code2 === null || code2 === 32 || code2 === 60 || asciiControl(code2)) {
      return nok(code2);
    }
    effects.consume(code2);
    return urlInside;
  }
  function emailAtext(code2) {
    if (code2 === 64) {
      effects.consume(code2);
      return emailAtSignOrDot;
    }
    if (asciiAtext(code2)) {
      effects.consume(code2);
      return emailAtext;
    }
    return nok(code2);
  }
  function emailAtSignOrDot(code2) {
    return asciiAlphanumeric(code2) ? emailLabel(code2) : nok(code2);
  }
  function emailLabel(code2) {
    if (code2 === 46) {
      effects.consume(code2);
      size = 0;
      return emailAtSignOrDot;
    }
    if (code2 === 62) {
      effects.exit("autolinkProtocol").type = "autolinkEmail";
      effects.enter("autolinkMarker");
      effects.consume(code2);
      effects.exit("autolinkMarker");
      effects.exit("autolink");
      return ok2;
    }
    return emailValue(code2);
  }
  function emailValue(code2) {
    if ((code2 === 45 || asciiAlphanumeric(code2)) && size++ < 63) {
      const next = code2 === 45 ? emailValue : emailLabel;
      effects.consume(code2);
      return next;
    }
    return nok(code2);
  }
}
const blankLine = {
  partial: true,
  tokenize: tokenizeBlankLine
};
function tokenizeBlankLine(effects, ok2, nok) {
  return start;
  function start(code2) {
    return markdownSpace(code2) ? factorySpace(effects, after, "linePrefix")(code2) : after(code2);
  }
  function after(code2) {
    return code2 === null || markdownLineEnding(code2) ? ok2(code2) : nok(code2);
  }
}
const blockQuote = {
  continuation: {
    tokenize: tokenizeBlockQuoteContinuation
  },
  exit,
  name: "blockQuote",
  tokenize: tokenizeBlockQuoteStart
};
function tokenizeBlockQuoteStart(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code2) {
    if (code2 === 62) {
      const state = self2.containerState;
      if (!state.open) {
        effects.enter("blockQuote", {
          _container: true
        });
        state.open = true;
      }
      effects.enter("blockQuotePrefix");
      effects.enter("blockQuoteMarker");
      effects.consume(code2);
      effects.exit("blockQuoteMarker");
      return after;
    }
    return nok(code2);
  }
  function after(code2) {
    if (markdownSpace(code2)) {
      effects.enter("blockQuotePrefixWhitespace");
      effects.consume(code2);
      effects.exit("blockQuotePrefixWhitespace");
      effects.exit("blockQuotePrefix");
      return ok2;
    }
    effects.exit("blockQuotePrefix");
    return ok2(code2);
  }
}
function tokenizeBlockQuoteContinuation(effects, ok2, nok) {
  const self2 = this;
  return contStart;
  function contStart(code2) {
    if (markdownSpace(code2)) {
      return factorySpace(effects, contBefore, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code2);
    }
    return contBefore(code2);
  }
  function contBefore(code2) {
    return effects.attempt(blockQuote, ok2, nok)(code2);
  }
}
function exit(effects) {
  effects.exit("blockQuote");
}
const characterEscape = {
  name: "characterEscape",
  tokenize: tokenizeCharacterEscape
};
function tokenizeCharacterEscape(effects, ok2, nok) {
  return start;
  function start(code2) {
    effects.enter("characterEscape");
    effects.enter("escapeMarker");
    effects.consume(code2);
    effects.exit("escapeMarker");
    return inside;
  }
  function inside(code2) {
    if (asciiPunctuation(code2)) {
      effects.enter("characterEscapeValue");
      effects.consume(code2);
      effects.exit("characterEscapeValue");
      effects.exit("characterEscape");
      return ok2;
    }
    return nok(code2);
  }
}
const characterReference = {
  name: "characterReference",
  tokenize: tokenizeCharacterReference
};
function tokenizeCharacterReference(effects, ok2, nok) {
  const self2 = this;
  let size = 0;
  let max2;
  let test2;
  return start;
  function start(code2) {
    effects.enter("characterReference");
    effects.enter("characterReferenceMarker");
    effects.consume(code2);
    effects.exit("characterReferenceMarker");
    return open;
  }
  function open(code2) {
    if (code2 === 35) {
      effects.enter("characterReferenceMarkerNumeric");
      effects.consume(code2);
      effects.exit("characterReferenceMarkerNumeric");
      return numeric;
    }
    effects.enter("characterReferenceValue");
    max2 = 31;
    test2 = asciiAlphanumeric;
    return value(code2);
  }
  function numeric(code2) {
    if (code2 === 88 || code2 === 120) {
      effects.enter("characterReferenceMarkerHexadecimal");
      effects.consume(code2);
      effects.exit("characterReferenceMarkerHexadecimal");
      effects.enter("characterReferenceValue");
      max2 = 6;
      test2 = asciiHexDigit;
      return value;
    }
    effects.enter("characterReferenceValue");
    max2 = 7;
    test2 = asciiDigit;
    return value(code2);
  }
  function value(code2) {
    if (code2 === 59 && size) {
      const token = effects.exit("characterReferenceValue");
      if (test2 === asciiAlphanumeric && !decodeNamedCharacterReference(self2.sliceSerialize(token))) {
        return nok(code2);
      }
      effects.enter("characterReferenceMarker");
      effects.consume(code2);
      effects.exit("characterReferenceMarker");
      effects.exit("characterReference");
      return ok2;
    }
    if (test2(code2) && size++ < max2) {
      effects.consume(code2);
      return value;
    }
    return nok(code2);
  }
}
const nonLazyContinuation = {
  partial: true,
  tokenize: tokenizeNonLazyContinuation
};
const codeFenced = {
  concrete: true,
  name: "codeFenced",
  tokenize: tokenizeCodeFenced
};
function tokenizeCodeFenced(effects, ok2, nok) {
  const self2 = this;
  const closeStart = {
    partial: true,
    tokenize: tokenizeCloseStart
  };
  let initialPrefix = 0;
  let sizeOpen = 0;
  let marker;
  return start;
  function start(code2) {
    return beforeSequenceOpen(code2);
  }
  function beforeSequenceOpen(code2) {
    const tail = self2.events[self2.events.length - 1];
    initialPrefix = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0;
    marker = code2;
    effects.enter("codeFenced");
    effects.enter("codeFencedFence");
    effects.enter("codeFencedFenceSequence");
    return sequenceOpen(code2);
  }
  function sequenceOpen(code2) {
    if (code2 === marker) {
      sizeOpen++;
      effects.consume(code2);
      return sequenceOpen;
    }
    if (sizeOpen < 3) {
      return nok(code2);
    }
    effects.exit("codeFencedFenceSequence");
    return markdownSpace(code2) ? factorySpace(effects, infoBefore, "whitespace")(code2) : infoBefore(code2);
  }
  function infoBefore(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("codeFencedFence");
      return self2.interrupt ? ok2(code2) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code2);
    }
    effects.enter("codeFencedFenceInfo");
    effects.enter("chunkString", {
      contentType: "string"
    });
    return info(code2);
  }
  function info(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("chunkString");
      effects.exit("codeFencedFenceInfo");
      return infoBefore(code2);
    }
    if (markdownSpace(code2)) {
      effects.exit("chunkString");
      effects.exit("codeFencedFenceInfo");
      return factorySpace(effects, metaBefore, "whitespace")(code2);
    }
    if (code2 === 96 && code2 === marker) {
      return nok(code2);
    }
    effects.consume(code2);
    return info;
  }
  function metaBefore(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      return infoBefore(code2);
    }
    effects.enter("codeFencedFenceMeta");
    effects.enter("chunkString", {
      contentType: "string"
    });
    return meta(code2);
  }
  function meta(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("chunkString");
      effects.exit("codeFencedFenceMeta");
      return infoBefore(code2);
    }
    if (code2 === 96 && code2 === marker) {
      return nok(code2);
    }
    effects.consume(code2);
    return meta;
  }
  function atNonLazyBreak(code2) {
    return effects.attempt(closeStart, after, contentBefore)(code2);
  }
  function contentBefore(code2) {
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return contentStart;
  }
  function contentStart(code2) {
    return initialPrefix > 0 && markdownSpace(code2) ? factorySpace(effects, beforeContentChunk, "linePrefix", initialPrefix + 1)(code2) : beforeContentChunk(code2);
  }
  function beforeContentChunk(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code2);
    }
    effects.enter("codeFlowValue");
    return contentChunk(code2);
  }
  function contentChunk(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("codeFlowValue");
      return beforeContentChunk(code2);
    }
    effects.consume(code2);
    return contentChunk;
  }
  function after(code2) {
    effects.exit("codeFenced");
    return ok2(code2);
  }
  function tokenizeCloseStart(effects2, ok3, nok2) {
    let size = 0;
    return startBefore;
    function startBefore(code2) {
      effects2.enter("lineEnding");
      effects2.consume(code2);
      effects2.exit("lineEnding");
      return start2;
    }
    function start2(code2) {
      effects2.enter("codeFencedFence");
      return markdownSpace(code2) ? factorySpace(effects2, beforeSequenceClose, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code2) : beforeSequenceClose(code2);
    }
    function beforeSequenceClose(code2) {
      if (code2 === marker) {
        effects2.enter("codeFencedFenceSequence");
        return sequenceClose(code2);
      }
      return nok2(code2);
    }
    function sequenceClose(code2) {
      if (code2 === marker) {
        size++;
        effects2.consume(code2);
        return sequenceClose;
      }
      if (size >= sizeOpen) {
        effects2.exit("codeFencedFenceSequence");
        return markdownSpace(code2) ? factorySpace(effects2, sequenceCloseAfter, "whitespace")(code2) : sequenceCloseAfter(code2);
      }
      return nok2(code2);
    }
    function sequenceCloseAfter(code2) {
      if (code2 === null || markdownLineEnding(code2)) {
        effects2.exit("codeFencedFence");
        return ok3(code2);
      }
      return nok2(code2);
    }
  }
}
function tokenizeNonLazyContinuation(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code2) {
    if (code2 === null) {
      return nok(code2);
    }
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return lineStart;
  }
  function lineStart(code2) {
    return self2.parser.lazy[self2.now().line] ? nok(code2) : ok2(code2);
  }
}
const codeIndented = {
  name: "codeIndented",
  tokenize: tokenizeCodeIndented
};
const furtherStart = {
  partial: true,
  tokenize: tokenizeFurtherStart
};
function tokenizeCodeIndented(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code2) {
    effects.enter("codeIndented");
    return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code2);
  }
  function afterPrefix(code2) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? atBreak(code2) : nok(code2);
  }
  function atBreak(code2) {
    if (code2 === null) {
      return after(code2);
    }
    if (markdownLineEnding(code2)) {
      return effects.attempt(furtherStart, atBreak, after)(code2);
    }
    effects.enter("codeFlowValue");
    return inside(code2);
  }
  function inside(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("codeFlowValue");
      return atBreak(code2);
    }
    effects.consume(code2);
    return inside;
  }
  function after(code2) {
    effects.exit("codeIndented");
    return ok2(code2);
  }
}
function tokenizeFurtherStart(effects, ok2, nok) {
  const self2 = this;
  return furtherStart2;
  function furtherStart2(code2) {
    if (self2.parser.lazy[self2.now().line]) {
      return nok(code2);
    }
    if (markdownLineEnding(code2)) {
      effects.enter("lineEnding");
      effects.consume(code2);
      effects.exit("lineEnding");
      return furtherStart2;
    }
    return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code2);
  }
  function afterPrefix(code2) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? ok2(code2) : markdownLineEnding(code2) ? furtherStart2(code2) : nok(code2);
  }
}
const codeText = {
  name: "codeText",
  previous,
  resolve: resolveCodeText,
  tokenize: tokenizeCodeText
};
function resolveCodeText(events) {
  let tailExitIndex = events.length - 4;
  let headEnterIndex = 3;
  let index2;
  let enter;
  if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) {
    index2 = headEnterIndex;
    while (++index2 < tailExitIndex) {
      if (events[index2][1].type === "codeTextData") {
        events[headEnterIndex][1].type = "codeTextPadding";
        events[tailExitIndex][1].type = "codeTextPadding";
        headEnterIndex += 2;
        tailExitIndex -= 2;
        break;
      }
    }
  }
  index2 = headEnterIndex - 1;
  tailExitIndex++;
  while (++index2 <= tailExitIndex) {
    if (enter === void 0) {
      if (index2 !== tailExitIndex && events[index2][1].type !== "lineEnding") {
        enter = index2;
      }
    } else if (index2 === tailExitIndex || events[index2][1].type === "lineEnding") {
      events[enter][1].type = "codeTextData";
      if (index2 !== enter + 2) {
        events[enter][1].end = events[index2 - 1][1].end;
        events.splice(enter + 2, index2 - enter - 2);
        tailExitIndex -= index2 - enter - 2;
        index2 = enter + 2;
      }
      enter = void 0;
    }
  }
  return events;
}
function previous(code2) {
  return code2 !== 96 || this.events[this.events.length - 1][1].type === "characterEscape";
}
function tokenizeCodeText(effects, ok2, nok) {
  let sizeOpen = 0;
  let size;
  let token;
  return start;
  function start(code2) {
    effects.enter("codeText");
    effects.enter("codeTextSequence");
    return sequenceOpen(code2);
  }
  function sequenceOpen(code2) {
    if (code2 === 96) {
      effects.consume(code2);
      sizeOpen++;
      return sequenceOpen;
    }
    effects.exit("codeTextSequence");
    return between(code2);
  }
  function between(code2) {
    if (code2 === null) {
      return nok(code2);
    }
    if (code2 === 32) {
      effects.enter("space");
      effects.consume(code2);
      effects.exit("space");
      return between;
    }
    if (code2 === 96) {
      token = effects.enter("codeTextSequence");
      size = 0;
      return sequenceClose(code2);
    }
    if (markdownLineEnding(code2)) {
      effects.enter("lineEnding");
      effects.consume(code2);
      effects.exit("lineEnding");
      return between;
    }
    effects.enter("codeTextData");
    return data(code2);
  }
  function data(code2) {
    if (code2 === null || code2 === 32 || code2 === 96 || markdownLineEnding(code2)) {
      effects.exit("codeTextData");
      return between(code2);
    }
    effects.consume(code2);
    return data;
  }
  function sequenceClose(code2) {
    if (code2 === 96) {
      effects.consume(code2);
      size++;
      return sequenceClose;
    }
    if (size === sizeOpen) {
      effects.exit("codeTextSequence");
      effects.exit("codeText");
      return ok2(code2);
    }
    token.type = "codeTextData";
    return data(code2);
  }
}
class SpliceBuffer {
  /**
   * @param {ReadonlyArray<T> | null | undefined} [initial]
   *   Initial items (optional).
   * @returns
   *   Splice buffer.
   */
  constructor(initial) {
    this.left = initial ? [...initial] : [];
    this.right = [];
  }
  /**
   * Array access;
   * does not move the cursor.
   *
   * @param {number} index
   *   Index.
   * @return {T}
   *   Item.
   */
  get(index2) {
    if (index2 < 0 || index2 >= this.left.length + this.right.length) {
      throw new RangeError("Cannot access index `" + index2 + "` in a splice buffer of size `" + (this.left.length + this.right.length) + "`");
    }
    if (index2 < this.left.length) return this.left[index2];
    return this.right[this.right.length - index2 + this.left.length - 1];
  }
  /**
   * The length of the splice buffer, one greater than the largest index in the
   * array.
   */
  get length() {
    return this.left.length + this.right.length;
  }
  /**
   * Remove and return `list[0]`;
   * moves the cursor to `0`.
   *
   * @returns {T | undefined}
   *   Item, optional.
   */
  shift() {
    this.setCursor(0);
    return this.right.pop();
  }
  /**
   * Slice the buffer to get an array;
   * does not move the cursor.
   *
   * @param {number} start
   *   Start.
   * @param {number | null | undefined} [end]
   *   End (optional).
   * @returns {Array<T>}
   *   Array of items.
   */
  slice(start, end) {
    const stop = end === null || end === void 0 ? Number.POSITIVE_INFINITY : end;
    if (stop < this.left.length) {
      return this.left.slice(start, stop);
    }
    if (start > this.left.length) {
      return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();
    }
    return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());
  }
  /**
   * Mimics the behavior of Array.prototype.splice() except for the change of
   * interface necessary to avoid segfaults when patching in very large arrays.
   *
   * This operation moves cursor is moved to `start` and results in the cursor
   * placed after any inserted items.
   *
   * @param {number} start
   *   Start;
   *   zero-based index at which to start changing the array;
   *   negative numbers count backwards from the end of the array and values
   *   that are out-of bounds are clamped to the appropriate end of the array.
   * @param {number | null | undefined} [deleteCount=0]
   *   Delete count (default: `0`);
   *   maximum number of elements to delete, starting from start.
   * @param {Array<T> | null | undefined} [items=[]]
   *   Items to include in place of the deleted items (default: `[]`).
   * @return {Array<T>}
   *   Any removed items.
   */
  splice(start, deleteCount, items) {
    const count = deleteCount || 0;
    this.setCursor(Math.trunc(start));
    const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);
    if (items) chunkedPush(this.left, items);
    return removed.reverse();
  }
  /**
   * Remove and return the highest-numbered item in the array, so
   * `list[list.length - 1]`;
   * Moves the cursor to `length`.
   *
   * @returns {T | undefined}
   *   Item, optional.
   */
  pop() {
    this.setCursor(Number.POSITIVE_INFINITY);
    return this.left.pop();
  }
  /**
   * Inserts a single item to the high-numbered side of the array;
   * moves the cursor to `length`.
   *
   * @param {T} item
   *   Item.
   * @returns {undefined}
   *   Nothing.
   */
  push(item) {
    this.setCursor(Number.POSITIVE_INFINITY);
    this.left.push(item);
  }
  /**
   * Inserts many items to the high-numbered side of the array.
   * Moves the cursor to `length`.
   *
   * @param {Array<T>} items
   *   Items.
   * @returns {undefined}
   *   Nothing.
   */
  pushMany(items) {
    this.setCursor(Number.POSITIVE_INFINITY);
    chunkedPush(this.left, items);
  }
  /**
   * Inserts a single item to the low-numbered side of the array;
   * Moves the cursor to `0`.
   *
   * @param {T} item
   *   Item.
   * @returns {undefined}
   *   Nothing.
   */
  unshift(item) {
    this.setCursor(0);
    this.right.push(item);
  }
  /**
   * Inserts many items to the low-numbered side of the array;
   * moves the cursor to `0`.
   *
   * @param {Array<T>} items
   *   Items.
   * @returns {undefined}
   *   Nothing.
   */
  unshiftMany(items) {
    this.setCursor(0);
    chunkedPush(this.right, items.reverse());
  }
  /**
   * Move the cursor to a specific position in the array. Requires
   * time proportional to the distance moved.
   *
   * If `n < 0`, the cursor will end up at the beginning.
   * If `n > length`, the cursor will end up at the end.
   *
   * @param {number} n
   *   Position.
   * @return {undefined}
   *   Nothing.
   */
  setCursor(n) {
    if (n === this.left.length || n > this.left.length && this.right.length === 0 || n < 0 && this.left.length === 0) return;
    if (n < this.left.length) {
      const removed = this.left.splice(n, Number.POSITIVE_INFINITY);
      chunkedPush(this.right, removed.reverse());
    } else {
      const removed = this.right.splice(this.left.length + this.right.length - n, Number.POSITIVE_INFINITY);
      chunkedPush(this.left, removed.reverse());
    }
  }
}
function chunkedPush(list2, right) {
  let chunkStart = 0;
  if (right.length < 1e4) {
    list2.push(...right);
  } else {
    while (chunkStart < right.length) {
      list2.push(...right.slice(chunkStart, chunkStart + 1e4));
      chunkStart += 1e4;
    }
  }
}
function subtokenize(eventsArray) {
  const jumps = {};
  let index2 = -1;
  let event;
  let lineIndex;
  let otherIndex;
  let otherEvent;
  let parameters;
  let subevents;
  let more;
  const events = new SpliceBuffer(eventsArray);
  while (++index2 < events.length) {
    while (index2 in jumps) {
      index2 = jumps[index2];
    }
    event = events.get(index2);
    if (index2 && event[1].type === "chunkFlow" && events.get(index2 - 1)[1].type === "listItemPrefix") {
      subevents = event[1]._tokenizer.events;
      otherIndex = 0;
      if (otherIndex < subevents.length && subevents[otherIndex][1].type === "lineEndingBlank") {
        otherIndex += 2;
      }
      if (otherIndex < subevents.length && subevents[otherIndex][1].type === "content") {
        while (++otherIndex < subevents.length) {
          if (subevents[otherIndex][1].type === "content") {
            break;
          }
          if (subevents[otherIndex][1].type === "chunkText") {
            subevents[otherIndex][1]._isInFirstContentOfListItem = true;
            otherIndex++;
          }
        }
      }
    }
    if (event[0] === "enter") {
      if (event[1].contentType) {
        Object.assign(jumps, subcontent(events, index2));
        index2 = jumps[index2];
        more = true;
      }
    } else if (event[1]._container) {
      otherIndex = index2;
      lineIndex = void 0;
      while (otherIndex--) {
        otherEvent = events.get(otherIndex);
        if (otherEvent[1].type === "lineEnding" || otherEvent[1].type === "lineEndingBlank") {
          if (otherEvent[0] === "enter") {
            if (lineIndex) {
              events.get(lineIndex)[1].type = "lineEndingBlank";
            }
            otherEvent[1].type = "lineEnding";
            lineIndex = otherIndex;
          }
        } else if (otherEvent[1].type === "linePrefix" || otherEvent[1].type === "listItemIndent") ;
        else {
          break;
        }
      }
      if (lineIndex) {
        event[1].end = {
          ...events.get(lineIndex)[1].start
        };
        parameters = events.slice(lineIndex, index2);
        parameters.unshift(event);
        events.splice(lineIndex, index2 - lineIndex + 1, parameters);
      }
    }
  }
  splice(eventsArray, 0, Number.POSITIVE_INFINITY, events.slice(0));
  return !more;
}
function subcontent(events, eventIndex) {
  const token = events.get(eventIndex)[1];
  const context = events.get(eventIndex)[2];
  let startPosition = eventIndex - 1;
  const startPositions = [];
  let tokenizer = token._tokenizer;
  if (!tokenizer) {
    tokenizer = context.parser[token.contentType](token.start);
    if (token._contentTypeTextTrailing) {
      tokenizer._contentTypeTextTrailing = true;
    }
  }
  const childEvents = tokenizer.events;
  const jumps = [];
  const gaps = {};
  let stream2;
  let previous2;
  let index2 = -1;
  let current = token;
  let adjust = 0;
  let start = 0;
  const breaks = [start];
  while (current) {
    while (events.get(++startPosition)[1] !== current) {
    }
    startPositions.push(startPosition);
    if (!current._tokenizer) {
      stream2 = context.sliceStream(current);
      if (!current.next) {
        stream2.push(null);
      }
      if (previous2) {
        tokenizer.defineSkip(current.start);
      }
      if (current._isInFirstContentOfListItem) {
        tokenizer._gfmTasklistFirstContentOfListItem = true;
      }
      tokenizer.write(stream2);
      if (current._isInFirstContentOfListItem) {
        tokenizer._gfmTasklistFirstContentOfListItem = void 0;
      }
    }
    previous2 = current;
    current = current.next;
  }
  current = token;
  while (++index2 < childEvents.length) {
    if (
      // Find a void token that includes a break.
      childEvents[index2][0] === "exit" && childEvents[index2 - 1][0] === "enter" && childEvents[index2][1].type === childEvents[index2 - 1][1].type && childEvents[index2][1].start.line !== childEvents[index2][1].end.line
    ) {
      start = index2 + 1;
      breaks.push(start);
      current._tokenizer = void 0;
      current.previous = void 0;
      current = current.next;
    }
  }
  tokenizer.events = [];
  if (current) {
    current._tokenizer = void 0;
    current.previous = void 0;
  } else {
    breaks.pop();
  }
  index2 = breaks.length;
  while (index2--) {
    const slice = childEvents.slice(breaks[index2], breaks[index2 + 1]);
    const start2 = startPositions.pop();
    jumps.push([start2, start2 + slice.length - 1]);
    events.splice(start2, 2, slice);
  }
  jumps.reverse();
  index2 = -1;
  while (++index2 < jumps.length) {
    gaps[adjust + jumps[index2][0]] = adjust + jumps[index2][1];
    adjust += jumps[index2][1] - jumps[index2][0] - 1;
  }
  return gaps;
}
const content = {
  resolve: resolveContent,
  tokenize: tokenizeContent
};
const continuationConstruct = {
  partial: true,
  tokenize: tokenizeContinuation
};
function resolveContent(events) {
  subtokenize(events);
  return events;
}
function tokenizeContent(effects, ok2) {
  let previous2;
  return chunkStart;
  function chunkStart(code2) {
    effects.enter("content");
    previous2 = effects.enter("chunkContent", {
      contentType: "content"
    });
    return chunkInside(code2);
  }
  function chunkInside(code2) {
    if (code2 === null) {
      return contentEnd(code2);
    }
    if (markdownLineEnding(code2)) {
      return effects.check(continuationConstruct, contentContinue, contentEnd)(code2);
    }
    effects.consume(code2);
    return chunkInside;
  }
  function contentEnd(code2) {
    effects.exit("chunkContent");
    effects.exit("content");
    return ok2(code2);
  }
  function contentContinue(code2) {
    effects.consume(code2);
    effects.exit("chunkContent");
    previous2.next = effects.enter("chunkContent", {
      contentType: "content",
      previous: previous2
    });
    previous2 = previous2.next;
    return chunkInside;
  }
}
function tokenizeContinuation(effects, ok2, nok) {
  const self2 = this;
  return startLookahead;
  function startLookahead(code2) {
    effects.exit("chunkContent");
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return factorySpace(effects, prefixed, "linePrefix");
  }
  function prefixed(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      return nok(code2);
    }
    const tail = self2.events[self2.events.length - 1];
    if (!self2.parser.constructs.disable.null.includes("codeIndented") && tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4) {
      return ok2(code2);
    }
    return effects.interrupt(self2.parser.constructs.flow, nok, ok2)(code2);
  }
}
function factoryDestination(effects, ok2, nok, type2, literalType, literalMarkerType, rawType, stringType, max2) {
  const limit = max2 || Number.POSITIVE_INFINITY;
  let balance = 0;
  return start;
  function start(code2) {
    if (code2 === 60) {
      effects.enter(type2);
      effects.enter(literalType);
      effects.enter(literalMarkerType);
      effects.consume(code2);
      effects.exit(literalMarkerType);
      return enclosedBefore;
    }
    if (code2 === null || code2 === 32 || code2 === 41 || asciiControl(code2)) {
      return nok(code2);
    }
    effects.enter(type2);
    effects.enter(rawType);
    effects.enter(stringType);
    effects.enter("chunkString", {
      contentType: "string"
    });
    return raw(code2);
  }
  function enclosedBefore(code2) {
    if (code2 === 62) {
      effects.enter(literalMarkerType);
      effects.consume(code2);
      effects.exit(literalMarkerType);
      effects.exit(literalType);
      effects.exit(type2);
      return ok2;
    }
    effects.enter(stringType);
    effects.enter("chunkString", {
      contentType: "string"
    });
    return enclosed(code2);
  }
  function enclosed(code2) {
    if (code2 === 62) {
      effects.exit("chunkString");
      effects.exit(stringType);
      return enclosedBefore(code2);
    }
    if (code2 === null || code2 === 60 || markdownLineEnding(code2)) {
      return nok(code2);
    }
    effects.consume(code2);
    return code2 === 92 ? enclosedEscape : enclosed;
  }
  function enclosedEscape(code2) {
    if (code2 === 60 || code2 === 62 || code2 === 92) {
      effects.consume(code2);
      return enclosed;
    }
    return enclosed(code2);
  }
  function raw(code2) {
    if (!balance && (code2 === null || code2 === 41 || markdownLineEndingOrSpace(code2))) {
      effects.exit("chunkString");
      effects.exit(stringType);
      effects.exit(rawType);
      effects.exit(type2);
      return ok2(code2);
    }
    if (balance < limit && code2 === 40) {
      effects.consume(code2);
      balance++;
      return raw;
    }
    if (code2 === 41) {
      effects.consume(code2);
      balance--;
      return raw;
    }
    if (code2 === null || code2 === 32 || code2 === 40 || asciiControl(code2)) {
      return nok(code2);
    }
    effects.consume(code2);
    return code2 === 92 ? rawEscape : raw;
  }
  function rawEscape(code2) {
    if (code2 === 40 || code2 === 41 || code2 === 92) {
      effects.consume(code2);
      return raw;
    }
    return raw(code2);
  }
}
function factoryLabel(effects, ok2, nok, type2, markerType, stringType) {
  const self2 = this;
  let size = 0;
  let seen;
  return start;
  function start(code2) {
    effects.enter(type2);
    effects.enter(markerType);
    effects.consume(code2);
    effects.exit(markerType);
    effects.enter(stringType);
    return atBreak;
  }
  function atBreak(code2) {
    if (size > 999 || code2 === null || code2 === 91 || code2 === 93 && !seen || // To do: remove in the future once we’ve switched from
    // `micromark-extension-footnote` to `micromark-extension-gfm-footnote`,
    // which doesn’t need this.
    // Hidden footnotes hook.
    /* c8 ignore next 3 */
    code2 === 94 && !size && "_hiddenFootnoteSupport" in self2.parser.constructs) {
      return nok(code2);
    }
    if (code2 === 93) {
      effects.exit(stringType);
      effects.enter(markerType);
      effects.consume(code2);
      effects.exit(markerType);
      effects.exit(type2);
      return ok2;
    }
    if (markdownLineEnding(code2)) {
      effects.enter("lineEnding");
      effects.consume(code2);
      effects.exit("lineEnding");
      return atBreak;
    }
    effects.enter("chunkString", {
      contentType: "string"
    });
    return labelInside(code2);
  }
  function labelInside(code2) {
    if (code2 === null || code2 === 91 || code2 === 93 || markdownLineEnding(code2) || size++ > 999) {
      effects.exit("chunkString");
      return atBreak(code2);
    }
    effects.consume(code2);
    if (!seen) seen = !markdownSpace(code2);
    return code2 === 92 ? labelEscape : labelInside;
  }
  function labelEscape(code2) {
    if (code2 === 91 || code2 === 92 || code2 === 93) {
      effects.consume(code2);
      size++;
      return labelInside;
    }
    return labelInside(code2);
  }
}
function factoryTitle(effects, ok2, nok, type2, markerType, stringType) {
  let marker;
  return start;
  function start(code2) {
    if (code2 === 34 || code2 === 39 || code2 === 40) {
      effects.enter(type2);
      effects.enter(markerType);
      effects.consume(code2);
      effects.exit(markerType);
      marker = code2 === 40 ? 41 : code2;
      return begin;
    }
    return nok(code2);
  }
  function begin(code2) {
    if (code2 === marker) {
      effects.enter(markerType);
      effects.consume(code2);
      effects.exit(markerType);
      effects.exit(type2);
      return ok2;
    }
    effects.enter(stringType);
    return atBreak(code2);
  }
  function atBreak(code2) {
    if (code2 === marker) {
      effects.exit(stringType);
      return begin(marker);
    }
    if (code2 === null) {
      return nok(code2);
    }
    if (markdownLineEnding(code2)) {
      effects.enter("lineEnding");
      effects.consume(code2);
      effects.exit("lineEnding");
      return factorySpace(effects, atBreak, "linePrefix");
    }
    effects.enter("chunkString", {
      contentType: "string"
    });
    return inside(code2);
  }
  function inside(code2) {
    if (code2 === marker || code2 === null || markdownLineEnding(code2)) {
      effects.exit("chunkString");
      return atBreak(code2);
    }
    effects.consume(code2);
    return code2 === 92 ? escape2 : inside;
  }
  function escape2(code2) {
    if (code2 === marker || code2 === 92) {
      effects.consume(code2);
      return inside;
    }
    return inside(code2);
  }
}
function factoryWhitespace(effects, ok2) {
  let seen;
  return start;
  function start(code2) {
    if (markdownLineEnding(code2)) {
      effects.enter("lineEnding");
      effects.consume(code2);
      effects.exit("lineEnding");
      seen = true;
      return start;
    }
    if (markdownSpace(code2)) {
      return factorySpace(effects, start, seen ? "linePrefix" : "lineSuffix")(code2);
    }
    return ok2(code2);
  }
}
const definition = {
  name: "definition",
  tokenize: tokenizeDefinition
};
const titleBefore = {
  partial: true,
  tokenize: tokenizeTitleBefore
};
function tokenizeDefinition(effects, ok2, nok) {
  const self2 = this;
  let identifier;
  return start;
  function start(code2) {
    effects.enter("definition");
    return before(code2);
  }
  function before(code2) {
    return factoryLabel.call(
      self2,
      effects,
      labelAfter,
      // Note: we don’t need to reset the way `markdown-rs` does.
      nok,
      "definitionLabel",
      "definitionLabelMarker",
      "definitionLabelString"
    )(code2);
  }
  function labelAfter(code2) {
    identifier = normalizeIdentifier(self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1));
    if (code2 === 58) {
      effects.enter("definitionMarker");
      effects.consume(code2);
      effects.exit("definitionMarker");
      return markerAfter;
    }
    return nok(code2);
  }
  function markerAfter(code2) {
    return markdownLineEndingOrSpace(code2) ? factoryWhitespace(effects, destinationBefore)(code2) : destinationBefore(code2);
  }
  function destinationBefore(code2) {
    return factoryDestination(
      effects,
      destinationAfter,
      // Note: we don’t need to reset the way `markdown-rs` does.
      nok,
      "definitionDestination",
      "definitionDestinationLiteral",
      "definitionDestinationLiteralMarker",
      "definitionDestinationRaw",
      "definitionDestinationString"
    )(code2);
  }
  function destinationAfter(code2) {
    return effects.attempt(titleBefore, after, after)(code2);
  }
  function after(code2) {
    return markdownSpace(code2) ? factorySpace(effects, afterWhitespace, "whitespace")(code2) : afterWhitespace(code2);
  }
  function afterWhitespace(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("definition");
      self2.parser.defined.push(identifier);
      return ok2(code2);
    }
    return nok(code2);
  }
}
function tokenizeTitleBefore(effects, ok2, nok) {
  return titleBefore2;
  function titleBefore2(code2) {
    return markdownLineEndingOrSpace(code2) ? factoryWhitespace(effects, beforeMarker)(code2) : nok(code2);
  }
  function beforeMarker(code2) {
    return factoryTitle(effects, titleAfter, nok, "definitionTitle", "definitionTitleMarker", "definitionTitleString")(code2);
  }
  function titleAfter(code2) {
    return markdownSpace(code2) ? factorySpace(effects, titleAfterOptionalWhitespace, "whitespace")(code2) : titleAfterOptionalWhitespace(code2);
  }
  function titleAfterOptionalWhitespace(code2) {
    return code2 === null || markdownLineEnding(code2) ? ok2(code2) : nok(code2);
  }
}
const hardBreakEscape = {
  name: "hardBreakEscape",
  tokenize: tokenizeHardBreakEscape
};
function tokenizeHardBreakEscape(effects, ok2, nok) {
  return start;
  function start(code2) {
    effects.enter("hardBreakEscape");
    effects.consume(code2);
    return after;
  }
  function after(code2) {
    if (markdownLineEnding(code2)) {
      effects.exit("hardBreakEscape");
      return ok2(code2);
    }
    return nok(code2);
  }
}
const headingAtx = {
  name: "headingAtx",
  resolve: resolveHeadingAtx,
  tokenize: tokenizeHeadingAtx
};
function resolveHeadingAtx(events, context) {
  let contentEnd = events.length - 2;
  let contentStart = 3;
  let content2;
  let text2;
  if (events[contentStart][1].type === "whitespace") {
    contentStart += 2;
  }
  if (contentEnd - 2 > contentStart && events[contentEnd][1].type === "whitespace") {
    contentEnd -= 2;
  }
  if (events[contentEnd][1].type === "atxHeadingSequence" && (contentStart === contentEnd - 1 || contentEnd - 4 > contentStart && events[contentEnd - 2][1].type === "whitespace")) {
    contentEnd -= contentStart + 1 === contentEnd ? 2 : 4;
  }
  if (contentEnd > contentStart) {
    content2 = {
      type: "atxHeadingText",
      start: events[contentStart][1].start,
      end: events[contentEnd][1].end
    };
    text2 = {
      type: "chunkText",
      start: events[contentStart][1].start,
      end: events[contentEnd][1].end,
      contentType: "text"
    };
    splice(events, contentStart, contentEnd - contentStart + 1, [["enter", content2, context], ["enter", text2, context], ["exit", text2, context], ["exit", content2, context]]);
  }
  return events;
}
function tokenizeHeadingAtx(effects, ok2, nok) {
  let size = 0;
  return start;
  function start(code2) {
    effects.enter("atxHeading");
    return before(code2);
  }
  function before(code2) {
    effects.enter("atxHeadingSequence");
    return sequenceOpen(code2);
  }
  function sequenceOpen(code2) {
    if (code2 === 35 && size++ < 6) {
      effects.consume(code2);
      return sequenceOpen;
    }
    if (code2 === null || markdownLineEndingOrSpace(code2)) {
      effects.exit("atxHeadingSequence");
      return atBreak(code2);
    }
    return nok(code2);
  }
  function atBreak(code2) {
    if (code2 === 35) {
      effects.enter("atxHeadingSequence");
      return sequenceFurther(code2);
    }
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("atxHeading");
      return ok2(code2);
    }
    if (markdownSpace(code2)) {
      return factorySpace(effects, atBreak, "whitespace")(code2);
    }
    effects.enter("atxHeadingText");
    return data(code2);
  }
  function sequenceFurther(code2) {
    if (code2 === 35) {
      effects.consume(code2);
      return sequenceFurther;
    }
    effects.exit("atxHeadingSequence");
    return atBreak(code2);
  }
  function data(code2) {
    if (code2 === null || code2 === 35 || markdownLineEndingOrSpace(code2)) {
      effects.exit("atxHeadingText");
      return atBreak(code2);
    }
    effects.consume(code2);
    return data;
  }
}
const htmlBlockNames = [
  "address",
  "article",
  "aside",
  "base",
  "basefont",
  "blockquote",
  "body",
  "caption",
  "center",
  "col",
  "colgroup",
  "dd",
  "details",
  "dialog",
  "dir",
  "div",
  "dl",
  "dt",
  "fieldset",
  "figcaption",
  "figure",
  "footer",
  "form",
  "frame",
  "frameset",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "head",
  "header",
  "hr",
  "html",
  "iframe",
  "legend",
  "li",
  "link",
  "main",
  "menu",
  "menuitem",
  "nav",
  "noframes",
  "ol",
  "optgroup",
  "option",
  "p",
  "param",
  "search",
  "section",
  "summary",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "title",
  "tr",
  "track",
  "ul"
];
const htmlRawNames = ["pre", "script", "style", "textarea"];
const htmlFlow = {
  concrete: true,
  name: "htmlFlow",
  resolveTo: resolveToHtmlFlow,
  tokenize: tokenizeHtmlFlow
};
const blankLineBefore = {
  partial: true,
  tokenize: tokenizeBlankLineBefore
};
const nonLazyContinuationStart = {
  partial: true,
  tokenize: tokenizeNonLazyContinuationStart
};
function resolveToHtmlFlow(events) {
  let index2 = events.length;
  while (index2--) {
    if (events[index2][0] === "enter" && events[index2][1].type === "htmlFlow") {
      break;
    }
  }
  if (index2 > 1 && events[index2 - 2][1].type === "linePrefix") {
    events[index2][1].start = events[index2 - 2][1].start;
    events[index2 + 1][1].start = events[index2 - 2][1].start;
    events.splice(index2 - 2, 2);
  }
  return events;
}
function tokenizeHtmlFlow(effects, ok2, nok) {
  const self2 = this;
  let marker;
  let closingTag;
  let buffer;
  let index2;
  let markerB;
  return start;
  function start(code2) {
    return before(code2);
  }
  function before(code2) {
    effects.enter("htmlFlow");
    effects.enter("htmlFlowData");
    effects.consume(code2);
    return open;
  }
  function open(code2) {
    if (code2 === 33) {
      effects.consume(code2);
      return declarationOpen;
    }
    if (code2 === 47) {
      effects.consume(code2);
      closingTag = true;
      return tagCloseStart;
    }
    if (code2 === 63) {
      effects.consume(code2);
      marker = 3;
      return self2.interrupt ? ok2 : continuationDeclarationInside;
    }
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      buffer = String.fromCharCode(code2);
      return tagName;
    }
    return nok(code2);
  }
  function declarationOpen(code2) {
    if (code2 === 45) {
      effects.consume(code2);
      marker = 2;
      return commentOpenInside;
    }
    if (code2 === 91) {
      effects.consume(code2);
      marker = 5;
      index2 = 0;
      return cdataOpenInside;
    }
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      marker = 4;
      return self2.interrupt ? ok2 : continuationDeclarationInside;
    }
    return nok(code2);
  }
  function commentOpenInside(code2) {
    if (code2 === 45) {
      effects.consume(code2);
      return self2.interrupt ? ok2 : continuationDeclarationInside;
    }
    return nok(code2);
  }
  function cdataOpenInside(code2) {
    const value = "CDATA[";
    if (code2 === value.charCodeAt(index2++)) {
      effects.consume(code2);
      if (index2 === value.length) {
        return self2.interrupt ? ok2 : continuation;
      }
      return cdataOpenInside;
    }
    return nok(code2);
  }
  function tagCloseStart(code2) {
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      buffer = String.fromCharCode(code2);
      return tagName;
    }
    return nok(code2);
  }
  function tagName(code2) {
    if (code2 === null || code2 === 47 || code2 === 62 || markdownLineEndingOrSpace(code2)) {
      const slash = code2 === 47;
      const name2 = buffer.toLowerCase();
      if (!slash && !closingTag && htmlRawNames.includes(name2)) {
        marker = 1;
        return self2.interrupt ? ok2(code2) : continuation(code2);
      }
      if (htmlBlockNames.includes(buffer.toLowerCase())) {
        marker = 6;
        if (slash) {
          effects.consume(code2);
          return basicSelfClosing;
        }
        return self2.interrupt ? ok2(code2) : continuation(code2);
      }
      marker = 7;
      return self2.interrupt && !self2.parser.lazy[self2.now().line] ? nok(code2) : closingTag ? completeClosingTagAfter(code2) : completeAttributeNameBefore(code2);
    }
    if (code2 === 45 || asciiAlphanumeric(code2)) {
      effects.consume(code2);
      buffer += String.fromCharCode(code2);
      return tagName;
    }
    return nok(code2);
  }
  function basicSelfClosing(code2) {
    if (code2 === 62) {
      effects.consume(code2);
      return self2.interrupt ? ok2 : continuation;
    }
    return nok(code2);
  }
  function completeClosingTagAfter(code2) {
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return completeClosingTagAfter;
    }
    return completeEnd(code2);
  }
  function completeAttributeNameBefore(code2) {
    if (code2 === 47) {
      effects.consume(code2);
      return completeEnd;
    }
    if (code2 === 58 || code2 === 95 || asciiAlpha(code2)) {
      effects.consume(code2);
      return completeAttributeName;
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return completeAttributeNameBefore;
    }
    return completeEnd(code2);
  }
  function completeAttributeName(code2) {
    if (code2 === 45 || code2 === 46 || code2 === 58 || code2 === 95 || asciiAlphanumeric(code2)) {
      effects.consume(code2);
      return completeAttributeName;
    }
    return completeAttributeNameAfter(code2);
  }
  function completeAttributeNameAfter(code2) {
    if (code2 === 61) {
      effects.consume(code2);
      return completeAttributeValueBefore;
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return completeAttributeNameAfter;
    }
    return completeAttributeNameBefore(code2);
  }
  function completeAttributeValueBefore(code2) {
    if (code2 === null || code2 === 60 || code2 === 61 || code2 === 62 || code2 === 96) {
      return nok(code2);
    }
    if (code2 === 34 || code2 === 39) {
      effects.consume(code2);
      markerB = code2;
      return completeAttributeValueQuoted;
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return completeAttributeValueBefore;
    }
    return completeAttributeValueUnquoted(code2);
  }
  function completeAttributeValueQuoted(code2) {
    if (code2 === markerB) {
      effects.consume(code2);
      markerB = null;
      return completeAttributeValueQuotedAfter;
    }
    if (code2 === null || markdownLineEnding(code2)) {
      return nok(code2);
    }
    effects.consume(code2);
    return completeAttributeValueQuoted;
  }
  function completeAttributeValueUnquoted(code2) {
    if (code2 === null || code2 === 34 || code2 === 39 || code2 === 47 || code2 === 60 || code2 === 61 || code2 === 62 || code2 === 96 || markdownLineEndingOrSpace(code2)) {
      return completeAttributeNameAfter(code2);
    }
    effects.consume(code2);
    return completeAttributeValueUnquoted;
  }
  function completeAttributeValueQuotedAfter(code2) {
    if (code2 === 47 || code2 === 62 || markdownSpace(code2)) {
      return completeAttributeNameBefore(code2);
    }
    return nok(code2);
  }
  function completeEnd(code2) {
    if (code2 === 62) {
      effects.consume(code2);
      return completeAfter;
    }
    return nok(code2);
  }
  function completeAfter(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      return continuation(code2);
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return completeAfter;
    }
    return nok(code2);
  }
  function continuation(code2) {
    if (code2 === 45 && marker === 2) {
      effects.consume(code2);
      return continuationCommentInside;
    }
    if (code2 === 60 && marker === 1) {
      effects.consume(code2);
      return continuationRawTagOpen;
    }
    if (code2 === 62 && marker === 4) {
      effects.consume(code2);
      return continuationClose;
    }
    if (code2 === 63 && marker === 3) {
      effects.consume(code2);
      return continuationDeclarationInside;
    }
    if (code2 === 93 && marker === 5) {
      effects.consume(code2);
      return continuationCdataInside;
    }
    if (markdownLineEnding(code2) && (marker === 6 || marker === 7)) {
      effects.exit("htmlFlowData");
      return effects.check(blankLineBefore, continuationAfter, continuationStart)(code2);
    }
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("htmlFlowData");
      return continuationStart(code2);
    }
    effects.consume(code2);
    return continuation;
  }
  function continuationStart(code2) {
    return effects.check(nonLazyContinuationStart, continuationStartNonLazy, continuationAfter)(code2);
  }
  function continuationStartNonLazy(code2) {
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return continuationBefore;
  }
  function continuationBefore(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      return continuationStart(code2);
    }
    effects.enter("htmlFlowData");
    return continuation(code2);
  }
  function continuationCommentInside(code2) {
    if (code2 === 45) {
      effects.consume(code2);
      return continuationDeclarationInside;
    }
    return continuation(code2);
  }
  function continuationRawTagOpen(code2) {
    if (code2 === 47) {
      effects.consume(code2);
      buffer = "";
      return continuationRawEndTag;
    }
    return continuation(code2);
  }
  function continuationRawEndTag(code2) {
    if (code2 === 62) {
      const name2 = buffer.toLowerCase();
      if (htmlRawNames.includes(name2)) {
        effects.consume(code2);
        return continuationClose;
      }
      return continuation(code2);
    }
    if (asciiAlpha(code2) && buffer.length < 8) {
      effects.consume(code2);
      buffer += String.fromCharCode(code2);
      return continuationRawEndTag;
    }
    return continuation(code2);
  }
  function continuationCdataInside(code2) {
    if (code2 === 93) {
      effects.consume(code2);
      return continuationDeclarationInside;
    }
    return continuation(code2);
  }
  function continuationDeclarationInside(code2) {
    if (code2 === 62) {
      effects.consume(code2);
      return continuationClose;
    }
    if (code2 === 45 && marker === 2) {
      effects.consume(code2);
      return continuationDeclarationInside;
    }
    return continuation(code2);
  }
  function continuationClose(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("htmlFlowData");
      return continuationAfter(code2);
    }
    effects.consume(code2);
    return continuationClose;
  }
  function continuationAfter(code2) {
    effects.exit("htmlFlow");
    return ok2(code2);
  }
}
function tokenizeNonLazyContinuationStart(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code2) {
    if (markdownLineEnding(code2)) {
      effects.enter("lineEnding");
      effects.consume(code2);
      effects.exit("lineEnding");
      return after;
    }
    return nok(code2);
  }
  function after(code2) {
    return self2.parser.lazy[self2.now().line] ? nok(code2) : ok2(code2);
  }
}
function tokenizeBlankLineBefore(effects, ok2, nok) {
  return start;
  function start(code2) {
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return effects.attempt(blankLine, ok2, nok);
  }
}
const htmlText = {
  name: "htmlText",
  tokenize: tokenizeHtmlText
};
function tokenizeHtmlText(effects, ok2, nok) {
  const self2 = this;
  let marker;
  let index2;
  let returnState;
  return start;
  function start(code2) {
    effects.enter("htmlText");
    effects.enter("htmlTextData");
    effects.consume(code2);
    return open;
  }
  function open(code2) {
    if (code2 === 33) {
      effects.consume(code2);
      return declarationOpen;
    }
    if (code2 === 47) {
      effects.consume(code2);
      return tagCloseStart;
    }
    if (code2 === 63) {
      effects.consume(code2);
      return instruction;
    }
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      return tagOpen;
    }
    return nok(code2);
  }
  function declarationOpen(code2) {
    if (code2 === 45) {
      effects.consume(code2);
      return commentOpenInside;
    }
    if (code2 === 91) {
      effects.consume(code2);
      index2 = 0;
      return cdataOpenInside;
    }
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      return declaration;
    }
    return nok(code2);
  }
  function commentOpenInside(code2) {
    if (code2 === 45) {
      effects.consume(code2);
      return commentEnd;
    }
    return nok(code2);
  }
  function comment(code2) {
    if (code2 === null) {
      return nok(code2);
    }
    if (code2 === 45) {
      effects.consume(code2);
      return commentClose;
    }
    if (markdownLineEnding(code2)) {
      returnState = comment;
      return lineEndingBefore(code2);
    }
    effects.consume(code2);
    return comment;
  }
  function commentClose(code2) {
    if (code2 === 45) {
      effects.consume(code2);
      return commentEnd;
    }
    return comment(code2);
  }
  function commentEnd(code2) {
    return code2 === 62 ? end(code2) : code2 === 45 ? commentClose(code2) : comment(code2);
  }
  function cdataOpenInside(code2) {
    const value = "CDATA[";
    if (code2 === value.charCodeAt(index2++)) {
      effects.consume(code2);
      return index2 === value.length ? cdata : cdataOpenInside;
    }
    return nok(code2);
  }
  function cdata(code2) {
    if (code2 === null) {
      return nok(code2);
    }
    if (code2 === 93) {
      effects.consume(code2);
      return cdataClose;
    }
    if (markdownLineEnding(code2)) {
      returnState = cdata;
      return lineEndingBefore(code2);
    }
    effects.consume(code2);
    return cdata;
  }
  function cdataClose(code2) {
    if (code2 === 93) {
      effects.consume(code2);
      return cdataEnd;
    }
    return cdata(code2);
  }
  function cdataEnd(code2) {
    if (code2 === 62) {
      return end(code2);
    }
    if (code2 === 93) {
      effects.consume(code2);
      return cdataEnd;
    }
    return cdata(code2);
  }
  function declaration(code2) {
    if (code2 === null || code2 === 62) {
      return end(code2);
    }
    if (markdownLineEnding(code2)) {
      returnState = declaration;
      return lineEndingBefore(code2);
    }
    effects.consume(code2);
    return declaration;
  }
  function instruction(code2) {
    if (code2 === null) {
      return nok(code2);
    }
    if (code2 === 63) {
      effects.consume(code2);
      return instructionClose;
    }
    if (markdownLineEnding(code2)) {
      returnState = instruction;
      return lineEndingBefore(code2);
    }
    effects.consume(code2);
    return instruction;
  }
  function instructionClose(code2) {
    return code2 === 62 ? end(code2) : instruction(code2);
  }
  function tagCloseStart(code2) {
    if (asciiAlpha(code2)) {
      effects.consume(code2);
      return tagClose;
    }
    return nok(code2);
  }
  function tagClose(code2) {
    if (code2 === 45 || asciiAlphanumeric(code2)) {
      effects.consume(code2);
      return tagClose;
    }
    return tagCloseBetween(code2);
  }
  function tagCloseBetween(code2) {
    if (markdownLineEnding(code2)) {
      returnState = tagCloseBetween;
      return lineEndingBefore(code2);
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return tagCloseBetween;
    }
    return end(code2);
  }
  function tagOpen(code2) {
    if (code2 === 45 || asciiAlphanumeric(code2)) {
      effects.consume(code2);
      return tagOpen;
    }
    if (code2 === 47 || code2 === 62 || markdownLineEndingOrSpace(code2)) {
      return tagOpenBetween(code2);
    }
    return nok(code2);
  }
  function tagOpenBetween(code2) {
    if (code2 === 47) {
      effects.consume(code2);
      return end;
    }
    if (code2 === 58 || code2 === 95 || asciiAlpha(code2)) {
      effects.consume(code2);
      return tagOpenAttributeName;
    }
    if (markdownLineEnding(code2)) {
      returnState = tagOpenBetween;
      return lineEndingBefore(code2);
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return tagOpenBetween;
    }
    return end(code2);
  }
  function tagOpenAttributeName(code2) {
    if (code2 === 45 || code2 === 46 || code2 === 58 || code2 === 95 || asciiAlphanumeric(code2)) {
      effects.consume(code2);
      return tagOpenAttributeName;
    }
    return tagOpenAttributeNameAfter(code2);
  }
  function tagOpenAttributeNameAfter(code2) {
    if (code2 === 61) {
      effects.consume(code2);
      return tagOpenAttributeValueBefore;
    }
    if (markdownLineEnding(code2)) {
      returnState = tagOpenAttributeNameAfter;
      return lineEndingBefore(code2);
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return tagOpenAttributeNameAfter;
    }
    return tagOpenBetween(code2);
  }
  function tagOpenAttributeValueBefore(code2) {
    if (code2 === null || code2 === 60 || code2 === 61 || code2 === 62 || code2 === 96) {
      return nok(code2);
    }
    if (code2 === 34 || code2 === 39) {
      effects.consume(code2);
      marker = code2;
      return tagOpenAttributeValueQuoted;
    }
    if (markdownLineEnding(code2)) {
      returnState = tagOpenAttributeValueBefore;
      return lineEndingBefore(code2);
    }
    if (markdownSpace(code2)) {
      effects.consume(code2);
      return tagOpenAttributeValueBefore;
    }
    effects.consume(code2);
    return tagOpenAttributeValueUnquoted;
  }
  function tagOpenAttributeValueQuoted(code2) {
    if (code2 === marker) {
      effects.consume(code2);
      marker = void 0;
      return tagOpenAttributeValueQuotedAfter;
    }
    if (code2 === null) {
      return nok(code2);
    }
    if (markdownLineEnding(code2)) {
      returnState = tagOpenAttributeValueQuoted;
      return lineEndingBefore(code2);
    }
    effects.consume(code2);
    return tagOpenAttributeValueQuoted;
  }
  function tagOpenAttributeValueUnquoted(code2) {
    if (code2 === null || code2 === 34 || code2 === 39 || code2 === 60 || code2 === 61 || code2 === 96) {
      return nok(code2);
    }
    if (code2 === 47 || code2 === 62 || markdownLineEndingOrSpace(code2)) {
      return tagOpenBetween(code2);
    }
    effects.consume(code2);
    return tagOpenAttributeValueUnquoted;
  }
  function tagOpenAttributeValueQuotedAfter(code2) {
    if (code2 === 47 || code2 === 62 || markdownLineEndingOrSpace(code2)) {
      return tagOpenBetween(code2);
    }
    return nok(code2);
  }
  function end(code2) {
    if (code2 === 62) {
      effects.consume(code2);
      effects.exit("htmlTextData");
      effects.exit("htmlText");
      return ok2;
    }
    return nok(code2);
  }
  function lineEndingBefore(code2) {
    effects.exit("htmlTextData");
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return lineEndingAfter;
  }
  function lineEndingAfter(code2) {
    return markdownSpace(code2) ? factorySpace(effects, lineEndingAfterPrefix, "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code2) : lineEndingAfterPrefix(code2);
  }
  function lineEndingAfterPrefix(code2) {
    effects.enter("htmlTextData");
    return returnState(code2);
  }
}
const labelEnd = {
  name: "labelEnd",
  resolveAll: resolveAllLabelEnd,
  resolveTo: resolveToLabelEnd,
  tokenize: tokenizeLabelEnd
};
const resourceConstruct = {
  tokenize: tokenizeResource
};
const referenceFullConstruct = {
  tokenize: tokenizeReferenceFull
};
const referenceCollapsedConstruct = {
  tokenize: tokenizeReferenceCollapsed
};
function resolveAllLabelEnd(events) {
  let index2 = -1;
  const newEvents = [];
  while (++index2 < events.length) {
    const token = events[index2][1];
    newEvents.push(events[index2]);
    if (token.type === "labelImage" || token.type === "labelLink" || token.type === "labelEnd") {
      const offset = token.type === "labelImage" ? 4 : 2;
      token.type = "data";
      index2 += offset;
    }
  }
  if (events.length !== newEvents.length) {
    splice(events, 0, events.length, newEvents);
  }
  return events;
}
function resolveToLabelEnd(events, context) {
  let index2 = events.length;
  let offset = 0;
  let token;
  let open;
  let close;
  let media;
  while (index2--) {
    token = events[index2][1];
    if (open) {
      if (token.type === "link" || token.type === "labelLink" && token._inactive) {
        break;
      }
      if (events[index2][0] === "enter" && token.type === "labelLink") {
        token._inactive = true;
      }
    } else if (close) {
      if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
        open = index2;
        if (token.type !== "labelLink") {
          offset = 2;
          break;
        }
      }
    } else if (token.type === "labelEnd") {
      close = index2;
    }
  }
  const group = {
    type: events[open][1].type === "labelLink" ? "link" : "image",
    start: {
      ...events[open][1].start
    },
    end: {
      ...events[events.length - 1][1].end
    }
  };
  const label = {
    type: "label",
    start: {
      ...events[open][1].start
    },
    end: {
      ...events[close][1].end
    }
  };
  const text2 = {
    type: "labelText",
    start: {
      ...events[open + offset + 2][1].end
    },
    end: {
      ...events[close - 2][1].start
    }
  };
  media = [["enter", group, context], ["enter", label, context]];
  media = push(media, events.slice(open + 1, open + offset + 3));
  media = push(media, [["enter", text2, context]]);
  media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + offset + 4, close - 3), context));
  media = push(media, [["exit", text2, context], events[close - 2], events[close - 1], ["exit", label, context]]);
  media = push(media, events.slice(close + 1));
  media = push(media, [["exit", group, context]]);
  splice(events, open, events.length, media);
  return events;
}
function tokenizeLabelEnd(effects, ok2, nok) {
  const self2 = this;
  let index2 = self2.events.length;
  let labelStart;
  let defined;
  while (index2--) {
    if ((self2.events[index2][1].type === "labelImage" || self2.events[index2][1].type === "labelLink") && !self2.events[index2][1]._balanced) {
      labelStart = self2.events[index2][1];
      break;
    }
  }
  return start;
  function start(code2) {
    if (!labelStart) {
      return nok(code2);
    }
    if (labelStart._inactive) {
      return labelEndNok(code2);
    }
    defined = self2.parser.defined.includes(normalizeIdentifier(self2.sliceSerialize({
      start: labelStart.end,
      end: self2.now()
    })));
    effects.enter("labelEnd");
    effects.enter("labelMarker");
    effects.consume(code2);
    effects.exit("labelMarker");
    effects.exit("labelEnd");
    return after;
  }
  function after(code2) {
    if (code2 === 40) {
      return effects.attempt(resourceConstruct, labelEndOk, defined ? labelEndOk : labelEndNok)(code2);
    }
    if (code2 === 91) {
      return effects.attempt(referenceFullConstruct, labelEndOk, defined ? referenceNotFull : labelEndNok)(code2);
    }
    return defined ? labelEndOk(code2) : labelEndNok(code2);
  }
  function referenceNotFull(code2) {
    return effects.attempt(referenceCollapsedConstruct, labelEndOk, labelEndNok)(code2);
  }
  function labelEndOk(code2) {
    return ok2(code2);
  }
  function labelEndNok(code2) {
    labelStart._balanced = true;
    return nok(code2);
  }
}
function tokenizeResource(effects, ok2, nok) {
  return resourceStart;
  function resourceStart(code2) {
    effects.enter("resource");
    effects.enter("resourceMarker");
    effects.consume(code2);
    effects.exit("resourceMarker");
    return resourceBefore;
  }
  function resourceBefore(code2) {
    return markdownLineEndingOrSpace(code2) ? factoryWhitespace(effects, resourceOpen)(code2) : resourceOpen(code2);
  }
  function resourceOpen(code2) {
    if (code2 === 41) {
      return resourceEnd(code2);
    }
    return factoryDestination(effects, resourceDestinationAfter, resourceDestinationMissing, "resourceDestination", "resourceDestinationLiteral", "resourceDestinationLiteralMarker", "resourceDestinationRaw", "resourceDestinationString", 32)(code2);
  }
  function resourceDestinationAfter(code2) {
    return markdownLineEndingOrSpace(code2) ? factoryWhitespace(effects, resourceBetween)(code2) : resourceEnd(code2);
  }
  function resourceDestinationMissing(code2) {
    return nok(code2);
  }
  function resourceBetween(code2) {
    if (code2 === 34 || code2 === 39 || code2 === 40) {
      return factoryTitle(effects, resourceTitleAfter, nok, "resourceTitle", "resourceTitleMarker", "resourceTitleString")(code2);
    }
    return resourceEnd(code2);
  }
  function resourceTitleAfter(code2) {
    return markdownLineEndingOrSpace(code2) ? factoryWhitespace(effects, resourceEnd)(code2) : resourceEnd(code2);
  }
  function resourceEnd(code2) {
    if (code2 === 41) {
      effects.enter("resourceMarker");
      effects.consume(code2);
      effects.exit("resourceMarker");
      effects.exit("resource");
      return ok2;
    }
    return nok(code2);
  }
}
function tokenizeReferenceFull(effects, ok2, nok) {
  const self2 = this;
  return referenceFull;
  function referenceFull(code2) {
    return factoryLabel.call(self2, effects, referenceFullAfter, referenceFullMissing, "reference", "referenceMarker", "referenceString")(code2);
  }
  function referenceFullAfter(code2) {
    return self2.parser.defined.includes(normalizeIdentifier(self2.sliceSerialize(self2.events[self2.events.length - 1][1]).slice(1, -1))) ? ok2(code2) : nok(code2);
  }
  function referenceFullMissing(code2) {
    return nok(code2);
  }
}
function tokenizeReferenceCollapsed(effects, ok2, nok) {
  return referenceCollapsedStart;
  function referenceCollapsedStart(code2) {
    effects.enter("reference");
    effects.enter("referenceMarker");
    effects.consume(code2);
    effects.exit("referenceMarker");
    return referenceCollapsedOpen;
  }
  function referenceCollapsedOpen(code2) {
    if (code2 === 93) {
      effects.enter("referenceMarker");
      effects.consume(code2);
      effects.exit("referenceMarker");
      effects.exit("reference");
      return ok2;
    }
    return nok(code2);
  }
}
const labelStartImage = {
  name: "labelStartImage",
  resolveAll: labelEnd.resolveAll,
  tokenize: tokenizeLabelStartImage
};
function tokenizeLabelStartImage(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code2) {
    effects.enter("labelImage");
    effects.enter("labelImageMarker");
    effects.consume(code2);
    effects.exit("labelImageMarker");
    return open;
  }
  function open(code2) {
    if (code2 === 91) {
      effects.enter("labelMarker");
      effects.consume(code2);
      effects.exit("labelMarker");
      effects.exit("labelImage");
      return after;
    }
    return nok(code2);
  }
  function after(code2) {
    return code2 === 94 && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code2) : ok2(code2);
  }
}
const labelStartLink = {
  name: "labelStartLink",
  resolveAll: labelEnd.resolveAll,
  tokenize: tokenizeLabelStartLink
};
function tokenizeLabelStartLink(effects, ok2, nok) {
  const self2 = this;
  return start;
  function start(code2) {
    effects.enter("labelLink");
    effects.enter("labelMarker");
    effects.consume(code2);
    effects.exit("labelMarker");
    effects.exit("labelLink");
    return after;
  }
  function after(code2) {
    return code2 === 94 && "_hiddenFootnoteSupport" in self2.parser.constructs ? nok(code2) : ok2(code2);
  }
}
const lineEnding = {
  name: "lineEnding",
  tokenize: tokenizeLineEnding
};
function tokenizeLineEnding(effects, ok2) {
  return start;
  function start(code2) {
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    return factorySpace(effects, ok2, "linePrefix");
  }
}
const thematicBreak$1 = {
  name: "thematicBreak",
  tokenize: tokenizeThematicBreak
};
function tokenizeThematicBreak(effects, ok2, nok) {
  let size = 0;
  let marker;
  return start;
  function start(code2) {
    effects.enter("thematicBreak");
    return before(code2);
  }
  function before(code2) {
    marker = code2;
    return atBreak(code2);
  }
  function atBreak(code2) {
    if (code2 === marker) {
      effects.enter("thematicBreakSequence");
      return sequence(code2);
    }
    if (size >= 3 && (code2 === null || markdownLineEnding(code2))) {
      effects.exit("thematicBreak");
      return ok2(code2);
    }
    return nok(code2);
  }
  function sequence(code2) {
    if (code2 === marker) {
      effects.consume(code2);
      size++;
      return sequence;
    }
    effects.exit("thematicBreakSequence");
    return markdownSpace(code2) ? factorySpace(effects, atBreak, "whitespace")(code2) : atBreak(code2);
  }
}
const list$1 = {
  continuation: {
    tokenize: tokenizeListContinuation
  },
  exit: tokenizeListEnd,
  name: "list",
  tokenize: tokenizeListStart
};
const listItemPrefixWhitespaceConstruct = {
  partial: true,
  tokenize: tokenizeListItemPrefixWhitespace
};
const indentConstruct = {
  partial: true,
  tokenize: tokenizeIndent
};
function tokenizeListStart(effects, ok2, nok) {
  const self2 = this;
  const tail = self2.events[self2.events.length - 1];
  let initialSize = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0;
  let size = 0;
  return start;
  function start(code2) {
    const kind = self2.containerState.type || (code2 === 42 || code2 === 43 || code2 === 45 ? "listUnordered" : "listOrdered");
    if (kind === "listUnordered" ? !self2.containerState.marker || code2 === self2.containerState.marker : asciiDigit(code2)) {
      if (!self2.containerState.type) {
        self2.containerState.type = kind;
        effects.enter(kind, {
          _container: true
        });
      }
      if (kind === "listUnordered") {
        effects.enter("listItemPrefix");
        return code2 === 42 || code2 === 45 ? effects.check(thematicBreak$1, nok, atMarker)(code2) : atMarker(code2);
      }
      if (!self2.interrupt || code2 === 49) {
        effects.enter("listItemPrefix");
        effects.enter("listItemValue");
        return inside(code2);
      }
    }
    return nok(code2);
  }
  function inside(code2) {
    if (asciiDigit(code2) && ++size < 10) {
      effects.consume(code2);
      return inside;
    }
    if ((!self2.interrupt || size < 2) && (self2.containerState.marker ? code2 === self2.containerState.marker : code2 === 41 || code2 === 46)) {
      effects.exit("listItemValue");
      return atMarker(code2);
    }
    return nok(code2);
  }
  function atMarker(code2) {
    effects.enter("listItemMarker");
    effects.consume(code2);
    effects.exit("listItemMarker");
    self2.containerState.marker = self2.containerState.marker || code2;
    return effects.check(
      blankLine,
      // Can’t be empty when interrupting.
      self2.interrupt ? nok : onBlank,
      effects.attempt(listItemPrefixWhitespaceConstruct, endOfPrefix, otherPrefix)
    );
  }
  function onBlank(code2) {
    self2.containerState.initialBlankLine = true;
    initialSize++;
    return endOfPrefix(code2);
  }
  function otherPrefix(code2) {
    if (markdownSpace(code2)) {
      effects.enter("listItemPrefixWhitespace");
      effects.consume(code2);
      effects.exit("listItemPrefixWhitespace");
      return endOfPrefix;
    }
    return nok(code2);
  }
  function endOfPrefix(code2) {
    self2.containerState.size = initialSize + self2.sliceSerialize(effects.exit("listItemPrefix"), true).length;
    return ok2(code2);
  }
}
function tokenizeListContinuation(effects, ok2, nok) {
  const self2 = this;
  self2.containerState._closeFlow = void 0;
  return effects.check(blankLine, onBlank, notBlank);
  function onBlank(code2) {
    self2.containerState.furtherBlankLines = self2.containerState.furtherBlankLines || self2.containerState.initialBlankLine;
    return factorySpace(effects, ok2, "listItemIndent", self2.containerState.size + 1)(code2);
  }
  function notBlank(code2) {
    if (self2.containerState.furtherBlankLines || !markdownSpace(code2)) {
      self2.containerState.furtherBlankLines = void 0;
      self2.containerState.initialBlankLine = void 0;
      return notInCurrentItem(code2);
    }
    self2.containerState.furtherBlankLines = void 0;
    self2.containerState.initialBlankLine = void 0;
    return effects.attempt(indentConstruct, ok2, notInCurrentItem)(code2);
  }
  function notInCurrentItem(code2) {
    self2.containerState._closeFlow = true;
    self2.interrupt = void 0;
    return factorySpace(effects, effects.attempt(list$1, ok2, nok), "linePrefix", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code2);
  }
}
function tokenizeIndent(effects, ok2, nok) {
  const self2 = this;
  return factorySpace(effects, afterPrefix, "listItemIndent", self2.containerState.size + 1);
  function afterPrefix(code2) {
    const tail = self2.events[self2.events.length - 1];
    return tail && tail[1].type === "listItemIndent" && tail[2].sliceSerialize(tail[1], true).length === self2.containerState.size ? ok2(code2) : nok(code2);
  }
}
function tokenizeListEnd(effects) {
  effects.exit(this.containerState.type);
}
function tokenizeListItemPrefixWhitespace(effects, ok2, nok) {
  const self2 = this;
  return factorySpace(effects, afterPrefix, "listItemPrefixWhitespace", self2.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4 + 1);
  function afterPrefix(code2) {
    const tail = self2.events[self2.events.length - 1];
    return !markdownSpace(code2) && tail && tail[1].type === "listItemPrefixWhitespace" ? ok2(code2) : nok(code2);
  }
}
const setextUnderline = {
  name: "setextUnderline",
  resolveTo: resolveToSetextUnderline,
  tokenize: tokenizeSetextUnderline
};
function resolveToSetextUnderline(events, context) {
  let index2 = events.length;
  let content2;
  let text2;
  let definition2;
  while (index2--) {
    if (events[index2][0] === "enter") {
      if (events[index2][1].type === "content") {
        content2 = index2;
        break;
      }
      if (events[index2][1].type === "paragraph") {
        text2 = index2;
      }
    } else {
      if (events[index2][1].type === "content") {
        events.splice(index2, 1);
      }
      if (!definition2 && events[index2][1].type === "definition") {
        definition2 = index2;
      }
    }
  }
  const heading2 = {
    type: "setextHeading",
    start: {
      ...events[content2][1].start
    },
    end: {
      ...events[events.length - 1][1].end
    }
  };
  events[text2][1].type = "setextHeadingText";
  if (definition2) {
    events.splice(text2, 0, ["enter", heading2, context]);
    events.splice(definition2 + 1, 0, ["exit", events[content2][1], context]);
    events[content2][1].end = {
      ...events[definition2][1].end
    };
  } else {
    events[content2][1] = heading2;
  }
  events.push(["exit", heading2, context]);
  return events;
}
function tokenizeSetextUnderline(effects, ok2, nok) {
  const self2 = this;
  let marker;
  return start;
  function start(code2) {
    let index2 = self2.events.length;
    let paragraph2;
    while (index2--) {
      if (self2.events[index2][1].type !== "lineEnding" && self2.events[index2][1].type !== "linePrefix" && self2.events[index2][1].type !== "content") {
        paragraph2 = self2.events[index2][1].type === "paragraph";
        break;
      }
    }
    if (!self2.parser.lazy[self2.now().line] && (self2.interrupt || paragraph2)) {
      effects.enter("setextHeadingLine");
      marker = code2;
      return before(code2);
    }
    return nok(code2);
  }
  function before(code2) {
    effects.enter("setextHeadingLineSequence");
    return inside(code2);
  }
  function inside(code2) {
    if (code2 === marker) {
      effects.consume(code2);
      return inside;
    }
    effects.exit("setextHeadingLineSequence");
    return markdownSpace(code2) ? factorySpace(effects, after, "lineSuffix")(code2) : after(code2);
  }
  function after(code2) {
    if (code2 === null || markdownLineEnding(code2)) {
      effects.exit("setextHeadingLine");
      return ok2(code2);
    }
    return nok(code2);
  }
}
const flow$1 = {
  tokenize: initializeFlow
};
function initializeFlow(effects) {
  const self2 = this;
  const initial = effects.attempt(
    // Try to parse a blank line.
    blankLine,
    atBlankEnding,
    // Try to parse initial flow (essentially, only code).
    effects.attempt(this.parser.constructs.flowInitial, afterConstruct, factorySpace(effects, effects.attempt(this.parser.constructs.flow, afterConstruct, effects.attempt(content, afterConstruct)), "linePrefix"))
  );
  return initial;
  function atBlankEnding(code2) {
    if (code2 === null) {
      effects.consume(code2);
      return;
    }
    effects.enter("lineEndingBlank");
    effects.consume(code2);
    effects.exit("lineEndingBlank");
    self2.currentConstruct = void 0;
    return initial;
  }
  function afterConstruct(code2) {
    if (code2 === null) {
      effects.consume(code2);
      return;
    }
    effects.enter("lineEnding");
    effects.consume(code2);
    effects.exit("lineEnding");
    self2.currentConstruct = void 0;
    return initial;
  }
}
const resolver = {
  resolveAll: createResolver()
};
const string$1 = initializeFactory("string");
const text$2 = initializeFactory("text");
function initializeFactory(field) {
  return {
    resolveAll: createResolver(field === "text" ? resolveAllLineSuffixes : void 0),
    tokenize: initializeText
  };
  function initializeText(effects) {
    const self2 = this;
    const constructs2 = this.parser.constructs[field];
    const text2 = effects.attempt(constructs2, start, notText);
    return start;
    function start(code2) {
      return atBreak(code2) ? text2(code2) : notText(code2);
    }
    function notText(code2) {
      if (code2 === null) {
        effects.consume(code2);
        return;
      }
      effects.enter("data");
      effects.consume(code2);
      return data;
    }
    function data(code2) {
      if (atBreak(code2)) {
        effects.exit("data");
        return text2(code2);
      }
      effects.consume(code2);
      return data;
    }
    function atBreak(code2) {
      if (code2 === null) {
        return true;
      }
      const list2 = constructs2[code2];
      let index2 = -1;
      if (list2) {
        while (++index2 < list2.length) {
          const item = list2[index2];
          if (!item.previous || item.previous.call(self2, self2.previous)) {
            return true;
          }
        }
      }
      return false;
    }
  }
}
function createResolver(extraResolver) {
  return resolveAllText;
  function resolveAllText(events, context) {
    let index2 = -1;
    let enter;
    while (++index2 <= events.length) {
      if (enter === void 0) {
        if (events[index2] && events[index2][1].type === "data") {
          enter = index2;
          index2++;
        }
      } else if (!events[index2] || events[index2][1].type !== "data") {
        if (index2 !== enter + 2) {
          events[enter][1].end = events[index2 - 1][1].end;
          events.splice(enter + 2, index2 - enter - 2);
          index2 = enter + 2;
        }
        enter = void 0;
      }
    }
    return extraResolver ? extraResolver(events, context) : events;
  }
}
function resolveAllLineSuffixes(events, context) {
  let eventIndex = 0;
  while (++eventIndex <= events.length) {
    if ((eventIndex === events.length || events[eventIndex][1].type === "lineEnding") && events[eventIndex - 1][1].type === "data") {
      const data = events[eventIndex - 1][1];
      const chunks = context.sliceStream(data);
      let index2 = chunks.length;
      let bufferIndex = -1;
      let size = 0;
      let tabs;
      while (index2--) {
        const chunk2 = chunks[index2];
        if (typeof chunk2 === "string") {
          bufferIndex = chunk2.length;
          while (chunk2.charCodeAt(bufferIndex - 1) === 32) {
            size++;
            bufferIndex--;
          }
          if (bufferIndex) break;
          bufferIndex = -1;
        } else if (chunk2 === -2) {
          tabs = true;
          size++;
        } else if (chunk2 === -1) ;
        else {
          index2++;
          break;
        }
      }
      if (context._contentTypeTextTrailing && eventIndex === events.length) {
        size = 0;
      }
      if (size) {
        const token = {
          type: eventIndex === events.length || tabs || size < 2 ? "lineSuffix" : "hardBreakTrailing",
          start: {
            _bufferIndex: index2 ? bufferIndex : data.start._bufferIndex + bufferIndex,
            _index: data.start._index + index2,
            line: data.end.line,
            column: data.end.column - size,
            offset: data.end.offset - size
          },
          end: {
            ...data.end
          }
        };
        data.end = {
          ...token.start
        };
        if (data.start.offset === data.end.offset) {
          Object.assign(data, token);
        } else {
          events.splice(eventIndex, 0, ["enter", token, context], ["exit", token, context]);
          eventIndex += 2;
        }
      }
      eventIndex++;
    }
  }
  return events;
}
const document$1 = {
  [42]: list$1,
  [43]: list$1,
  [45]: list$1,
  [48]: list$1,
  [49]: list$1,
  [50]: list$1,
  [51]: list$1,
  [52]: list$1,
  [53]: list$1,
  [54]: list$1,
  [55]: list$1,
  [56]: list$1,
  [57]: list$1,
  [62]: blockQuote
};
const contentInitial = {
  [91]: definition
};
const flowInitial = {
  [-2]: codeIndented,
  [-1]: codeIndented,
  [32]: codeIndented
};
const flow = {
  [35]: headingAtx,
  [42]: thematicBreak$1,
  [45]: [setextUnderline, thematicBreak$1],
  [60]: htmlFlow,
  [61]: setextUnderline,
  [95]: thematicBreak$1,
  [96]: codeFenced,
  [126]: codeFenced
};
const string = {
  [38]: characterReference,
  [92]: characterEscape
};
const text$1 = {
  [-5]: lineEnding,
  [-4]: lineEnding,
  [-3]: lineEnding,
  [33]: labelStartImage,
  [38]: characterReference,
  [42]: attention,
  [60]: [autolink, htmlText],
  [91]: labelStartLink,
  [92]: [hardBreakEscape, characterEscape],
  [93]: labelEnd,
  [95]: attention,
  [96]: codeText
};
const insideSpan = {
  null: [attention, resolver]
};
const attentionMarkers = {
  null: [42, 95]
};
const disable = {
  null: []
};
const defaultConstructs = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  attentionMarkers,
  contentInitial,
  disable,
  document: document$1,
  flow,
  flowInitial,
  insideSpan,
  string,
  text: text$1
}, Symbol.toStringTag, { value: "Module" }));
function createTokenizer(parser, initialize, from) {
  let point2 = {
    _bufferIndex: -1,
    _index: 0,
    line: from && from.line || 1,
    column: from && from.column || 1,
    offset: from && from.offset || 0
  };
  const columnStart = {};
  const resolveAllConstructs = [];
  let chunks = [];
  let stack = [];
  const effects = {
    attempt: constructFactory(onsuccessfulconstruct),
    check: constructFactory(onsuccessfulcheck),
    consume,
    enter,
    exit: exit2,
    interrupt: constructFactory(onsuccessfulcheck, {
      interrupt: true
    })
  };
  const context = {
    code: null,
    containerState: {},
    defineSkip,
    events: [],
    now,
    parser,
    previous: null,
    sliceSerialize,
    sliceStream,
    write
  };
  let state = initialize.tokenize.call(context, effects);
  if (initialize.resolveAll) {
    resolveAllConstructs.push(initialize);
  }
  return context;
  function write(slice) {
    chunks = push(chunks, slice);
    main();
    if (chunks[chunks.length - 1] !== null) {
      return [];
    }
    addResult(initialize, 0);
    context.events = resolveAll(resolveAllConstructs, context.events, context);
    return context.events;
  }
  function sliceSerialize(token, expandTabs) {
    return serializeChunks(sliceStream(token), expandTabs);
  }
  function sliceStream(token) {
    return sliceChunks(chunks, token);
  }
  function now() {
    const {
      _bufferIndex,
      _index,
      line,
      column,
      offset
    } = point2;
    return {
      _bufferIndex,
      _index,
      line,
      column,
      offset
    };
  }
  function defineSkip(value) {
    columnStart[value.line] = value.column;
    accountForPotentialSkip();
  }
  function main() {
    let chunkIndex;
    while (point2._index < chunks.length) {
      const chunk2 = chunks[point2._index];
      if (typeof chunk2 === "string") {
        chunkIndex = point2._index;
        if (point2._bufferIndex < 0) {
          point2._bufferIndex = 0;
        }
        while (point2._index === chunkIndex && point2._bufferIndex < chunk2.length) {
          go(chunk2.charCodeAt(point2._bufferIndex));
        }
      } else {
        go(chunk2);
      }
    }
  }
  function go(code2) {
    state = state(code2);
  }
  function consume(code2) {
    if (markdownLineEnding(code2)) {
      point2.line++;
      point2.column = 1;
      point2.offset += code2 === -3 ? 2 : 1;
      accountForPotentialSkip();
    } else if (code2 !== -1) {
      point2.column++;
      point2.offset++;
    }
    if (point2._bufferIndex < 0) {
      point2._index++;
    } else {
      point2._bufferIndex++;
      if (point2._bufferIndex === // Points w/ non-negative `_bufferIndex` reference
      // strings.
      /** @type {string} */
      chunks[point2._index].length) {
        point2._bufferIndex = -1;
        point2._index++;
      }
    }
    context.previous = code2;
  }
  function enter(type2, fields) {
    const token = fields || {};
    token.type = type2;
    token.start = now();
    context.events.push(["enter", token, context]);
    stack.push(token);
    return token;
  }
  function exit2(type2) {
    const token = stack.pop();
    token.end = now();
    context.events.push(["exit", token, context]);
    return token;
  }
  function onsuccessfulconstruct(construct, info) {
    addResult(construct, info.from);
  }
  function onsuccessfulcheck(_2, info) {
    info.restore();
  }
  function constructFactory(onreturn, fields) {
    return hook;
    function hook(constructs2, returnState, bogusState) {
      let listOfConstructs;
      let constructIndex;
      let currentConstruct;
      let info;
      return Array.isArray(constructs2) ? (
        /* c8 ignore next 1 */
        handleListOfConstructs(constructs2)
      ) : "tokenize" in constructs2 ? (
        // Looks like a construct.
        handleListOfConstructs([
          /** @type {Construct} */
          constructs2
        ])
      ) : handleMapOfConstructs(constructs2);
      function handleMapOfConstructs(map) {
        return start;
        function start(code2) {
          const left = code2 !== null && map[code2];
          const all3 = code2 !== null && map.null;
          const list2 = [
            // To do: add more extension tests.
            /* c8 ignore next 2 */
            ...Array.isArray(left) ? left : left ? [left] : [],
            ...Array.isArray(all3) ? all3 : all3 ? [all3] : []
          ];
          return handleListOfConstructs(list2)(code2);
        }
      }
      function handleListOfConstructs(list2) {
        listOfConstructs = list2;
        constructIndex = 0;
        if (list2.length === 0) {
          return bogusState;
        }
        return handleConstruct(list2[constructIndex]);
      }
      function handleConstruct(construct) {
        return start;
        function start(code2) {
          info = store();
          currentConstruct = construct;
          if (!construct.partial) {
            context.currentConstruct = construct;
          }
          if (construct.name && context.parser.constructs.disable.null.includes(construct.name)) {
            return nok();
          }
          return construct.tokenize.call(
            // If we do have fields, create an object w/ `context` as its
            // prototype.
            // This allows a “live binding”, which is needed for `interrupt`.
            fields ? Object.assign(Object.create(context), fields) : context,
            effects,
            ok2,
            nok
          )(code2);
        }
      }
      function ok2(code2) {
        onreturn(currentConstruct, info);
        return returnState;
      }
      function nok(code2) {
        info.restore();
        if (++constructIndex < listOfConstructs.length) {
          return handleConstruct(listOfConstructs[constructIndex]);
        }
        return bogusState;
      }
    }
  }
  function addResult(construct, from2) {
    if (construct.resolveAll && !resolveAllConstructs.includes(construct)) {
      resolveAllConstructs.push(construct);
    }
    if (construct.resolve) {
      splice(context.events, from2, context.events.length - from2, construct.resolve(context.events.slice(from2), context));
    }
    if (construct.resolveTo) {
      context.events = construct.resolveTo(context.events, context);
    }
  }
  function store() {
    const startPoint = now();
    const startPrevious = context.previous;
    const startCurrentConstruct = context.currentConstruct;
    const startEventsIndex = context.events.length;
    const startStack = Array.from(stack);
    return {
      from: startEventsIndex,
      restore
    };
    function restore() {
      point2 = startPoint;
      context.previous = startPrevious;
      context.currentConstruct = startCurrentConstruct;
      context.events.length = startEventsIndex;
      stack = startStack;
      accountForPotentialSkip();
    }
  }
  function accountForPotentialSkip() {
    if (point2.line in columnStart && point2.column < 2) {
      point2.column = columnStart[point2.line];
      point2.offset += columnStart[point2.line] - 1;
    }
  }
}
function sliceChunks(chunks, token) {
  const startIndex = token.start._index;
  const startBufferIndex = token.start._bufferIndex;
  const endIndex = token.end._index;
  const endBufferIndex = token.end._bufferIndex;
  let view;
  if (startIndex === endIndex) {
    view = [chunks[startIndex].slice(startBufferIndex, endBufferIndex)];
  } else {
    view = chunks.slice(startIndex, endIndex);
    if (startBufferIndex > -1) {
      const head = view[0];
      if (typeof head === "string") {
        view[0] = head.slice(startBufferIndex);
      } else {
        view.shift();
      }
    }
    if (endBufferIndex > 0) {
      view.push(chunks[endIndex].slice(0, endBufferIndex));
    }
  }
  return view;
}
function serializeChunks(chunks, expandTabs) {
  let index2 = -1;
  const result = [];
  let atTab;
  while (++index2 < chunks.length) {
    const chunk2 = chunks[index2];
    let value;
    if (typeof chunk2 === "string") {
      value = chunk2;
    } else switch (chunk2) {
      case -5: {
        value = "\r";
        break;
      }
      case -4: {
        value = "\n";
        break;
      }
      case -3: {
        value = "\r\n";
        break;
      }
      case -2: {
        value = expandTabs ? " " : "	";
        break;
      }
      case -1: {
        if (!expandTabs && atTab) continue;
        value = " ";
        break;
      }
      default: {
        value = String.fromCharCode(chunk2);
      }
    }
    atTab = chunk2 === -2;
    result.push(value);
  }
  return result.join("");
}
function parse(options) {
  const settings = options || {};
  const constructs2 = (
    /** @type {FullNormalizedExtension} */
    combineExtensions([defaultConstructs, ...settings.extensions || []])
  );
  const parser = {
    constructs: constructs2,
    content: create2(content$1),
    defined: [],
    document: create2(document$2),
    flow: create2(flow$1),
    lazy: {},
    string: create2(string$1),
    text: create2(text$2)
  };
  return parser;
  function create2(initial) {
    return creator;
    function creator(from) {
      return createTokenizer(parser, initial, from);
    }
  }
}
function postprocess(events) {
  while (!subtokenize(events)) {
  }
  return events;
}
const search = /[\0\t\n\r]/g;
function preprocess() {
  let column = 1;
  let buffer = "";
  let start = true;
  let atCarriageReturn;
  return preprocessor;
  function preprocessor(value, encoding, end) {
    const chunks = [];
    let match;
    let next;
    let startPosition;
    let endPosition;
    let code2;
    value = buffer + (typeof value === "string" ? value.toString() : new TextDecoder(encoding || void 0).decode(value));
    startPosition = 0;
    buffer = "";
    if (start) {
      if (value.charCodeAt(0) === 65279) {
        startPosition++;
      }
      start = void 0;
    }
    while (startPosition < value.length) {
      search.lastIndex = startPosition;
      match = search.exec(value);
      endPosition = match && match.index !== void 0 ? match.index : value.length;
      code2 = value.charCodeAt(endPosition);
      if (!match) {
        buffer = value.slice(startPosition);
        break;
      }
      if (code2 === 10 && startPosition === endPosition && atCarriageReturn) {
        chunks.push(-3);
        atCarriageReturn = void 0;
      } else {
        if (atCarriageReturn) {
          chunks.push(-5);
          atCarriageReturn = void 0;
        }
        if (startPosition < endPosition) {
          chunks.push(value.slice(startPosition, endPosition));
          column += endPosition - startPosition;
        }
        switch (code2) {
          case 0: {
            chunks.push(65533);
            column++;
            break;
          }
          case 9: {
            next = Math.ceil(column / 4) * 4;
            chunks.push(-2);
            while (column++ < next) chunks.push(-1);
            break;
          }
          case 10: {
            chunks.push(-4);
            column = 1;
            break;
          }
          default: {
            atCarriageReturn = true;
            column = 1;
          }
        }
      }
      startPosition = endPosition + 1;
    }
    if (end) {
      if (atCarriageReturn) chunks.push(-5);
      if (buffer) chunks.push(buffer);
      chunks.push(null);
    }
    return chunks;
  }
}
const characterEscapeOrReference = /\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;
function decodeString(value) {
  return value.replace(characterEscapeOrReference, decode);
}
function decode($0, $1, $2) {
  if ($1) {
    return $1;
  }
  const head = $2.charCodeAt(0);
  if (head === 35) {
    const head2 = $2.charCodeAt(1);
    const hex = head2 === 120 || head2 === 88;
    return decodeNumericCharacterReference($2.slice(hex ? 2 : 1), hex ? 16 : 10);
  }
  return decodeNamedCharacterReference($2) || $0;
}
const own$2 = {}.hasOwnProperty;
function fromMarkdown(value, encoding, options) {
  if (encoding && typeof encoding === "object") {
    options = encoding;
    encoding = void 0;
  }
  return compiler(options)(postprocess(parse(options).document().write(preprocess()(value, encoding, true))));
}
function compiler(options) {
  const config = {
    transforms: [],
    canContainEols: ["emphasis", "fragment", "heading", "paragraph", "strong"],
    enter: {
      autolink: opener(link2),
      autolinkProtocol: onenterdata,
      autolinkEmail: onenterdata,
      atxHeading: opener(heading2),
      blockQuote: opener(blockQuote2),
      characterEscape: onenterdata,
      characterReference: onenterdata,
      codeFenced: opener(codeFlow),
      codeFencedFenceInfo: buffer,
      codeFencedFenceMeta: buffer,
      codeIndented: opener(codeFlow, buffer),
      codeText: opener(codeText2, buffer),
      codeTextData: onenterdata,
      data: onenterdata,
      codeFlowValue: onenterdata,
      definition: opener(definition2),
      definitionDestinationString: buffer,
      definitionLabelString: buffer,
      definitionTitleString: buffer,
      emphasis: opener(emphasis2),
      hardBreakEscape: opener(hardBreak2),
      hardBreakTrailing: opener(hardBreak2),
      htmlFlow: opener(html2, buffer),
      htmlFlowData: onenterdata,
      htmlText: opener(html2, buffer),
      htmlTextData: onenterdata,
      image: opener(image2),
      label: buffer,
      link: opener(link2),
      listItem: opener(listItem2),
      listItemValue: onenterlistitemvalue,
      listOrdered: opener(list2, onenterlistordered),
      listUnordered: opener(list2),
      paragraph: opener(paragraph2),
      reference: onenterreference,
      referenceString: buffer,
      resourceDestinationString: buffer,
      resourceTitleString: buffer,
      setextHeading: opener(heading2),
      strong: opener(strong2),
      thematicBreak: opener(thematicBreak2)
    },
    exit: {
      atxHeading: closer(),
      atxHeadingSequence: onexitatxheadingsequence,
      autolink: closer(),
      autolinkEmail: onexitautolinkemail,
      autolinkProtocol: onexitautolinkprotocol,
      blockQuote: closer(),
      characterEscapeValue: onexitdata,
      characterReferenceMarkerHexadecimal: onexitcharacterreferencemarker,
      characterReferenceMarkerNumeric: onexitcharacterreferencemarker,
      characterReferenceValue: onexitcharacterreferencevalue,
      characterReference: onexitcharacterreference,
      codeFenced: closer(onexitcodefenced),
      codeFencedFence: onexitcodefencedfence,
      codeFencedFenceInfo: onexitcodefencedfenceinfo,
      codeFencedFenceMeta: onexitcodefencedfencemeta,
      codeFlowValue: onexitdata,
      codeIndented: closer(onexitcodeindented),
      codeText: closer(onexitcodetext),
      codeTextData: onexitdata,
      data: onexitdata,
      definition: closer(),
      definitionDestinationString: onexitdefinitiondestinationstring,
      definitionLabelString: onexitdefinitionlabelstring,
      definitionTitleString: onexitdefinitiontitlestring,
      emphasis: closer(),
      hardBreakEscape: closer(onexithardbreak),
      hardBreakTrailing: closer(onexithardbreak),
      htmlFlow: closer(onexithtmlflow),
      htmlFlowData: onexitdata,
      htmlText: closer(onexithtmltext),
      htmlTextData: onexitdata,
      image: closer(onexitimage),
      label: onexitlabel,
      labelText: onexitlabeltext,
      lineEnding: onexitlineending,
      link: closer(onexitlink),
      listItem: closer(),
      listOrdered: closer(),
      listUnordered: closer(),
      paragraph: closer(),
      referenceString: onexitreferencestring,
      resourceDestinationString: onexitresourcedestinationstring,
      resourceTitleString: onexitresourcetitlestring,
      resource: onexitresource,
      setextHeading: closer(onexitsetextheading),
      setextHeadingLineSequence: onexitsetextheadinglinesequence,
      setextHeadingText: onexitsetextheadingtext,
      strong: closer(),
      thematicBreak: closer()
    }
  };
  configure(config, (options || {}).mdastExtensions || []);
  const data = {};
  return compile;
  function compile(events) {
    let tree = {
      type: "root",
      children: []
    };
    const context = {
      stack: [tree],
      tokenStack: [],
      config,
      enter,
      exit: exit2,
      buffer,
      resume,
      data
    };
    const listStack = [];
    let index2 = -1;
    while (++index2 < events.length) {
      if (events[index2][1].type === "listOrdered" || events[index2][1].type === "listUnordered") {
        if (events[index2][0] === "enter") {
          listStack.push(index2);
        } else {
          const tail = listStack.pop();
          index2 = prepareList(events, tail, index2);
        }
      }
    }
    index2 = -1;
    while (++index2 < events.length) {
      const handler = config[events[index2][0]];
      if (own$2.call(handler, events[index2][1].type)) {
        handler[events[index2][1].type].call(Object.assign({
          sliceSerialize: events[index2][2].sliceSerialize
        }, context), events[index2][1]);
      }
    }
    if (context.tokenStack.length > 0) {
      const tail = context.tokenStack[context.tokenStack.length - 1];
      const handler = tail[1] || defaultOnError;
      handler.call(context, void 0, tail[0]);
    }
    tree.position = {
      start: point(events.length > 0 ? events[0][1].start : {
        line: 1,
        column: 1,
        offset: 0
      }),
      end: point(events.length > 0 ? events[events.length - 2][1].end : {
        line: 1,
        column: 1,
        offset: 0
      })
    };
    index2 = -1;
    while (++index2 < config.transforms.length) {
      tree = config.transforms[index2](tree) || tree;
    }
    return tree;
  }
  function prepareList(events, start, length) {
    let index2 = start - 1;
    let containerBalance = -1;
    let listSpread = false;
    let listItem3;
    let lineIndex;
    let firstBlankLineIndex;
    let atMarker;
    while (++index2 <= length) {
      const event = events[index2];
      switch (event[1].type) {
        case "listUnordered":
        case "listOrdered":
        case "blockQuote": {
          if (event[0] === "enter") {
            containerBalance++;
          } else {
            containerBalance--;
          }
          atMarker = void 0;
          break;
        }
        case "lineEndingBlank": {
          if (event[0] === "enter") {
            if (listItem3 && !atMarker && !containerBalance && !firstBlankLineIndex) {
              firstBlankLineIndex = index2;
            }
            atMarker = void 0;
          }
          break;
        }
        case "linePrefix":
        case "listItemValue":
        case "listItemMarker":
        case "listItemPrefix":
        case "listItemPrefixWhitespace": {
          break;
        }
        default: {
          atMarker = void 0;
        }
      }
      if (!containerBalance && event[0] === "enter" && event[1].type === "listItemPrefix" || containerBalance === -1 && event[0] === "exit" && (event[1].type === "listUnordered" || event[1].type === "listOrdered")) {
        if (listItem3) {
          let tailIndex = index2;
          lineIndex = void 0;
          while (tailIndex--) {
            const tailEvent = events[tailIndex];
            if (tailEvent[1].type === "lineEnding" || tailEvent[1].type === "lineEndingBlank") {
              if (tailEvent[0] === "exit") continue;
              if (lineIndex) {
                events[lineIndex][1].type = "lineEndingBlank";
                listSpread = true;
              }
              tailEvent[1].type = "lineEnding";
              lineIndex = tailIndex;
            } else if (tailEvent[1].type === "linePrefix" || tailEvent[1].type === "blockQuotePrefix" || tailEvent[1].type === "blockQuotePrefixWhitespace" || tailEvent[1].type === "blockQuoteMarker" || tailEvent[1].type === "listItemIndent") ;
            else {
              break;
            }
          }
          if (firstBlankLineIndex && (!lineIndex || firstBlankLineIndex < lineIndex)) {
            listItem3._spread = true;
          }
          listItem3.end = Object.assign({}, lineIndex ? events[lineIndex][1].start : event[1].end);
          events.splice(lineIndex || index2, 0, ["exit", listItem3, event[2]]);
          index2++;
          length++;
        }
        if (event[1].type === "listItemPrefix") {
          const item = {
            type: "listItem",
            _spread: false,
            start: Object.assign({}, event[1].start),
            // @ts-expect-error: we’ll add `end` in a second.
            end: void 0
          };
          listItem3 = item;
          events.splice(index2, 0, ["enter", item, event[2]]);
          index2++;
          length++;
          firstBlankLineIndex = void 0;
          atMarker = true;
        }
      }
    }
    events[start][1]._spread = listSpread;
    return length;
  }
  function opener(create2, and) {
    return open;
    function open(token) {
      enter.call(this, create2(token), token);
      if (and) and.call(this, token);
    }
  }
  function buffer() {
    this.stack.push({
      type: "fragment",
      children: []
    });
  }
  function enter(node2, token, errorHandler) {
    const parent = this.stack[this.stack.length - 1];
    const siblings = parent.children;
    siblings.push(node2);
    this.stack.push(node2);
    this.tokenStack.push([token, errorHandler || void 0]);
    node2.position = {
      start: point(token.start),
      // @ts-expect-error: `end` will be patched later.
      end: void 0
    };
  }
  function closer(and) {
    return close;
    function close(token) {
      if (and) and.call(this, token);
      exit2.call(this, token);
    }
  }
  function exit2(token, onExitError) {
    const node2 = this.stack.pop();
    const open = this.tokenStack.pop();
    if (!open) {
      throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
        start: token.start,
        end: token.end
      }) + "): it’s not open");
    } else if (open[0].type !== token.type) {
      if (onExitError) {
        onExitError.call(this, token, open[0]);
      } else {
        const handler = open[1] || defaultOnError;
        handler.call(this, token, open[0]);
      }
    }
    node2.position.end = point(token.end);
  }
  function resume() {
    return toString$1(this.stack.pop());
  }
  function onenterlistordered() {
    this.data.expectingFirstListItemValue = true;
  }
  function onenterlistitemvalue(token) {
    if (this.data.expectingFirstListItemValue) {
      const ancestor = this.stack[this.stack.length - 2];
      ancestor.start = Number.parseInt(this.sliceSerialize(token), 10);
      this.data.expectingFirstListItemValue = void 0;
    }
  }
  function onexitcodefencedfenceinfo() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.lang = data2;
  }
  function onexitcodefencedfencemeta() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.meta = data2;
  }
  function onexitcodefencedfence() {
    if (this.data.flowCodeInside) return;
    this.buffer();
    this.data.flowCodeInside = true;
  }
  function onexitcodefenced() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.value = data2.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g, "");
    this.data.flowCodeInside = void 0;
  }
  function onexitcodeindented() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.value = data2.replace(/(\r?\n|\r)$/g, "");
  }
  function onexitdefinitionlabelstring(token) {
    const label = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.label = label;
    node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
  }
  function onexitdefinitiontitlestring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.title = data2;
  }
  function onexitdefinitiondestinationstring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.url = data2;
  }
  function onexitatxheadingsequence(token) {
    const node2 = this.stack[this.stack.length - 1];
    if (!node2.depth) {
      const depth = this.sliceSerialize(token).length;
      node2.depth = depth;
    }
  }
  function onexitsetextheadingtext() {
    this.data.setextHeadingSlurpLineEnding = true;
  }
  function onexitsetextheadinglinesequence(token) {
    const node2 = this.stack[this.stack.length - 1];
    node2.depth = this.sliceSerialize(token).codePointAt(0) === 61 ? 1 : 2;
  }
  function onexitsetextheading() {
    this.data.setextHeadingSlurpLineEnding = void 0;
  }
  function onenterdata(token) {
    const node2 = this.stack[this.stack.length - 1];
    const siblings = node2.children;
    let tail = siblings[siblings.length - 1];
    if (!tail || tail.type !== "text") {
      tail = text2();
      tail.position = {
        start: point(token.start),
        // @ts-expect-error: we’ll add `end` later.
        end: void 0
      };
      siblings.push(tail);
    }
    this.stack.push(tail);
  }
  function onexitdata(token) {
    const tail = this.stack.pop();
    tail.value += this.sliceSerialize(token);
    tail.position.end = point(token.end);
  }
  function onexitlineending(token) {
    const context = this.stack[this.stack.length - 1];
    if (this.data.atHardBreak) {
      const tail = context.children[context.children.length - 1];
      tail.position.end = point(token.end);
      this.data.atHardBreak = void 0;
      return;
    }
    if (!this.data.setextHeadingSlurpLineEnding && config.canContainEols.includes(context.type)) {
      onenterdata.call(this, token);
      onexitdata.call(this, token);
    }
  }
  function onexithardbreak() {
    this.data.atHardBreak = true;
  }
  function onexithtmlflow() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.value = data2;
  }
  function onexithtmltext() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.value = data2;
  }
  function onexitcodetext() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.value = data2;
  }
  function onexitlink() {
    const node2 = this.stack[this.stack.length - 1];
    if (this.data.inReference) {
      const referenceType = this.data.referenceType || "shortcut";
      node2.type += "Reference";
      node2.referenceType = referenceType;
      delete node2.url;
      delete node2.title;
    } else {
      delete node2.identifier;
      delete node2.label;
    }
    this.data.referenceType = void 0;
  }
  function onexitimage() {
    const node2 = this.stack[this.stack.length - 1];
    if (this.data.inReference) {
      const referenceType = this.data.referenceType || "shortcut";
      node2.type += "Reference";
      node2.referenceType = referenceType;
      delete node2.url;
      delete node2.title;
    } else {
      delete node2.identifier;
      delete node2.label;
    }
    this.data.referenceType = void 0;
  }
  function onexitlabeltext(token) {
    const string2 = this.sliceSerialize(token);
    const ancestor = this.stack[this.stack.length - 2];
    ancestor.label = decodeString(string2);
    ancestor.identifier = normalizeIdentifier(string2).toLowerCase();
  }
  function onexitlabel() {
    const fragment = this.stack[this.stack.length - 1];
    const value = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    this.data.inReference = true;
    if (node2.type === "link") {
      const children = fragment.children;
      node2.children = children;
    } else {
      node2.alt = value;
    }
  }
  function onexitresourcedestinationstring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.url = data2;
  }
  function onexitresourcetitlestring() {
    const data2 = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.title = data2;
  }
  function onexitresource() {
    this.data.inReference = void 0;
  }
  function onenterreference() {
    this.data.referenceType = "collapsed";
  }
  function onexitreferencestring(token) {
    const label = this.resume();
    const node2 = this.stack[this.stack.length - 1];
    node2.label = label;
    node2.identifier = normalizeIdentifier(this.sliceSerialize(token)).toLowerCase();
    this.data.referenceType = "full";
  }
  function onexitcharacterreferencemarker(token) {
    this.data.characterReferenceType = token.type;
  }
  function onexitcharacterreferencevalue(token) {
    const data2 = this.sliceSerialize(token);
    const type2 = this.data.characterReferenceType;
    let value;
    if (type2) {
      value = decodeNumericCharacterReference(data2, type2 === "characterReferenceMarkerNumeric" ? 10 : 16);
      this.data.characterReferenceType = void 0;
    } else {
      const result = decodeNamedCharacterReference(data2);
      value = result;
    }
    const tail = this.stack[this.stack.length - 1];
    tail.value += value;
  }
  function onexitcharacterreference(token) {
    const tail = this.stack.pop();
    tail.position.end = point(token.end);
  }
  function onexitautolinkprotocol(token) {
    onexitdata.call(this, token);
    const node2 = this.stack[this.stack.length - 1];
    node2.url = this.sliceSerialize(token);
  }
  function onexitautolinkemail(token) {
    onexitdata.call(this, token);
    const node2 = this.stack[this.stack.length - 1];
    node2.url = "mailto:" + this.sliceSerialize(token);
  }
  function blockQuote2() {
    return {
      type: "blockquote",
      children: []
    };
  }
  function codeFlow() {
    return {
      type: "code",
      lang: null,
      meta: null,
      value: ""
    };
  }
  function codeText2() {
    return {
      type: "inlineCode",
      value: ""
    };
  }
  function definition2() {
    return {
      type: "definition",
      identifier: "",
      label: null,
      title: null,
      url: ""
    };
  }
  function emphasis2() {
    return {
      type: "emphasis",
      children: []
    };
  }
  function heading2() {
    return {
      type: "heading",
      // @ts-expect-error `depth` will be set later.
      depth: 0,
      children: []
    };
  }
  function hardBreak2() {
    return {
      type: "break"
    };
  }
  function html2() {
    return {
      type: "html",
      value: ""
    };
  }
  function image2() {
    return {
      type: "image",
      title: null,
      url: "",
      alt: null
    };
  }
  function link2() {
    return {
      type: "link",
      title: null,
      url: "",
      children: []
    };
  }
  function list2(token) {
    return {
      type: "list",
      ordered: token.type === "listOrdered",
      start: null,
      spread: token._spread,
      children: []
    };
  }
  function listItem2(token) {
    return {
      type: "listItem",
      spread: token._spread,
      checked: null,
      children: []
    };
  }
  function paragraph2() {
    return {
      type: "paragraph",
      children: []
    };
  }
  function strong2() {
    return {
      type: "strong",
      children: []
    };
  }
  function text2() {
    return {
      type: "text",
      value: ""
    };
  }
  function thematicBreak2() {
    return {
      type: "thematicBreak"
    };
  }
}
function point(d2) {
  return {
    line: d2.line,
    column: d2.column,
    offset: d2.offset
  };
}
function configure(combined, extensions) {
  let index2 = -1;
  while (++index2 < extensions.length) {
    const value = extensions[index2];
    if (Array.isArray(value)) {
      configure(combined, value);
    } else {
      extension(combined, value);
    }
  }
}
function extension(combined, extension2) {
  let key;
  for (key in extension2) {
    if (own$2.call(extension2, key)) {
      switch (key) {
        case "canContainEols": {
          const right = extension2[key];
          if (right) {
            combined[key].push(...right);
          }
          break;
        }
        case "transforms": {
          const right = extension2[key];
          if (right) {
            combined[key].push(...right);
          }
          break;
        }
        case "enter":
        case "exit": {
          const right = extension2[key];
          if (right) {
            Object.assign(combined[key], right);
          }
          break;
        }
      }
    }
  }
}
function defaultOnError(left, right) {
  if (left) {
    throw new Error("Cannot close `" + left.type + "` (" + stringifyPosition({
      start: left.start,
      end: left.end
    }) + "): a different token (`" + right.type + "`, " + stringifyPosition({
      start: right.start,
      end: right.end
    }) + ") is open");
  } else {
    throw new Error("Cannot close document, a token (`" + right.type + "`, " + stringifyPosition({
      start: right.start,
      end: right.end
    }) + ") is still open");
  }
}
function remarkParse(options) {
  const self2 = this;
  self2.parser = parser;
  function parser(doc) {
    return fromMarkdown(doc, {
      ...self2.data("settings"),
      ...options,
      // Note: these options are not in the readme.
      // The goal is for them to be set by plugins on `data` instead of being
      // passed by users.
      extensions: self2.data("micromarkExtensions") || [],
      mdastExtensions: self2.data("fromMarkdownExtensions") || []
    });
  }
}
function blockquote(state, node2) {
  const result = {
    type: "element",
    tagName: "blockquote",
    properties: {},
    children: state.wrap(state.all(node2), true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function hardBreak(state, node2) {
  const result = { type: "element", tagName: "br", properties: {}, children: [] };
  state.patch(node2, result);
  return [state.applyData(node2, result), { type: "text", value: "\n" }];
}
function code(state, node2) {
  const value = node2.value ? node2.value + "\n" : "";
  const properties = {};
  const language = node2.lang ? node2.lang.split(/\s+/) : [];
  if (language.length > 0) {
    properties.className = ["language-" + language[0]];
  }
  let result = {
    type: "element",
    tagName: "code",
    properties,
    children: [{ type: "text", value }]
  };
  if (node2.meta) {
    result.data = { meta: node2.meta };
  }
  state.patch(node2, result);
  result = state.applyData(node2, result);
  result = { type: "element", tagName: "pre", properties: {}, children: [result] };
  state.patch(node2, result);
  return result;
}
function strikethrough(state, node2) {
  const result = {
    type: "element",
    tagName: "del",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function emphasis(state, node2) {
  const result = {
    type: "element",
    tagName: "em",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function footnoteReference(state, node2) {
  const clobberPrefix = typeof state.options.clobberPrefix === "string" ? state.options.clobberPrefix : "user-content-";
  const id = String(node2.identifier).toUpperCase();
  const safeId = normalizeUri(id.toLowerCase());
  const index2 = state.footnoteOrder.indexOf(id);
  let counter;
  let reuseCounter = state.footnoteCounts.get(id);
  if (reuseCounter === void 0) {
    reuseCounter = 0;
    state.footnoteOrder.push(id);
    counter = state.footnoteOrder.length;
  } else {
    counter = index2 + 1;
  }
  reuseCounter += 1;
  state.footnoteCounts.set(id, reuseCounter);
  const link2 = {
    type: "element",
    tagName: "a",
    properties: {
      href: "#" + clobberPrefix + "fn-" + safeId,
      id: clobberPrefix + "fnref-" + safeId + (reuseCounter > 1 ? "-" + reuseCounter : ""),
      dataFootnoteRef: true,
      ariaDescribedBy: ["footnote-label"]
    },
    children: [{ type: "text", value: String(counter) }]
  };
  state.patch(node2, link2);
  const sup = {
    type: "element",
    tagName: "sup",
    properties: {},
    children: [link2]
  };
  state.patch(node2, sup);
  return state.applyData(node2, sup);
}
function heading(state, node2) {
  const result = {
    type: "element",
    tagName: "h" + node2.depth,
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function html(state, node2) {
  if (state.options.allowDangerousHtml) {
    const result = { type: "raw", value: node2.value };
    state.patch(node2, result);
    return state.applyData(node2, result);
  }
  return void 0;
}
function revert(state, node2) {
  const subtype = node2.referenceType;
  let suffix = "]";
  if (subtype === "collapsed") {
    suffix += "[]";
  } else if (subtype === "full") {
    suffix += "[" + (node2.label || node2.identifier) + "]";
  }
  if (node2.type === "imageReference") {
    return [{ type: "text", value: "![" + node2.alt + suffix }];
  }
  const contents = state.all(node2);
  const head = contents[0];
  if (head && head.type === "text") {
    head.value = "[" + head.value;
  } else {
    contents.unshift({ type: "text", value: "[" });
  }
  const tail = contents[contents.length - 1];
  if (tail && tail.type === "text") {
    tail.value += suffix;
  } else {
    contents.push({ type: "text", value: suffix });
  }
  return contents;
}
function imageReference(state, node2) {
  const id = String(node2.identifier).toUpperCase();
  const definition2 = state.definitionById.get(id);
  if (!definition2) {
    return revert(state, node2);
  }
  const properties = { src: normalizeUri(definition2.url || ""), alt: node2.alt };
  if (definition2.title !== null && definition2.title !== void 0) {
    properties.title = definition2.title;
  }
  const result = { type: "element", tagName: "img", properties, children: [] };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function image(state, node2) {
  const properties = { src: normalizeUri(node2.url) };
  if (node2.alt !== null && node2.alt !== void 0) {
    properties.alt = node2.alt;
  }
  if (node2.title !== null && node2.title !== void 0) {
    properties.title = node2.title;
  }
  const result = { type: "element", tagName: "img", properties, children: [] };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function inlineCode(state, node2) {
  const text2 = { type: "text", value: node2.value.replace(/\r?\n|\r/g, " ") };
  state.patch(node2, text2);
  const result = {
    type: "element",
    tagName: "code",
    properties: {},
    children: [text2]
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function linkReference(state, node2) {
  const id = String(node2.identifier).toUpperCase();
  const definition2 = state.definitionById.get(id);
  if (!definition2) {
    return revert(state, node2);
  }
  const properties = { href: normalizeUri(definition2.url || "") };
  if (definition2.title !== null && definition2.title !== void 0) {
    properties.title = definition2.title;
  }
  const result = {
    type: "element",
    tagName: "a",
    properties,
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function link(state, node2) {
  const properties = { href: normalizeUri(node2.url) };
  if (node2.title !== null && node2.title !== void 0) {
    properties.title = node2.title;
  }
  const result = {
    type: "element",
    tagName: "a",
    properties,
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function listItem(state, node2, parent) {
  const results = state.all(node2);
  const loose = parent ? listLoose(parent) : listItemLoose(node2);
  const properties = {};
  const children = [];
  if (typeof node2.checked === "boolean") {
    const head = results[0];
    let paragraph2;
    if (head && head.type === "element" && head.tagName === "p") {
      paragraph2 = head;
    } else {
      paragraph2 = { type: "element", tagName: "p", properties: {}, children: [] };
      results.unshift(paragraph2);
    }
    if (paragraph2.children.length > 0) {
      paragraph2.children.unshift({ type: "text", value: " " });
    }
    paragraph2.children.unshift({
      type: "element",
      tagName: "input",
      properties: { type: "checkbox", checked: node2.checked, disabled: true },
      children: []
    });
    properties.className = ["task-list-item"];
  }
  let index2 = -1;
  while (++index2 < results.length) {
    const child = results[index2];
    if (loose || index2 !== 0 || child.type !== "element" || child.tagName !== "p") {
      children.push({ type: "text", value: "\n" });
    }
    if (child.type === "element" && child.tagName === "p" && !loose) {
      children.push(...child.children);
    } else {
      children.push(child);
    }
  }
  const tail = results[results.length - 1];
  if (tail && (loose || tail.type !== "element" || tail.tagName !== "p")) {
    children.push({ type: "text", value: "\n" });
  }
  const result = { type: "element", tagName: "li", properties, children };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function listLoose(node2) {
  let loose = false;
  if (node2.type === "list") {
    loose = node2.spread || false;
    const children = node2.children;
    let index2 = -1;
    while (!loose && ++index2 < children.length) {
      loose = listItemLoose(children[index2]);
    }
  }
  return loose;
}
function listItemLoose(node2) {
  const spread2 = node2.spread;
  return spread2 === null || spread2 === void 0 ? node2.children.length > 1 : spread2;
}
function list(state, node2) {
  const properties = {};
  const results = state.all(node2);
  let index2 = -1;
  if (typeof node2.start === "number" && node2.start !== 1) {
    properties.start = node2.start;
  }
  while (++index2 < results.length) {
    const child = results[index2];
    if (child.type === "element" && child.tagName === "li" && child.properties && Array.isArray(child.properties.className) && child.properties.className.includes("task-list-item")) {
      properties.className = ["contains-task-list"];
      break;
    }
  }
  const result = {
    type: "element",
    tagName: node2.ordered ? "ol" : "ul",
    properties,
    children: state.wrap(results, true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function paragraph(state, node2) {
  const result = {
    type: "element",
    tagName: "p",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function root(state, node2) {
  const result = { type: "root", children: state.wrap(state.all(node2)) };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function strong(state, node2) {
  const result = {
    type: "element",
    tagName: "strong",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function table(state, node2) {
  const rows = state.all(node2);
  const firstRow = rows.shift();
  const tableContent = [];
  if (firstRow) {
    const head = {
      type: "element",
      tagName: "thead",
      properties: {},
      children: state.wrap([firstRow], true)
    };
    state.patch(node2.children[0], head);
    tableContent.push(head);
  }
  if (rows.length > 0) {
    const body2 = {
      type: "element",
      tagName: "tbody",
      properties: {},
      children: state.wrap(rows, true)
    };
    const start = pointStart(node2.children[1]);
    const end = pointEnd(node2.children[node2.children.length - 1]);
    if (start && end) body2.position = { start, end };
    tableContent.push(body2);
  }
  const result = {
    type: "element",
    tagName: "table",
    properties: {},
    children: state.wrap(tableContent, true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function tableRow(state, node2, parent) {
  const siblings = parent ? parent.children : void 0;
  const rowIndex = siblings ? siblings.indexOf(node2) : 1;
  const tagName = rowIndex === 0 ? "th" : "td";
  const align = parent && parent.type === "table" ? parent.align : void 0;
  const length = align ? align.length : node2.children.length;
  let cellIndex = -1;
  const cells = [];
  while (++cellIndex < length) {
    const cell = node2.children[cellIndex];
    const properties = {};
    const alignValue = align ? align[cellIndex] : void 0;
    if (alignValue) {
      properties.align = alignValue;
    }
    let result2 = { type: "element", tagName, properties, children: [] };
    if (cell) {
      result2.children = state.all(cell);
      state.patch(cell, result2);
      result2 = state.applyData(cell, result2);
    }
    cells.push(result2);
  }
  const result = {
    type: "element",
    tagName: "tr",
    properties: {},
    children: state.wrap(cells, true)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function tableCell(state, node2) {
  const result = {
    type: "element",
    tagName: "td",
    // Assume body cell.
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
const tab = 9;
const space = 32;
function trimLines(value) {
  const source = String(value);
  const search2 = /\r?\n|\r/g;
  let match = search2.exec(source);
  let last = 0;
  const lines = [];
  while (match) {
    lines.push(
      trimLine(source.slice(last, match.index), last > 0, true),
      match[0]
    );
    last = match.index + match[0].length;
    match = search2.exec(source);
  }
  lines.push(trimLine(source.slice(last), last > 0, false));
  return lines.join("");
}
function trimLine(value, start, end) {
  let startIndex = 0;
  let endIndex = value.length;
  if (start) {
    let code2 = value.codePointAt(startIndex);
    while (code2 === tab || code2 === space) {
      startIndex++;
      code2 = value.codePointAt(startIndex);
    }
  }
  if (end) {
    let code2 = value.codePointAt(endIndex - 1);
    while (code2 === tab || code2 === space) {
      endIndex--;
      code2 = value.codePointAt(endIndex - 1);
    }
  }
  return endIndex > startIndex ? value.slice(startIndex, endIndex) : "";
}
function text(state, node2) {
  const result = { type: "text", value: trimLines(String(node2.value)) };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function thematicBreak(state, node2) {
  const result = {
    type: "element",
    tagName: "hr",
    properties: {},
    children: []
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
const handlers = {
  blockquote,
  break: hardBreak,
  code,
  delete: strikethrough,
  emphasis,
  footnoteReference,
  heading,
  html,
  imageReference,
  image,
  inlineCode,
  linkReference,
  link,
  listItem,
  list,
  paragraph,
  // @ts-expect-error: root is different, but hard to type.
  root,
  strong,
  table,
  tableCell,
  tableRow,
  text,
  thematicBreak,
  toml: ignore,
  yaml: ignore,
  definition: ignore,
  footnoteDefinition: ignore
};
function ignore() {
  return void 0;
}
const VOID = -1;
const PRIMITIVE = 0;
const ARRAY = 1;
const OBJECT = 2;
const DATE = 3;
const REGEXP = 4;
const MAP = 5;
const SET = 6;
const ERROR = 7;
const BIGINT = 8;
const env = typeof self === "object" ? self : globalThis;
const deserializer = ($2, _2) => {
  const as = (out, index2) => {
    $2.set(index2, out);
    return out;
  };
  const unpair = (index2) => {
    if ($2.has(index2))
      return $2.get(index2);
    const [type2, value] = _2[index2];
    switch (type2) {
      case PRIMITIVE:
      case VOID:
        return as(value, index2);
      case ARRAY: {
        const arr = as([], index2);
        for (const index3 of value)
          arr.push(unpair(index3));
        return arr;
      }
      case OBJECT: {
        const object = as({}, index2);
        for (const [key, index3] of value)
          object[unpair(key)] = unpair(index3);
        return object;
      }
      case DATE:
        return as(new Date(value), index2);
      case REGEXP: {
        const { source, flags } = value;
        return as(new RegExp(source, flags), index2);
      }
      case MAP: {
        const map = as(/* @__PURE__ */ new Map(), index2);
        for (const [key, index3] of value)
          map.set(unpair(key), unpair(index3));
        return map;
      }
      case SET: {
        const set = as(/* @__PURE__ */ new Set(), index2);
        for (const index3 of value)
          set.add(unpair(index3));
        return set;
      }
      case ERROR: {
        const { name: name2, message } = value;
        return as(new env[name2](message), index2);
      }
      case BIGINT:
        return as(BigInt(value), index2);
      case "BigInt":
        return as(Object(BigInt(value)), index2);
      case "ArrayBuffer":
        return as(new Uint8Array(value).buffer, value);
      case "DataView": {
        const { buffer } = new Uint8Array(value);
        return as(new DataView(buffer), value);
      }
    }
    return as(new env[type2](value), index2);
  };
  return unpair;
};
const deserialize = (serialized) => deserializer(/* @__PURE__ */ new Map(), serialized)(0);
const EMPTY = "";
const { toString: toString2 } = {};
const { keys } = Object;
const typeOf = (value) => {
  const type2 = typeof value;
  if (type2 !== "object" || !value)
    return [PRIMITIVE, type2];
  const asString = toString2.call(value).slice(8, -1);
  switch (asString) {
    case "Array":
      return [ARRAY, EMPTY];
    case "Object":
      return [OBJECT, EMPTY];
    case "Date":
      return [DATE, EMPTY];
    case "RegExp":
      return [REGEXP, EMPTY];
    case "Map":
      return [MAP, EMPTY];
    case "Set":
      return [SET, EMPTY];
    case "DataView":
      return [ARRAY, asString];
  }
  if (asString.includes("Array"))
    return [ARRAY, asString];
  if (asString.includes("Error"))
    return [ERROR, asString];
  return [OBJECT, asString];
};
const shouldSkip = ([TYPE, type2]) => TYPE === PRIMITIVE && (type2 === "function" || type2 === "symbol");
const serializer = (strict, json, $2, _2) => {
  const as = (out, value) => {
    const index2 = _2.push(out) - 1;
    $2.set(value, index2);
    return index2;
  };
  const pair = (value) => {
    if ($2.has(value))
      return $2.get(value);
    let [TYPE, type2] = typeOf(value);
    switch (TYPE) {
      case PRIMITIVE: {
        let entry = value;
        switch (type2) {
          case "bigint":
            TYPE = BIGINT;
            entry = value.toString();
            break;
          case "function":
          case "symbol":
            if (strict)
              throw new TypeError("unable to serialize " + type2);
            entry = null;
            break;
          case "undefined":
            return as([VOID], value);
        }
        return as([TYPE, entry], value);
      }
      case ARRAY: {
        if (type2) {
          let spread2 = value;
          if (type2 === "DataView") {
            spread2 = new Uint8Array(value.buffer);
          } else if (type2 === "ArrayBuffer") {
            spread2 = new Uint8Array(value);
          }
          return as([type2, [...spread2]], value);
        }
        const arr = [];
        const index2 = as([TYPE, arr], value);
        for (const entry of value)
          arr.push(pair(entry));
        return index2;
      }
      case OBJECT: {
        if (type2) {
          switch (type2) {
            case "BigInt":
              return as([type2, value.toString()], value);
            case "Boolean":
            case "Number":
            case "String":
              return as([type2, value.valueOf()], value);
          }
        }
        if (json && "toJSON" in value)
          return pair(value.toJSON());
        const entries = [];
        const index2 = as([TYPE, entries], value);
        for (const key of keys(value)) {
          if (strict || !shouldSkip(typeOf(value[key])))
            entries.push([pair(key), pair(value[key])]);
        }
        return index2;
      }
      case DATE:
        return as([TYPE, value.toISOString()], value);
      case REGEXP: {
        const { source, flags } = value;
        return as([TYPE, { source, flags }], value);
      }
      case MAP: {
        const entries = [];
        const index2 = as([TYPE, entries], value);
        for (const [key, entry] of value) {
          if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
            entries.push([pair(key), pair(entry)]);
        }
        return index2;
      }
      case SET: {
        const entries = [];
        const index2 = as([TYPE, entries], value);
        for (const entry of value) {
          if (strict || !shouldSkip(typeOf(entry)))
            entries.push(pair(entry));
        }
        return index2;
      }
    }
    const { message } = value;
    return as([TYPE, { name: type2, message }], value);
  };
  return pair;
};
const serialize = (value, { json, lossy } = {}) => {
  const _2 = [];
  return serializer(!(json || lossy), !!json, /* @__PURE__ */ new Map(), _2)(value), _2;
};
const structuredClone$1 = typeof structuredClone === "function" ? (
  /* c8 ignore start */
  (any, options) => options && ("json" in options || "lossy" in options) ? deserialize(serialize(any, options)) : structuredClone(any)
) : (any, options) => deserialize(serialize(any, options));
function defaultFootnoteBackContent(_2, rereferenceIndex) {
  const result = [{ type: "text", value: "↩" }];
  if (rereferenceIndex > 1) {
    result.push({
      type: "element",
      tagName: "sup",
      properties: {},
      children: [{ type: "text", value: String(rereferenceIndex) }]
    });
  }
  return result;
}
function defaultFootnoteBackLabel(referenceIndex, rereferenceIndex) {
  return "Back to reference " + (referenceIndex + 1) + (rereferenceIndex > 1 ? "-" + rereferenceIndex : "");
}
function footer(state) {
  const clobberPrefix = typeof state.options.clobberPrefix === "string" ? state.options.clobberPrefix : "user-content-";
  const footnoteBackContent = state.options.footnoteBackContent || defaultFootnoteBackContent;
  const footnoteBackLabel = state.options.footnoteBackLabel || defaultFootnoteBackLabel;
  const footnoteLabel = state.options.footnoteLabel || "Footnotes";
  const footnoteLabelTagName = state.options.footnoteLabelTagName || "h2";
  const footnoteLabelProperties = state.options.footnoteLabelProperties || {
    className: ["sr-only"]
  };
  const listItems = [];
  let referenceIndex = -1;
  while (++referenceIndex < state.footnoteOrder.length) {
    const definition2 = state.footnoteById.get(
      state.footnoteOrder[referenceIndex]
    );
    if (!definition2) {
      continue;
    }
    const content2 = state.all(definition2);
    const id = String(definition2.identifier).toUpperCase();
    const safeId = normalizeUri(id.toLowerCase());
    let rereferenceIndex = 0;
    const backReferences = [];
    const counts = state.footnoteCounts.get(id);
    while (counts !== void 0 && ++rereferenceIndex <= counts) {
      if (backReferences.length > 0) {
        backReferences.push({ type: "text", value: " " });
      }
      let children = typeof footnoteBackContent === "string" ? footnoteBackContent : footnoteBackContent(referenceIndex, rereferenceIndex);
      if (typeof children === "string") {
        children = { type: "text", value: children };
      }
      backReferences.push({
        type: "element",
        tagName: "a",
        properties: {
          href: "#" + clobberPrefix + "fnref-" + safeId + (rereferenceIndex > 1 ? "-" + rereferenceIndex : ""),
          dataFootnoteBackref: "",
          ariaLabel: typeof footnoteBackLabel === "string" ? footnoteBackLabel : footnoteBackLabel(referenceIndex, rereferenceIndex),
          className: ["data-footnote-backref"]
        },
        children: Array.isArray(children) ? children : [children]
      });
    }
    const tail = content2[content2.length - 1];
    if (tail && tail.type === "element" && tail.tagName === "p") {
      const tailTail = tail.children[tail.children.length - 1];
      if (tailTail && tailTail.type === "text") {
        tailTail.value += " ";
      } else {
        tail.children.push({ type: "text", value: " " });
      }
      tail.children.push(...backReferences);
    } else {
      content2.push(...backReferences);
    }
    const listItem2 = {
      type: "element",
      tagName: "li",
      properties: { id: clobberPrefix + "fn-" + safeId },
      children: state.wrap(content2, true)
    };
    state.patch(definition2, listItem2);
    listItems.push(listItem2);
  }
  if (listItems.length === 0) {
    return;
  }
  return {
    type: "element",
    tagName: "section",
    properties: { dataFootnotes: true, className: ["footnotes"] },
    children: [
      {
        type: "element",
        tagName: footnoteLabelTagName,
        properties: {
          ...structuredClone$1(footnoteLabelProperties),
          id: "footnote-label"
        },
        children: [{ type: "text", value: footnoteLabel }]
      },
      { type: "text", value: "\n" },
      {
        type: "element",
        tagName: "ol",
        properties: {},
        children: state.wrap(listItems, true)
      },
      { type: "text", value: "\n" }
    ]
  };
}
const convert = (
  // Note: overloads in JSDoc can’t yet use different `@template`s.
  /**
   * @type {(
   *   (<Condition extends string>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & {type: Condition}) &
   *   (<Condition extends Props>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Condition) &
   *   (<Condition extends TestFunction>(test: Condition) => (node: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node & Predicate<Condition, Node>) &
   *   ((test?: null | undefined) => (node?: unknown, index?: number | null | undefined, parent?: Parent | null | undefined, context?: unknown) => node is Node) &
   *   ((test?: Test) => Check)
   * )}
   */
  /**
   * @param {Test} [test]
   * @returns {Check}
   */
  (function(test2) {
    if (test2 === null || test2 === void 0) {
      return ok;
    }
    if (typeof test2 === "function") {
      return castFactory(test2);
    }
    if (typeof test2 === "object") {
      return Array.isArray(test2) ? anyFactory(test2) : (
        // Cast because `ReadonlyArray` goes into the above but `isArray`
        // narrows to `Array`.
        propertiesFactory(
          /** @type {Props} */
          test2
        )
      );
    }
    if (typeof test2 === "string") {
      return typeFactory(test2);
    }
    throw new Error("Expected function, string, or object as test");
  })
);
function anyFactory(tests) {
  const checks2 = [];
  let index2 = -1;
  while (++index2 < tests.length) {
    checks2[index2] = convert(tests[index2]);
  }
  return castFactory(any);
  function any(...parameters) {
    let index3 = -1;
    while (++index3 < checks2.length) {
      if (checks2[index3].apply(this, parameters)) return true;
    }
    return false;
  }
}
function propertiesFactory(check) {
  const checkAsRecord = (
    /** @type {Record<string, unknown>} */
    check
  );
  return castFactory(all3);
  function all3(node2) {
    const nodeAsRecord = (
      /** @type {Record<string, unknown>} */
      /** @type {unknown} */
      node2
    );
    let key;
    for (key in check) {
      if (nodeAsRecord[key] !== checkAsRecord[key]) return false;
    }
    return true;
  }
}
function typeFactory(check) {
  return castFactory(type2);
  function type2(node2) {
    return node2 && node2.type === check;
  }
}
function castFactory(testFunction) {
  return check;
  function check(value, index2, parent) {
    return Boolean(
      looksLikeANode(value) && testFunction.call(
        this,
        value,
        typeof index2 === "number" ? index2 : void 0,
        parent || void 0
      )
    );
  }
}
function ok() {
  return true;
}
function looksLikeANode(value) {
  return value !== null && typeof value === "object" && "type" in value;
}
function color(d2) {
  return "\x1B[33m" + d2 + "\x1B[39m";
}
const empty = [];
const CONTINUE = true;
const EXIT = false;
const SKIP = "skip";
function visitParents(tree, test2, visitor, reverse) {
  let check;
  if (typeof test2 === "function" && typeof visitor !== "function") {
    reverse = visitor;
    visitor = test2;
  } else {
    check = test2;
  }
  const is = convert(check);
  const step = reverse ? -1 : 1;
  factory2(tree, void 0, [])();
  function factory2(node2, index2, parents) {
    const value = (
      /** @type {Record<string, unknown>} */
      node2 && typeof node2 === "object" ? node2 : {}
    );
    if (typeof value.type === "string") {
      const name2 = (
        // `hast`
        typeof value.tagName === "string" ? value.tagName : (
          // `xast`
          typeof value.name === "string" ? value.name : void 0
        )
      );
      Object.defineProperty(visit2, "name", {
        value: "node (" + color(node2.type + (name2 ? "<" + name2 + ">" : "")) + ")"
      });
    }
    return visit2;
    function visit2() {
      let result = empty;
      let subresult;
      let offset;
      let grandparents;
      if (!test2 || is(node2, index2, parents[parents.length - 1] || void 0)) {
        result = toResult(visitor(node2, parents));
        if (result[0] === EXIT) {
          return result;
        }
      }
      if ("children" in node2 && node2.children) {
        const nodeAsParent = (
          /** @type {UnistParent} */
          node2
        );
        if (nodeAsParent.children && result[0] !== SKIP) {
          offset = (reverse ? nodeAsParent.children.length : -1) + step;
          grandparents = parents.concat(nodeAsParent);
          while (offset > -1 && offset < nodeAsParent.children.length) {
            const child = nodeAsParent.children[offset];
            subresult = factory2(child, offset, grandparents)();
            if (subresult[0] === EXIT) {
              return subresult;
            }
            offset = typeof subresult[1] === "number" ? subresult[1] : offset + step;
          }
        }
      }
      return result;
    }
  }
}
function toResult(value) {
  if (Array.isArray(value)) {
    return value;
  }
  if (typeof value === "number") {
    return [CONTINUE, value];
  }
  return value === null || value === void 0 ? empty : [value];
}
function visit(tree, testOrVisitor, visitorOrReverse, maybeReverse) {
  let reverse;
  let test2;
  let visitor;
  if (typeof testOrVisitor === "function" && typeof visitorOrReverse !== "function") {
    test2 = void 0;
    visitor = testOrVisitor;
    reverse = visitorOrReverse;
  } else {
    test2 = testOrVisitor;
    visitor = visitorOrReverse;
    reverse = maybeReverse;
  }
  visitParents(tree, test2, overload, reverse);
  function overload(node2, parents) {
    const parent = parents[parents.length - 1];
    const index2 = parent ? parent.children.indexOf(node2) : void 0;
    return visitor(node2, index2, parent);
  }
}
const own$1 = {}.hasOwnProperty;
const emptyOptions = {};
function createState(tree, options) {
  const settings = options || emptyOptions;
  const definitionById = /* @__PURE__ */ new Map();
  const footnoteById = /* @__PURE__ */ new Map();
  const footnoteCounts = /* @__PURE__ */ new Map();
  const handlers$1 = { ...handlers, ...settings.handlers };
  const state = {
    all: all3,
    applyData,
    definitionById,
    footnoteById,
    footnoteCounts,
    footnoteOrder: [],
    handlers: handlers$1,
    one: one2,
    options: settings,
    patch,
    wrap: wrap$1
  };
  visit(tree, function(node2) {
    if (node2.type === "definition" || node2.type === "footnoteDefinition") {
      const map = node2.type === "definition" ? definitionById : footnoteById;
      const id = String(node2.identifier).toUpperCase();
      if (!map.has(id)) {
        map.set(id, node2);
      }
    }
  });
  return state;
  function one2(node2, parent) {
    const type2 = node2.type;
    const handle = state.handlers[type2];
    if (own$1.call(state.handlers, type2) && handle) {
      return handle(state, node2, parent);
    }
    if (state.options.passThrough && state.options.passThrough.includes(type2)) {
      if ("children" in node2) {
        const { children, ...shallow } = node2;
        const result = structuredClone$1(shallow);
        result.children = state.all(node2);
        return result;
      }
      return structuredClone$1(node2);
    }
    const unknown = state.options.unknownHandler || defaultUnknownHandler;
    return unknown(state, node2, parent);
  }
  function all3(parent) {
    const values = [];
    if ("children" in parent) {
      const nodes = parent.children;
      let index2 = -1;
      while (++index2 < nodes.length) {
        const result = state.one(nodes[index2], parent);
        if (result) {
          if (index2 && nodes[index2 - 1].type === "break") {
            if (!Array.isArray(result) && result.type === "text") {
              result.value = trimMarkdownSpaceStart(result.value);
            }
            if (!Array.isArray(result) && result.type === "element") {
              const head = result.children[0];
              if (head && head.type === "text") {
                head.value = trimMarkdownSpaceStart(head.value);
              }
            }
          }
          if (Array.isArray(result)) {
            values.push(...result);
          } else {
            values.push(result);
          }
        }
      }
    }
    return values;
  }
}
function patch(from, to) {
  if (from.position) to.position = position$1(from);
}
function applyData(from, to) {
  let result = to;
  if (from && from.data) {
    const hName = from.data.hName;
    const hChildren = from.data.hChildren;
    const hProperties = from.data.hProperties;
    if (typeof hName === "string") {
      if (result.type === "element") {
        result.tagName = hName;
      } else {
        const children = "children" in result ? result.children : [result];
        result = { type: "element", tagName: hName, properties: {}, children };
      }
    }
    if (result.type === "element" && hProperties) {
      Object.assign(result.properties, structuredClone$1(hProperties));
    }
    if ("children" in result && result.children && hChildren !== null && hChildren !== void 0) {
      result.children = hChildren;
    }
  }
  return result;
}
function defaultUnknownHandler(state, node2) {
  const data = node2.data || {};
  const result = "value" in node2 && !(own$1.call(data, "hProperties") || own$1.call(data, "hChildren")) ? { type: "text", value: node2.value } : {
    type: "element",
    tagName: "div",
    properties: {},
    children: state.all(node2)
  };
  state.patch(node2, result);
  return state.applyData(node2, result);
}
function wrap$1(nodes, loose) {
  const result = [];
  let index2 = -1;
  if (loose) {
    result.push({ type: "text", value: "\n" });
  }
  while (++index2 < nodes.length) {
    if (index2) result.push({ type: "text", value: "\n" });
    result.push(nodes[index2]);
  }
  if (loose && nodes.length > 0) {
    result.push({ type: "text", value: "\n" });
  }
  return result;
}
function trimMarkdownSpaceStart(value) {
  let index2 = 0;
  let code2 = value.charCodeAt(index2);
  while (code2 === 9 || code2 === 32) {
    index2++;
    code2 = value.charCodeAt(index2);
  }
  return value.slice(index2);
}
function toHast(tree, options) {
  const state = createState(tree, options);
  const node2 = state.one(tree, void 0);
  const foot = footer(state);
  const result = Array.isArray(node2) ? { type: "root", children: node2 } : node2 || { type: "root", children: [] };
  if (foot) {
    result.children.push({ type: "text", value: "\n" }, foot);
  }
  return result;
}
function remarkRehype(destination, options) {
  if (destination && "run" in destination) {
    return async function(tree, file) {
      const hastTree = (
        /** @type {HastRoot} */
        toHast(tree, { file, ...options })
      );
      await destination.run(hastTree, file);
    };
  }
  return function(tree, file) {
    return (
      /** @type {HastRoot} */
      toHast(tree, { file, ...destination || options })
    );
  };
}
function bail(error) {
  if (error) {
    throw error;
  }
}
var extend$1;
var hasRequiredExtend;
function requireExtend() {
  if (hasRequiredExtend) return extend$1;
  hasRequiredExtend = 1;
  var hasOwn = Object.prototype.hasOwnProperty;
  var toStr = Object.prototype.toString;
  var defineProperty = Object.defineProperty;
  var gOPD2 = Object.getOwnPropertyDescriptor;
  var isArray2 = function isArray3(arr) {
    if (typeof Array.isArray === "function") {
      return Array.isArray(arr);
    }
    return toStr.call(arr) === "[object Array]";
  };
  var isPlainObject2 = function isPlainObject3(obj) {
    if (!obj || toStr.call(obj) !== "[object Object]") {
      return false;
    }
    var hasOwnConstructor = hasOwn.call(obj, "constructor");
    var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf");
    if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
      return false;
    }
    var key;
    for (key in obj) {
    }
    return typeof key === "undefined" || hasOwn.call(obj, key);
  };
  var setProperty = function setProperty2(target, options) {
    if (defineProperty && options.name === "__proto__") {
      defineProperty(target, options.name, {
        enumerable: true,
        configurable: true,
        value: options.newValue,
        writable: true
      });
    } else {
      target[options.name] = options.newValue;
    }
  };
  var getProperty = function getProperty2(obj, name2) {
    if (name2 === "__proto__") {
      if (!hasOwn.call(obj, name2)) {
        return void 0;
      } else if (gOPD2) {
        return gOPD2(obj, name2).value;
      }
    }
    return obj[name2];
  };
  extend$1 = function extend2() {
    var options, name2, src2, copy, copyIsArray, clone;
    var target = arguments[0];
    var i = 1;
    var length = arguments.length;
    var deep = false;
    if (typeof target === "boolean") {
      deep = target;
      target = arguments[1] || {};
      i = 2;
    }
    if (target == null || typeof target !== "object" && typeof target !== "function") {
      target = {};
    }
    for (; i < length; ++i) {
      options = arguments[i];
      if (options != null) {
        for (name2 in options) {
          src2 = getProperty(target, name2);
          copy = getProperty(options, name2);
          if (target !== copy) {
            if (deep && copy && (isPlainObject2(copy) || (copyIsArray = isArray2(copy)))) {
              if (copyIsArray) {
                copyIsArray = false;
                clone = src2 && isArray2(src2) ? src2 : [];
              } else {
                clone = src2 && isPlainObject2(src2) ? src2 : {};
              }
              setProperty(target, { name: name2, newValue: extend2(deep, clone, copy) });
            } else if (typeof copy !== "undefined") {
              setProperty(target, { name: name2, newValue: copy });
            }
          }
        }
      }
    }
    return target;
  };
  return extend$1;
}
var extendExports = requireExtend();
const extend = /* @__PURE__ */ getDefaultExportFromCjs(extendExports);
function isPlainObject(value) {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  const prototype2 = Object.getPrototypeOf(value);
  return (prototype2 === null || prototype2 === Object.prototype || Object.getPrototypeOf(prototype2) === null) && !(Symbol.toStringTag in value) && !(Symbol.iterator in value);
}
function trough() {
  const fns = [];
  const pipeline = { run, use };
  return pipeline;
  function run(...values) {
    let middlewareIndex = -1;
    const callback = values.pop();
    if (typeof callback !== "function") {
      throw new TypeError("Expected function as last argument, not " + callback);
    }
    next(null, ...values);
    function next(error, ...output) {
      const fn = fns[++middlewareIndex];
      let index2 = -1;
      if (error) {
        callback(error);
        return;
      }
      while (++index2 < values.length) {
        if (output[index2] === null || output[index2] === void 0) {
          output[index2] = values[index2];
        }
      }
      values = output;
      if (fn) {
        wrap(fn, next)(...output);
      } else {
        callback(null, ...output);
      }
    }
  }
  function use(middelware) {
    if (typeof middelware !== "function") {
      throw new TypeError(
        "Expected `middelware` to be a function, not " + middelware
      );
    }
    fns.push(middelware);
    return pipeline;
  }
}
function wrap(middleware, callback) {
  let called;
  return wrapped;
  function wrapped(...parameters) {
    const fnExpectsCallback = middleware.length > parameters.length;
    let result;
    if (fnExpectsCallback) {
      parameters.push(done);
    }
    try {
      result = middleware.apply(this, parameters);
    } catch (error) {
      const exception = (
        /** @type {Error} */
        error
      );
      if (fnExpectsCallback && called) {
        throw exception;
      }
      return done(exception);
    }
    if (!fnExpectsCallback) {
      if (result && result.then && typeof result.then === "function") {
        result.then(then, done);
      } else if (result instanceof Error) {
        done(result);
      } else {
        then(result);
      }
    }
  }
  function done(error, ...output) {
    if (!called) {
      called = true;
      callback(error, ...output);
    }
  }
  function then(value) {
    done(null, value);
  }
}
function isUrl(fileUrlOrPath) {
  return Boolean(
    fileUrlOrPath !== null && typeof fileUrlOrPath === "object" && "href" in fileUrlOrPath && fileUrlOrPath.href && "protocol" in fileUrlOrPath && fileUrlOrPath.protocol && // @ts-expect-error: indexing is fine.
    fileUrlOrPath.auth === void 0
  );
}
const order = (
  /** @type {const} */
  [
    "history",
    "path",
    "basename",
    "stem",
    "extname",
    "dirname"
  ]
);
class VFile {
  /**
   * Create a new virtual file.
   *
   * `options` is treated as:
   *
   * *   `string` or `Uint8Array` — `{value: options}`
   * *   `URL` — `{path: options}`
   * *   `VFile` — shallow copies its data over to the new file
   * *   `object` — all fields are shallow copied over to the new file
   *
   * Path related fields are set in the following order (least specific to
   * most specific): `history`, `path`, `basename`, `stem`, `extname`,
   * `dirname`.
   *
   * You cannot set `dirname` or `extname` without setting either `history`,
   * `path`, `basename`, or `stem` too.
   *
   * @param {Compatible | null | undefined} [value]
   *   File value.
   * @returns
   *   New instance.
   */
  constructor(value) {
    let options;
    if (!value) {
      options = {};
    } else if (isUrl(value)) {
      options = { path: value };
    } else if (typeof value === "string" || isUint8Array$1(value)) {
      options = { value };
    } else {
      options = value;
    }
    this.cwd = "cwd" in options ? "" : minproc.cwd();
    this.data = {};
    this.history = [];
    this.messages = [];
    this.value;
    this.map;
    this.result;
    this.stored;
    let index2 = -1;
    while (++index2 < order.length) {
      const field2 = order[index2];
      if (field2 in options && options[field2] !== void 0 && options[field2] !== null) {
        this[field2] = field2 === "history" ? [...options[field2]] : options[field2];
      }
    }
    let field;
    for (field in options) {
      if (!order.includes(field)) {
        this[field] = options[field];
      }
    }
  }
  /**
   * Get the basename (including extname) (example: `'index.min.js'`).
   *
   * @returns {string | undefined}
   *   Basename.
   */
  get basename() {
    return typeof this.path === "string" ? minpath.basename(this.path) : void 0;
  }
  /**
   * Set basename (including extname) (`'index.min.js'`).
   *
   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
   * on windows).
   * Cannot be nullified (use `file.path = file.dirname` instead).
   *
   * @param {string} basename
   *   Basename.
   * @returns {undefined}
   *   Nothing.
   */
  set basename(basename) {
    assertNonEmpty(basename, "basename");
    assertPart(basename, "basename");
    this.path = minpath.join(this.dirname || "", basename);
  }
  /**
   * Get the parent path (example: `'~'`).
   *
   * @returns {string | undefined}
   *   Dirname.
   */
  get dirname() {
    return typeof this.path === "string" ? minpath.dirname(this.path) : void 0;
  }
  /**
   * Set the parent path (example: `'~'`).
   *
   * Cannot be set if there’s no `path` yet.
   *
   * @param {string | undefined} dirname
   *   Dirname.
   * @returns {undefined}
   *   Nothing.
   */
  set dirname(dirname) {
    assertPath(this.basename, "dirname");
    this.path = minpath.join(dirname || "", this.basename);
  }
  /**
   * Get the extname (including dot) (example: `'.js'`).
   *
   * @returns {string | undefined}
   *   Extname.
   */
  get extname() {
    return typeof this.path === "string" ? minpath.extname(this.path) : void 0;
  }
  /**
   * Set the extname (including dot) (example: `'.js'`).
   *
   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
   * on windows).
   * Cannot be set if there’s no `path` yet.
   *
   * @param {string | undefined} extname
   *   Extname.
   * @returns {undefined}
   *   Nothing.
   */
  set extname(extname) {
    assertPart(extname, "extname");
    assertPath(this.dirname, "extname");
    if (extname) {
      if (extname.codePointAt(0) !== 46) {
        throw new Error("`extname` must start with `.`");
      }
      if (extname.includes(".", 1)) {
        throw new Error("`extname` cannot contain multiple dots");
      }
    }
    this.path = minpath.join(this.dirname, this.stem + (extname || ""));
  }
  /**
   * Get the full path (example: `'~/index.min.js'`).
   *
   * @returns {string}
   *   Path.
   */
  get path() {
    return this.history[this.history.length - 1];
  }
  /**
   * Set the full path (example: `'~/index.min.js'`).
   *
   * Cannot be nullified.
   * You can set a file URL (a `URL` object with a `file:` protocol) which will
   * be turned into a path with `url.fileURLToPath`.
   *
   * @param {URL | string} path
   *   Path.
   * @returns {undefined}
   *   Nothing.
   */
  set path(path) {
    if (isUrl(path)) {
      path = fileURLToPath(path);
    }
    assertNonEmpty(path, "path");
    if (this.path !== path) {
      this.history.push(path);
    }
  }
  /**
   * Get the stem (basename w/o extname) (example: `'index.min'`).
   *
   * @returns {string | undefined}
   *   Stem.
   */
  get stem() {
    return typeof this.path === "string" ? minpath.basename(this.path, this.extname) : void 0;
  }
  /**
   * Set the stem (basename w/o extname) (example: `'index.min'`).
   *
   * Cannot contain path separators (`'/'` on unix, macOS, and browsers, `'\'`
   * on windows).
   * Cannot be nullified (use `file.path = file.dirname` instead).
   *
   * @param {string} stem
   *   Stem.
   * @returns {undefined}
   *   Nothing.
   */
  set stem(stem) {
    assertNonEmpty(stem, "stem");
    assertPart(stem, "stem");
    this.path = minpath.join(this.dirname || "", stem + (this.extname || ""));
  }
  // Normal prototypal methods.
  /**
   * Create a fatal message for `reason` associated with the file.
   *
   * The `fatal` field of the message is set to `true` (error; file not usable)
   * and the `file` field is set to the current file path.
   * The message is added to the `messages` field on `file`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {MessageOptions | null | undefined} [options]
   * @returns {never}
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns {never}
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns {never}
   *   Never.
   * @throws {VFileMessage}
   *   Message.
   */
  fail(causeOrReason, optionsOrParentOrPlace, origin2) {
    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin2);
    message.fatal = true;
    throw message;
  }
  /**
   * Create an info message for `reason` associated with the file.
   *
   * The `fatal` field of the message is set to `undefined` (info; change
   * likely not needed) and the `file` field is set to the current file path.
   * The message is added to the `messages` field on `file`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {MessageOptions | null | undefined} [options]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns {VFileMessage}
   *   Message.
   */
  info(causeOrReason, optionsOrParentOrPlace, origin2) {
    const message = this.message(causeOrReason, optionsOrParentOrPlace, origin2);
    message.fatal = void 0;
    return message;
  }
  /**
   * Create a message for `reason` associated with the file.
   *
   * The `fatal` field of the message is set to `false` (warning; change may be
   * needed) and the `file` field is set to the current file path.
   * The message is added to the `messages` field on `file`.
   *
   * > 🪦 **Note**: also has obsolete signatures.
   *
   * @overload
   * @param {string} reason
   * @param {MessageOptions | null | undefined} [options]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {string} reason
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Node | NodeLike | null | undefined} parent
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {Point | Position | null | undefined} place
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @overload
   * @param {Error | VFileMessage} cause
   * @param {string | null | undefined} [origin]
   * @returns {VFileMessage}
   *
   * @param {Error | VFileMessage | string} causeOrReason
   *   Reason for message, should use markdown.
   * @param {Node | NodeLike | MessageOptions | Point | Position | string | null | undefined} [optionsOrParentOrPlace]
   *   Configuration (optional).
   * @param {string | null | undefined} [origin]
   *   Place in code where the message originates (example:
   *   `'my-package:my-rule'` or `'my-rule'`).
   * @returns {VFileMessage}
   *   Message.
   */
  message(causeOrReason, optionsOrParentOrPlace, origin2) {
    const message = new VFileMessage(
      // @ts-expect-error: the overloads are fine.
      causeOrReason,
      optionsOrParentOrPlace,
      origin2
    );
    if (this.path) {
      message.name = this.path + ":" + message.name;
      message.file = this.path;
    }
    message.fatal = false;
    this.messages.push(message);
    return message;
  }
  /**
   * Serialize the file.
   *
   * > **Note**: which encodings are supported depends on the engine.
   * > For info on Node.js, see:
   * > <https://nodejs.org/api/util.html#whatwg-supported-encodings>.
   *
   * @param {string | null | undefined} [encoding='utf8']
   *   Character encoding to understand `value` as when it’s a `Uint8Array`
   *   (default: `'utf-8'`).
   * @returns {string}
   *   Serialized file.
   */
  toString(encoding) {
    if (this.value === void 0) {
      return "";
    }
    if (typeof this.value === "string") {
      return this.value;
    }
    const decoder = new TextDecoder(encoding || void 0);
    return decoder.decode(this.value);
  }
}
function assertPart(part, name2) {
  if (part && part.includes(minpath.sep)) {
    throw new Error(
      "`" + name2 + "` cannot be a path: did not expect `" + minpath.sep + "`"
    );
  }
}
function assertNonEmpty(part, name2) {
  if (!part) {
    throw new Error("`" + name2 + "` cannot be empty");
  }
}
function assertPath(path, name2) {
  if (!path) {
    throw new Error("Setting `" + name2 + "` requires `path` to be set too");
  }
}
function isUint8Array$1(value) {
  return Boolean(
    value && typeof value === "object" && "byteLength" in value && "byteOffset" in value
  );
}
const CallableInstance = (
  /**
   * @type {new <Parameters extends Array<unknown>, Result>(property: string | symbol) => (...parameters: Parameters) => Result}
   */
  /** @type {unknown} */
  /**
   * @this {Function}
   * @param {string | symbol} property
   * @returns {(...parameters: Array<unknown>) => unknown}
   */
  (function(property) {
    const self2 = this;
    const constr = self2.constructor;
    const proto = (
      /** @type {Record<string | symbol, Function>} */
      // Prototypes do exist.
      // type-coverage:ignore-next-line
      constr.prototype
    );
    const value = proto[property];
    const apply = function() {
      return value.apply(apply, arguments);
    };
    Object.setPrototypeOf(apply, proto);
    return apply;
  })
);
const own = {}.hasOwnProperty;
class Processor extends CallableInstance {
  /**
   * Create a processor.
   */
  constructor() {
    super("copy");
    this.Compiler = void 0;
    this.Parser = void 0;
    this.attachers = [];
    this.compiler = void 0;
    this.freezeIndex = -1;
    this.frozen = void 0;
    this.namespace = {};
    this.parser = void 0;
    this.transformers = trough();
  }
  /**
   * Copy a processor.
   *
   * @deprecated
   *   This is a private internal method and should not be used.
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *   New *unfrozen* processor ({@linkcode Processor}) that is
   *   configured to work the same as its ancestor.
   *   When the descendant processor is configured in the future it does not
   *   affect the ancestral processor.
   */
  copy() {
    const destination = (
      /** @type {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>} */
      new Processor()
    );
    let index2 = -1;
    while (++index2 < this.attachers.length) {
      const attacher = this.attachers[index2];
      destination.use(...attacher);
    }
    destination.data(extend(true, {}, this.namespace));
    return destination;
  }
  /**
   * Configure the processor with info available to all plugins.
   * Information is stored in an object.
   *
   * Typically, options can be given to a specific plugin, but sometimes it
   * makes sense to have information shared with several plugins.
   * For example, a list of HTML elements that are self-closing, which is
   * needed during all phases.
   *
   * > **Note**: setting information cannot occur on *frozen* processors.
   * > Call the processor first to create a new unfrozen processor.
   *
   * > **Note**: to register custom data in TypeScript, augment the
   * > {@linkcode Data} interface.
   *
   * @example
   *   This example show how to get and set info:
   *
   *   ```js
   *   import {unified} from 'unified'
   *
   *   const processor = unified().data('alpha', 'bravo')
   *
   *   processor.data('alpha') // => 'bravo'
   *
   *   processor.data() // => {alpha: 'bravo'}
   *
   *   processor.data({charlie: 'delta'})
   *
   *   processor.data() // => {charlie: 'delta'}
   *   ```
   *
   * @template {keyof Data} Key
   *
   * @overload
   * @returns {Data}
   *
   * @overload
   * @param {Data} dataset
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @overload
   * @param {Key} key
   * @returns {Data[Key]}
   *
   * @overload
   * @param {Key} key
   * @param {Data[Key]} value
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @param {Data | Key} [key]
   *   Key to get or set, or entire dataset to set, or nothing to get the
   *   entire dataset (optional).
   * @param {Data[Key]} [value]
   *   Value to set (optional).
   * @returns {unknown}
   *   The current processor when setting, the value at `key` when getting, or
   *   the entire dataset when getting without key.
   */
  data(key, value) {
    if (typeof key === "string") {
      if (arguments.length === 2) {
        assertUnfrozen("data", this.frozen);
        this.namespace[key] = value;
        return this;
      }
      return own.call(this.namespace, key) && this.namespace[key] || void 0;
    }
    if (key) {
      assertUnfrozen("data", this.frozen);
      this.namespace = key;
      return this;
    }
    return this.namespace;
  }
  /**
   * Freeze a processor.
   *
   * Frozen processors are meant to be extended and not to be configured
   * directly.
   *
   * When a processor is frozen it cannot be unfrozen.
   * New processors working the same way can be created by calling the
   * processor.
   *
   * It’s possible to freeze processors explicitly by calling `.freeze()`.
   * Processors freeze automatically when `.parse()`, `.run()`, `.runSync()`,
   * `.stringify()`, `.process()`, or `.processSync()` are called.
   *
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *   The current processor.
   */
  freeze() {
    if (this.frozen) {
      return this;
    }
    const self2 = (
      /** @type {Processor} */
      /** @type {unknown} */
      this
    );
    while (++this.freezeIndex < this.attachers.length) {
      const [attacher, ...options] = this.attachers[this.freezeIndex];
      if (options[0] === false) {
        continue;
      }
      if (options[0] === true) {
        options[0] = void 0;
      }
      const transformer = attacher.call(self2, ...options);
      if (typeof transformer === "function") {
        this.transformers.use(transformer);
      }
    }
    this.frozen = true;
    this.freezeIndex = Number.POSITIVE_INFINITY;
    return this;
  }
  /**
   * Parse text to a syntax tree.
   *
   * > **Note**: `parse` freezes the processor if not already *frozen*.
   *
   * > **Note**: `parse` performs the parse phase, not the run phase or other
   * > phases.
   *
   * @param {Compatible | undefined} [file]
   *   file to parse (optional); typically `string` or `VFile`; any value
   *   accepted as `x` in `new VFile(x)`.
   * @returns {ParseTree extends undefined ? Node : ParseTree}
   *   Syntax tree representing `file`.
   */
  parse(file) {
    this.freeze();
    const realFile = vfile(file);
    const parser = this.parser || this.Parser;
    assertParser("parse", parser);
    return parser(String(realFile), realFile);
  }
  /**
   * Process the given file as configured on the processor.
   *
   * > **Note**: `process` freezes the processor if not already *frozen*.
   *
   * > **Note**: `process` performs the parse, run, and stringify phases.
   *
   * @overload
   * @param {Compatible | undefined} file
   * @param {ProcessCallback<VFileWithOutput<CompileResult>>} done
   * @returns {undefined}
   *
   * @overload
   * @param {Compatible | undefined} [file]
   * @returns {Promise<VFileWithOutput<CompileResult>>}
   *
   * @param {Compatible | undefined} [file]
   *   File (optional); typically `string` or `VFile`]; any value accepted as
   *   `x` in `new VFile(x)`.
   * @param {ProcessCallback<VFileWithOutput<CompileResult>> | undefined} [done]
   *   Callback (optional).
   * @returns {Promise<VFile> | undefined}
   *   Nothing if `done` is given.
   *   Otherwise a promise, rejected with a fatal error or resolved with the
   *   processed file.
   *
   *   The parsed, transformed, and compiled value is available at
   *   `file.value` (see note).
   *
   *   > **Note**: unified typically compiles by serializing: most
   *   > compilers return `string` (or `Uint8Array`).
   *   > Some compilers, such as the one configured with
   *   > [`rehype-react`][rehype-react], return other values (in this case, a
   *   > React tree).
   *   > If you’re using a compiler that doesn’t serialize, expect different
   *   > result values.
   *   >
   *   > To register custom results in TypeScript, add them to
   *   > {@linkcode CompileResultMap}.
   *
   *   [rehype-react]: https://github.com/rehypejs/rehype-react
   */
  process(file, done) {
    const self2 = this;
    this.freeze();
    assertParser("process", this.parser || this.Parser);
    assertCompiler("process", this.compiler || this.Compiler);
    return done ? executor(void 0, done) : new Promise(executor);
    function executor(resolve, reject) {
      const realFile = vfile(file);
      const parseTree = (
        /** @type {HeadTree extends undefined ? Node : HeadTree} */
        /** @type {unknown} */
        self2.parse(realFile)
      );
      self2.run(parseTree, realFile, function(error, tree, file2) {
        if (error || !tree || !file2) {
          return realDone(error);
        }
        const compileTree = (
          /** @type {CompileTree extends undefined ? Node : CompileTree} */
          /** @type {unknown} */
          tree
        );
        const compileResult = self2.stringify(compileTree, file2);
        if (looksLikeAValue(compileResult)) {
          file2.value = compileResult;
        } else {
          file2.result = compileResult;
        }
        realDone(
          error,
          /** @type {VFileWithOutput<CompileResult>} */
          file2
        );
      });
      function realDone(error, file2) {
        if (error || !file2) {
          reject(error);
        } else if (resolve) {
          resolve(file2);
        } else {
          done(void 0, file2);
        }
      }
    }
  }
  /**
   * Process the given file as configured on the processor.
   *
   * An error is thrown if asynchronous transforms are configured.
   *
   * > **Note**: `processSync` freezes the processor if not already *frozen*.
   *
   * > **Note**: `processSync` performs the parse, run, and stringify phases.
   *
   * @param {Compatible | undefined} [file]
   *   File (optional); typically `string` or `VFile`; any value accepted as
   *   `x` in `new VFile(x)`.
   * @returns {VFileWithOutput<CompileResult>}
   *   The processed file.
   *
   *   The parsed, transformed, and compiled value is available at
   *   `file.value` (see note).
   *
   *   > **Note**: unified typically compiles by serializing: most
   *   > compilers return `string` (or `Uint8Array`).
   *   > Some compilers, such as the one configured with
   *   > [`rehype-react`][rehype-react], return other values (in this case, a
   *   > React tree).
   *   > If you’re using a compiler that doesn’t serialize, expect different
   *   > result values.
   *   >
   *   > To register custom results in TypeScript, add them to
   *   > {@linkcode CompileResultMap}.
   *
   *   [rehype-react]: https://github.com/rehypejs/rehype-react
   */
  processSync(file) {
    let complete = false;
    let result;
    this.freeze();
    assertParser("processSync", this.parser || this.Parser);
    assertCompiler("processSync", this.compiler || this.Compiler);
    this.process(file, realDone);
    assertDone("processSync", "process", complete);
    return result;
    function realDone(error, file2) {
      complete = true;
      bail(error);
      result = file2;
    }
  }
  /**
   * Run *transformers* on a syntax tree.
   *
   * > **Note**: `run` freezes the processor if not already *frozen*.
   *
   * > **Note**: `run` performs the run phase, not other phases.
   *
   * @overload
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
   * @returns {undefined}
   *
   * @overload
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   * @param {Compatible | undefined} file
   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} done
   * @returns {undefined}
   *
   * @overload
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   * @param {Compatible | undefined} [file]
   * @returns {Promise<TailTree extends undefined ? Node : TailTree>}
   *
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   *   Tree to transform and inspect.
   * @param {(
   *   RunCallback<TailTree extends undefined ? Node : TailTree> |
   *   Compatible
   * )} [file]
   *   File associated with `node` (optional); any value accepted as `x` in
   *   `new VFile(x)`.
   * @param {RunCallback<TailTree extends undefined ? Node : TailTree>} [done]
   *   Callback (optional).
   * @returns {Promise<TailTree extends undefined ? Node : TailTree> | undefined}
   *   Nothing if `done` is given.
   *   Otherwise, a promise rejected with a fatal error or resolved with the
   *   transformed tree.
   */
  run(tree, file, done) {
    assertNode(tree);
    this.freeze();
    const transformers = this.transformers;
    if (!done && typeof file === "function") {
      done = file;
      file = void 0;
    }
    return done ? executor(void 0, done) : new Promise(executor);
    function executor(resolve, reject) {
      const realFile = vfile(file);
      transformers.run(tree, realFile, realDone);
      function realDone(error, outputTree, file2) {
        const resultingTree = (
          /** @type {TailTree extends undefined ? Node : TailTree} */
          outputTree || tree
        );
        if (error) {
          reject(error);
        } else if (resolve) {
          resolve(resultingTree);
        } else {
          done(void 0, resultingTree, file2);
        }
      }
    }
  }
  /**
   * Run *transformers* on a syntax tree.
   *
   * An error is thrown if asynchronous transforms are configured.
   *
   * > **Note**: `runSync` freezes the processor if not already *frozen*.
   *
   * > **Note**: `runSync` performs the run phase, not other phases.
   *
   * @param {HeadTree extends undefined ? Node : HeadTree} tree
   *   Tree to transform and inspect.
   * @param {Compatible | undefined} [file]
   *   File associated with `node` (optional); any value accepted as `x` in
   *   `new VFile(x)`.
   * @returns {TailTree extends undefined ? Node : TailTree}
   *   Transformed tree.
   */
  runSync(tree, file) {
    let complete = false;
    let result;
    this.run(tree, file, realDone);
    assertDone("runSync", "run", complete);
    return result;
    function realDone(error, tree2) {
      bail(error);
      result = tree2;
      complete = true;
    }
  }
  /**
   * Compile a syntax tree.
   *
   * > **Note**: `stringify` freezes the processor if not already *frozen*.
   *
   * > **Note**: `stringify` performs the stringify phase, not the run phase
   * > or other phases.
   *
   * @param {CompileTree extends undefined ? Node : CompileTree} tree
   *   Tree to compile.
   * @param {Compatible | undefined} [file]
   *   File associated with `node` (optional); any value accepted as `x` in
   *   `new VFile(x)`.
   * @returns {CompileResult extends undefined ? Value : CompileResult}
   *   Textual representation of the tree (see note).
   *
   *   > **Note**: unified typically compiles by serializing: most compilers
   *   > return `string` (or `Uint8Array`).
   *   > Some compilers, such as the one configured with
   *   > [`rehype-react`][rehype-react], return other values (in this case, a
   *   > React tree).
   *   > If you’re using a compiler that doesn’t serialize, expect different
   *   > result values.
   *   >
   *   > To register custom results in TypeScript, add them to
   *   > {@linkcode CompileResultMap}.
   *
   *   [rehype-react]: https://github.com/rehypejs/rehype-react
   */
  stringify(tree, file) {
    this.freeze();
    const realFile = vfile(file);
    const compiler2 = this.compiler || this.Compiler;
    assertCompiler("stringify", compiler2);
    assertNode(tree);
    return compiler2(tree, realFile);
  }
  /**
   * Configure the processor to use a plugin, a list of usable values, or a
   * preset.
   *
   * If the processor is already using a plugin, the previous plugin
   * configuration is changed based on the options that are passed in.
   * In other words, the plugin is not added a second time.
   *
   * > **Note**: `use` cannot be called on *frozen* processors.
   * > Call the processor first to create a new unfrozen processor.
   *
   * @example
   *   There are many ways to pass plugins to `.use()`.
   *   This example gives an overview:
   *
   *   ```js
   *   import {unified} from 'unified'
   *
   *   unified()
   *     // Plugin with options:
   *     .use(pluginA, {x: true, y: true})
   *     // Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
   *     .use(pluginA, {y: false, z: true})
   *     // Plugins:
   *     .use([pluginB, pluginC])
   *     // Two plugins, the second with options:
   *     .use([pluginD, [pluginE, {}]])
   *     // Preset with plugins and settings:
   *     .use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
   *     // Settings only:
   *     .use({settings: {position: false}})
   *   ```
   *
   * @template {Array<unknown>} [Parameters=[]]
   * @template {Node | string | undefined} [Input=undefined]
   * @template [Output=Input]
   *
   * @overload
   * @param {Preset | null | undefined} [preset]
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @overload
   * @param {PluggableList} list
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *
   * @overload
   * @param {Plugin<Parameters, Input, Output>} plugin
   * @param {...(Parameters | [boolean])} parameters
   * @returns {UsePlugin<ParseTree, HeadTree, TailTree, CompileTree, CompileResult, Input, Output>}
   *
   * @param {PluggableList | Plugin | Preset | null | undefined} value
   *   Usable value.
   * @param {...unknown} parameters
   *   Parameters, when a plugin is given as a usable value.
   * @returns {Processor<ParseTree, HeadTree, TailTree, CompileTree, CompileResult>}
   *   Current processor.
   */
  use(value, ...parameters) {
    const attachers = this.attachers;
    const namespace = this.namespace;
    assertUnfrozen("use", this.frozen);
    if (value === null || value === void 0) ;
    else if (typeof value === "function") {
      addPlugin(value, parameters);
    } else if (typeof value === "object") {
      if (Array.isArray(value)) {
        addList(value);
      } else {
        addPreset(value);
      }
    } else {
      throw new TypeError("Expected usable value, not `" + value + "`");
    }
    return this;
    function add(value2) {
      if (typeof value2 === "function") {
        addPlugin(value2, []);
      } else if (typeof value2 === "object") {
        if (Array.isArray(value2)) {
          const [plugin, ...parameters2] = (
            /** @type {PluginTuple<Array<unknown>>} */
            value2
          );
          addPlugin(plugin, parameters2);
        } else {
          addPreset(value2);
        }
      } else {
        throw new TypeError("Expected usable value, not `" + value2 + "`");
      }
    }
    function addPreset(result) {
      if (!("plugins" in result) && !("settings" in result)) {
        throw new Error(
          "Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither"
        );
      }
      addList(result.plugins);
      if (result.settings) {
        namespace.settings = extend(true, namespace.settings, result.settings);
      }
    }
    function addList(plugins) {
      let index2 = -1;
      if (plugins === null || plugins === void 0) ;
      else if (Array.isArray(plugins)) {
        while (++index2 < plugins.length) {
          const thing = plugins[index2];
          add(thing);
        }
      } else {
        throw new TypeError("Expected a list of plugins, not `" + plugins + "`");
      }
    }
    function addPlugin(plugin, parameters2) {
      let index2 = -1;
      let entryIndex = -1;
      while (++index2 < attachers.length) {
        if (attachers[index2][0] === plugin) {
          entryIndex = index2;
          break;
        }
      }
      if (entryIndex === -1) {
        attachers.push([plugin, ...parameters2]);
      } else if (parameters2.length > 0) {
        let [primary, ...rest] = parameters2;
        const currentPrimary = attachers[entryIndex][1];
        if (isPlainObject(currentPrimary) && isPlainObject(primary)) {
          primary = extend(true, currentPrimary, primary);
        }
        attachers[entryIndex] = [plugin, primary, ...rest];
      }
    }
  }
}
const unified = new Processor().freeze();
function assertParser(name2, value) {
  if (typeof value !== "function") {
    throw new TypeError("Cannot `" + name2 + "` without `parser`");
  }
}
function assertCompiler(name2, value) {
  if (typeof value !== "function") {
    throw new TypeError("Cannot `" + name2 + "` without `compiler`");
  }
}
function assertUnfrozen(name2, frozen) {
  if (frozen) {
    throw new Error(
      "Cannot call `" + name2 + "` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`."
    );
  }
}
function assertNode(node2) {
  if (!isPlainObject(node2) || typeof node2.type !== "string") {
    throw new TypeError("Expected node, got `" + node2 + "`");
  }
}
function assertDone(name2, asyncName, complete) {
  if (!complete) {
    throw new Error(
      "`" + name2 + "` finished async. Use `" + asyncName + "` instead"
    );
  }
}
function vfile(value) {
  return looksLikeAVFile(value) ? value : new VFile(value);
}
function looksLikeAVFile(value) {
  return Boolean(
    value && typeof value === "object" && "message" in value && "messages" in value
  );
}
function looksLikeAValue(value) {
  return typeof value === "string" || isUint8Array(value);
}
function isUint8Array(value) {
  return Boolean(
    value && typeof value === "object" && "byteLength" in value && "byteOffset" in value
  );
}
const changelog = "https://github.com/remarkjs/react-markdown/blob/main/changelog.md";
const emptyPlugins = [];
const emptyRemarkRehypeOptions = { allowDangerousHtml: true };
const safeProtocol = /^(https?|ircs?|mailto|xmpp)$/i;
const deprecations = [
  { from: "astPlugins", id: "remove-buggy-html-in-markdown-parser" },
  { from: "allowDangerousHtml", id: "remove-buggy-html-in-markdown-parser" },
  {
    from: "allowNode",
    id: "replace-allownode-allowedtypes-and-disallowedtypes",
    to: "allowElement"
  },
  {
    from: "allowedTypes",
    id: "replace-allownode-allowedtypes-and-disallowedtypes",
    to: "allowedElements"
  },
  { from: "className", id: "remove-classname" },
  {
    from: "disallowedTypes",
    id: "replace-allownode-allowedtypes-and-disallowedtypes",
    to: "disallowedElements"
  },
  { from: "escapeHtml", id: "remove-buggy-html-in-markdown-parser" },
  { from: "includeElementIndex", id: "#remove-includeelementindex" },
  {
    from: "includeNodeIndex",
    id: "change-includenodeindex-to-includeelementindex"
  },
  { from: "linkTarget", id: "remove-linktarget" },
  { from: "plugins", id: "change-plugins-to-remarkplugins", to: "remarkPlugins" },
  { from: "rawSourcePos", id: "#remove-rawsourcepos" },
  { from: "renderers", id: "change-renderers-to-components", to: "components" },
  { from: "source", id: "change-source-to-children", to: "children" },
  { from: "sourcePos", id: "#remove-sourcepos" },
  { from: "transformImageUri", id: "#add-urltransform", to: "urlTransform" },
  { from: "transformLinkUri", id: "#add-urltransform", to: "urlTransform" }
];
function Markdown(options) {
  const processor = createProcessor(options);
  const file = createFile(options);
  return post(processor.runSync(processor.parse(file), file), options);
}
function createProcessor(options) {
  const rehypePlugins = options.rehypePlugins || emptyPlugins;
  const remarkPlugins = options.remarkPlugins || emptyPlugins;
  const remarkRehypeOptions = options.remarkRehypeOptions ? { ...options.remarkRehypeOptions, ...emptyRemarkRehypeOptions } : emptyRemarkRehypeOptions;
  const processor = unified().use(remarkParse).use(remarkPlugins).use(remarkRehype, remarkRehypeOptions).use(rehypePlugins);
  return processor;
}
function createFile(options) {
  const children = options.children || "";
  const file = new VFile();
  if (typeof children === "string") {
    file.value = children;
  }
  return file;
}
function post(tree, options) {
  const allowedElements = options.allowedElements;
  const allowElement = options.allowElement;
  const components = options.components;
  const disallowedElements = options.disallowedElements;
  const skipHtml = options.skipHtml;
  const unwrapDisallowed = options.unwrapDisallowed;
  const urlTransform = options.urlTransform || defaultUrlTransform;
  for (const deprecation of deprecations) {
    if (Object.hasOwn(options, deprecation.from)) {
      unreachable(
        "Unexpected `" + deprecation.from + "` prop, " + (deprecation.to ? "use `" + deprecation.to + "` instead" : "remove it") + " (see <" + changelog + "#" + deprecation.id + "> for more info)"
      );
    }
  }
  visit(tree, transform);
  return toJsxRuntime(tree, {
    Fragment: jsxRuntimeExports.Fragment,
    components,
    ignoreInvalidStyle: true,
    jsx: jsxRuntimeExports.jsx,
    jsxs: jsxRuntimeExports.jsxs,
    passKeys: true,
    passNode: true
  });
  function transform(node2, index2, parent) {
    if (node2.type === "raw" && parent && typeof index2 === "number") {
      if (skipHtml) {
        parent.children.splice(index2, 1);
      } else {
        parent.children[index2] = { type: "text", value: node2.value };
      }
      return index2;
    }
    if (node2.type === "element") {
      let key;
      for (key in urlAttributes) {
        if (Object.hasOwn(urlAttributes, key) && Object.hasOwn(node2.properties, key)) {
          const value = node2.properties[key];
          const test2 = urlAttributes[key];
          if (test2 === null || test2.includes(node2.tagName)) {
            node2.properties[key] = urlTransform(String(value || ""), key, node2);
          }
        }
      }
    }
    if (node2.type === "element") {
      let remove = allowedElements ? !allowedElements.includes(node2.tagName) : disallowedElements ? disallowedElements.includes(node2.tagName) : false;
      if (!remove && allowElement && typeof index2 === "number") {
        remove = !allowElement(node2, index2, parent);
      }
      if (remove && parent && typeof index2 === "number") {
        if (unwrapDisallowed && node2.children) {
          parent.children.splice(index2, 1, ...node2.children);
        } else {
          parent.children.splice(index2, 1);
        }
        return index2;
      }
    }
  }
}
function defaultUrlTransform(value) {
  const colon = value.indexOf(":");
  const questionMark = value.indexOf("?");
  const numberSign = value.indexOf("#");
  const slash = value.indexOf("/");
  if (
    // If there is no protocol, it’s relative.
    colon === -1 || // If the first colon is after a `?`, `#`, or `/`, it’s not a protocol.
    slash !== -1 && colon > slash || questionMark !== -1 && colon > questionMark || numberSign !== -1 && colon > numberSign || // It is a protocol, it should be allowed.
    safeProtocol.test(value.slice(0, colon))
  ) {
    return value;
  }
  return "";
}
function EmojiPickerButton({ onEmojiSelect, disabled = false, className = "" }) {
  const [open, setOpen] = reactExports.useState(false);
  const [pickerData, setPickerData] = reactExports.useState(null);
  const wrapRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open || pickerData) return;
    let cancelled = false;
    loadEmojiMartData().then((data) => {
      if (!cancelled) {
        setPickerData(data);
      }
    });
    return () => {
      cancelled = true;
    };
  }, [open, pickerData]);
  reactExports.useEffect(() => {
    if (!open) return;
    function handleClick(e) {
      if (!isEventWithinNode(e, wrapRef.current)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClick);
    return () => document.removeEventListener("mousedown", handleClick);
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return;
    function handleKey(e) {
      if (e.key === "Escape") setOpen(false);
    }
    document.addEventListener("keydown", handleKey);
    return () => document.removeEventListener("keydown", handleKey);
  }, [open]);
  const handleSelect = reactExports.useCallback(
    (emoji) => {
      const nativeEmoji = extractNativeEmoji(emoji);
      if (nativeEmoji) {
        onEmojiSelect?.(nativeEmoji);
      }
      setOpen(false);
    },
    [onEmojiSelect]
  );
  return /* @__PURE__ */ React.createElement("div", { ref: wrapRef, className: "relative inline-block" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled,
      onClick: () => setOpen((v2) => !v2),
      "aria-label": "Open emoji picker",
      "aria-expanded": open,
      className: [
        "flex items-center justify-center w-8 h-8 rounded-md",
        "text-white/40 hover:text-white/70 hover:bg-white/[0.07]",
        "transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-500",
        "disabled:opacity-30 disabled:pointer-events-none",
        className
      ].filter(Boolean).join(" ")
    },
    "😊"
  ), open && /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "absolute bottom-full mb-2 right-0 z-50 shadow-2xl rounded-xl overflow-hidden",
      style: { filter: "drop-shadow(0 8px 32px rgba(0,0,0,0.6))" }
    },
    pickerData ? /* @__PURE__ */ React.createElement(
      EmojiMartPicker,
      {
        data: pickerData,
        onEmojiSelect: handleSelect,
        theme: "dark",
        previewPosition: "none",
        skinTonePosition: "none",
        maxFrequentRows: 2,
        perLine: 8
      }
    ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-56 items-center justify-center bg-zinc-900 px-4 text-sm text-zinc-300" }, "Loading emojis...")
  ));
}
function BoldIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.5, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 4h8a4 4 0 0 1 0 8H6zM6 12h9a4 4 0 0 1 0 8H6z" }));
}
function ItalicIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.5, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }));
}
function CodeIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("polyline", { points: "16 18 22 12 16 6" }), /* @__PURE__ */ React.createElement("polyline", { points: "8 6 2 12 8 18" }));
}
function LinkIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" }));
}
function ListIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("line", { x1: "8", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "8", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "8", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "3", cy: "6", r: "1", fill: "currentColor", stroke: "none" }), /* @__PURE__ */ React.createElement("circle", { cx: "3", cy: "12", r: "1", fill: "currentColor", stroke: "none" }), /* @__PURE__ */ React.createElement("circle", { cx: "3", cy: "18", r: "1", fill: "currentColor", stroke: "none" }));
}
function QuoteIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.176 11 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179zM15.583 17.321C14.553 16.227 14 15 14 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C20.591 11.68 22 13.176 22 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179z" }));
}
function ToolbarBtn$1({ title, onClick, children }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      title,
      onMouseDown: (e) => {
        e.preventDefault();
        onClick();
      },
      className: "flex h-7 w-7 items-center justify-center rounded-md text-white/40 transition-colors hover:bg-white/[0.08] hover:text-white/70"
    },
    children
  );
}
function CommentForm$1({
  artworkId,
  onPosted,
  isLoggedIn = false,
  loginUrl = "/login",
  parentId = null,
  replyTo = null,
  onCancelReply = null,
  compact = false,
  submitUrl = null,
  contentField = "content",
  maxLength = 1e4,
  placeholder = "Share your thoughts…",
  submitLabel = "Post comment",
  submittingLabel = "Posting…"
}) {
  const [content2, setContent] = reactExports.useState("");
  const [tab2, setTab] = reactExports.useState("write");
  const [submitting, setSubmitting] = reactExports.useState(false);
  const [errors, setErrors] = reactExports.useState([]);
  const textareaRef = reactExports.useRef(null);
  const formRef = reactExports.useRef(null);
  const resolvedSubmitUrl = submitUrl || (artworkId ? `/api/artworks/${artworkId}/comments` : null);
  const warningThreshold = Math.max(1, Math.floor(maxLength * 0.9));
  reactExports.useEffect(() => {
    if (replyTo && textareaRef.current) {
      textareaRef.current.focus();
      formRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
    }
  }, [replyTo]);
  const wrapSelection = reactExports.useCallback((before, after) => {
    const el = textareaRef.current;
    if (!el) return;
    const start = el.selectionStart;
    const end = el.selectionEnd;
    const selected = content2.slice(start, end);
    const replacement = before + (selected || "text") + after;
    const next = content2.slice(0, start) + replacement + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      const cursorPos = selected ? start + replacement.length : start + before.length;
      const cursorEnd = selected ? start + replacement.length : start + before.length + 4;
      el.selectionStart = cursorPos;
      el.selectionEnd = cursorEnd;
      el.focus();
    });
  }, [content2]);
  const prefixLines = reactExports.useCallback((prefix) => {
    const el = textareaRef.current;
    if (!el) return;
    const start = el.selectionStart;
    const end = el.selectionEnd;
    const selected = content2.slice(start, end);
    const lines = selected ? selected.split("\n") : [""];
    const prefixed = lines.map((l3) => prefix + l3).join("\n");
    const next = content2.slice(0, start) + prefixed + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      el.selectionStart = start;
      el.selectionEnd = start + prefixed.length;
      el.focus();
    });
  }, [content2]);
  const insertLink = reactExports.useCallback(() => {
    const el = textareaRef.current;
    if (!el) return;
    const start = el.selectionStart;
    const end = el.selectionEnd;
    const selected = content2.slice(start, end);
    const isUrl2 = /^https?:\/\//.test(selected);
    const replacement = isUrl2 ? `[link](${selected})` : `[${selected || "link"}](https://)`;
    const next = content2.slice(0, start) + replacement + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      if (isUrl2) {
        el.selectionStart = start + 1;
        el.selectionEnd = start + 5;
      } else {
        const urlStart = start + replacement.length - 1;
        el.selectionStart = urlStart - 8;
        el.selectionEnd = urlStart - 1;
      }
      el.focus();
    });
  }, [content2]);
  const insertAtCursor = reactExports.useCallback((text2) => {
    const el = textareaRef.current;
    if (!el) {
      setContent((v2) => v2 + text2);
      return;
    }
    const start = el.selectionStart ?? content2.length;
    const end = el.selectionEnd ?? content2.length;
    const next = content2.slice(0, start) + text2 + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      el.selectionStart = start + text2.length;
      el.selectionEnd = start + text2.length;
      el.focus();
    });
  }, [content2]);
  const handleEmojiSelect = reactExports.useCallback((emoji) => {
    insertAtCursor(emoji);
  }, [insertAtCursor]);
  const handleKeyDown2 = reactExports.useCallback((e) => {
    const mod = e.ctrlKey || e.metaKey;
    if (!mod) return;
    switch (e.key.toLowerCase()) {
      case "b":
        e.preventDefault();
        wrapSelection("**", "**");
        break;
      case "i":
        e.preventDefault();
        wrapSelection("*", "*");
        break;
      case "k":
        e.preventDefault();
        insertLink();
        break;
      case "e":
        e.preventDefault();
        wrapSelection("`", "`");
        break;
    }
  }, [wrapSelection, insertLink]);
  const handleSubmit = reactExports.useCallback(
    async (e) => {
      e.preventDefault();
      if (!isLoggedIn) {
        window.location.href = loginUrl;
        return;
      }
      const trimmed = content2.trim();
      if (!trimmed || !resolvedSubmitUrl) return;
      setSubmitting(true);
      setErrors([]);
      try {
        const { data } = await axios.post(resolvedSubmitUrl, {
          [contentField]: trimmed,
          parent_id: parentId || null
        });
        setContent("");
        setTab("write");
        onPosted?.(data.data);
        onCancelReply?.();
      } catch (err) {
        if (err.response?.status === 422) {
          const fieldErrors = err.response.data?.errors ?? {};
          const allErrors = [
            ...Array.isArray(fieldErrors[contentField]) ? fieldErrors[contentField] : [],
            ...Object.entries(fieldErrors).filter(([field]) => field !== contentField).flatMap(([, messages]) => Array.isArray(messages) ? messages : [])
          ];
          setErrors(allErrors.length ? allErrors : ["Invalid content."]);
        } else {
          setErrors(["Something went wrong. Please try again."]);
        }
      } finally {
        setSubmitting(false);
      }
    },
    [content2, contentField, isLoggedIn, loginUrl, onPosted, parentId, onCancelReply, resolvedSubmitUrl]
  );
  if (!isLoggedIn) {
    return /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/[0.06] bg-white/[0.03] px-5 py-4 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5 shrink-0 text-white/25" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/40" }, /* @__PURE__ */ React.createElement("a", { href: loginUrl, className: "font-medium text-accent transition-colors hover:text-accent/80" }, "Sign in"), " ", "to join the conversation."));
  }
  return /* @__PURE__ */ React.createElement("form", { id: parentId ? `reply-form-${parentId}` : "comment-form", ref: formRef, onSubmit: handleSubmit, className: "space-y-3" }, replyTo && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 rounded-lg bg-accent/[0.06] px-3 py-2" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-3.5 w-3.5 text-accent/60 shrink-0" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M7.793 2.232a.75.75 0 0 1-.025 1.06L3.622 7.25h10.003a5.375 5.375 0 0 1 0 10.75H10.75a.75.75 0 0 1 0-1.5h2.875a3.875 3.875 0 0 0 0-7.75H3.622l4.146 3.957a.75.75 0 0 1-1.036 1.085l-5.5-5.25a.75.75 0 0 1 0-1.085l5.5-5.25a.75.75 0 0 1 1.06.025Z", clipRule: "evenodd" })), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-white/50" }, "Replying to ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white/70" }, replyTo)), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onCancelReply,
      className: "ml-auto text-[11px] font-medium text-white/30 transition-colors hover:text-white/60"
    },
    "Cancel"
  )), /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border border-white/[0.06] bg-white/[0.03] transition-all duration-200 focus-within:border-white/[0.12] focus-within:shadow-lg focus-within:shadow-black/20 ${compact ? "rounded-xl" : ""}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/[0.06] px-3 py-1.5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTab("write"),
      className: [
        "rounded-md px-3 py-1 text-xs font-medium transition-colors",
        tab2 === "write" ? "bg-white/[0.08] text-white" : "text-white/40 hover:text-white/60"
      ].join(" ")
    },
    "Write"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTab("preview"),
      className: [
        "rounded-md px-3 py-1 text-xs font-medium transition-colors",
        tab2 === "preview" ? "bg-white/[0.08] text-white" : "text-white/40 hover:text-white/60"
      ].join(" ")
    },
    "Preview"
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ React.createElement(
    "span",
    {
      className: [
        "text-[11px] tabular-nums font-medium transition-colors",
        content2.length > warningThreshold ? "text-amber-400/80" : "text-white/20"
      ].join(" ")
    },
    content2.length > 0 && `${content2.length.toLocaleString()}/${maxLength.toLocaleString()}`
  ), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: handleEmojiSelect, disabled: submitting }))), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 border-b border-white/[0.04] px-3 py-1" }, /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, /* @__PURE__ */ React.createElement(BoldIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, /* @__PURE__ */ React.createElement(ItalicIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, /* @__PURE__ */ React.createElement(CodeIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Link (Ctrl+K)", onClick: insertLink }, /* @__PURE__ */ React.createElement(LinkIcon$1, null)), /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-4 w-px bg-white/[0.08]" }), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Bulleted list", onClick: () => prefixLines("- ") }, /* @__PURE__ */ React.createElement(ListIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Quote", onClick: () => prefixLines("> ") }, /* @__PURE__ */ React.createElement(QuoteIcon$1, null))), tab2 === "write" && /* @__PURE__ */ React.createElement(
    "textarea",
    {
      ref: textareaRef,
      value: content2,
      onChange: (e) => setContent(e.target.value),
      onKeyDown: handleKeyDown2,
      placeholder: replyTo ? `Reply to ${replyTo}…` : placeholder,
      rows: compact ? 2 : 4,
      maxLength,
      disabled: submitting,
      "aria-label": "Comment text",
      className: "w-full resize-none bg-transparent px-4 py-3 text-[13px] leading-relaxed text-white/90 placeholder-white/25 focus:outline-none disabled:opacity-50"
    }
  ), tab2 === "preview" && /* @__PURE__ */ React.createElement("div", { className: "min-h-[7rem] px-4 py-3" }, content2.trim() ? /* @__PURE__ */ React.createElement("div", { className: "prose prose-invert prose-sm max-w-none text-[13px] leading-relaxed text-white/80 [&_a]:text-accent [&_a]:no-underline hover:[&_a]:underline [&_code]:rounded [&_code]:bg-white/[0.08] [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:text-[12px] [&_code]:text-amber-300/80 [&_blockquote]:border-l-2 [&_blockquote]:border-accent/40 [&_blockquote]:pl-3 [&_blockquote]:text-white/50 [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:list-decimal [&_ol]:pl-4 [&_li]:text-white/70 [&_strong]:text-white [&_em]:text-white/70 [&_p]:mb-2 [&_p:last-child]:mb-0" }, /* @__PURE__ */ React.createElement(
    Markdown,
    {
      allowedElements: ["p", "strong", "em", "a", "code", "pre", "ul", "ol", "li", "blockquote", "br"],
      unwrapDisallowed: true,
      components: {
        a: ({ href, children }) => /* @__PURE__ */ React.createElement("a", { href, target: "_blank", rel: "noopener noreferrer nofollow" }, children)
      }
    },
    content2
  )) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/25 italic" }, "Nothing to preview")), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "px-4 pb-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-white/15" }, "Markdown supported · ", /* @__PURE__ */ React.createElement("kbd", { className: "rounded bg-white/[0.06] px-1 py-0.5 text-[10px] text-white/25" }, "Ctrl+B"), " bold · ", /* @__PURE__ */ React.createElement("kbd", { className: "rounded bg-white/[0.06] px-1 py-0.5 text-[10px] text-white/25" }, "Ctrl+I"), " italic · ", /* @__PURE__ */ React.createElement("kbd", { className: "rounded bg-white/[0.06] px-1 py-0.5 text-[10px] text-white/25" }, "Ctrl+K"), " link"))), errors.length > 0 && /* @__PURE__ */ React.createElement("ul", { className: "space-y-1 rounded-xl border border-red-500/20 bg-red-500/[0.06] px-4 py-2.5", role: "alert" }, errors.map((e, i) => /* @__PURE__ */ React.createElement("li", { key: i, className: "text-xs font-medium text-red-400" }, e))), /* @__PURE__ */ React.createElement("div", { className: "flex justify-end" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: submitting || !content2.trim(),
      className: "rounded-full bg-accent px-6 py-2 text-sm font-semibold text-white shadow-lg shadow-accent/20 transition-all duration-200 hover:bg-accent/90 hover:shadow-xl hover:shadow-accent/25 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:ring-offset-2 focus-visible:ring-offset-deep disabled:pointer-events-none disabled:opacity-40 disabled:shadow-none"
    },
    submitting ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 animate-spin", viewBox: "0 0 24 24", fill: "none" }, /* @__PURE__ */ React.createElement("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3" }), /* @__PURE__ */ React.createElement("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" })), submittingLabel) : submitLabel
  )));
}
const REACTIONS$1 = [
  { slug: "thumbs_up", emoji: "👍", label: "Like" },
  { slug: "heart", emoji: "❤️", label: "Love" },
  { slug: "fire", emoji: "🔥", label: "Fire" },
  { slug: "laugh", emoji: "😂", label: "Haha" },
  { slug: "clap", emoji: "👏", label: "Clap" },
  { slug: "wow", emoji: "😮", label: "Wow" }
];
function HeartOutlineIcon({ className }) {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z" }));
}
function ReactionBar({ entityType, entityId, initialTotals = {}, isLoggedIn = false, endpoint = null }) {
  const [totals, setTotals] = reactExports.useState(initialTotals);
  const [loading, setLoading] = reactExports.useState(null);
  const [pickerOpen, setPickerOpen] = reactExports.useState(false);
  const containerRef = reactExports.useRef(null);
  const hoverTimeout = reactExports.useRef(null);
  reactExports.useEffect(() => {
    setTotals(initialTotals ?? {});
  }, [entityId, initialTotals]);
  const resolvedEndpoint = endpoint || (entityType === "artwork" ? `/api/artworks/${entityId}/reactions` : `/api/comments/${entityId}/reactions`);
  reactExports.useEffect(() => {
    if (!pickerOpen) return;
    const handler = (e) => {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setPickerOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [pickerOpen]);
  const toggle = reactExports.useCallback(
    async (slug) => {
      if (!isLoggedIn) {
        window.location.href = "/login";
        return;
      }
      if (loading) return;
      setLoading(slug);
      setPickerOpen(false);
      setTotals((prev) => {
        const entry = prev[slug] ?? { count: 0, mine: false, emoji: REACTIONS$1.find((r) => r.slug === slug)?.emoji, label: REACTIONS$1.find((r) => r.slug === slug)?.label };
        return {
          ...prev,
          [slug]: {
            ...entry,
            count: entry.mine ? Math.max(0, entry.count - 1) : entry.count + 1,
            mine: !entry.mine
          }
        };
      });
      try {
        const { data } = await axios.post(resolvedEndpoint, { reaction: slug });
        setTotals(data.totals);
      } catch {
        setTotals((prev) => {
          const entry = prev[slug] ?? { count: 0, mine: false };
          return {
            ...prev,
            [slug]: {
              ...entry,
              count: entry.mine ? Math.max(0, entry.count - 1) : entry.count + 1,
              mine: !entry.mine
            }
          };
        });
      } finally {
        setLoading(null);
      }
    },
    [resolvedEndpoint, isLoggedIn, loading]
  );
  const entries = Object.entries(totals);
  const activeReactions = entries.filter(([, info]) => info.count > 0);
  const totalCount = activeReactions.reduce((sum, [, info]) => sum + info.count, 0);
  const myReaction = entries.find(([, info]) => info.mine)?.[0] ?? null;
  const myReactionData = myReaction ? REACTIONS$1.find((r) => r.slug === myReaction) : null;
  const onMouseEnter = () => {
    clearTimeout(hoverTimeout.current);
    hoverTimeout.current = setTimeout(() => setPickerOpen(true), 200);
  };
  const onMouseLeave = () => {
    clearTimeout(hoverTimeout.current);
    hoverTimeout.current = setTimeout(() => setPickerOpen(false), 400);
  };
  const isArtworkVariant = entityType === "artwork";
  const triggerClassName = isArtworkVariant ? [
    "inline-flex items-center gap-2.5 rounded-full border px-4 py-2.5 text-sm font-semibold transition-all duration-200",
    "focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50",
    myReaction ? "border-accent/35 bg-accent/12 text-accent shadow-[0_12px_30px_rgba(245,158,11,0.14)] hover:bg-accent/18" : "border-white/[0.12] bg-white/[0.06] text-white/75 hover:border-accent/30 hover:bg-white/[0.1] hover:text-white"
  ].join(" ") : [
    "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-all duration-200",
    "focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50",
    myReaction ? "text-accent" : "text-white/40 hover:text-white/70"
  ].join(" ");
  const summaryClassName = isArtworkVariant ? "inline-flex items-center gap-2 rounded-full border border-white/[0.1] bg-white/[0.05] px-3 py-1.5 transition-colors hover:border-white/[0.16] hover:bg-white/[0.08] group/summary" : "inline-flex items-center gap-1.5 rounded-full px-1.5 py-0.5 transition-colors hover:bg-white/[0.06] group/summary";
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: containerRef,
      className: isArtworkVariant ? "flex flex-wrap items-center gap-3" : "flex items-center gap-2",
      onMouseLeave
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative", onMouseEnter }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => {
          if (isArtworkVariant) {
            setPickerOpen((value) => !value);
            return;
          }
          if (myReaction) {
            toggle(myReaction);
          } else {
            toggle("thumbs_up");
          }
        },
        className: triggerClassName,
        "aria-label": isArtworkVariant ? myReaction ? `Open reaction picker. Current reaction: ${myReactionData?.label}.` : "React to this artwork" : myReaction ? `You reacted with ${myReactionData?.label}. Click to remove.` : "React to this comment"
      },
      myReaction ? /* @__PURE__ */ React.createElement("span", { className: isArtworkVariant ? "text-xl leading-none" : "text-base leading-none" }, myReactionData?.emoji) : /* @__PURE__ */ React.createElement(HeartOutlineIcon, { className: isArtworkVariant ? "h-5 w-5" : "h-4 w-4" }),
      /* @__PURE__ */ React.createElement("span", null, myReaction ? myReactionData?.label : isArtworkVariant ? "React to this artwork" : "React")
    ), pickerOpen && /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "absolute bottom-full left-0 mb-2 z-[200] animate-in fade-in slide-in-from-bottom-2 duration-200",
        onMouseEnter: () => {
          clearTimeout(hoverTimeout.current);
        },
        onMouseLeave
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 rounded-full bg-nova-800/95 border border-white/[0.1] px-2 py-1.5 shadow-xl shadow-black/40 backdrop-blur-xl" }, REACTIONS$1.map((r, i) => {
        const isActive = totals[r.slug]?.mine;
        return /* @__PURE__ */ React.createElement(
          "button",
          {
            key: r.slug,
            type: "button",
            onClick: () => toggle(r.slug),
            disabled: loading === r.slug,
            "aria-label": `${r.label}${isActive ? " (selected)" : ""}`,
            className: [
              "group/reaction relative flex items-center justify-center w-9 h-9 rounded-full transition-all duration-200",
              "hover:bg-white/[0.08] hover:scale-125 hover:-translate-y-1",
              "focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/50",
              "disabled:opacity-50",
              isActive ? "bg-white/[0.1] scale-110" : ""
            ].join(" "),
            style: { animationDelay: `${i * 30}ms` },
            title: r.label
          },
          /* @__PURE__ */ React.createElement("span", { className: "text-xl leading-none transition-transform duration-150 group-hover/reaction:scale-110" }, r.emoji),
          /* @__PURE__ */ React.createElement("span", { className: "pointer-events-none absolute -top-7 left-1/2 -translate-x-1/2 rounded bg-black/80 px-1.5 py-0.5 text-[10px] font-medium text-white/90 opacity-0 transition-opacity group-hover/reaction:opacity-100 whitespace-nowrap" }, r.label)
        );
      }))
    )),
    totalCount > 0 && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setPickerOpen((v2) => !v2),
        className: summaryClassName,
        "aria-label": `${totalCount} reaction${totalCount !== 1 ? "s" : ""}`
      },
      /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center -space-x-1" }, activeReactions.slice(0, 3).map(([slug, info], i) => /* @__PURE__ */ React.createElement(
        "span",
        {
          key: slug,
          className: "relative flex items-center justify-center w-5 h-5 rounded-full bg-nova-700 border border-nova-800 text-xs leading-none",
          style: { zIndex: 3 - i },
          title: info.label
        },
        info.emoji
      ))),
      /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium tabular-nums text-white/50 group-hover/summary:text-white/70 transition-colors" }, totalCount)
    )
  );
}
const TONES$4 = {
  1: "border-slate-500/30 bg-slate-500/10 text-slate-200",
  2: "border-sky-400/35 bg-sky-500/10 text-sky-200",
  3: "border-emerald-400/35 bg-emerald-500/10 text-emerald-200",
  4: "border-fuchsia-400/35 bg-fuchsia-500/10 text-fuchsia-200",
  5: "border-amber-400/35 bg-amber-500/10 text-amber-100",
  6: "border-rose-400/35 bg-rose-500/10 text-rose-100",
  7: "border-violet-400/35 bg-violet-500/10 text-violet-100"
};
function cx$8(...parts) {
  return parts.filter(Boolean).join(" ");
}
function LevelBadge({ level = 1, rank = "Newbie", compact = false, className = "" }) {
  const numericLevel = Number(level || 1);
  const tone = TONES$4[numericLevel] || TONES$4[1];
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: cx$8(
        "inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-semibold tracking-[0.08em]",
        compact ? "text-[10px] uppercase" : "text-[11px] uppercase",
        tone,
        className
      )
    },
    /* @__PURE__ */ React.createElement("span", null, "LVL ", numericLevel),
    /* @__PURE__ */ React.createElement("span", { className: "text-current/75" }, rank)
  );
}
const FLOOD_COUNT_THRESHOLD = 20;
const FLOOD_DENSITY_THRESHOLD = 0.4;
const EMOJI_UNIT_RE = /[\u{1F000}-\u{1FFFF}\u{2600}-\u{27BF}]\uFE0F?/gu;
function countEmoji(text2) {
  if (!text2) return 0;
  return (text2.match(EMOJI_UNIT_RE) || []).length;
}
function isFlood(text2, { maxCount = FLOOD_COUNT_THRESHOLD, maxDensity = FLOOD_DENSITY_THRESHOLD } = {}) {
  if (!text2) return false;
  const count = countEmoji(text2);
  if (count > maxCount) return true;
  if (count > 5 && text2.length > 0 && count / text2.length > maxDensity) return true;
  return false;
}
const ABSOLUTE_DATE_FORMATTER$2 = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "numeric",
  timeZone: "UTC"
});
const ABSOLUTE_DATE_TIME_FORMATTER$1 = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "numeric",
  hour: "numeric",
  minute: "2-digit",
  timeZone: "UTC"
});
function formatAbsoluteDate$1(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return ABSOLUTE_DATE_FORMATTER$2.format(date);
}
function formatAbsoluteDateTime$1(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return ABSOLUTE_DATE_TIME_FORMATTER$1.format(date);
}
function formatCommentTime$1(primaryLabel, createdAt) {
  return primaryLabel || formatAbsoluteDate$1(createdAt);
}
function ReplyIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-3.5 w-3.5" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M7.793 2.232a.75.75 0 0 1-.025 1.06L3.622 7.25h10.003a5.375 5.375 0 0 1 0 10.75H10.75a.75.75 0 0 1 0-1.5h2.875a3.875 3.875 0 0 0 0-7.75H3.622l4.146 3.957a.75.75 0 0 1-1.036 1.085l-5.5-5.25a.75.75 0 0 1 0-1.085l5.5-5.25a.75.75 0 0 1 1.06.025Z", clipRule: "evenodd" }));
}
function ChatBubbleIcon$1() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.2, stroke: "currentColor", className: "h-10 w-10 text-white/15" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.625 12a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0H8.25m4.125 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0H12m4.125 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 0 1-2.555-.337A5.972 5.972 0 0 1 5.41 20.97a5.969 5.969 0 0 1-.474-.065 4.48 4.48 0 0 0 .978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25Z" }));
}
function ChevronDownIcon$1({ className }) {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z", clipRule: "evenodd" }));
}
function Avatar$1({ user, size = 36 }) {
  if (user?.avatar_url) {
    return /* @__PURE__ */ React.createElement(
      "img",
      {
        src: user.avatar_url,
        alt: user.name || user.username || "",
        width: size,
        height: size,
        className: "rounded-full object-cover shrink-0 ring-1 ring-white/10",
        style: { width: size, height: size },
        loading: "lazy",
        onError: (e) => {
          e.currentTarget.onerror = null;
          e.currentTarget.src = "https://files.skinbase.org/default/avatar_default.webp";
        }
      }
    );
  }
  const initials = (user?.name || user?.username || "?").slice(0, 1).toUpperCase();
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: "flex items-center justify-center rounded-full bg-gradient-to-br from-nova-600 to-nova-800 text-sm font-bold text-white/90 shrink-0 ring-1 ring-white/10",
      style: { width: size, height: size }
    },
    initials
  );
}
function ReplyItem$1({ reply, parentId, artworkId, isLoggedIn, onReplyPosted, depth = 1 }) {
  const user = reply.user;
  const html2 = reply.rendered_content ?? null;
  const plain = reply.content ?? reply.raw_content ?? "";
  const profileLabel = user?.display || user?.username || user?.name || "Member";
  const replies = reply.replies || [];
  const [showReplyForm, setShowReplyForm] = reactExports.useState(false);
  const [showAllReplies, setShowAllReplies] = reactExports.useState(false);
  const [reactionTotals, setReactionTotals] = reactExports.useState(reply.reactions ?? {});
  reactExports.useEffect(() => {
    if (reply.reactions || !reply.id) return;
    axios.get(`/api/comments/${reply.id}/reactions`).then(({ data }) => setReactionTotals(data.totals ?? {})).catch(() => {
    });
  }, [reply.id, reply.reactions]);
  const handleReplyPosted = reactExports.useCallback((newReply) => {
    onReplyPosted?.(reply.id, newReply);
    setShowReplyForm(false);
    setShowAllReplies(true);
  }, [reply.id, onReplyPosted]);
  const visibleReplies = showAllReplies ? replies : replies.slice(0, 2);
  const hiddenReplyCount = replies.length - 2;
  const avatarSize = depth >= 3 ? 22 : 28;
  return /* @__PURE__ */ React.createElement("li", { className: "rounded-lg bg-white/[0.02] px-3 py-2.5", id: `comment-${reply.id}` }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-2.5" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "shrink-0 mt-0.5", tabIndex: -1 }, /* @__PURE__ */ React.createElement(Avatar$1, { user, size: avatarSize })) : /* @__PURE__ */ React.createElement("span", { className: "shrink-0 mt-0.5" }, /* @__PURE__ */ React.createElement(Avatar$1, { user, size: avatarSize })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 flex-wrap" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "text-[12px] font-semibold text-white/90 hover:text-accent transition-colors" }, profileLabel) : /* @__PURE__ */ React.createElement("span", { className: "text-[12px] font-semibold text-white/90" }, profileLabel), /* @__PURE__ */ React.createElement(LevelBadge, { level: user?.level, rank: user?.rank, compact: true, className: "shrink-0" }), /* @__PURE__ */ React.createElement("span", { className: "text-white/15", "aria-hidden": "true" }, "·"), /* @__PURE__ */ React.createElement(
    "time",
    {
      dateTime: reply.created_at,
      title: formatAbsoluteDateTime$1(reply.created_at),
      className: "text-[10px] font-medium tracking-wide text-white/25 uppercase"
    },
    formatCommentTime$1(reply.time_ago, reply.created_at)
  )), html2 ? /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "mt-1 text-[12.5px] leading-[1.65] text-white/70 prose prose-invert prose-sm max-w-none prose-p:my-1 prose-a:text-sky-400 prose-a:no-underline hover:prose-a:underline prose-code:bg-white/[0.07] prose-code:px-1 prose-code:py-0.5 prose-code:rounded-md prose-code:text-xs",
      dangerouslySetInnerHTML: { __html: html2 }
    }
  ) : /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[12.5px] leading-[1.65] text-white/70 whitespace-pre-line break-words" }, plain), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5 pt-1" }, isLoggedIn && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShowReplyForm((v2) => !v2),
      className: [
        "inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] font-medium uppercase tracking-wider transition-all duration-200 focus:outline-none",
        showReplyForm ? "bg-accent/10 text-accent" : "text-white/35 hover:bg-white/[0.06] hover:text-white/65"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(ReplyIcon$1, null),
    "Reply"
  ), /* @__PURE__ */ React.createElement(
    ReactionBar,
    {
      entityType: "comment",
      entityId: reply.id,
      initialTotals: reactionTotals,
      isLoggedIn
    }
  )), showReplyForm && /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement(
    CommentForm$1,
    {
      artworkId,
      parentId: reply.id,
      replyTo: profileLabel,
      onCancelReply: () => setShowReplyForm(false),
      onPosted: handleReplyPosted,
      isLoggedIn,
      compact: true
    }
  )), replies.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement("ul", { className: `space-y-1 pl-3 border-l-2 ${depth >= 3 ? "border-white/[0.03]" : "border-white/[0.05]"}` }, visibleReplies.map((child) => /* @__PURE__ */ React.createElement(
    ReplyItem$1,
    {
      key: child.id,
      reply: child,
      parentId: reply.id,
      artworkId,
      isLoggedIn,
      onReplyPosted,
      depth: depth + 1
    }
  ))), !showAllReplies && hiddenReplyCount > 0 && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShowAllReplies(true),
      className: "mt-1.5 ml-3 inline-flex items-center gap-1 text-[10px] font-medium text-accent/70 transition-colors hover:text-accent"
    },
    /* @__PURE__ */ React.createElement(ChevronDownIcon$1, { className: "h-3 w-3" }),
    "Show ",
    hiddenReplyCount,
    " more ",
    hiddenReplyCount === 1 ? "reply" : "replies"
  )))));
}
function CommentItem$3({ comment, isLoggedIn, artworkId, onReplyPosted }) {
  const user = comment.user;
  const html2 = comment.rendered_content ?? null;
  const plain = comment.content ?? comment.raw_content ?? "";
  const profileLabel = user?.display || user?.username || user?.name || "Member";
  const replies = comment.replies || [];
  const flood = isFlood(plain);
  const [expanded, setExpanded] = reactExports.useState(!flood);
  const [showReplyForm, setShowReplyForm] = reactExports.useState(false);
  const [showAllReplies, setShowAllReplies] = reactExports.useState(false);
  const [reactionTotals, setReactionTotals] = reactExports.useState(comment.reactions ?? {});
  reactExports.useEffect(() => {
    if (comment.reactions || !comment.id) return;
    axios.get(`/api/comments/${comment.id}/reactions`).then(({ data }) => setReactionTotals(data.totals ?? {})).catch(() => {
    });
  }, [comment.id, comment.reactions]);
  const handleReplyPosted = reactExports.useCallback((newReply) => {
    onReplyPosted?.(comment.id, newReply);
    setShowReplyForm(false);
    setShowAllReplies(true);
  }, [comment.id, onReplyPosted]);
  const visibleReplies = showAllReplies ? replies : replies.slice(0, 2);
  const hiddenReplyCount = replies.length - 2;
  return /* @__PURE__ */ React.createElement(
    "li",
    {
      id: `comment-${comment.id}`,
      className: "group/comment rounded-2xl border border-white/[0.06] bg-white/[0.03] shadow-[0_1px_3px_rgba(0,0,0,.25)] backdrop-blur-sm transition-all duration-200 hover:border-white/[0.1] hover:bg-white/[0.05]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3.5" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "shrink-0 mt-0.5", tabIndex: -1, "aria-hidden": "true" }, /* @__PURE__ */ React.createElement(Avatar$1, { user, size: 38 })) : /* @__PURE__ */ React.createElement("span", { className: "shrink-0 mt-0.5" }, /* @__PURE__ */ React.createElement(Avatar$1, { user, size: 38 })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 flex-wrap" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "text-[13px] font-semibold text-white/95 transition-colors hover:text-accent" }, profileLabel) : /* @__PURE__ */ React.createElement("span", { className: "text-[13px] font-semibold text-white/95" }, profileLabel), /* @__PURE__ */ React.createElement(LevelBadge, { level: user?.level, rank: user?.rank, compact: true, className: "shrink-0" }), /* @__PURE__ */ React.createElement("span", { className: "text-white/15", "aria-hidden": "true" }, "·"), /* @__PURE__ */ React.createElement(
      "time",
      {
        dateTime: comment.created_at,
        title: formatAbsoluteDateTime$1(comment.created_at),
        className: "text-[11px] font-medium tracking-wide text-white/30 uppercase"
      },
      formatCommentTime$1(comment.time_ago, comment.created_at)
    )), /* @__PURE__ */ React.createElement(
      "div",
      {
        className: !expanded ? "overflow-hidden relative" : void 0,
        style: !expanded ? { maxHeight: "5em" } : void 0
      },
      html2 ? /* @__PURE__ */ React.createElement(
        "div",
        {
          className: "text-[13px] leading-[1.7] text-white/80 prose prose-invert prose-sm max-w-none prose-p:my-1.5 prose-a:text-sky-400 prose-a:no-underline hover:prose-a:underline prose-code:bg-white/[0.07] prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded-md prose-code:text-xs prose-code:font-normal",
          dangerouslySetInnerHTML: { __html: html2 }
        }
      ) : /* @__PURE__ */ React.createElement("p", { className: "text-[13px] leading-[1.7] text-white/80 whitespace-pre-line break-words" }, plain),
      flood && !expanded && /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-nova-900/95 to-transparent", "aria-hidden": "true" })
    ), flood && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setExpanded((e) => !e),
        className: "rounded-md px-2 py-0.5 text-xs font-medium text-sky-400 transition-all hover:bg-sky-500/10 hover:text-sky-300",
        "aria-expanded": expanded
      },
      expanded ? "↑ Collapse" : "↓ Show full comment"
    ), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5 pt-0.5" }, isLoggedIn && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowReplyForm((v2) => !v2),
        className: [
          "inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] font-medium uppercase tracking-wider transition-all duration-200 focus:outline-none",
          showReplyForm ? "bg-accent/10 text-accent" : "text-white/40 hover:bg-white/[0.06] hover:text-white/70"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement(ReplyIcon$1, null),
      "Reply"
    ), /* @__PURE__ */ React.createElement(
      ReactionBar,
      {
        entityType: "comment",
        entityId: comment.id,
        initialTotals: reactionTotals,
        isLoggedIn
      }
    ))))),
    (replies.length > 0 || showReplyForm) && /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.04] bg-white/[0.01] px-4 pb-4 pt-3 sm:px-5 sm:pb-5" }, replies.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("ul", { className: "space-y-1 pl-4 border-l-2 border-white/[0.06]" }, visibleReplies.map((reply) => /* @__PURE__ */ React.createElement(
      ReplyItem$1,
      {
        key: reply.id,
        reply,
        parentId: comment.id,
        artworkId,
        isLoggedIn,
        onReplyPosted
      }
    ))), !showAllReplies && hiddenReplyCount > 0 && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowAllReplies(true),
        className: "mt-2 ml-4 inline-flex items-center gap-1 text-[11px] font-medium text-accent/70 transition-colors hover:text-accent"
      },
      /* @__PURE__ */ React.createElement(ChevronDownIcon$1, { className: "h-3.5 w-3.5" }),
      "Show ",
      hiddenReplyCount,
      " more ",
      hiddenReplyCount === 1 ? "reply" : "replies"
    )), showReplyForm && /* @__PURE__ */ React.createElement("div", { className: replies.length > 0 ? "mt-3 pl-4 border-l-2 border-accent/20" : "" }, /* @__PURE__ */ React.createElement(
      CommentForm$1,
      {
        artworkId,
        parentId: comment.id,
        replyTo: profileLabel,
        onCancelReply: () => setShowReplyForm(false),
        onPosted: handleReplyPosted,
        isLoggedIn,
        compact: true
      }
    )))
  );
}
function Skeleton$1() {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, Array.from({ length: 3 }).map((_2, i) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: i,
      className: "flex gap-3.5 rounded-2xl border border-white/[0.04] bg-white/[0.02] p-5 animate-pulse",
      style: { animationDelay: `${i * 120}ms` }
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-[38px] h-[38px] rounded-full bg-white/[0.06] shrink-0" }),
    /* @__PURE__ */ React.createElement("div", { className: "flex-1 space-y-3 pt-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-2.5" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.06] rounded-full w-24" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.04] rounded-full w-14" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.05] rounded-full w-full" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.04] rounded-full w-4/5" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.03] rounded-full w-2/5" })))
  )));
}
function ArtworkComments({
  artworkId,
  comments: initialComments = [],
  isLoggedIn = false,
  loginUrl = "/login"
}) {
  const [comments, setComments] = reactExports.useState(initialComments);
  const [loading, setLoading] = reactExports.useState(false);
  const [page, setPage] = reactExports.useState(1);
  const [lastPage, setLastPage] = reactExports.useState(1);
  const [total, setTotal] = reactExports.useState(initialComments.length);
  const initialized = reactExports.useRef(false);
  const loadComments = reactExports.useCallback(
    async (p = 1) => {
      if (!artworkId) return;
      setLoading(true);
      try {
        const { data } = await axios.get(`/api/artworks/${artworkId}/comments?page=${p}`);
        if (p === 1) {
          setComments(data.data ?? []);
        } else {
          setComments((prev) => [...prev, ...data.data ?? []]);
        }
        setPage(data.meta?.current_page ?? p);
        setLastPage(data.meta?.last_page ?? 1);
        setTotal(data.meta?.total ?? 0);
      } catch {
      } finally {
        setLoading(false);
      }
    },
    [artworkId]
  );
  reactExports.useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;
    if (artworkId && initialComments.length === 0) {
      loadComments(1);
    } else {
      setTotal(initialComments.length);
    }
  }, [artworkId, initialComments.length, loadComments]);
  const handlePosted = reactExports.useCallback((newComment) => {
    const comment = { ...newComment, replies: newComment.replies || [] };
    setComments((prev) => [comment, ...prev]);
    setTotal((t) => t + 1);
  }, []);
  const handleReplyPosted = reactExports.useCallback((parentId, newReply) => {
    const insertReply = (nodes) => nodes.map((c) => {
      if (c.id === parentId) {
        return { ...c, replies: [...c.replies || [], { ...newReply, replies: [] }] };
      }
      if (c.replies?.length) {
        return { ...c, replies: insertReply(c.replies) };
      }
      return c;
    });
    setComments((prev) => insertReply(prev));
    setTotal((t) => t + 1);
  }, []);
  return /* @__PURE__ */ React.createElement("section", { "aria-label": "Comments", className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold tracking-tight text-white sm:text-xl" }, "Comments"), total > 0 && /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full bg-white/[0.06] px-2.5 py-0.5 text-xs font-medium tabular-nums text-white/50" }, total)), loading && comments.length === 0 ? /* @__PURE__ */ React.createElement(Skeleton$1, null) : comments.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center gap-3 rounded-2xl border border-dashed border-white/[0.08] bg-white/[0.015] px-6 py-10 text-center" }, /* @__PURE__ */ React.createElement(ChatBubbleIcon$1, null), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/40" }, "No comments yet"), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/25" }, "Be the first to share your thoughts.")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("ul", { className: "space-y-3 sm:space-y-4" }, comments.map((comment) => /* @__PURE__ */ React.createElement(
    CommentItem$3,
    {
      key: comment.id,
      comment,
      artworkId,
      isLoggedIn,
      onReplyPosted: handleReplyPosted
    }
  ))), page < lastPage && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center pt-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: loading,
      onClick: () => loadComments(page + 1),
      className: "group relative rounded-full border border-white/[0.08] bg-white/[0.03] px-6 py-2.5 text-sm font-medium text-white/50 transition-all duration-200 hover:border-white/[0.15] hover:bg-white/[0.06] hover:text-white/80 hover:shadow-lg hover:shadow-black/20 disabled:opacity-40 disabled:pointer-events-none"
    },
    loading ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 animate-spin", viewBox: "0 0 24 24", fill: "none" }, /* @__PURE__ */ React.createElement("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3" }), /* @__PURE__ */ React.createElement("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" })), "Loading…") : "Load more comments"
  ))), artworkId && /* @__PURE__ */ React.createElement(
    CommentForm$1,
    {
      artworkId,
      onPosted: handlePosted,
      isLoggedIn,
      loginUrl
    }
  ));
}
function useWebShare({ onFallback } = {}) {
  const canNativeShare = reactExports.useMemo(
    () => typeof navigator !== "undefined" && typeof navigator.share === "function",
    []
  );
  const share = reactExports.useCallback(
    async ({ title, text: text2, url }) => {
      if (canNativeShare) {
        try {
          await navigator.share({ title, text: text2, url });
          return { shared: true, native: true };
        } catch (err) {
          if (err?.name === "AbortError") {
            return { shared: false, native: true };
          }
        }
      }
      onFallback?.({ title, text: text2, url });
      return { shared: false, native: false };
    },
    [canNativeShare, onFallback]
  );
  return { canNativeShare, share };
}
const ArtworkShareModal = reactExports.lazy(() => import("./assets/ArtworkShareModal-BI8kkaqs.js"));
function ShareIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 1 1 0-2.684m0 2.684 6.632 3.316m-6.632-6 6.632-3.316m0 0a3 3 0 1 0 5.367-2.684 3 3 0 0 0-5.367 2.684Zm0 9.316a3 3 0 1 0 5.368 2.684 3 3 0 0 0-5.368-2.684Z" }));
}
function ArtworkShareButton({ artwork, shareUrl, size = "default", isLoggedIn = false }) {
  const [modalOpen, setModalOpen] = reactExports.useState(false);
  const openModal = reactExports.useCallback(
    () => setModalOpen(true),
    []
  );
  const closeModal = reactExports.useCallback(
    () => setModalOpen(false),
    []
  );
  const { share } = useWebShare({ onFallback: openModal });
  const handleClick = async () => {
    const result = await share({
      title: artwork?.title || "Artwork",
      text: artwork?.description?.substring(0, 120) || "",
      url: shareUrl || artwork?.canonical_url || window.location.href
    });
    if (result?.shared && result?.native && artwork?.id) {
      const csrfToken2 = document.head.querySelector('meta[name="csrf-token"]')?.content;
      fetch(`/api/artworks/${artwork.id}/share`, {
        method: "POST",
        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken2 || "" },
        credentials: "same-origin",
        body: JSON.stringify({ platform: "native" })
      }).catch(() => {
      });
    }
  };
  const isSmall = size === "small";
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Share artwork",
      onClick: handleClick,
      className: isSmall ? "inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.04] px-3.5 py-2 text-xs font-medium text-white/70 transition-all hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white" : "group inline-flex items-center gap-2 rounded-full border border-white/[0.08] bg-white/[0.04] px-5 py-2.5 text-sm font-medium text-white/70 transition-all duration-200 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white hover:shadow-lg hover:shadow-white/[0.03]",
      title: "Share"
    },
    /* @__PURE__ */ React.createElement(ShareIcon, null),
    !isSmall && /* @__PURE__ */ React.createElement("span", null, "Share")
  ), modalOpen && /* @__PURE__ */ React.createElement(reactExports.Suspense, { fallback: null }, /* @__PURE__ */ React.createElement(
    ArtworkShareModal,
    {
      open: modalOpen,
      onClose: closeModal,
      artwork,
      shareUrl,
      isLoggedIn
    }
  )));
}
function formatCount$2(value) {
  const n = Number(value || 0);
  if (n >= 1e6) return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
  if (n >= 1e3) return `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
  return `${n}`;
}
function HeartIcon$1({ filled }) {
  return filled ? /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "m11.645 20.91-.007-.003-.022-.012a15.247 15.247 0 0 1-.383-.218 25.18 25.18 0 0 1-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0 1 12 5.052 5.5 5.5 0 0 1 16.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 0 1-4.244 3.17 15.247 15.247 0 0 1-.383.219l-.022.012-.007.004-.003.001a.752.752 0 0 1-.704 0l-.003-.001Z" })) : /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z" }));
}
function BookmarkIcon({ filled }) {
  return filled ? /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M6.32 2.577a49.255 49.255 0 0 1 11.36 0c1.497.174 2.57 1.46 2.57 2.93V21a.75.75 0 0 1-1.085.67L12 18.089l-7.165 3.583A.75.75 0 0 1 3.75 21V5.507c0-1.47 1.073-2.756 2.57-2.93Z", clipRule: "evenodd" })) : /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0 1 11.186 0Z" }));
}
function DownloadArrowIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 2, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" }));
}
function ChartIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 3v18h18" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M7 15.5 10.5 12l3 2.5 4.5-6" }));
}
function EnhanceIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 3l1.9 4.6L18.5 9l-4.6 1.4L12 15l-1.9-4.6L5.5 9l4.6-1.4L12 3Z" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M18 15l.95 2.05L21 18l-2.05.95L18 21l-.95-2.05L15 18l2.05-.95L18 15Z" }));
}
function FlagIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 3v1.5M3 21v-6m0 0 2.77-.693a9 9 0 0 1 6.208.682l.108.054a9 9 0 0 0 6.086.71l3.114-.732a48.524 48.524 0 0 1-.005-10.499l-3.11.732a9 9 0 0 1-6.085-.711l-.108-.054a9 9 0 0 0-6.208-.682L3 4.5M3 15V4.5" }));
}
const REPORT_REASONS = [
  "Inappropriate content",
  "Copyright violation",
  "Spam or misleading",
  "Offensive or abusive"
];
function ReportModal({ open, onClose, onSubmit, submitting }) {
  const [selected, setSelected] = reactExports.useState("");
  const [details, setDetails] = reactExports.useState("");
  const backdropRef = reactExports.useRef(null);
  const inputRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (open) {
      setSelected("");
      setDetails("");
      const t = setTimeout(() => inputRef.current?.focus(), 80);
      return () => clearTimeout(t);
    }
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return;
    const handler = (e) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose]);
  if (!open) return null;
  const trimmedDetails = details.trim();
  const canSubmit = selected.length > 0 && trimmedDetails.length >= 10 && !submitting;
  const fullReason = `${selected}: ${trimmedDetails}`;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        onClick: (e) => {
          if (e.target === backdropRef.current) onClose();
        },
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4"
      },
      /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-md rounded-2xl border border-white/[0.08] bg-nova-900 shadow-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Report Artwork"), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: onClose,
          className: "rounded-lg p-1.5 text-white/40 transition hover:bg-white/[0.06] hover:text-white/70",
          "aria-label": "Close"
        },
        /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 2, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18 18 6M6 6l12 12" }))
      )), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-medium text-white/60" }, "Reason ", /* @__PURE__ */ React.createElement("span", { className: "text-red-400" }, "*")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, REPORT_REASONS.map((r) => /* @__PURE__ */ React.createElement(
        "button",
        {
          key: r,
          type: "button",
          onClick: () => setSelected(r),
          className: [
            "rounded-full border px-3.5 py-1.5 text-xs font-medium transition-all",
            selected === r ? "border-red-500/50 bg-red-500/15 text-red-400" : "border-white/[0.08] bg-white/[0.04] text-white/60 hover:border-white/[0.15] hover:text-white/80"
          ].join(" ")
        },
        r
      )))), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-medium text-white/60" }, "Details & proof ", /* @__PURE__ */ React.createElement("span", { className: "text-red-400" }, "*")), /* @__PURE__ */ React.createElement(
        "textarea",
        {
          ref: inputRef,
          value: details,
          onChange: (e) => setDetails(e.target.value),
          maxLength: 1e3,
          rows: 4,
          placeholder: "Please describe the issue and provide any links or evidence that support your report…",
          className: "w-full resize-none rounded-xl border border-white/[0.08] bg-white/[0.03] px-4 py-3 text-sm text-white placeholder-white/30 outline-none transition focus:border-white/[0.15] focus:ring-1 focus:ring-white/[0.1]"
        }
      ), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/30" }, trimmedDetails.length < 10 ? `At least 10 characters required (${trimmedDetails.length}/10)` : `${details.length}/1000`))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: onClose,
          className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-5 py-2 text-sm font-medium text-white/60 transition hover:bg-white/[0.07] hover:text-white/80"
        },
        "Cancel"
      ), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          disabled: !canSubmit,
          onClick: () => onSubmit(fullReason),
          className: "rounded-full bg-red-600 px-5 py-2 text-sm font-semibold text-white shadow-lg shadow-red-600/20 transition hover:bg-red-500 disabled:cursor-not-allowed disabled:opacity-40"
        },
        submitting ? "Sending…" : "Submit Report"
      )))
    ),
    document.body
  );
}
function ArtworkActionBar({ artwork, stats, canonicalUrl, onStatsChange }) {
  const [favorited, setFavorited] = reactExports.useState(Boolean(artwork?.viewer?.is_favorited));
  const [bookmarked, setBookmarked] = reactExports.useState(Boolean(artwork?.viewer?.is_bookmarked));
  const [bookmarkCount, setBookmarkCount] = reactExports.useState(Number(stats?.bookmarks ?? artwork?.stats?.bookmarks ?? 0));
  const [downloading, setDownloading] = reactExports.useState(false);
  const [reporting, setReporting] = reactExports.useState(false);
  const [reported, setReported] = reactExports.useState(false);
  const [reportOpen, setReportOpen] = reactExports.useState(false);
  const isLoggedIn = Boolean(artwork?.viewer?.is_authenticated);
  reactExports.useEffect(() => {
    setFavorited(Boolean(artwork?.viewer?.is_favorited));
  }, [artwork?.id, artwork?.viewer?.is_favorited]);
  reactExports.useEffect(() => {
    setBookmarked(Boolean(artwork?.viewer?.is_bookmarked));
  }, [artwork?.id, artwork?.viewer?.is_bookmarked]);
  reactExports.useEffect(() => {
    setBookmarkCount(Number(stats?.bookmarks ?? artwork?.stats?.bookmarks ?? 0));
  }, [artwork?.id, artwork?.stats?.bookmarks, stats?.bookmarks]);
  const shareUrl = canonicalUrl || artwork?.canonical_url || (typeof window !== "undefined" ? window.location.href : "#");
  const analyticsUrl = artwork?.management?.analytics_url || (artwork?.viewer?.is_owner ? `/studio/artworks/${artwork.id}/analytics` : null);
  const enhanceUrl = artwork?.viewer?.is_owner && artwork?.id ? `/enhance/create?artwork=${encodeURIComponent(artwork.id)}` : null;
  const csrfToken2 = typeof document !== "undefined" ? document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") : null;
  reactExports.useEffect(() => {
    if (!artwork?.id) return;
    const postView = () => {
      fetch(`/api/art/${artwork.id}/view`, {
        method: "POST",
        headers: { "X-CSRF-TOKEN": csrfToken2 || "", "Content-Type": "application/json" },
        credentials: "same-origin",
        keepalive: true
      }).catch(() => {
      });
    };
    if (typeof window === "undefined") {
      postView();
      return void 0;
    }
    if (typeof window.requestIdleCallback === "function") {
      const handle2 = window.requestIdleCallback(postView, { timeout: 1500 });
      return () => window.cancelIdleCallback(handle2);
    }
    const handle = window.setTimeout(postView, 1200);
    return () => window.clearTimeout(handle);
  }, [artwork?.id]);
  const postInteraction = async (url, body2) => {
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken2 || "" },
      credentials: "same-origin",
      body: JSON.stringify(body2)
    });
    if (!response.ok) throw new Error("Request failed");
    return response.json();
  };
  const handleDownload = async () => {
    if (downloading || !artwork?.id) return;
    setDownloading(true);
    try {
      const a = document.createElement("a");
      a.href = `/download/artwork/${artwork.id}`;
      a.rel = "noopener noreferrer";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    } catch {
      window.open(`/download/artwork/${artwork.id}`, "_blank", "noopener,noreferrer");
    } finally {
      setDownloading(false);
    }
  };
  const onToggleFavorite = async () => {
    if (!isLoggedIn) {
      window.location.href = "/login";
      return;
    }
    const nextState = !favorited;
    setFavorited(nextState);
    try {
      await postInteraction(`/api/artworks/${artwork.id}/favorite`, { state: nextState });
      onStatsChange?.({ favorites: nextState ? 1 : -1 });
    } catch {
      setFavorited(!nextState);
    }
  };
  const onToggleBookmark = async () => {
    if (!isLoggedIn) {
      window.location.href = "/login";
      return;
    }
    const nextState = !bookmarked;
    setBookmarked(nextState);
    setBookmarkCount((current) => Math.max(0, current + (nextState ? 1 : -1)));
    try {
      const payload = await postInteraction(`/api/artworks/${artwork.id}/bookmark`, { state: nextState });
      setBookmarked(Boolean(payload?.is_bookmarked));
      setBookmarkCount(Number(payload?.stats?.bookmarks ?? 0));
    } catch {
      setBookmarked(!nextState);
      setBookmarkCount((current) => Math.max(0, current + (nextState ? -1 : 1)));
    }
  };
  const openReport = () => {
    if (reported) return;
    setReportOpen(true);
  };
  const submitReport = async (reason) => {
    if (reporting) return;
    setReporting(true);
    try {
      await postInteraction(`/api/artworks/${artwork.id}/report`, { reason });
      setReported(true);
      setReportOpen(false);
    } catch {
    } finally {
      setReporting(false);
    }
  };
  const favCount = formatCount$2(stats?.favorites ?? artwork?.stats?.favorites ?? 0);
  const savedCount = formatCount$2(bookmarkCount);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "hidden lg:flex lg:items-center lg:justify-center lg:gap-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": favorited ? "Remove from favourites" : "Add to favourites",
      onClick: onToggleFavorite,
      className: [
        "inline-flex items-center gap-2 rounded-full border px-5 py-2.5 text-sm font-medium transition-all duration-200",
        favorited ? "border-rose-500/40 bg-rose-500/15 text-rose-400 shadow-lg shadow-rose-500/10 hover:bg-rose-500/20" : "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(HeartIcon$1, { filled: favorited }),
    /* @__PURE__ */ React.createElement("span", { className: "tabular-nums", "aria-hidden": "true" }, favCount)
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": bookmarked ? "Remove bookmark" : "Save artwork",
      onClick: onToggleBookmark,
      className: [
        "inline-flex items-center gap-2 rounded-full border px-5 py-2.5 text-sm font-medium transition-all duration-200",
        bookmarked ? "border-amber-400/35 bg-amber-400/14 text-amber-200 shadow-lg shadow-amber-500/10 hover:bg-amber-400/18" : "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(BookmarkIcon, { filled: bookmarked }),
    /* @__PURE__ */ React.createElement("span", { className: "tabular-nums", "aria-hidden": "true" }, savedCount)
  ), /* @__PURE__ */ React.createElement(ArtworkShareButton, { artwork, shareUrl, size: "default", isLoggedIn }), analyticsUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: analyticsUrl,
      className: "inline-flex items-center gap-2 rounded-full border border-sky-400/30 bg-sky-400/12 px-5 py-2.5 text-sm font-medium text-sky-100 transition-all duration-200 hover:border-sky-300/45 hover:bg-sky-400/18 hover:text-white"
    },
    /* @__PURE__ */ React.createElement(ChartIcon, null),
    "Statistics"
  ) : null, enhanceUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: enhanceUrl,
      className: "inline-flex items-center gap-2 rounded-full border border-violet-300/25 bg-violet-400/12 px-5 py-2.5 text-sm font-medium text-violet-50 transition-all duration-200 hover:border-violet-200/40 hover:bg-violet-400/18 hover:text-white"
    },
    /* @__PURE__ */ React.createElement(EnhanceIcon, null),
    "Enhance image"
  ) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Report artwork",
      onClick: openReport,
      disabled: reported,
      className: [
        "inline-flex items-center gap-2 rounded-full border px-5 py-2.5 text-sm font-medium transition-all duration-200",
        reported ? "border-red-500/30 bg-red-500/10 text-red-400/70 cursor-default" : "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-red-500/40 hover:bg-red-500/10 hover:text-red-400"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(FlagIcon, null),
    reported ? "Reported" : "Report"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Download artwork",
      onClick: handleDownload,
      disabled: downloading,
      className: "inline-flex items-center gap-2 rounded-full bg-accent px-6 py-2.5 text-sm font-bold text-deep shadow-lg shadow-accent/25 transition-all duration-200 hover:brightness-110 hover:shadow-xl hover:shadow-accent/30 focus:outline-none focus-visible:ring-2 focus-visible:ring-accent/60 disabled:cursor-wait disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement(DownloadArrowIcon, null),
    downloading ? "Downloading…" : "Download"
  )), /* @__PURE__ */ React.createElement("div", { className: "fixed inset-x-0 bottom-0 z-50 border-t border-white/[0.08] bg-nova-900/95 px-3 py-2.5 backdrop-blur-md lg:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": favorited ? "Remove from favourites" : "Add to favourites",
      onClick: onToggleFavorite,
      className: [
        "inline-flex items-center gap-1.5 rounded-full border px-3.5 py-2 text-xs font-medium transition-all",
        favorited ? "border-rose-500/40 bg-rose-500/15 text-rose-400" : "border-white/[0.08] bg-white/[0.04] text-white/70"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(HeartIcon$1, { filled: favorited }),
    /* @__PURE__ */ React.createElement("span", { className: "tabular-nums", "aria-hidden": "true" }, favCount)
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": bookmarked ? "Remove bookmark" : "Save artwork",
      onClick: onToggleBookmark,
      className: [
        "inline-flex items-center gap-1.5 rounded-full border px-3.5 py-2 text-xs font-medium transition-all",
        bookmarked ? "border-amber-400/35 bg-amber-400/14 text-amber-200" : "border-white/[0.08] bg-white/[0.04] text-white/70"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(BookmarkIcon, { filled: bookmarked }),
    /* @__PURE__ */ React.createElement("span", { className: "tabular-nums", "aria-hidden": "true" }, savedCount)
  ), /* @__PURE__ */ React.createElement(ArtworkShareButton, { artwork, shareUrl, size: "small", isLoggedIn }), analyticsUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: analyticsUrl,
      "aria-label": "Open artwork statistics",
      title: "Statistics",
      className: "inline-flex items-center gap-1.5 rounded-full border border-sky-400/30 bg-sky-400/12 px-3.5 py-2 text-xs font-medium text-sky-100 transition-all hover:border-sky-300/45 hover:bg-sky-400/18 hover:text-white"
    },
    /* @__PURE__ */ React.createElement(ChartIcon, null)
  ) : null, enhanceUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: enhanceUrl,
      "aria-label": "Enhance artwork image",
      title: "Enhance image",
      className: "inline-flex items-center gap-1.5 rounded-full border border-violet-300/25 bg-violet-400/12 px-3.5 py-2 text-xs font-medium text-violet-50 transition-all hover:border-violet-200/40 hover:bg-violet-400/18 hover:text-white"
    },
    /* @__PURE__ */ React.createElement(EnhanceIcon, null),
    "Enhance"
  ) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Report",
      onClick: openReport,
      disabled: reported,
      className: [
        "inline-flex items-center gap-1.5 rounded-full border px-3.5 py-2 text-xs font-medium transition-all",
        reported ? "border-red-500/30 bg-red-500/10 text-red-400/70 cursor-default" : "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-red-500/40 hover:text-red-400"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(FlagIcon, null)
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Download artwork",
      onClick: handleDownload,
      disabled: downloading,
      className: "inline-flex items-center gap-1.5 rounded-full bg-accent px-5 py-2 text-xs font-bold text-deep transition hover:brightness-110 disabled:cursor-wait disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement(DownloadArrowIcon, null),
    downloading ? "…" : "Download"
  ))), /* @__PURE__ */ React.createElement(
    ReportModal,
    {
      open: reportOpen,
      onClose: () => setReportOpen(false),
      onSubmit: submitReport,
      submitting: reporting
    }
  ));
}
const RESOLUTION_TIERS = [
  { label: "8K", width: 7680, height: 4320, tone: "amber" },
  { label: "5K", width: 5120, height: 2880, tone: "violet" },
  { label: "4K", width: 3840, height: 2160, tone: "sky" },
  { label: "QHD", width: 2560, height: 1440, tone: "emerald" },
  { label: "Full HD", width: 1920, height: 1080, tone: "cyan" },
  { label: "HD", width: 1280, height: 720, tone: "slate" }
];
const ASPECT_RATIOS = [
  { label: "21:9", ratio: 21 / 9 },
  { label: "16:10", ratio: 16 / 10 },
  { label: "16:9", ratio: 16 / 9 },
  { label: "3:2", ratio: 3 / 2 },
  { label: "4:3", ratio: 4 / 3 },
  { label: "1:1", ratio: 1 },
  { label: "4:5", ratio: 4 / 5 },
  { label: "3:4", ratio: 3 / 4 },
  { label: "9:16", ratio: 9 / 16 }
];
const TONE_CLASSES$2 = {
  amber: "border-amber-400/25 bg-amber-400/10 text-amber-100",
  violet: "border-violet-400/25 bg-violet-400/10 text-violet-100",
  sky: "border-sky-400/25 bg-sky-400/10 text-sky-100",
  emerald: "border-emerald-400/25 bg-emerald-400/10 text-emerald-100",
  cyan: "border-cyan-400/25 bg-cyan-400/10 text-cyan-100",
  slate: "border-white/10 bg-white/[0.04] text-white/80"
};
function ScreenIcon({ className }) {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 17.25h6m-3 0v2.25m-7.5-15h15A1.5 1.5 0 0 1 21 6v9A1.5 1.5 0 0 1 19.5 16.5h-15A1.5 1.5 0 0 1 3 15V6A1.5 1.5 0 0 1 4.5 4.5Z" }));
}
function RatioIcon({ className }) {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 8.25V6A1.5 1.5 0 0 1 6 4.5h2.25m7.5 0H18A1.5 1.5 0 0 1 19.5 6v2.25m0 7.5V18A1.5 1.5 0 0 1 18 19.5h-2.25m-7.5 0H6A1.5 1.5 0 0 1 4.5 18v-2.25" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.25 12h7.5" }));
}
function FormatIcon({ className, variant }) {
  if (variant === "ultrawide") {
    return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("rect", { x: "3.75", y: "7.5", width: "16.5", height: "9", rx: "2.25" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M7.5 12h9" }));
  }
  if (variant === "vertical") {
    return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("rect", { x: "7.25", y: "3.75", width: "9.5", height: "16.5", rx: "2.25" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 7.5v9" }));
  }
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 18c2.5-5.5 5-8.25 7.5-8.25S17 12.5 19.5 18" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M7.5 6.75h9" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 4.5h6v4.5H9z" }));
}
function OrientationIcon({ className, orientation }) {
  if (orientation === "square") {
    return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("rect", { x: "5.5", y: "5.5", width: "13", height: "13", rx: "2.25" }));
  }
  if (orientation === "portrait") {
    return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("rect", { x: "7.25", y: "4.5", width: "9.5", height: "15", rx: "2.25" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 8.25v7.5" }));
  }
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className }, /* @__PURE__ */ React.createElement("rect", { x: "4.5", y: "7.25", width: "15", height: "9.5", rx: "2.25" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.25 12h7.5" }));
}
function Badge$1({ label, tone, icon }) {
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] ${TONE_CLASSES$2[tone] || TONE_CLASSES$2.slate}` }, /* @__PURE__ */ React.createElement("span", { className: "text-current/90" }, icon), /* @__PURE__ */ React.createElement("span", null, label));
}
function pickResolutionTier(width, height) {
  const longSide = Math.max(width, height);
  const shortSide = Math.min(width, height);
  for (const tier of RESOLUTION_TIERS) {
    if (longSide >= tier.width && shortSide >= tier.height) {
      return tier;
    }
  }
  return null;
}
function pickOrientation(width, height) {
  if (width === height) {
    return {
      key: "orientation-square",
      label: "Square",
      tone: "amber",
      icon: /* @__PURE__ */ React.createElement(OrientationIcon, { className: "h-3.5 w-3.5", orientation: "square" }),
      isSquare: true
    };
  }
  if (width > height) {
    return {
      key: "orientation-landscape",
      label: "Landscape",
      tone: "emerald",
      icon: /* @__PURE__ */ React.createElement(OrientationIcon, { className: "h-3.5 w-3.5", orientation: "landscape" }),
      isSquare: false
    };
  }
  return {
    key: "orientation-portrait",
    label: "Portrait",
    tone: "violet",
    icon: /* @__PURE__ */ React.createElement(OrientationIcon, { className: "h-3.5 w-3.5", orientation: "portrait" }),
    isSquare: false
  };
}
function pickAspectRatio(width, height) {
  const ratio = width / height;
  let best = null;
  for (const candidate of ASPECT_RATIOS) {
    const delta = Math.abs(ratio - candidate.ratio) / candidate.ratio;
    if (delta > 0.03) {
      continue;
    }
    if (best === null || delta < best.delta) {
      best = { ...candidate, delta };
    }
  }
  return best;
}
function pickSemanticFormat(width, height, aspectRatio, orientation) {
  if (!orientation || orientation.isSquare) {
    return null;
  }
  const ratio = width / height;
  if (ratio >= 2.1) {
    return {
      key: "semantic-ultrawide",
      label: "Ultrawide",
      tone: "sky",
      icon: /* @__PURE__ */ React.createElement(FormatIcon, { className: "h-3.5 w-3.5", variant: "ultrawide" })
    };
  }
  if (ratio <= 0.75) {
    return {
      key: "semantic-vertical",
      label: "Vertical",
      tone: "violet",
      icon: /* @__PURE__ */ React.createElement(FormatIcon, { className: "h-3.5 w-3.5", variant: "vertical" })
    };
  }
  if (aspectRatio && ["4:3", "3:2", "16:10"].includes(aspectRatio.label)) {
    return {
      key: "semantic-classic",
      label: "Classic",
      tone: "amber",
      icon: /* @__PURE__ */ React.createElement(FormatIcon, { className: "h-3.5 w-3.5", variant: "classic" })
    };
  }
  return null;
}
function getArtworkFormatBadges(width, height) {
  if (!(width > 0 && height > 0)) {
    return [];
  }
  const badges = [];
  const orientation = pickOrientation(width, height);
  const resolutionTier = pickResolutionTier(width, height);
  if (resolutionTier) {
    badges.push({
      key: `resolution-${resolutionTier.label}`,
      label: resolutionTier.label,
      tone: resolutionTier.tone,
      icon: /* @__PURE__ */ React.createElement(ScreenIcon, { className: "h-3.5 w-3.5" })
    });
  }
  if (orientation) {
    badges.push(orientation);
  }
  const aspectRatio = pickAspectRatio(width, height);
  const semanticFormat = pickSemanticFormat(width, height, aspectRatio, orientation);
  if (semanticFormat) {
    badges.push(semanticFormat);
  }
  if (aspectRatio && !orientation?.isSquare) {
    badges.push({
      key: `ratio-${aspectRatio.label}`,
      label: aspectRatio.label,
      tone: "slate",
      icon: /* @__PURE__ */ React.createElement(RatioIcon, { className: "h-3.5 w-3.5" })
    });
  }
  return badges;
}
function ArtworkFormatBadges({ width, height, className = "" }) {
  const badges = getArtworkFormatBadges(width, height);
  if (badges.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: `flex flex-wrap gap-2 ${className}`.trim() }, badges.map((badge) => /* @__PURE__ */ React.createElement(Badge$1, { key: badge.key, label: badge.label, tone: badge.tone, icon: badge.icon })));
}
const NUMBER_FORMATTER$2 = new Intl.NumberFormat("en-US");
const ABSOLUTE_DATE_FORMATTER$1 = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "numeric",
  timeZone: "UTC"
});
function formatCount$1(value) {
  const n = Number(value || 0);
  if (n >= 1e6) return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
  if (n >= 1e3) return `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
  return NUMBER_FORMATTER$2.format(n);
}
function formatDate$i(value, useRelative = true) {
  if (!value) return "—";
  try {
    const d2 = new Date(value);
    if (!useRelative) return ABSOLUTE_DATE_FORMATTER$1.format(d2);
    const now = Date.now();
    const diff = now - d2.getTime();
    const days = Math.floor(diff / 864e5);
    if (days === 0) return "Today";
    if (days === 1) return "Yesterday";
    if (days < 30) return `${days} days ago`;
    return ABSOLUTE_DATE_FORMATTER$1.format(d2);
  } catch {
    return "—";
  }
}
function StatTile({ icon, label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center gap-1.5 rounded-xl bg-white/[0.03] px-3 py-3.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-white/30" }, icon), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold tabular-nums text-white/90" }, value), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] uppercase tracking-wider text-white/35" }, label));
}
function InfoRow$1({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between py-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-wider text-white/35" }, label), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/80" }, value));
}
function ArtworkDetailsPanel({ artwork, stats }) {
  const [hydrated, setHydrated] = reactExports.useState(false);
  const width = artwork?.dimensions?.width || artwork?.width || 0;
  const height = artwork?.dimensions?.height || artwork?.height || 0;
  const resolution = width > 0 && height > 0 ? `${NUMBER_FORMATTER$2.format(width)} × ${NUMBER_FORMATTER$2.format(height)}` : null;
  reactExports.useEffect(() => {
    setHydrated(true);
  }, []);
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-2.5" }, /* @__PURE__ */ React.createElement(
    StatTile,
    {
      icon: /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-4.5 w-4.5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" })),
      label: "Views",
      value: formatCount$1(stats?.views)
    }
  ), /* @__PURE__ */ React.createElement(
    StatTile,
    {
      icon: /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-4.5 w-4.5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5M16.5 12 12 16.5m0 0L7.5 12m4.5 4.5V3" })),
      label: "Downloads",
      value: formatCount$1(stats?.downloads)
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 divide-y divide-white/[0.05]" }, resolution ? /* @__PURE__ */ React.createElement("div", { className: "py-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-wider text-white/35" }, "Resolution"), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/80" }, resolution)), /* @__PURE__ */ React.createElement(ArtworkFormatBadges, { width, height, className: "mt-2" })) : null, /* @__PURE__ */ React.createElement(InfoRow$1, { label: "Uploaded", value: formatDate$i(artwork?.published_at, hydrated) })));
}
function galleryUrlFor(author) {
  if (!author?.username) return null;
  return `/@${author.username}/gallery`;
}
function AuthorBioPopover({ author }) {
  const [open, setOpen] = reactExports.useState(false);
  const [loading, setLoading] = reactExports.useState(false);
  const [bio, setBio] = reactExports.useState(void 0);
  const [error, setError] = reactExports.useState("");
  const username = author?.username || "";
  const profileUrl = author?.profile_url || (username ? `/@${username}` : null);
  const galleryUrl = galleryUrlFor(author);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    function onKeyDown(event) {
      if (event.key === "Escape") {
        setOpen(false);
      }
    }
    document.addEventListener("keydown", onKeyDown);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
    };
  }, [open]);
  async function loadBio() {
    if (!username || loading || bio !== void 0) {
      return;
    }
    setLoading(true);
    setError("");
    try {
      const response = await fetch(`/api/profile/${encodeURIComponent(username)}/ai-biography`, {
        credentials: "same-origin",
        headers: {
          Accept: "application/json",
          "X-Requested-With": "XMLHttpRequest"
        }
      });
      if (!response.ok) {
        throw new Error(`Failed to load biography (${response.status})`);
      }
      const payload = await response.json();
      setBio(payload?.data?.text || null);
    } catch {
      setError("Biography is unavailable right now.");
      setBio(null);
    } finally {
      setLoading(false);
    }
  }
  if (!username || !profileUrl) {
    return null;
  }
  const dialog = open ? reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-[220] overflow-y-auto" }, /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 bg-slate-950/80 backdrop-blur-md", "aria-hidden": "true" }), /* @__PURE__ */ React.createElement("div", { className: "flex min-h-screen items-center justify-center p-4 sm:p-6 lg:p-8" }, /* @__PURE__ */ React.createElement(
      "div",
      {
        role: "dialog",
        "aria-modal": "true",
        "aria-label": `About ${author?.name || author?.username || "author"}`,
        className: "relative z-[221] flex max-h-[min(88vh,52rem)] w-full max-w-2xl flex-col overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/96 p-5 shadow-[0_36px_100px_rgba(2,6,23,0.75)] backdrop-blur-xl sm:p-6 lg:p-7"
      },
      /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          "aria-label": "Close author biography overlay",
          onClick: () => setOpen(false),
          className: "absolute inset-0"
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "relative z-10 flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-200/70" }, "About the author"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xl font-semibold text-white sm:text-2xl" }, author?.name || author?.username), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/40 sm:text-base" }, "@", username)), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          "aria-label": "Close author biography",
          onClick: () => setOpen(false),
          className: "inline-flex h-10 w-10 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-white/60 transition hover:bg-white/[0.08] hover:text-white"
        },
        /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18 18 6M6 6l12 12" }))
      )),
      /* @__PURE__ */ React.createElement("div", { className: "relative z-10 mt-5 min-h-0 flex-1 overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "max-h-full overflow-y-auto p-4 text-[15px] leading-8 text-white/85 sm:p-5 sm:text-base lg:text-[17px] lg:leading-8" }, loading ? /* @__PURE__ */ React.createElement("p", { className: "text-white/60" }, "Loading biography...") : null, !loading && error ? /* @__PURE__ */ React.createElement("p", { className: "text-rose-200/90" }, error) : null, !loading && !error && bio ? /* @__PURE__ */ React.createElement("p", null, bio) : null, !loading && !error && bio === null ? /* @__PURE__ */ React.createElement("p", { className: "text-white/60" }, "No public biography available yet.") : null)),
      /* @__PURE__ */ React.createElement("div", { className: "relative z-10 mt-5 flex shrink-0 flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
        "a",
        {
          href: profileUrl,
          className: "inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-medium text-white transition hover:bg-white/[0.08]"
        },
        "View profile"
      ), galleryUrl ? /* @__PURE__ */ React.createElement(
        "a",
        {
          href: galleryUrl,
          className: "inline-flex items-center gap-2 rounded-xl border border-sky-300/20 bg-sky-300/10 px-4 py-2.5 text-sm font-medium text-sky-100 transition hover:border-sky-300/30 hover:bg-sky-300/16"
        },
        "Open gallery"
      ) : null)
    ))),
    document.body
  ) : null;
  return /* @__PURE__ */ React.createElement("span", { className: "relative inline-flex items-center" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-haspopup": "dialog",
      "aria-expanded": open ? "true" : "false",
      "aria-label": `More about ${author?.name || author?.username || "this author"}`,
      onClick: () => {
        const nextOpen = !open;
        setOpen(nextOpen);
        if (!open) {
          void loadBio();
        }
      },
      className: "inline-flex h-7 w-7 items-center justify-center rounded-full border border-sky-300/20 bg-sky-300/8 text-sky-100/80 transition hover:border-sky-300/35 hover:bg-sky-300/14 hover:text-sky-50"
    },
    /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.8, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M11.25 11.25 12 12v4.5m0-8.25h.008v.008H12V8.25Zm9 3.75a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" }))
  ), dialog);
}
function NovaConfirmDialog({
  open,
  title = "Please confirm",
  message,
  children,
  confirmLabel = "Confirm",
  cancelLabel = "Cancel",
  confirmTone = "danger",
  onConfirm,
  onClose,
  busy = false
}) {
  const backdropRef = reactExports.useRef(null);
  const cancelButtonRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const timeoutId = window.setTimeout(() => cancelButtonRef.current?.focus(), 60);
    return () => window.clearTimeout(timeoutId);
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape" && !busy) {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [busy, onClose, open]);
  if (!open) return null;
  const confirmClassName = confirmTone === "danger" ? "border border-rose-400/25 bg-rose-500/12 text-rose-100 hover:bg-rose-500/18 focus-visible:ring-rose-300/50" : "border border-accent/25 bg-accent/90 text-deep hover:brightness-110 focus-visible:ring-accent/50";
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current && !busy) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "dialog",
          "aria-modal": "true",
          "aria-labelledby": "nova-confirm-title",
          className: "w-full max-w-md overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]"
        },
        /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Skinbase"), /* @__PURE__ */ React.createElement("h3", { id: "nova-confirm-title", className: "mt-2 text-lg font-semibold text-white" }, title)),
        /* @__PURE__ */ React.createElement("div", { className: "px-6 py-5" }, message ? /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, message) : null, children ? /* @__PURE__ */ React.createElement("div", { className: message ? "mt-4" : "" }, children) : null),
        /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement(
          "button",
          {
            ref: cancelButtonRef,
            type: "button",
            onClick: () => onClose?.(),
            disabled: busy,
            className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/20 disabled:cursor-not-allowed disabled:opacity-60"
          },
          cancelLabel
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onConfirm?.(),
            disabled: busy,
            className: `inline-flex items-center justify-center rounded-full px-4 py-2 text-sm font-semibold transition focus-visible:outline-none focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-60 ${confirmClassName}`
          },
          busy ? "Working…" : confirmLabel
        ))
      )
    ),
    document.body
  );
}
function FollowButton({
  username,
  initialFollowing = false,
  initialCount = 0,
  showCount = true,
  className = "",
  followingClassName = "bg-white/[0.04] border border-white/[0.08] text-white/75 hover:bg-white/[0.08]",
  idleClassName = "bg-accent text-deep hover:brightness-110",
  sizeClassName = "px-4 py-2.5 text-sm",
  confirmMessage,
  onChange
}) {
  const [following, setFollowing] = reactExports.useState(Boolean(initialFollowing));
  const [count, setCount] = reactExports.useState(Number(initialCount || 0));
  const [loading, setLoading] = reactExports.useState(false);
  const [confirmOpen, setConfirmOpen] = reactExports.useState(false);
  const [hovered, setHovered] = reactExports.useState(false);
  const csrfToken2 = typeof document !== "undefined" ? document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") : null;
  const persist = async (nextState) => {
    if (!username || loading) return;
    setLoading(true);
    try {
      const response = await fetch(`/api/user/${encodeURIComponent(username)}/follow`, {
        method: nextState ? "POST" : "DELETE",
        headers: {
          Accept: "application/json",
          "X-CSRF-TOKEN": csrfToken2 || ""
        },
        credentials: "same-origin"
      });
      if (!response.ok) throw new Error("Follow request failed");
      const payload = await response.json();
      const nextFollowing = Boolean(payload?.following);
      const nextCount = Number(payload?.followers_count ?? count);
      setFollowing(nextFollowing);
      setCount(nextCount);
      onChange?.({ following: nextFollowing, followersCount: nextCount });
    } catch {
    } finally {
      setLoading(false);
    }
  };
  const onToggle = async () => {
    if (!following) {
      await persist(true);
      return;
    }
    setConfirmOpen(true);
  };
  const toneClassName = following ? followingClassName : idleClassName;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onToggle,
      onMouseEnter: () => setHovered(true),
      onMouseLeave: () => setHovered(false),
      disabled: loading || !username,
      "aria-label": following ? "Unfollow creator" : "Follow creator",
      className: [
        "inline-flex items-center justify-center gap-2 rounded-xl font-semibold transition-all disabled:cursor-not-allowed disabled:opacity-60",
        sizeClassName,
        toneClassName,
        className
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid fa-fw ${loading ? "fa-circle-notch fa-spin" : following ? hovered ? "fa-user-minus" : "fa-user-check" : "fa-user-plus"}` }),
    /* @__PURE__ */ React.createElement("span", null, following ? hovered ? "Unfollow" : "Following" : "Follow"),
    showCount ? /* @__PURE__ */ React.createElement("span", { className: "text-xs opacity-70" }, count.toLocaleString()) : null
  ), /* @__PURE__ */ React.createElement(
    NovaConfirmDialog,
    {
      open: confirmOpen,
      title: "Unfollow creator?",
      message: confirmMessage || `You will stop seeing updates from @${username} in your following feed.`,
      confirmLabel: "Unfollow",
      cancelLabel: "Keep following",
      confirmTone: "danger",
      onConfirm: async () => {
        setConfirmOpen(false);
        await persist(false);
      },
      onClose: () => setConfirmOpen(false)
    }
  ));
}
const AVATAR_FALLBACK$2 = "https://files.skinbase.org/default/missing_sq.webp";
const NUMBER_FORMATTER$1 = new Intl.NumberFormat("en-US");
function formatCount(value) {
  const n = Number(value || 0);
  if (n >= 1e6) return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
  if (n >= 1e3) return `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k`;
  return `${n}`;
}
function toCard(item) {
  return {
    id: item?.id || item?.slug || item?.url,
    title: item?.title,
    author: item?.author,
    authorId: Number(item?.author_id || 0),
    publisherType: item?.publisher_type || "user",
    publisherId: Number(item?.publisher_id || 0),
    url: item?.url,
    thumb: item?.thumb,
    thumbSrcSet: item?.thumb_srcset
  };
}
function CreatorSpotlight({ artwork, presentSq, related = [] }) {
  const publisher = artwork?.publisher || null;
  const isGroupPublisher = publisher?.type === "group";
  const [following, setFollowing] = reactExports.useState(Boolean(isGroupPublisher ? artwork?.viewer?.is_following_group : artwork?.viewer?.is_following_author));
  const [followersCount, setFollowersCount] = reactExports.useState(Number(isGroupPublisher ? publisher?.followers_count || 0 : artwork?.user?.followers_count || 0));
  const user = artwork?.credits?.primary_author || artwork?.user || {};
  const primaryAuthor = artwork?.credits?.primary_author || null;
  const bioAuthor = isGroupPublisher ? primaryAuthor : user;
  const isOwnArtwork = Number(artwork?.viewer?.id || 0) > 0 && Number(artwork?.viewer?.id) === Number(user.id || 0);
  const authorName = isGroupPublisher ? publisher?.name || "Group" : user.name || user.username || "Artist";
  const profileUrl = isGroupPublisher ? publisher?.profile_url || "#" : user.profile_url || (user.username ? `/@${user.username}` : "#");
  const avatar = (isGroupPublisher ? publisher?.avatar_url : user.avatar_url) || presentSq?.url || AVATAR_FALLBACK$2;
  const creatorItems = reactExports.useMemo(() => {
    const currentAuthorId = Number(user?.id || 0);
    const currentPublisherId = Number(publisher?.id || user?.id || 0);
    const filtered = (Array.isArray(related) ? related : []).filter((item) => {
      const notCurrent = item?.url && item.url !== artwork?.canonical_url;
      if (!notCurrent) {
        return false;
      }
      if (isGroupPublisher) {
        return item?.publisher_type === "group" && Number(item?.publisher_id || 0) === currentPublisherId;
      }
      return Number(item?.author_id || 0) === currentAuthorId;
    });
    return filtered.slice(0, 12).map(toCard);
  }, [related, isGroupPublisher, publisher?.id, user?.id, artwork?.canonical_url]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center text-center" }, /* @__PURE__ */ React.createElement("a", { href: profileUrl, className: "group" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: avatar,
      alt: authorName,
      className: "h-16 w-16 rounded-full border-2 border-white/10 object-cover shadow-lg shadow-black/40 transition-transform duration-200 group-hover:scale-105",
      loading: "lazy",
      decoding: "async",
      onError: (event) => {
        event.currentTarget.src = AVATAR_FALLBACK$2;
      }
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "relative mt-3 w-full px-10 text-center" }, /* @__PURE__ */ React.createElement("a", { href: profileUrl, className: "block text-base font-bold text-white transition-colors hover:text-accent" }, authorName), !isGroupPublisher && user.username ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/40" }, "@", user.username) : null, isGroupPublisher && primaryAuthor ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/40" }, "Primary author: ", primaryAuthor.name || primaryAuthor.username) : null, bioAuthor?.username ? /* @__PURE__ */ React.createElement("span", { className: "absolute right-0 top-1/2 -translate-y-1/2" }, /* @__PURE__ */ React.createElement(AuthorBioPopover, { author: bioAuthor })) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs font-medium text-white/30" }, NUMBER_FORMATTER$1.format(followersCount), " Followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex w-full gap-2" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: profileUrl,
      title: "View profile",
      className: "flex flex-1 items-center justify-center gap-1.5 rounded-xl border border-white/[0.08] bg-white/[0.04] px-3 py-2.5 text-sm font-medium text-white/70 transition-all hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" })),
    "Profile"
  ), !isOwnArtwork && !isGroupPublisher ? /* @__PURE__ */ React.createElement(
    FollowButton,
    {
      username: user.username,
      initialFollowing: following,
      initialCount: followersCount,
      showCount: false,
      className: "flex-1",
      onChange: ({ following: nextFollowing, followersCount: nextFollowersCount }) => {
        setFollowing(nextFollowing);
        setFollowersCount(nextFollowersCount);
      }
    }
  ) : null, !isOwnArtwork && isGroupPublisher ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: async () => {
        const method = following ? "DELETE" : "POST";
        const response = await fetch(following ? artwork.publisher?.unfollow_url || `${publisher.profile_url}/follow` : artwork.publisher?.follow_url || `${publisher.profile_url}/follow`, {
          method,
          credentials: "same-origin",
          headers: {
            Accept: "application/json",
            "X-Requested-With": "XMLHttpRequest",
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""
          }
        });
        const payload = await response.json().catch(() => ({}));
        if (response.ok) {
          setFollowing(Boolean(payload?.following));
          setFollowersCount(Number(payload?.followers_count || 0));
        }
      },
      className: `flex-1 rounded-xl border px-3 py-2.5 text-sm font-medium transition ${following ? "border-white/[0.12] bg-white/[0.05] text-white" : "border-sky-300/25 bg-sky-300/10 text-sky-100 hover:border-sky-300/35 hover:bg-sky-300/15"}`
    },
    following ? "Following" : "Follow group"
  ) : null)), creatorItems.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-5 border-t border-white/[0.06] pt-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white/80" }, isGroupPublisher ? "More related works" : `More from ${authorName}`), /* @__PURE__ */ React.createElement("a", { href: profileUrl, "aria-label": isGroupPublisher ? "View more related works" : `View all from ${authorName}`, className: "text-white/30 transition-colors hover:text-white/60" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 2, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "m8.25 4.5 7.5 7.5-7.5 7.5" })))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-2" }, creatorItems.slice(0, 3).map((item, idx) => /* @__PURE__ */ React.createElement("a", { key: `${item.id || item.url}-${idx}`, href: item.url, className: "group/mini relative overflow-hidden rounded-xl" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square overflow-hidden bg-deep" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: item.thumb || AVATAR_FALLBACK$2,
      alt: item.title || "Artwork",
      className: "h-full w-full object-cover transition duration-300 group-hover/mini:scale-[1.06]",
      loading: "lazy",
      decoding: "async"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-1.5 left-1.5 right-1.5 flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-3 w-3 text-rose-400" }, /* @__PURE__ */ React.createElement("path", { d: "m9.653 16.915-.005-.003-.019-.01a20.759 20.759 0 0 1-1.162-.682 22.045 22.045 0 0 1-2.582-1.9C4.045 12.733 2 10.352 2 7.5a4.5 4.5 0 0 1 8-2.828A4.5 4.5 0 0 1 18 7.5c0 2.852-2.044 5.233-3.885 6.82a22.049 22.049 0 0 1-3.744 2.582l-.019.01-.005.003h-.002a.723.723 0 0 1-.69 0h-.002Z" })), /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-bold text-white drop-shadow" }, item.likes ? formatCount(item.likes) : ""))))))));
}
const FALLBACK = "https://files.skinbase.org/default/missing_md.webp";
const AVATAR_FALLBACK$1 = "https://files.skinbase.org/default/avatar_default.webp";
function normalizeRelated(item) {
  if (!item?.url) return null;
  return {
    id: item.id || item.slug || item.url,
    title: item.title || "Untitled",
    author: item.author || "Artist",
    authorAvatar: item.author_avatar || null,
    url: item.url,
    thumb: item.thumb || null,
    thumbSrcSet: item.thumb_srcset || null,
    maturity: item.maturity || null
  };
}
function normalizeSimilar(item) {
  if (!item?.url) return null;
  return {
    id: item.id || item.slug || item.url,
    title: item.title || "Untitled",
    author: item.author || "Artist",
    authorAvatar: item.author_avatar || null,
    url: item.url,
    thumb: item.thumb || null,
    thumbSrcSet: item.thumb_srcset || null,
    maturity: item.maturity || null
  };
}
function normalizeRankItem(item) {
  const url = item?.urls?.direct || item?.urls?.web || item?.url || null;
  if (!url) return null;
  return {
    id: item.id || item.slug || url,
    title: item.title || "Untitled",
    author: item?.author?.name || "Artist",
    authorAvatar: item?.author?.avatar_url || null,
    url,
    thumb: item.thumbnail_url || item.thumb || null,
    thumbSrcSet: null,
    maturity: item.maturity || null
  };
}
function dedupeByUrl(items) {
  const seen = /* @__PURE__ */ new Set();
  return items.filter((item) => {
    if (item?.maturity?.should_hide) return false;
    if (!item?.url || seen.has(item.url)) return false;
    seen.add(item.url);
    return true;
  });
}
function RailCard({ item }) {
  const shouldBlur = Boolean(item?.maturity?.should_blur);
  const isMature = Boolean(item?.maturity?.is_mature_effective);
  return /* @__PURE__ */ React.createElement("article", { className: "w-[240px] shrink-0 snap-start sm:w-[220px] lg:w-[200px] xl:w-[210px] 2xl:w-[220px]" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: item.url,
      className: "group relative block overflow-hidden rounded-2xl ring-1 ring-white/5 bg-black/20 shadow-lg shadow-black/40 transition-all duration-200 ease-out hover:-translate-y-0.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70"
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[4/3] overflow-hidden bg-neutral-900" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-br from-white/10 via-white/5 to-transparent pointer-events-none z-10" }), /* @__PURE__ */ React.createElement(
      "img",
      {
        src: item.thumb || FALLBACK,
        srcSet: item.thumbSrcSet || void 0,
        sizes: "(min-width: 1280px) 210px, (min-width: 640px) 220px, 240px",
        alt: item.title || "Artwork",
        className: `h-full w-full object-cover transition-[transform,filter] duration-300 ease-out group-hover:scale-[1.04] ${shouldBlur ? "scale-[1.02] blur-xl" : ""}`,
        loading: "lazy",
        decoding: "async",
        onError: (e) => {
          e.currentTarget.src = FALLBACK;
        }
      }
    ), isMature ? /* @__PURE__ */ React.createElement("div", { className: "absolute left-3 top-3 z-20 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Mature") : null, shouldBlur ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-3 bottom-3 z-20 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your settings") : null, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 backdrop-blur-[2px] opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100 md:group-focus-visible:opacity-100" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-center gap-2 text-xs text-white/80" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: item.authorAvatar || AVATAR_FALLBACK$1,
        alt: item.author,
        className: "w-5 h-5 rounded-full object-cover shrink-0 ring-1 ring-white/20",
        onError: (e) => {
          e.currentTarget.src = AVATAR_FALLBACK$1;
        }
      }
    ), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.author)))),
    /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, item.title, " by ", item.author)
  ));
}
function ScrollBtn({ direction, onClick, visible }) {
  if (!visible) return null;
  const isLeft = direction === "left";
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick,
      "aria-label": `Scroll ${direction}`,
      className: `absolute top-1/2 z-30 -translate-y-1/2 hidden lg:flex h-10 w-10 items-center justify-center rounded-full bg-black/60 text-white ring-1 ring-white/10 backdrop-blur-md transition hover:bg-black/80 ${isLeft ? "left-2" : "right-2"}`
    },
    /* @__PURE__ */ React.createElement("svg", { className: "w-5 h-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2 }, isLeft ? /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 19l-7-7 7-7" }) : /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M9 5l7 7-7 7" }))
  );
}
function Rail({ title, emoji, items, seeAllHref }) {
  const scrollRef = reactExports.useRef(null);
  const isResettingRef = reactExports.useRef(false);
  const scrollEndTimer = reactExports.useRef(null);
  const suppressClickTimerRef = reactExports.useRef(null);
  const touchStartRef = reactExports.useRef({ x: 0, y: 0 });
  const draggedRef = reactExports.useRef(false);
  const suppressClickRef = reactExports.useRef(false);
  const itemCount = items.length;
  const loopItems = reactExports.useMemo(() => {
    if (!items.length) return [];
    return [...items, ...items, ...items];
  }, [items]);
  const getSetWidth = reactExports.useCallback(() => {
    const el = scrollRef.current;
    if (!el || el.children.length < itemCount + 1) return 0;
    return el.children[itemCount].offsetLeft - el.children[0].offsetLeft;
  }, [itemCount]);
  const getStepWidth = reactExports.useCallback(() => {
    const el = scrollRef.current;
    if (!el || el.children.length < 2) return el ? el.clientWidth * 0.75 : 0;
    return el.children[1].offsetLeft - el.children[0].offsetLeft;
  }, []);
  reactExports.useEffect(() => {
    const el = scrollRef.current;
    if (!el || !itemCount) return;
    requestAnimationFrame(() => {
      const sw = getSetWidth();
      if (sw) {
        el.style.scrollBehavior = "auto";
        el.scrollLeft = sw;
        el.style.scrollBehavior = "";
      }
    });
  }, [loopItems, getSetWidth, itemCount]);
  const resetIfNeeded = reactExports.useCallback(() => {
    if (isResettingRef.current) return;
    const el = scrollRef.current;
    if (!el || !itemCount) return;
    const setW = getSetWidth();
    if (setW === 0) return;
    if (el.scrollLeft < setW) {
      isResettingRef.current = true;
      el.style.scrollBehavior = "auto";
      el.scrollLeft += setW;
      el.style.scrollBehavior = "";
      requestAnimationFrame(() => {
        isResettingRef.current = false;
      });
    } else if (el.scrollLeft >= setW * 2) {
      isResettingRef.current = true;
      el.style.scrollBehavior = "auto";
      el.scrollLeft -= setW;
      el.style.scrollBehavior = "";
      requestAnimationFrame(() => {
        isResettingRef.current = false;
      });
    }
  }, [getSetWidth, itemCount]);
  const normalizeToMiddle = reactExports.useCallback(() => {
    const el = scrollRef.current;
    if (!el || !itemCount) return;
    const setW = getSetWidth();
    if (setW === 0) return;
    if (el.scrollLeft < setW || el.scrollLeft >= setW * 2) {
      el.style.scrollBehavior = "auto";
      el.scrollLeft = (el.scrollLeft % setW + setW) % setW + setW;
      el.style.scrollBehavior = "";
    }
  }, [getSetWidth, itemCount]);
  reactExports.useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => {
      clearTimeout(scrollEndTimer.current);
      scrollEndTimer.current = setTimeout(resetIfNeeded, 80);
    };
    el.addEventListener("scroll", onScroll, { passive: true });
    const onResize = () => {
      const sw = getSetWidth();
      if (sw) {
        el.style.scrollBehavior = "auto";
        el.scrollLeft = sw;
        el.style.scrollBehavior = "";
      }
    };
    window.addEventListener("resize", onResize);
    return () => {
      el.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onResize);
      clearTimeout(scrollEndTimer.current);
      clearTimeout(suppressClickTimerRef.current);
    };
  }, [loopItems, resetIfNeeded, getSetWidth]);
  reactExports.useEffect(() => {
    const el = scrollRef.current;
    if (!el || !loopItems.length) return;
    const onWheel = (e) => {
      if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
        e.preventDefault();
        el.scrollLeft += e.deltaY;
      }
    };
    el.addEventListener("wheel", onWheel, { passive: false });
    return () => el.removeEventListener("wheel", onWheel);
  }, [loopItems]);
  const scroll = reactExports.useCallback((dir) => {
    const el = scrollRef.current;
    if (!el) return;
    normalizeToMiddle();
    const step = getStepWidth();
    const amount = step > 0 ? step * 2 : el.clientWidth * 0.75;
    el.scrollBy({ left: dir === "left" ? -amount : amount, behavior: "smooth" });
    clearTimeout(scrollEndTimer.current);
    scrollEndTimer.current = setTimeout(resetIfNeeded, 260);
  }, [getStepWidth, normalizeToMiddle, resetIfNeeded]);
  const onTouchStart = reactExports.useCallback((e) => {
    if (!e.touches?.length) return;
    const t = e.touches[0];
    touchStartRef.current = { x: t.clientX, y: t.clientY };
    draggedRef.current = false;
  }, []);
  const onTouchMove = reactExports.useCallback((e) => {
    if (!e.touches?.length) return;
    const t = e.touches[0];
    const dx = Math.abs(t.clientX - touchStartRef.current.x);
    const dy = Math.abs(t.clientY - touchStartRef.current.y);
    if (dx > 10 && dx > dy) {
      draggedRef.current = true;
    }
  }, []);
  const onTouchEnd = reactExports.useCallback(() => {
    if (!draggedRef.current) return;
    suppressClickRef.current = true;
    clearTimeout(suppressClickTimerRef.current);
    suppressClickTimerRef.current = setTimeout(() => {
      suppressClickRef.current = false;
    }, 260);
  }, []);
  const onClickCapture = reactExports.useCallback((e) => {
    if (!suppressClickRef.current) return;
    const link2 = e.target?.closest?.("a");
    if (link2) {
      e.preventDefault();
      e.stopPropagation();
    }
  }, []);
  if (!items.length) return null;
  return /* @__PURE__ */ React.createElement("section", null, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, emoji && /* @__PURE__ */ React.createElement("span", { className: "mr-1.5" }, emoji), title), seeAllHref && /* @__PURE__ */ React.createElement("a", { href: seeAllHref, className: "text-sm text-nova-300 hover:text-white transition" }, "See all →")), /* @__PURE__ */ React.createElement("div", { className: "relative", "data-nav-swipe-ignore": "1" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-y-0 left-0 z-20 w-24 bg-gradient-to-r from-[#0F1724] to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-y-0 right-0 z-20 w-24 bg-gradient-to-l from-[#0F1724] to-transparent" }), /* @__PURE__ */ React.createElement(ScrollBtn, { direction: "left", onClick: () => scroll("left"), visible: true }), /* @__PURE__ */ React.createElement(ScrollBtn, { direction: "right", onClick: () => scroll("right"), visible: true }), /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: scrollRef,
      onTouchStart,
      onTouchMove,
      onTouchEnd,
      onClickCapture,
      className: "flex gap-4 overflow-x-auto px-4 pb-3 sm:px-6 lg:px-8 snap-x snap-mandatory scroll-smooth scrollbar-hide [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"
    },
    loopItems.map((item, idx) => /* @__PURE__ */ React.createElement(RailCard, { key: `${item.id || item.url}-${idx}`, item }))
  )));
}
function ArtworkRecommendationsRails({ artwork, related = [], similarApiData = [], trendingData = [] }) {
  const relatedCards = reactExports.useMemo(() => {
    return dedupeByUrl((Array.isArray(related) ? related : []).map(normalizeRelated).filter(Boolean));
  }, [related]);
  const similarApiItems = reactExports.useMemo(() => {
    return dedupeByUrl((Array.isArray(similarApiData) ? similarApiData : []).map(normalizeSimilar).filter(Boolean));
  }, [similarApiData]);
  const trendingItems = reactExports.useMemo(() => {
    return dedupeByUrl((Array.isArray(trendingData) ? trendingData : []).map(normalizeRankItem).filter(Boolean));
  }, [trendingData]);
  const authorName = String(artwork?.user?.name || artwork?.user?.username || "").trim().toLowerCase();
  const tagBasedFallback = reactExports.useMemo(() => {
    return relatedCards.filter((item) => String(item.author || "").trim().toLowerCase() !== authorName);
  }, [relatedCards, authorName]);
  const similarItems = reactExports.useMemo(() => {
    if (similarApiItems.length > 0) return similarApiItems.slice(0, 12);
    if (tagBasedFallback.length > 0) return tagBasedFallback.slice(0, 12);
    return trendingItems.slice(0, 12);
  }, [similarApiItems, tagBasedFallback, trendingItems]);
  const trendingRailItems = reactExports.useMemo(() => trendingItems.slice(0, 12), [trendingItems]);
  if (similarItems.length === 0 && trendingRailItems.length === 0) return null;
  const categoryName = artwork?.categories?.[0]?.name;
  const trendingLabel = categoryName ? `Trending in ${categoryName}` : "Trending on Skinbase";
  const trendingHref = "/discover/trending";
  const similarHref = artwork?.id ? `/art/${artwork.id}/similar` : null;
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-14" }, /* @__PURE__ */ React.createElement(Rail, { title: "Similar Artworks", emoji: "✨", items: similarItems, seeAllHref: similarHref }), /* @__PURE__ */ React.createElement(Rail, { title: trendingLabel, emoji: "🔥", items: trendingRailItems, seeAllHref: trendingHref }));
}
const fallbackCache = /* @__PURE__ */ new Map();
async function fetchFallback(artworkId) {
  const key = String(artworkId);
  if (fallbackCache.has(key)) return fallbackCache.get(key);
  try {
    const res = await fetch(`/api/artworks/navigation/${artworkId}`, {
      headers: { Accept: "application/json" }
    });
    if (!res.ok) return { prevId: null, nextId: null, prevUrl: null, nextUrl: null };
    const data = await res.json();
    const result = {
      prevId: data.prev_id ?? null,
      nextId: data.next_id ?? null,
      prevUrl: data.prev_url ?? null,
      nextUrl: data.next_url ?? null
    };
    fallbackCache.set(key, result);
    return result;
  } catch {
    return { prevId: null, nextId: null, prevUrl: null, nextUrl: null };
  }
}
function useNavContext(currentArtworkId) {
  const getNeighbors = reactExports.useCallback(async () => {
    return fetchFallback(currentArtworkId);
  }, [currentArtworkId]);
  return { getNeighbors };
}
const preloadCache = /* @__PURE__ */ new Set();
function scheduleIdleTask(callback, delay = 1200) {
  if (typeof window === "undefined") {
    callback();
    return () => {
    };
  }
  if (typeof window.requestIdleCallback === "function") {
    const handle2 = window.requestIdleCallback(callback, { timeout: delay });
    return () => window.cancelIdleCallback(handle2);
  }
  const handle = window.setTimeout(callback, delay);
  return () => window.clearTimeout(handle);
}
function preloadImage(src2) {
  if (!src2 || preloadCache.has(src2)) return;
  preloadCache.add(src2);
  const img = new Image();
  img.src = src2;
}
function ArtworkNavigator({ artworkId, onNavigate, onOpenViewer, onReady }) {
  const { getNeighbors } = useNavContext(artworkId);
  const [neighbors, setNeighbors] = reactExports.useState({ prevId: null, nextId: null, prevUrl: null, nextUrl: null });
  const navigatingRef = reactExports.useRef(false);
  const neighborsRef = reactExports.useRef(neighbors);
  const onNavigateRef = reactExports.useRef(onNavigate);
  const onOpenViewerRef = reactExports.useRef(onOpenViewer);
  const onReadyRef = reactExports.useRef(onReady);
  reactExports.useEffect(() => {
    neighborsRef.current = neighbors;
  }, [neighbors]);
  reactExports.useEffect(() => {
    onNavigateRef.current = onNavigate;
  }, [onNavigate]);
  reactExports.useEffect(() => {
    onOpenViewerRef.current = onOpenViewer;
  }, [onOpenViewer]);
  reactExports.useEffect(() => {
    onReadyRef.current = onReady;
  }, [onReady]);
  const touchStartX = reactExports.useRef(null);
  const touchStartY = reactExports.useRef(null);
  const touchIgnoreSwipe = reactExports.useRef(false);
  reactExports.useEffect(() => {
    let cancelled = false;
    getNeighbors().then((n) => {
      if (cancelled) return;
      setNeighbors(n);
    });
    return () => {
      cancelled = true;
    };
  }, [artworkId, getNeighbors]);
  reactExports.useEffect(() => {
    const ids = [neighbors.prevId, neighbors.nextId].filter(Boolean);
    if (ids.length === 0) return void 0;
    let cancelled = false;
    const cancelIdleTask = scheduleIdleTask(() => {
      ids.forEach((id) => {
        fetch(`/api/artworks/${id}/page`, { headers: { Accept: "application/json" } }).then((r) => r.ok ? r.json() : null).then((data) => {
          if (cancelled || !data) return;
          const imgUrl = data.thumbs?.lg?.url || data.thumbs?.md?.url;
          if (imgUrl) preloadImage(imgUrl);
        }).catch(() => {
        });
      });
    });
    return () => {
      cancelled = true;
      cancelIdleTask();
    };
  }, [neighbors.prevId, neighbors.nextId]);
  const navigate = reactExports.useCallback(async (targetId, targetUrl) => {
    if (!targetId && !targetUrl) return;
    if (navigatingRef.current) return;
    const fallbackUrl = targetUrl || `/art/${targetId}`;
    const currentOnNavigate = onNavigateRef.current;
    if (!currentOnNavigate || !targetId) {
      window.location.href = fallbackUrl;
      return;
    }
    navigatingRef.current = true;
    try {
      const res = await fetch(`/api/artworks/${targetId}/page`, {
        headers: { Accept: "application/json" }
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const data = await res.json();
      const canonicalSlug = (data.slug || data.title || String(data.id)).toString().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || String(data.id);
      history.pushState({ artworkId: data.id }, "", `/art/${data.id}/${canonicalSlug}`);
      document.title = `${data.title} | Skinbase`;
      currentOnNavigate(data);
    } catch {
      window.location.href = fallbackUrl;
    } finally {
      navigatingRef.current = false;
    }
  }, []);
  reactExports.useEffect(() => {
    const hasPrev = Boolean(neighbors.prevId || neighbors.prevUrl);
    const hasNext = Boolean(neighbors.nextId || neighbors.nextUrl);
    onReadyRef.current?.({
      hasPrev,
      hasNext,
      navigatePrev: hasPrev ? () => navigate(neighbors.prevId, neighbors.prevUrl) : null,
      navigateNext: hasNext ? () => navigate(neighbors.nextId, neighbors.nextUrl) : null
    });
  }, [neighbors, navigate]);
  reactExports.useEffect(() => {
    function onPop() {
      window.location.reload();
    }
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);
  reactExports.useEffect(() => {
    function onKey(e) {
      const tag = e.target?.tagName?.toLowerCase?.() ?? "";
      if (["input", "textarea", "select"].includes(tag) || e.target?.isContentEditable) return;
      const n = neighborsRef.current;
      if (e.key === "ArrowLeft") {
        e.preventDefault();
        navigate(n.prevId, n.prevUrl);
      } else if (e.key === "ArrowRight") {
        e.preventDefault();
        navigate(n.nextId, n.nextUrl);
      } else if ((e.key === "f" || e.key === "F") && !e.ctrlKey && !e.metaKey) {
        onOpenViewerRef.current?.();
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [navigate]);
  reactExports.useEffect(() => {
    function onTouchStart(e) {
      touchIgnoreSwipe.current = Boolean(e.target?.closest?.('[data-nav-swipe-ignore="1"]'));
      if (touchIgnoreSwipe.current) {
        touchStartX.current = null;
        touchStartY.current = null;
        return;
      }
      touchStartX.current = e.touches[0].clientX;
      touchStartY.current = e.touches[0].clientY;
    }
    function onTouchEnd(e) {
      if (touchIgnoreSwipe.current) {
        touchIgnoreSwipe.current = false;
        return;
      }
      if (touchStartX.current === null) return;
      const dx = e.changedTouches[0].clientX - touchStartX.current;
      const dy = e.changedTouches[0].clientY - touchStartY.current;
      touchStartX.current = null;
      touchStartY.current = null;
      if (Math.abs(dx) > 50 && Math.abs(dy) < 80) {
        const n = neighborsRef.current;
        if (dx > 0) navigate(n.prevId, n.prevUrl);
        else navigate(n.nextId, n.nextUrl);
      }
    }
    window.addEventListener("touchstart", onTouchStart, { passive: true });
    window.addEventListener("touchend", onTouchEnd, { passive: true });
    return () => {
      window.removeEventListener("touchstart", onTouchStart);
      window.removeEventListener("touchend", onTouchEnd);
    };
  }, [navigate]);
  return null;
}
function ArtworkViewer({ isOpen, onClose, artwork, presentLg, presentXl }) {
  const dialogRef = reactExports.useRef(null);
  const imgSrc = presentXl?.url || presentLg?.url || artwork?.thumbs?.xl?.url || artwork?.thumbs?.lg?.url || artwork?.thumb || null;
  reactExports.useEffect(() => {
    if (!isOpen) return;
    function onKey(e) {
      if (e.key === "Escape") onClose();
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [isOpen, onClose]);
  reactExports.useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
      requestAnimationFrame(() => dialogRef.current?.focus());
    } else {
      document.body.style.overflow = "";
    }
    return () => {
      document.body.style.overflow = "";
    };
  }, [isOpen]);
  if (!isOpen || !imgSrc) return null;
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: dialogRef,
      role: "dialog",
      "aria-modal": "true",
      "aria-label": "Fullscreen artwork viewer",
      tabIndex: -1,
      className: "fixed inset-0 z-50 flex items-center justify-center bg-black/90 backdrop-blur-sm outline-none",
      onClick: onClose
    },
    /* @__PURE__ */ React.createElement(
      "button",
      {
        className: "absolute right-4 top-4 z-10 flex h-10 w-10 items-center justify-center rounded-full bg-black/60 text-white/70 ring-1 ring-white/15 transition-colors hover:bg-black/80 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-accent",
        onClick: onClose,
        "aria-label": "Close viewer (Esc)",
        type: "button"
      },
      /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18L18 6M6 6l12 12" }))
    ),
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: imgSrc,
        alt: artwork?.title ?? "Artwork",
        className: "max-h-[90vh] max-w-[90vw] rounded-xl object-contain shadow-2xl shadow-black/60 select-none",
        onClick: (e) => e.stopPropagation(),
        draggable: false,
        loading: "eager",
        decoding: "async"
      }
    ),
    artwork?.title && /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "absolute bottom-5 left-1/2 -translate-x-1/2 max-w-[70vw] truncate rounded-lg bg-black/65 px-4 py-2 text-center text-sm text-white backdrop-blur-sm",
        onClick: (e) => e.stopPropagation()
      },
      artwork.title
    ),
    /* @__PURE__ */ React.createElement("span", { className: "pointer-events-none absolute bottom-5 right-5 text-xs text-white/30 select-none" }, "ESC to close")
  );
}
function cx$7(...parts) {
  return parts.filter(Boolean).join(" ");
}
function formatCompactNumber$3(value) {
  return new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(Number(value || 0));
}
const TONE_CLASSES$1 = {
  sky: "border-sky-300/25 bg-sky-300/10 text-sky-100",
  emerald: "border-emerald-300/25 bg-emerald-300/10 text-emerald-100",
  amber: "border-amber-300/25 bg-amber-300/10 text-amber-100",
  violet: "border-violet-300/25 bg-violet-300/10 text-violet-100",
  slate: "border-white/10 bg-white/[0.04] text-slate-200"
};
function toneClasses$1(tone = "slate") {
  return TONE_CLASSES$1[tone] || TONE_CLASSES$1.slate;
}
function GroupBadgePill({ label, tone = "slate", className = "" }) {
  if (!label) return null;
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${toneClasses$1(tone)} ${className}`.trim() }, label);
}
const NUMBER_FORMATTER = new Intl.NumberFormat("en-US");
function GroupSummaryPanel({ group, artwork }) {
  if (!group) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[28px] border border-white/[0.08] bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_36%),linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.02))] px-5 py-5 shadow-[0_22px_55px_rgba(0,0,0,0.26)] backdrop-blur-xl sm:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public || "/groups", className: "flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-white/[0.04]" }, group.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: group.avatar_url, alt: group.name, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-slate-300" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Published as a group"), /* @__PURE__ */ React.createElement("a", { href: group.urls?.public || "/groups", className: "mt-2 block text-xl font-semibold tracking-[-0.02em] text-white transition hover:text-sky-300" }, group.name), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, group.headline || group.bio_excerpt || `${artwork?.title || "This artwork"} is credited to a collaborative group identity on Skinbase.`))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, (Array.isArray(group.trust_signals) ? group.trust_signals : []).slice(0, 3).map((signal) => /* @__PURE__ */ React.createElement(GroupBadgePill, { key: signal.key, label: signal.label, tone: signal.tone })), group.is_recruiting ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Recruiting", tone: "emerald" }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-3 gap-2 rounded-2xl border border-white/10 bg-black/20 p-3 text-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, NUMBER_FORMATTER.format(Number(group.counts?.artworks || 0))), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, "Artworks")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, NUMBER_FORMATTER.format(Number(group.counts?.members || 0))), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, "Members")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, NUMBER_FORMATTER.format(Number(group.counts?.followers || 0))), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, "Followers"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public || "/groups", className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, "Open group page"), group.urls?.releases ? /* @__PURE__ */ React.createElement("a", { href: group.urls.releases, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Browse releases") : null));
}
function publisherToGroupSummary(publisher) {
  if (!publisher || publisher.type !== "group") return null;
  return {
    id: publisher.id,
    name: publisher.name,
    slug: publisher.slug,
    headline: publisher.headline,
    avatar_url: publisher.avatar_url,
    counts: {
      followers: publisher.followers_count || 0,
      artworks: 0,
      members: 0
    },
    trust_signals: [],
    urls: {
      public: publisher.profile_url,
      follow: publisher.follow_url,
      unfollow: publisher.unfollow_url
    }
  };
}
function ArtworkPage({ artwork: initialArtwork, related: initialRelated, presentMd: initialMd, presentLg: initialLg, presentXl: initialXl, presentSq: initialSq, canonicalUrl: initialCanonical, isAuthenticated = false, comments: initialComments = [], groupSummary: initialGroupSummary = null, reactionTotals: initialReactionTotals = {}, seo = null }) {
  const [viewerOpen, setViewerOpen] = reactExports.useState(false);
  const [showMatureArtwork, setShowMatureArtwork] = reactExports.useState(false);
  const openViewer = reactExports.useCallback(() => setViewerOpen(true), []);
  const closeViewer = reactExports.useCallback(() => setViewerOpen(false), []);
  const [artwork, setArtwork] = reactExports.useState(initialArtwork);
  const [liveStats, setLiveStats] = reactExports.useState(initialArtwork?.stats || {});
  const handleStatsChange = reactExports.useCallback((delta) => {
    setLiveStats((prev) => {
      const next = { ...prev };
      Object.entries(delta).forEach(([key, val]) => {
        next[key] = Math.max(0, (Number(next[key]) || 0) + val);
      });
      return next;
    });
  }, []);
  const [presentMd, setPresentMd] = reactExports.useState(initialMd);
  const [presentLg, setPresentLg] = reactExports.useState(initialLg);
  const [presentXl, setPresentXl] = reactExports.useState(initialXl);
  const [presentSq, setPresentSq] = reactExports.useState(initialSq);
  const [related, setRelated] = reactExports.useState(initialRelated);
  const [comments, setComments] = reactExports.useState(initialComments);
  const [canonicalUrl, setCanonicalUrl] = reactExports.useState(initialCanonical);
  const [groupSummary, setGroupSummary] = reactExports.useState(initialGroupSummary || publisherToGroupSummary(initialArtwork?.publisher));
  const [selectedMediaId, setSelectedMediaId] = reactExports.useState("cover");
  const [similarRecommendations, setSimilarRecommendations] = reactExports.useState([]);
  const [trendingRecommendations, setTrendingRecommendations] = reactExports.useState([]);
  const [navState, setNavState] = reactExports.useState({ hasPrev: false, hasNext: false, navigatePrev: null, navigateNext: null });
  const initialArtworkIdRef = reactExports.useRef(initialArtwork?.id);
  const [reactionTotals, setReactionTotals] = reactExports.useState(initialReactionTotals ?? {});
  reactExports.useEffect(() => {
    if (!artwork?.id) return;
    if (artwork.id === initialArtworkIdRef.current) return;
    axios.get(`/api/artworks/${artwork.id}/reactions`).then(({ data }) => setReactionTotals(data.totals ?? {})).catch(() => setReactionTotals({}));
  }, [artwork?.id]);
  reactExports.useEffect(() => {
    let isCancelled = false;
    const loadSimilarRecommendations = async () => {
      if (!artwork?.id) {
        setSimilarRecommendations([]);
        return;
      }
      try {
        const response = await fetch(`/api/art/${artwork.id}/similar-ai`, { credentials: "same-origin" });
        if (!response.ok) throw new Error("similar fetch failed");
        const payload = await response.json();
        if (!isCancelled) setSimilarRecommendations(payload?.data || []);
      } catch {
        if (!isCancelled) setSimilarRecommendations([]);
      }
    };
    loadSimilarRecommendations();
    return () => {
      isCancelled = true;
    };
  }, [artwork?.id]);
  reactExports.useEffect(() => {
    let isCancelled = false;
    const loadTrendingRecommendations = async () => {
      const categoryId = artwork?.categories?.[0]?.id;
      const endpoints = categoryId ? [`/api/rank/category/${categoryId}?type=trending`, "/api/rank/global?type=trending"] : ["/api/rank/global?type=trending"];
      for (const endpoint of endpoints) {
        try {
          const response = await fetch(endpoint, { credentials: "same-origin" });
          if (!response.ok) continue;
          const payload = await response.json();
          const items = Array.isArray(payload?.data) ? payload.data : [];
          if (items.length > 0) {
            if (!isCancelled) setTrendingRecommendations(items);
            return;
          }
        } catch {
        }
      }
      if (!isCancelled) setTrendingRecommendations([]);
    };
    loadTrendingRecommendations();
    return () => {
      isCancelled = true;
    };
  }, [artwork?.categories]);
  const handleNavigate = reactExports.useCallback((data) => {
    setArtwork(data);
    setLiveStats(data.stats || {});
    setPresentMd(data.thumbs?.md ?? null);
    setPresentLg(data.thumbs?.lg ?? null);
    setPresentXl(data.thumbs?.xl ?? null);
    setPresentSq(data.thumbs?.sq ?? null);
    setRelated([]);
    setComments([]);
    setCanonicalUrl(data.canonical_url ?? window.location.href);
    setGroupSummary(data.group_summary ?? publisherToGroupSummary(data.publisher));
    setSelectedMediaId("cover");
    setSimilarRecommendations([]);
    setTrendingRecommendations([]);
    setViewerOpen(false);
    setShowMatureArtwork(false);
  }, []);
  if (!artwork) return null;
  const requiresInterstitial = Boolean(artwork?.maturity?.requires_interstitial) && !showMatureArtwork;
  const preloadSrcset = [presentMd?.url && `${presentMd.url} 640w`, presentLg?.url && `${presentLg.url} 1280w`, presentXl?.url && `${presentXl.url} 1920w`].filter(Boolean).join(", ");
  const heroImageSizes = "(min-width: 1536px) 1400px, (min-width: 1024px) 92vw, 100vw";
  const heroPreloadHref = presentLg?.url || presentMd?.url || null;
  if (requiresInterstitial) {
    return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("main", { className: "pb-24 pt-8 lg:pb-12 lg:pt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto w-full max-w-3xl px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-amber-300/20 bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.18),transparent_32%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.34)] md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-amber-200/80" }, "Content warning"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, artwork?.maturity?.warning_title || "Mature content warning"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-relaxed text-slate-200/90" }, artwork?.maturity?.warning_message || "This artwork may contain mature material. Continue only if you want to view it."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, "by ", artwork?.publisher?.name || artwork?.user?.name || "Artist")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowMatureArtwork(true),
        className: "inline-flex items-center gap-2 rounded-2xl border border-amber-300/25 bg-amber-400/12 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/18"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-eye" }),
      "Show artwork"
    ), /* @__PURE__ */ React.createElement(
      "a",
      {
        href: artwork?.publisher?.profile_url || "/discover/trending",
        className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }),
      "Leave this page"
    ))))));
  }
  const coverItem = {
    id: "cover",
    label: "Cover art",
    thumbUrl: presentSq?.url || presentMd?.url || presentLg?.url || artwork?.thumbs?.sq?.url || artwork?.thumbs?.md?.url || null,
    mdUrl: presentMd?.url || artwork?.thumbs?.md?.url || null,
    lgUrl: presentLg?.url || artwork?.thumbs?.lg?.url || null,
    xlUrl: presentXl?.url || artwork?.thumbs?.xl?.url || null,
    width: Number(artwork?.dimensions?.width || artwork?.width || 0) || null,
    height: Number(artwork?.dimensions?.height || artwork?.height || 0) || null
  };
  const screenshotItems = Array.isArray(artwork?.screenshots) ? artwork.screenshots.map((item, index2) => ({
    id: item.id || `shot-${index2 + 1}`,
    label: item.label || `Screenshot ${index2 + 1}`,
    thumbUrl: item.thumb_url || item.url || null,
    mdUrl: item.url || item.thumb_url || null,
    lgUrl: item.url || item.thumb_url || null,
    xlUrl: item.url || item.thumb_url || null,
    width: null,
    height: null
  })) : [];
  const mediaItems = [coverItem, ...screenshotItems].filter((item) => Boolean(item.thumbUrl || item.lgUrl || item.xlUrl));
  const selectedMedia = mediaItems.find((item) => item.id === selectedMediaId) || mediaItems[0] || null;
  const initialAwards = artwork?.medals ?? artwork?.awards ?? null;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), heroPreloadHref ? /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement(
    "link",
    {
      "head-key": "artwork-hero-preload",
      rel: "preload",
      as: "image",
      href: heroPreloadHref,
      imagesrcset: preloadSrcset || void 0,
      imagesizes: preloadSrcset ? heroImageSizes : void 0,
      fetchPriority: "high"
    }
  ), presentMd?.url ? /* @__PURE__ */ React.createElement(
    "link",
    {
      "head-key": "artwork-backdrop-preload",
      rel: "preload",
      as: "image",
      href: presentMd.url,
      fetchPriority: "high"
    }
  ) : null) : null, /* @__PURE__ */ React.createElement("main", { className: "pb-24 pt-6 lg:pb-12 lg:pt-8" }, /* @__PURE__ */ React.createElement("div", { id: "artwork-hero-anchor", className: "mx-auto w-full max-w-screen-2xl px-3 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(
    ArtworkHero,
    {
      artwork,
      presentMd: selectedMedia?.mdUrl ? { url: selectedMedia.mdUrl } : presentMd,
      presentLg: selectedMedia?.lgUrl ? { url: selectedMedia.lgUrl } : presentLg,
      presentXl: selectedMedia?.xlUrl ? { url: selectedMedia.xlUrl } : presentXl,
      mediaWidth: selectedMedia?.width ?? null,
      mediaHeight: selectedMedia?.height ?? null,
      mediaKey: selectedMedia?.id || "cover",
      onOpenViewer: openViewer,
      hasPrev: navState.hasPrev,
      hasNext: navState.hasNext,
      onPrev: navState.navigatePrev,
      onNext: navState.navigateNext
    }
  ), /* @__PURE__ */ React.createElement(
    ArtworkMediaStrip,
    {
      items: mediaItems,
      selectedId: selectedMedia?.id || "cover",
      onSelect: setSelectedMediaId
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mx-auto mt-5 w-full max-w-screen-xl px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(
    ArtworkActionBar,
    {
      artwork,
      stats: liveStats,
      canonicalUrl,
      onStatsChange: handleStatsChange
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mx-auto mt-8 w-full max-w-screen-xl px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-8 lg:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("div", { className: "relative z-10 min-w-0 space-y-5" }, /* @__PURE__ */ React.createElement(ArtworkMeta, { artwork }), /* @__PURE__ */ React.createElement(ArtworkDescription, { artwork }), /* @__PURE__ */ React.createElement(ArtworkEvolutionPanel, { evolution: artwork?.evolution }), /* @__PURE__ */ React.createElement("section", { className: "relative z-20 overflow-visible rounded-[28px] border border-white/[0.08] bg-[radial-gradient(circle_at_top_left,rgba(245,158,11,0.14),transparent_42%),linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.02))] px-5 py-5 shadow-[0_22px_55px_rgba(0,0,0,0.26)] backdrop-blur-xl sm:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-accent/80" }, "Artwork Reactions"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.02em] text-white" }, "Make this artwork feel alive"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-white/55" }, "Drop a reaction so other people instantly see whether this piece hits with love, fire, wow, or a quick clap.")), /* @__PURE__ */ React.createElement("div", { className: "sm:shrink-0" }, /* @__PURE__ */ React.createElement(
    ReactionBar,
    {
      entityType: "artwork",
      entityId: artwork.id,
      initialTotals: reactionTotals,
      isLoggedIn: isAuthenticated
    }
  )))), /* @__PURE__ */ React.createElement(ArtworkTags, { artwork }), /* @__PURE__ */ React.createElement(
    ArtworkComments,
    {
      artworkId: artwork.id,
      comments,
      isLoggedIn: isAuthenticated,
      loginUrl: "/login"
    }
  )), /* @__PURE__ */ React.createElement("aside", { className: "space-y-5 lg:sticky lg:top-6 lg:self-start" }, /* @__PURE__ */ React.createElement(CreatorSpotlight, { artwork, presentSq, related }), groupSummary ? /* @__PURE__ */ React.createElement(GroupSummaryPanel, { group: groupSummary, artwork }) : null, /* @__PURE__ */ React.createElement(ArtworkDetailsPanel, { artwork, stats: liveStats }), /* @__PURE__ */ React.createElement(ArtworkAwards, { artwork, initialAwards, isAuthenticated })))), /* @__PURE__ */ React.createElement("div", { className: "mt-14 w-full max-w-screen-2xl mx-auto min-h-[640px]" }, /* @__PURE__ */ React.createElement(
    ArtworkRecommendationsRails,
    {
      artwork,
      related,
      similarApiData: similarRecommendations,
      trendingData: trendingRecommendations
    }
  ))), /* @__PURE__ */ React.createElement(
    ArtworkNavigator,
    {
      artworkId: artwork.id,
      onNavigate: handleNavigate,
      onOpenViewer: openViewer,
      onReady: setNavState
    }
  ), /* @__PURE__ */ React.createElement(
    ArtworkViewer,
    {
      isOpen: viewerOpen,
      onClose: closeViewer,
      artwork,
      presentLg: selectedMedia?.lgUrl ? { url: selectedMedia.lgUrl } : presentLg,
      presentXl: selectedMedia?.xlUrl ? { url: selectedMedia.xlUrl } : presentXl
    }
  ));
}
const __vite_glob_0_39 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ArtworkPage
}, Symbol.toStringTag, { value: "Module" }));
var client = { exports: {} };
var reactDomClient_production = {};
var scheduler = { exports: {} };
var scheduler_production = {};
var hasRequiredScheduler_production;
function requireScheduler_production() {
  if (hasRequiredScheduler_production) return scheduler_production;
  hasRequiredScheduler_production = 1;
  (function(exports$1) {
    function push2(heap, node2) {
      var index2 = heap.length;
      heap.push(node2);
      a: for (; 0 < index2; ) {
        var parentIndex = index2 - 1 >>> 1, parent = heap[parentIndex];
        if (0 < compare(parent, node2))
          heap[parentIndex] = node2, heap[index2] = parent, index2 = parentIndex;
        else break a;
      }
    }
    function peek(heap) {
      return 0 === heap.length ? null : heap[0];
    }
    function pop(heap) {
      if (0 === heap.length) return null;
      var first = heap[0], last = heap.pop();
      if (last !== first) {
        heap[0] = last;
        a: for (var index2 = 0, length = heap.length, halfLength = length >>> 1; index2 < halfLength; ) {
          var leftIndex = 2 * (index2 + 1) - 1, left = heap[leftIndex], rightIndex = leftIndex + 1, right = heap[rightIndex];
          if (0 > compare(left, last))
            rightIndex < length && 0 > compare(right, left) ? (heap[index2] = right, heap[rightIndex] = last, index2 = rightIndex) : (heap[index2] = left, heap[leftIndex] = last, index2 = leftIndex);
          else if (rightIndex < length && 0 > compare(right, last))
            heap[index2] = right, heap[rightIndex] = last, index2 = rightIndex;
          else break a;
        }
      }
      return first;
    }
    function compare(a, b2) {
      var diff = a.sortIndex - b2.sortIndex;
      return 0 !== diff ? diff : a.id - b2.id;
    }
    exports$1.unstable_now = void 0;
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var localPerformance = performance;
      exports$1.unstable_now = function() {
        return localPerformance.now();
      };
    } else {
      var localDate = Date, initialTime = localDate.now();
      exports$1.unstable_now = function() {
        return localDate.now() - initialTime;
      };
    }
    var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, needsPaint = false, localSetTimeout = "function" === typeof setTimeout ? setTimeout : null, localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null, localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null;
    function advanceTimers(currentTime) {
      for (var timer = peek(timerQueue); null !== timer; ) {
        if (null === timer.callback) pop(timerQueue);
        else if (timer.startTime <= currentTime)
          pop(timerQueue), timer.sortIndex = timer.expirationTime, push2(taskQueue, timer);
        else break;
        timer = peek(timerQueue);
      }
    }
    function handleTimeout(currentTime) {
      isHostTimeoutScheduled = false;
      advanceTimers(currentTime);
      if (!isHostCallbackScheduled)
        if (null !== peek(taskQueue))
          isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
        else {
          var firstTimer = peek(timerQueue);
          null !== firstTimer && requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime);
        }
    }
    var isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
    function shouldYieldToHost() {
      return needsPaint ? true : exports$1.unstable_now() - startTime < frameInterval ? false : true;
    }
    function performWorkUntilDeadline() {
      needsPaint = false;
      if (isMessageLoopRunning) {
        var currentTime = exports$1.unstable_now();
        startTime = currentTime;
        var hasMoreWork = true;
        try {
          a: {
            isHostCallbackScheduled = false;
            isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
            isPerformingWork = true;
            var previousPriorityLevel = currentPriorityLevel;
            try {
              b: {
                advanceTimers(currentTime);
                for (currentTask = peek(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                  var callback = currentTask.callback;
                  if ("function" === typeof callback) {
                    currentTask.callback = null;
                    currentPriorityLevel = currentTask.priorityLevel;
                    var continuationCallback = callback(
                      currentTask.expirationTime <= currentTime
                    );
                    currentTime = exports$1.unstable_now();
                    if ("function" === typeof continuationCallback) {
                      currentTask.callback = continuationCallback;
                      advanceTimers(currentTime);
                      hasMoreWork = true;
                      break b;
                    }
                    currentTask === peek(taskQueue) && pop(taskQueue);
                    advanceTimers(currentTime);
                  } else pop(taskQueue);
                  currentTask = peek(taskQueue);
                }
                if (null !== currentTask) hasMoreWork = true;
                else {
                  var firstTimer = peek(timerQueue);
                  null !== firstTimer && requestHostTimeout(
                    handleTimeout,
                    firstTimer.startTime - currentTime
                  );
                  hasMoreWork = false;
                }
              }
              break a;
            } finally {
              currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
            }
            hasMoreWork = void 0;
          }
        } finally {
          hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
        }
      }
    }
    var schedulePerformWorkUntilDeadline;
    if ("function" === typeof localSetImmediate)
      schedulePerformWorkUntilDeadline = function() {
        localSetImmediate(performWorkUntilDeadline);
      };
    else if ("undefined" !== typeof MessageChannel) {
      var channel = new MessageChannel(), port = channel.port2;
      channel.port1.onmessage = performWorkUntilDeadline;
      schedulePerformWorkUntilDeadline = function() {
        port.postMessage(null);
      };
    } else
      schedulePerformWorkUntilDeadline = function() {
        localSetTimeout(performWorkUntilDeadline, 0);
      };
    function requestHostTimeout(callback, ms2) {
      taskTimeoutID = localSetTimeout(function() {
        callback(exports$1.unstable_now());
      }, ms2);
    }
    exports$1.unstable_IdlePriority = 5;
    exports$1.unstable_ImmediatePriority = 1;
    exports$1.unstable_LowPriority = 4;
    exports$1.unstable_NormalPriority = 3;
    exports$1.unstable_Profiling = null;
    exports$1.unstable_UserBlockingPriority = 2;
    exports$1.unstable_cancelCallback = function(task) {
      task.callback = null;
    };
    exports$1.unstable_forceFrameRate = function(fps) {
      0 > fps || 125 < fps ? console.error(
        "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
      ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
    };
    exports$1.unstable_getCurrentPriorityLevel = function() {
      return currentPriorityLevel;
    };
    exports$1.unstable_next = function(eventHandler) {
      switch (currentPriorityLevel) {
        case 1:
        case 2:
        case 3:
          var priorityLevel = 3;
          break;
        default:
          priorityLevel = currentPriorityLevel;
      }
      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = priorityLevel;
      try {
        return eventHandler();
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    };
    exports$1.unstable_requestPaint = function() {
      needsPaint = true;
    };
    exports$1.unstable_runWithPriority = function(priorityLevel, eventHandler) {
      switch (priorityLevel) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          break;
        default:
          priorityLevel = 3;
      }
      var previousPriorityLevel = currentPriorityLevel;
      currentPriorityLevel = priorityLevel;
      try {
        return eventHandler();
      } finally {
        currentPriorityLevel = previousPriorityLevel;
      }
    };
    exports$1.unstable_scheduleCallback = function(priorityLevel, callback, options) {
      var currentTime = exports$1.unstable_now();
      "object" === typeof options && null !== options ? (options = options.delay, options = "number" === typeof options && 0 < options ? currentTime + options : currentTime) : options = currentTime;
      switch (priorityLevel) {
        case 1:
          var timeout = -1;
          break;
        case 2:
          timeout = 250;
          break;
        case 5:
          timeout = 1073741823;
          break;
        case 4:
          timeout = 1e4;
          break;
        default:
          timeout = 5e3;
      }
      timeout = options + timeout;
      priorityLevel = {
        id: taskIdCounter++,
        callback,
        priorityLevel,
        startTime: options,
        expirationTime: timeout,
        sortIndex: -1
      };
      options > currentTime ? (priorityLevel.sortIndex = options, push2(timerQueue, priorityLevel), null === peek(taskQueue) && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options - currentTime))) : (priorityLevel.sortIndex = timeout, push2(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
      return priorityLevel;
    };
    exports$1.unstable_shouldYield = shouldYieldToHost;
    exports$1.unstable_wrapCallback = function(callback) {
      var parentPriorityLevel = currentPriorityLevel;
      return function() {
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = parentPriorityLevel;
        try {
          return callback.apply(this, arguments);
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
    };
  })(scheduler_production);
  return scheduler_production;
}
var scheduler_development = {};
var hasRequiredScheduler_development;
function requireScheduler_development() {
  if (hasRequiredScheduler_development) return scheduler_development;
  hasRequiredScheduler_development = 1;
  (function(exports$1) {
    "production" !== process.env.NODE_ENV && (function() {
      function performWorkUntilDeadline() {
        needsPaint = false;
        if (isMessageLoopRunning) {
          var currentTime = exports$1.unstable_now();
          startTime = currentTime;
          var hasMoreWork = true;
          try {
            a: {
              isHostCallbackScheduled = false;
              isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
              isPerformingWork = true;
              var previousPriorityLevel = currentPriorityLevel;
              try {
                b: {
                  advanceTimers(currentTime);
                  for (currentTask = peek(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                    var callback = currentTask.callback;
                    if ("function" === typeof callback) {
                      currentTask.callback = null;
                      currentPriorityLevel = currentTask.priorityLevel;
                      var continuationCallback = callback(
                        currentTask.expirationTime <= currentTime
                      );
                      currentTime = exports$1.unstable_now();
                      if ("function" === typeof continuationCallback) {
                        currentTask.callback = continuationCallback;
                        advanceTimers(currentTime);
                        hasMoreWork = true;
                        break b;
                      }
                      currentTask === peek(taskQueue) && pop(taskQueue);
                      advanceTimers(currentTime);
                    } else pop(taskQueue);
                    currentTask = peek(taskQueue);
                  }
                  if (null !== currentTask) hasMoreWork = true;
                  else {
                    var firstTimer = peek(timerQueue);
                    null !== firstTimer && requestHostTimeout(
                      handleTimeout,
                      firstTimer.startTime - currentTime
                    );
                    hasMoreWork = false;
                  }
                }
                break a;
              } finally {
                currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
              }
              hasMoreWork = void 0;
            }
          } finally {
            hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
          }
        }
      }
      function push2(heap, node2) {
        var index2 = heap.length;
        heap.push(node2);
        a: for (; 0 < index2; ) {
          var parentIndex = index2 - 1 >>> 1, parent = heap[parentIndex];
          if (0 < compare(parent, node2))
            heap[parentIndex] = node2, heap[index2] = parent, index2 = parentIndex;
          else break a;
        }
      }
      function peek(heap) {
        return 0 === heap.length ? null : heap[0];
      }
      function pop(heap) {
        if (0 === heap.length) return null;
        var first = heap[0], last = heap.pop();
        if (last !== first) {
          heap[0] = last;
          a: for (var index2 = 0, length = heap.length, halfLength = length >>> 1; index2 < halfLength; ) {
            var leftIndex = 2 * (index2 + 1) - 1, left = heap[leftIndex], rightIndex = leftIndex + 1, right = heap[rightIndex];
            if (0 > compare(left, last))
              rightIndex < length && 0 > compare(right, left) ? (heap[index2] = right, heap[rightIndex] = last, index2 = rightIndex) : (heap[index2] = left, heap[leftIndex] = last, index2 = leftIndex);
            else if (rightIndex < length && 0 > compare(right, last))
              heap[index2] = right, heap[rightIndex] = last, index2 = rightIndex;
            else break a;
          }
        }
        return first;
      }
      function compare(a, b2) {
        var diff = a.sortIndex - b2.sortIndex;
        return 0 !== diff ? diff : a.id - b2.id;
      }
      function advanceTimers(currentTime) {
        for (var timer = peek(timerQueue); null !== timer; ) {
          if (null === timer.callback) pop(timerQueue);
          else if (timer.startTime <= currentTime)
            pop(timerQueue), timer.sortIndex = timer.expirationTime, push2(taskQueue, timer);
          else break;
          timer = peek(timerQueue);
        }
      }
      function handleTimeout(currentTime) {
        isHostTimeoutScheduled = false;
        advanceTimers(currentTime);
        if (!isHostCallbackScheduled)
          if (null !== peek(taskQueue))
            isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
          else {
            var firstTimer = peek(timerQueue);
            null !== firstTimer && requestHostTimeout(
              handleTimeout,
              firstTimer.startTime - currentTime
            );
          }
      }
      function shouldYieldToHost() {
        return needsPaint ? true : exports$1.unstable_now() - startTime < frameInterval ? false : true;
      }
      function requestHostTimeout(callback, ms2) {
        taskTimeoutID = localSetTimeout(function() {
          callback(exports$1.unstable_now());
        }, ms2);
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      exports$1.unstable_now = void 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        exports$1.unstable_now = function() {
          return localPerformance.now();
        };
      } else {
        var localDate = Date, initialTime = localDate.now();
        exports$1.unstable_now = function() {
          return localDate.now() - initialTime;
        };
      }
      var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, needsPaint = false, localSetTimeout = "function" === typeof setTimeout ? setTimeout : null, localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null, localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null, isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
      if ("function" === typeof localSetImmediate)
        var schedulePerformWorkUntilDeadline = function() {
          localSetImmediate(performWorkUntilDeadline);
        };
      else if ("undefined" !== typeof MessageChannel) {
        var channel = new MessageChannel(), port = channel.port2;
        channel.port1.onmessage = performWorkUntilDeadline;
        schedulePerformWorkUntilDeadline = function() {
          port.postMessage(null);
        };
      } else
        schedulePerformWorkUntilDeadline = function() {
          localSetTimeout(performWorkUntilDeadline, 0);
        };
      exports$1.unstable_IdlePriority = 5;
      exports$1.unstable_ImmediatePriority = 1;
      exports$1.unstable_LowPriority = 4;
      exports$1.unstable_NormalPriority = 3;
      exports$1.unstable_Profiling = null;
      exports$1.unstable_UserBlockingPriority = 2;
      exports$1.unstable_cancelCallback = function(task) {
        task.callback = null;
      };
      exports$1.unstable_forceFrameRate = function(fps) {
        0 > fps || 125 < fps ? console.error(
          "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
        ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
      };
      exports$1.unstable_getCurrentPriorityLevel = function() {
        return currentPriorityLevel;
      };
      exports$1.unstable_next = function(eventHandler) {
        switch (currentPriorityLevel) {
          case 1:
          case 2:
          case 3:
            var priorityLevel = 3;
            break;
          default:
            priorityLevel = currentPriorityLevel;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports$1.unstable_requestPaint = function() {
        needsPaint = true;
      };
      exports$1.unstable_runWithPriority = function(priorityLevel, eventHandler) {
        switch (priorityLevel) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
            break;
          default:
            priorityLevel = 3;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports$1.unstable_scheduleCallback = function(priorityLevel, callback, options) {
        var currentTime = exports$1.unstable_now();
        "object" === typeof options && null !== options ? (options = options.delay, options = "number" === typeof options && 0 < options ? currentTime + options : currentTime) : options = currentTime;
        switch (priorityLevel) {
          case 1:
            var timeout = -1;
            break;
          case 2:
            timeout = 250;
            break;
          case 5:
            timeout = 1073741823;
            break;
          case 4:
            timeout = 1e4;
            break;
          default:
            timeout = 5e3;
        }
        timeout = options + timeout;
        priorityLevel = {
          id: taskIdCounter++,
          callback,
          priorityLevel,
          startTime: options,
          expirationTime: timeout,
          sortIndex: -1
        };
        options > currentTime ? (priorityLevel.sortIndex = options, push2(timerQueue, priorityLevel), null === peek(taskQueue) && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options - currentTime))) : (priorityLevel.sortIndex = timeout, push2(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
        return priorityLevel;
      };
      exports$1.unstable_shouldYield = shouldYieldToHost;
      exports$1.unstable_wrapCallback = function(callback) {
        var parentPriorityLevel = currentPriorityLevel;
        return function() {
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = parentPriorityLevel;
          try {
            return callback.apply(this, arguments);
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        };
      };
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  })(scheduler_development);
  return scheduler_development;
}
var hasRequiredScheduler;
function requireScheduler() {
  if (hasRequiredScheduler) return scheduler.exports;
  hasRequiredScheduler = 1;
  if (process.env.NODE_ENV === "production") {
    scheduler.exports = requireScheduler_production();
  } else {
    scheduler.exports = requireScheduler_development();
  }
  return scheduler.exports;
}
var hasRequiredReactDomClient_production;
function requireReactDomClient_production() {
  if (hasRequiredReactDomClient_production) return reactDomClient_production;
  hasRequiredReactDomClient_production = 1;
  var Scheduler = requireScheduler(), React2 = requireReact(), ReactDOM = requireReactDom();
  function formatProdErrorMessage(code2) {
    var url = "https://react.dev/errors/" + code2;
    if (1 < arguments.length) {
      url += "?args[]=" + encodeURIComponent(arguments[1]);
      for (var i = 2; i < arguments.length; i++)
        url += "&args[]=" + encodeURIComponent(arguments[i]);
    }
    return "Minified React error #" + code2 + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
  }
  function isValidContainer(node2) {
    return !(!node2 || 1 !== node2.nodeType && 9 !== node2.nodeType && 11 !== node2.nodeType);
  }
  function getNearestMountedFiber(fiber) {
    var node2 = fiber, nearestMounted = fiber;
    if (fiber.alternate) for (; node2.return; ) node2 = node2.return;
    else {
      fiber = node2;
      do
        node2 = fiber, 0 !== (node2.flags & 4098) && (nearestMounted = node2.return), fiber = node2.return;
      while (fiber);
    }
    return 3 === node2.tag ? nearestMounted : null;
  }
  function getSuspenseInstanceFromFiber(fiber) {
    if (13 === fiber.tag) {
      var suspenseState = fiber.memoizedState;
      null === suspenseState && (fiber = fiber.alternate, null !== fiber && (suspenseState = fiber.memoizedState));
      if (null !== suspenseState) return suspenseState.dehydrated;
    }
    return null;
  }
  function getActivityInstanceFromFiber(fiber) {
    if (31 === fiber.tag) {
      var activityState = fiber.memoizedState;
      null === activityState && (fiber = fiber.alternate, null !== fiber && (activityState = fiber.memoizedState));
      if (null !== activityState) return activityState.dehydrated;
    }
    return null;
  }
  function assertIsMounted(fiber) {
    if (getNearestMountedFiber(fiber) !== fiber)
      throw Error(formatProdErrorMessage(188));
  }
  function findCurrentFiberUsingSlowPath(fiber) {
    var alternate = fiber.alternate;
    if (!alternate) {
      alternate = getNearestMountedFiber(fiber);
      if (null === alternate) throw Error(formatProdErrorMessage(188));
      return alternate !== fiber ? null : fiber;
    }
    for (var a = fiber, b2 = alternate; ; ) {
      var parentA = a.return;
      if (null === parentA) break;
      var parentB = parentA.alternate;
      if (null === parentB) {
        b2 = parentA.return;
        if (null !== b2) {
          a = b2;
          continue;
        }
        break;
      }
      if (parentA.child === parentB.child) {
        for (parentB = parentA.child; parentB; ) {
          if (parentB === a) return assertIsMounted(parentA), fiber;
          if (parentB === b2) return assertIsMounted(parentA), alternate;
          parentB = parentB.sibling;
        }
        throw Error(formatProdErrorMessage(188));
      }
      if (a.return !== b2.return) a = parentA, b2 = parentB;
      else {
        for (var didFindChild = false, child$0 = parentA.child; child$0; ) {
          if (child$0 === a) {
            didFindChild = true;
            a = parentA;
            b2 = parentB;
            break;
          }
          if (child$0 === b2) {
            didFindChild = true;
            b2 = parentA;
            a = parentB;
            break;
          }
          child$0 = child$0.sibling;
        }
        if (!didFindChild) {
          for (child$0 = parentB.child; child$0; ) {
            if (child$0 === a) {
              didFindChild = true;
              a = parentB;
              b2 = parentA;
              break;
            }
            if (child$0 === b2) {
              didFindChild = true;
              b2 = parentB;
              a = parentA;
              break;
            }
            child$0 = child$0.sibling;
          }
          if (!didFindChild) throw Error(formatProdErrorMessage(189));
        }
      }
      if (a.alternate !== b2) throw Error(formatProdErrorMessage(190));
    }
    if (3 !== a.tag) throw Error(formatProdErrorMessage(188));
    return a.stateNode.current === a ? fiber : alternate;
  }
  function findCurrentHostFiberImpl(node2) {
    var tag = node2.tag;
    if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node2;
    for (node2 = node2.child; null !== node2; ) {
      tag = findCurrentHostFiberImpl(node2);
      if (null !== tag) return tag;
      node2 = node2.sibling;
    }
    return null;
  }
  var assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.element"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
  var REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity");
  var REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel");
  var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  function getIteratorFn(maybeIterable) {
    if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
    maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
    return "function" === typeof maybeIterable ? maybeIterable : null;
  }
  var REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference");
  function getComponentNameFromType(type2) {
    if (null == type2) return null;
    if ("function" === typeof type2)
      return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
    if ("string" === typeof type2) return type2;
    switch (type2) {
      case REACT_FRAGMENT_TYPE:
        return "Fragment";
      case REACT_PROFILER_TYPE:
        return "Profiler";
      case REACT_STRICT_MODE_TYPE:
        return "StrictMode";
      case REACT_SUSPENSE_TYPE:
        return "Suspense";
      case REACT_SUSPENSE_LIST_TYPE:
        return "SuspenseList";
      case REACT_ACTIVITY_TYPE:
        return "Activity";
    }
    if ("object" === typeof type2)
      switch (type2.$$typeof) {
        case REACT_PORTAL_TYPE:
          return "Portal";
        case REACT_CONTEXT_TYPE:
          return type2.displayName || "Context";
        case REACT_CONSUMER_TYPE:
          return (type2._context.displayName || "Context") + ".Consumer";
        case REACT_FORWARD_REF_TYPE:
          var innerType = type2.render;
          type2 = type2.displayName;
          type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
          return type2;
        case REACT_MEMO_TYPE:
          return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
        case REACT_LAZY_TYPE:
          innerType = type2._payload;
          type2 = type2._init;
          try {
            return getComponentNameFromType(type2(innerType));
          } catch (x2) {
          }
      }
    return null;
  }
  var isArrayImpl = Array.isArray, ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, sharedNotPendingObject = {
    pending: false,
    data: null,
    method: null,
    action: null
  }, valueStack = [], index2 = -1;
  function createCursor(defaultValue) {
    return { current: defaultValue };
  }
  function pop(cursor) {
    0 > index2 || (cursor.current = valueStack[index2], valueStack[index2] = null, index2--);
  }
  function push2(cursor, value) {
    index2++;
    valueStack[index2] = cursor.current;
    cursor.current = value;
  }
  var contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null);
  function pushHostContainer(fiber, nextRootInstance) {
    push2(rootInstanceStackCursor, nextRootInstance);
    push2(contextFiberStackCursor, fiber);
    push2(contextStackCursor, null);
    switch (nextRootInstance.nodeType) {
      case 9:
      case 11:
        fiber = (fiber = nextRootInstance.documentElement) ? (fiber = fiber.namespaceURI) ? getOwnHostContext(fiber) : 0 : 0;
        break;
      default:
        if (fiber = nextRootInstance.tagName, nextRootInstance = nextRootInstance.namespaceURI)
          nextRootInstance = getOwnHostContext(nextRootInstance), fiber = getChildHostContextProd(nextRootInstance, fiber);
        else
          switch (fiber) {
            case "svg":
              fiber = 1;
              break;
            case "math":
              fiber = 2;
              break;
            default:
              fiber = 0;
          }
    }
    pop(contextStackCursor);
    push2(contextStackCursor, fiber);
  }
  function popHostContainer() {
    pop(contextStackCursor);
    pop(contextFiberStackCursor);
    pop(rootInstanceStackCursor);
  }
  function pushHostContext(fiber) {
    null !== fiber.memoizedState && push2(hostTransitionProviderCursor, fiber);
    var context = contextStackCursor.current;
    var JSCompiler_inline_result = getChildHostContextProd(context, fiber.type);
    context !== JSCompiler_inline_result && (push2(contextFiberStackCursor, fiber), push2(contextStackCursor, JSCompiler_inline_result));
  }
  function popHostContext(fiber) {
    contextFiberStackCursor.current === fiber && (pop(contextStackCursor), pop(contextFiberStackCursor));
    hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor), HostTransitionContext._currentValue = sharedNotPendingObject);
  }
  var prefix, suffix;
  function describeBuiltInComponentFrame(name2) {
    if (void 0 === prefix)
      try {
        throw Error();
      } catch (x2) {
        var match = x2.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || "";
        suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
      }
    return "\n" + prefix + name2 + suffix;
  }
  var reentry = false;
  function describeNativeComponentFrame(fn, construct) {
    if (!fn || reentry) return "";
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace;
    Error.prepareStackTrace = void 0;
    try {
      var RunInRootFrame = {
        DetermineComponentFrameRoot: function() {
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if ("object" === typeof Reflect && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  var control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x$1) {
                  control = x$1;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x$2) {
                control = x$2;
              }
              (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
              });
            }
          } catch (sample) {
            if (sample && control && "string" === typeof sample.stack)
              return [sample.stack, control.stack];
          }
          return [null, null];
        }
      };
      RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
      var namePropDescriptor = Object.getOwnPropertyDescriptor(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name"
      );
      namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name",
        { value: "DetermineComponentFrameRoot" }
      );
      var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
      if (sampleStack && controlStack) {
        var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
        for (namePropDescriptor = RunInRootFrame = 0; RunInRootFrame < sampleLines.length && !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); )
          RunInRootFrame++;
        for (; namePropDescriptor < controlLines.length && !controlLines[namePropDescriptor].includes(
          "DetermineComponentFrameRoot"
        ); )
          namePropDescriptor++;
        if (RunInRootFrame === sampleLines.length || namePropDescriptor === controlLines.length)
          for (RunInRootFrame = sampleLines.length - 1, namePropDescriptor = controlLines.length - 1; 1 <= RunInRootFrame && 0 <= namePropDescriptor && sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; )
            namePropDescriptor--;
        for (; 1 <= RunInRootFrame && 0 <= namePropDescriptor; RunInRootFrame--, namePropDescriptor--)
          if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
            if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
              do
                if (RunInRootFrame--, namePropDescriptor--, 0 > namePropDescriptor || sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
                  var frame = "\n" + sampleLines[RunInRootFrame].replace(" at new ", " at ");
                  fn.displayName && frame.includes("<anonymous>") && (frame = frame.replace("<anonymous>", fn.displayName));
                  return frame;
                }
              while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
            }
            break;
          }
      }
    } finally {
      reentry = false, Error.prepareStackTrace = previousPrepareStackTrace;
    }
    return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(previousPrepareStackTrace) : "";
  }
  function describeFiber(fiber, childFiber) {
    switch (fiber.tag) {
      case 26:
      case 27:
      case 5:
        return describeBuiltInComponentFrame(fiber.type);
      case 16:
        return describeBuiltInComponentFrame("Lazy");
      case 13:
        return fiber.child !== childFiber && null !== childFiber ? describeBuiltInComponentFrame("Suspense Fallback") : describeBuiltInComponentFrame("Suspense");
      case 19:
        return describeBuiltInComponentFrame("SuspenseList");
      case 0:
      case 15:
        return describeNativeComponentFrame(fiber.type, false);
      case 11:
        return describeNativeComponentFrame(fiber.type.render, false);
      case 1:
        return describeNativeComponentFrame(fiber.type, true);
      case 31:
        return describeBuiltInComponentFrame("Activity");
      default:
        return "";
    }
  }
  function getStackByFiberInDevAndProd(workInProgress2) {
    try {
      var info = "", previous2 = null;
      do
        info += describeFiber(workInProgress2, previous2), previous2 = workInProgress2, workInProgress2 = workInProgress2.return;
      while (workInProgress2);
      return info;
    } catch (x2) {
      return "\nError generating stack: " + x2.message + "\n" + x2.stack;
    }
  }
  var hasOwnProperty2 = Object.prototype.hasOwnProperty, scheduleCallback$3 = Scheduler.unstable_scheduleCallback, cancelCallback$1 = Scheduler.unstable_cancelCallback, shouldYield = Scheduler.unstable_shouldYield, requestPaint = Scheduler.unstable_requestPaint, now = Scheduler.unstable_now, getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel, ImmediatePriority = Scheduler.unstable_ImmediatePriority, UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler.unstable_NormalPriority, LowPriority = Scheduler.unstable_LowPriority, IdlePriority = Scheduler.unstable_IdlePriority, log$1 = Scheduler.log, unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue, rendererID = null, injectedHook = null;
  function setIsStrictModeForDevtools(newIsStrictMode) {
    "function" === typeof log$1 && unstable_setDisableYieldValue(newIsStrictMode);
    if (injectedHook && "function" === typeof injectedHook.setStrictMode)
      try {
        injectedHook.setStrictMode(rendererID, newIsStrictMode);
      } catch (err) {
      }
  }
  var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2;
  function clz32Fallback(x2) {
    x2 >>>= 0;
    return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
  }
  var nextTransitionUpdateLane = 256, nextTransitionDeferredLane = 262144, nextRetryLane = 4194304;
  function getHighestPriorityLanes(lanes) {
    var pendingSyncLanes = lanes & 42;
    if (0 !== pendingSyncLanes) return pendingSyncLanes;
    switch (lanes & -lanes) {
      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:
        return 64;
      case 128:
        return 128;
      case 256:
      case 512:
      case 1024:
      case 2048:
      case 4096:
      case 8192:
      case 16384:
      case 32768:
      case 65536:
      case 131072:
        return lanes & 261888;
      case 262144:
      case 524288:
      case 1048576:
      case 2097152:
        return lanes & 3932160;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
        return lanes & 62914560;
      case 67108864:
        return 67108864;
      case 134217728:
        return 134217728;
      case 268435456:
        return 268435456;
      case 536870912:
        return 536870912;
      case 1073741824:
        return 0;
      default:
        return lanes;
    }
  }
  function getNextLanes(root3, wipLanes, rootHasPendingCommit) {
    var pendingLanes = root3.pendingLanes;
    if (0 === pendingLanes) return 0;
    var nextLanes = 0, suspendedLanes = root3.suspendedLanes, pingedLanes = root3.pingedLanes;
    root3 = root3.warmLanes;
    var nonIdlePendingLanes = pendingLanes & 134217727;
    0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root3, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root3, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
    return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
  }
  function checkIfRootIsPrerendering(root3, renderLanes2) {
    return 0 === (root3.pendingLanes & ~(root3.suspendedLanes & ~root3.pingedLanes) & renderLanes2);
  }
  function computeExpirationTime(lane, currentTime) {
    switch (lane) {
      case 1:
      case 2:
      case 4:
      case 8:
      case 64:
        return currentTime + 250;
      case 16:
      case 32:
      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 currentTime + 5e3;
      case 4194304:
      case 8388608:
      case 16777216:
      case 33554432:
        return -1;
      case 67108864:
      case 134217728:
      case 268435456:
      case 536870912:
      case 1073741824:
        return -1;
      default:
        return -1;
    }
  }
  function claimNextRetryLane() {
    var lane = nextRetryLane;
    nextRetryLane <<= 1;
    0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
    return lane;
  }
  function createLaneMap(initial) {
    for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
    return laneMap;
  }
  function markRootUpdated$1(root3, updateLane) {
    root3.pendingLanes |= updateLane;
    268435456 !== updateLane && (root3.suspendedLanes = 0, root3.pingedLanes = 0, root3.warmLanes = 0);
  }
  function markRootFinished(root3, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
    var previouslyPendingLanes = root3.pendingLanes;
    root3.pendingLanes = remainingLanes;
    root3.suspendedLanes = 0;
    root3.pingedLanes = 0;
    root3.warmLanes = 0;
    root3.expiredLanes &= remainingLanes;
    root3.entangledLanes &= remainingLanes;
    root3.errorRecoveryDisabledLanes &= remainingLanes;
    root3.shellSuspendCounter = 0;
    var entanglements = root3.entanglements, expirationTimes = root3.expirationTimes, hiddenUpdates = root3.hiddenUpdates;
    for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
      var index$7 = 31 - clz32(remainingLanes), lane = 1 << index$7;
      entanglements[index$7] = 0;
      expirationTimes[index$7] = -1;
      var hiddenUpdatesForLane = hiddenUpdates[index$7];
      if (null !== hiddenUpdatesForLane)
        for (hiddenUpdates[index$7] = null, index$7 = 0; index$7 < hiddenUpdatesForLane.length; index$7++) {
          var update = hiddenUpdatesForLane[index$7];
          null !== update && (update.lane &= -536870913);
        }
      remainingLanes &= ~lane;
    }
    0 !== spawnedLane && markSpawnedDeferredLane(root3, spawnedLane, 0);
    0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root3.tag && (root3.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
  }
  function markSpawnedDeferredLane(root3, spawnedLane, entangledLanes) {
    root3.pendingLanes |= spawnedLane;
    root3.suspendedLanes &= ~spawnedLane;
    var spawnedLaneIndex = 31 - clz32(spawnedLane);
    root3.entangledLanes |= spawnedLane;
    root3.entanglements[spawnedLaneIndex] = root3.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 261930;
  }
  function markRootEntangled(root3, entangledLanes) {
    var rootEntangledLanes = root3.entangledLanes |= entangledLanes;
    for (root3 = root3.entanglements; rootEntangledLanes; ) {
      var index$8 = 31 - clz32(rootEntangledLanes), lane = 1 << index$8;
      lane & entangledLanes | root3[index$8] & entangledLanes && (root3[index$8] |= entangledLanes);
      rootEntangledLanes &= ~lane;
    }
  }
  function getBumpedLaneForHydration(root3, renderLanes2) {
    var renderLane = renderLanes2 & -renderLanes2;
    renderLane = 0 !== (renderLane & 42) ? 1 : getBumpedLaneForHydrationByLane(renderLane);
    return 0 !== (renderLane & (root3.suspendedLanes | renderLanes2)) ? 0 : renderLane;
  }
  function getBumpedLaneForHydrationByLane(lane) {
    switch (lane) {
      case 2:
        lane = 1;
        break;
      case 8:
        lane = 4;
        break;
      case 32:
        lane = 16;
        break;
      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:
        lane = 128;
        break;
      case 268435456:
        lane = 134217728;
        break;
      default:
        lane = 0;
    }
    return lane;
  }
  function lanesToEventPriority(lanes) {
    lanes &= -lanes;
    return 2 < lanes ? 8 < lanes ? 0 !== (lanes & 134217727) ? 32 : 268435456 : 8 : 2;
  }
  function resolveUpdatePriority() {
    var updatePriority = ReactDOMSharedInternals.p;
    if (0 !== updatePriority) return updatePriority;
    updatePriority = window.event;
    return void 0 === updatePriority ? 32 : getEventPriority(updatePriority.type);
  }
  function runWithPriority(priority, fn) {
    var previousPriority = ReactDOMSharedInternals.p;
    try {
      return ReactDOMSharedInternals.p = priority, fn();
    } finally {
      ReactDOMSharedInternals.p = previousPriority;
    }
  }
  var randomKey = Math.random().toString(36).slice(2), internalInstanceKey = "__reactFiber$" + randomKey, internalPropsKey = "__reactProps$" + randomKey, internalContainerInstanceKey = "__reactContainer$" + randomKey, internalEventHandlersKey = "__reactEvents$" + randomKey, internalEventHandlerListenersKey = "__reactListeners$" + randomKey, internalEventHandlesSetKey = "__reactHandles$" + randomKey, internalRootNodeResourcesKey = "__reactResources$" + randomKey, internalHoistableMarker = "__reactMarker$" + randomKey;
  function detachDeletedInstance(node2) {
    delete node2[internalInstanceKey];
    delete node2[internalPropsKey];
    delete node2[internalEventHandlersKey];
    delete node2[internalEventHandlerListenersKey];
    delete node2[internalEventHandlesSetKey];
  }
  function getClosestInstanceFromNode(targetNode) {
    var targetInst = targetNode[internalInstanceKey];
    if (targetInst) return targetInst;
    for (var parentNode = targetNode.parentNode; parentNode; ) {
      if (targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]) {
        parentNode = targetInst.alternate;
        if (null !== targetInst.child || null !== parentNode && null !== parentNode.child)
          for (targetNode = getParentHydrationBoundary(targetNode); null !== targetNode; ) {
            if (parentNode = targetNode[internalInstanceKey]) return parentNode;
            targetNode = getParentHydrationBoundary(targetNode);
          }
        return targetInst;
      }
      targetNode = parentNode;
      parentNode = targetNode.parentNode;
    }
    return null;
  }
  function getInstanceFromNode(node2) {
    if (node2 = node2[internalInstanceKey] || node2[internalContainerInstanceKey]) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag || 13 === tag || 31 === tag || 26 === tag || 27 === tag || 3 === tag)
        return node2;
    }
    return null;
  }
  function getNodeFromInstance(inst) {
    var tag = inst.tag;
    if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return inst.stateNode;
    throw Error(formatProdErrorMessage(33));
  }
  function getResourcesFromRoot(root3) {
    var resources = root3[internalRootNodeResourcesKey];
    resources || (resources = root3[internalRootNodeResourcesKey] = { hoistableStyles: /* @__PURE__ */ new Map(), hoistableScripts: /* @__PURE__ */ new Map() });
    return resources;
  }
  function markNodeAsHoistable(node2) {
    node2[internalHoistableMarker] = true;
  }
  var allNativeEvents = /* @__PURE__ */ new Set(), registrationNameDependencies = {};
  function registerTwoPhaseEvent(registrationName, dependencies) {
    registerDirectEvent(registrationName, dependencies);
    registerDirectEvent(registrationName + "Capture", dependencies);
  }
  function registerDirectEvent(registrationName, dependencies) {
    registrationNameDependencies[registrationName] = dependencies;
    for (registrationName = 0; registrationName < dependencies.length; registrationName++)
      allNativeEvents.add(dependencies[registrationName]);
  }
  var VALID_ATTRIBUTE_NAME_REGEX = RegExp(
    "^[: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]*$"
  ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {};
  function isAttributeNameSafe(attributeName) {
    if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
      return true;
    if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName)) return false;
    if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
      return validatedAttributeNameCache[attributeName] = true;
    illegalAttributeNameCache[attributeName] = true;
    return false;
  }
  function setValueForAttribute(node2, name2, value) {
    if (isAttributeNameSafe(name2))
      if (null === value) node2.removeAttribute(name2);
      else {
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
            node2.removeAttribute(name2);
            return;
          case "boolean":
            var prefix$10 = name2.toLowerCase().slice(0, 5);
            if ("data-" !== prefix$10 && "aria-" !== prefix$10) {
              node2.removeAttribute(name2);
              return;
            }
        }
        node2.setAttribute(name2, "" + value);
      }
  }
  function setValueForKnownAttribute(node2, name2, value) {
    if (null === value) node2.removeAttribute(name2);
    else {
      switch (typeof value) {
        case "undefined":
        case "function":
        case "symbol":
        case "boolean":
          node2.removeAttribute(name2);
          return;
      }
      node2.setAttribute(name2, "" + value);
    }
  }
  function setValueForNamespacedAttribute(node2, namespace, name2, value) {
    if (null === value) node2.removeAttribute(name2);
    else {
      switch (typeof value) {
        case "undefined":
        case "function":
        case "symbol":
        case "boolean":
          node2.removeAttribute(name2);
          return;
      }
      node2.setAttributeNS(namespace, name2, "" + value);
    }
  }
  function getToStringValue(value) {
    switch (typeof value) {
      case "bigint":
      case "boolean":
      case "number":
      case "string":
      case "undefined":
        return value;
      case "object":
        return value;
      default:
        return "";
    }
  }
  function isCheckable(elem) {
    var type2 = elem.type;
    return (elem = elem.nodeName) && "input" === elem.toLowerCase() && ("checkbox" === type2 || "radio" === type2);
  }
  function trackValueOnNode(node2, valueField, currentValue) {
    var descriptor = Object.getOwnPropertyDescriptor(
      node2.constructor.prototype,
      valueField
    );
    if (!node2.hasOwnProperty(valueField) && "undefined" !== typeof descriptor && "function" === typeof descriptor.get && "function" === typeof descriptor.set) {
      var get2 = descriptor.get, set = descriptor.set;
      Object.defineProperty(node2, valueField, {
        configurable: true,
        get: function() {
          return get2.call(this);
        },
        set: function(value) {
          currentValue = "" + value;
          set.call(this, value);
        }
      });
      Object.defineProperty(node2, valueField, {
        enumerable: descriptor.enumerable
      });
      return {
        getValue: function() {
          return currentValue;
        },
        setValue: function(value) {
          currentValue = "" + value;
        },
        stopTracking: function() {
          node2._valueTracker = null;
          delete node2[valueField];
        }
      };
    }
  }
  function track(node2) {
    if (!node2._valueTracker) {
      var valueField = isCheckable(node2) ? "checked" : "value";
      node2._valueTracker = trackValueOnNode(
        node2,
        valueField,
        "" + node2[valueField]
      );
    }
  }
  function updateValueIfChanged(node2) {
    if (!node2) return false;
    var tracker = node2._valueTracker;
    if (!tracker) return true;
    var lastValue = tracker.getValue();
    var value = "";
    node2 && (value = isCheckable(node2) ? node2.checked ? "true" : "false" : node2.value);
    node2 = value;
    return node2 !== lastValue ? (tracker.setValue(node2), true) : false;
  }
  function getActiveElement(doc) {
    doc = doc || ("undefined" !== typeof document ? document : void 0);
    if ("undefined" === typeof doc) return null;
    try {
      return doc.activeElement || doc.body;
    } catch (e) {
      return doc.body;
    }
  }
  var escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n"\\]/g;
  function escapeSelectorAttributeValueInsideDoubleQuotes(value) {
    return value.replace(
      escapeSelectorAttributeValueInsideDoubleQuotesRegex,
      function(ch) {
        return "\\" + ch.charCodeAt(0).toString(16) + " ";
      }
    );
  }
  function updateInput(element2, value, defaultValue, lastDefaultValue, checked, defaultChecked, type2, name2) {
    element2.name = "";
    null != type2 && "function" !== typeof type2 && "symbol" !== typeof type2 && "boolean" !== typeof type2 ? element2.type = type2 : element2.removeAttribute("type");
    if (null != value)
      if ("number" === type2) {
        if (0 === value && "" === element2.value || element2.value != value)
          element2.value = "" + getToStringValue(value);
      } else
        element2.value !== "" + getToStringValue(value) && (element2.value = "" + getToStringValue(value));
    else
      "submit" !== type2 && "reset" !== type2 || element2.removeAttribute("value");
    null != value ? setDefaultValue(element2, type2, getToStringValue(value)) : null != defaultValue ? setDefaultValue(element2, type2, getToStringValue(defaultValue)) : null != lastDefaultValue && element2.removeAttribute("value");
    null == checked && null != defaultChecked && (element2.defaultChecked = !!defaultChecked);
    null != checked && (element2.checked = checked && "function" !== typeof checked && "symbol" !== typeof checked);
    null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 ? element2.name = "" + getToStringValue(name2) : element2.removeAttribute("name");
  }
  function initInput(element2, value, defaultValue, checked, defaultChecked, type2, name2, isHydrating2) {
    null != type2 && "function" !== typeof type2 && "symbol" !== typeof type2 && "boolean" !== typeof type2 && (element2.type = type2);
    if (null != value || null != defaultValue) {
      if (!("submit" !== type2 && "reset" !== type2 || void 0 !== value && null !== value)) {
        track(element2);
        return;
      }
      defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
      value = null != value ? "" + getToStringValue(value) : defaultValue;
      isHydrating2 || value === element2.value || (element2.value = value);
      element2.defaultValue = value;
    }
    checked = null != checked ? checked : defaultChecked;
    checked = "function" !== typeof checked && "symbol" !== typeof checked && !!checked;
    element2.checked = isHydrating2 ? element2.checked : !!checked;
    element2.defaultChecked = !!checked;
    null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 && (element2.name = name2);
    track(element2);
  }
  function setDefaultValue(node2, type2, value) {
    "number" === type2 && getActiveElement(node2.ownerDocument) === node2 || node2.defaultValue === "" + value || (node2.defaultValue = "" + value);
  }
  function updateOptions(node2, multiple, propValue, setDefaultSelected) {
    node2 = node2.options;
    if (multiple) {
      multiple = {};
      for (var i = 0; i < propValue.length; i++)
        multiple["$" + propValue[i]] = true;
      for (propValue = 0; propValue < node2.length; propValue++)
        i = multiple.hasOwnProperty("$" + node2[propValue].value), node2[propValue].selected !== i && (node2[propValue].selected = i), i && setDefaultSelected && (node2[propValue].defaultSelected = true);
    } else {
      propValue = "" + getToStringValue(propValue);
      multiple = null;
      for (i = 0; i < node2.length; i++) {
        if (node2[i].value === propValue) {
          node2[i].selected = true;
          setDefaultSelected && (node2[i].defaultSelected = true);
          return;
        }
        null !== multiple || node2[i].disabled || (multiple = node2[i]);
      }
      null !== multiple && (multiple.selected = true);
    }
  }
  function updateTextarea(element2, value, defaultValue) {
    if (null != value && (value = "" + getToStringValue(value), value !== element2.value && (element2.value = value), null == defaultValue)) {
      element2.defaultValue !== value && (element2.defaultValue = value);
      return;
    }
    element2.defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
  }
  function initTextarea(element2, value, defaultValue, children) {
    if (null == value) {
      if (null != children) {
        if (null != defaultValue) throw Error(formatProdErrorMessage(92));
        if (isArrayImpl(children)) {
          if (1 < children.length) throw Error(formatProdErrorMessage(93));
          children = children[0];
        }
        defaultValue = children;
      }
      null == defaultValue && (defaultValue = "");
      value = defaultValue;
    }
    defaultValue = getToStringValue(value);
    element2.defaultValue = defaultValue;
    children = element2.textContent;
    children === defaultValue && "" !== children && null !== children && (element2.value = children);
    track(element2);
  }
  function setTextContent(node2, text2) {
    if (text2) {
      var firstChild = node2.firstChild;
      if (firstChild && firstChild === node2.lastChild && 3 === firstChild.nodeType) {
        firstChild.nodeValue = text2;
        return;
      }
    }
    node2.textContent = text2;
  }
  var unitlessNumbers = new Set(
    "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
      " "
    )
  );
  function setValueForStyle(style2, styleName, value) {
    var isCustomProperty = 0 === styleName.indexOf("--");
    null == value || "boolean" === typeof value || "" === value ? isCustomProperty ? style2.setProperty(styleName, "") : "float" === styleName ? style2.cssFloat = "" : style2[styleName] = "" : isCustomProperty ? style2.setProperty(styleName, value) : "number" !== typeof value || 0 === value || unitlessNumbers.has(styleName) ? "float" === styleName ? style2.cssFloat = value : style2[styleName] = ("" + value).trim() : style2[styleName] = value + "px";
  }
  function setValueForStyles(node2, styles2, prevStyles) {
    if (null != styles2 && "object" !== typeof styles2)
      throw Error(formatProdErrorMessage(62));
    node2 = node2.style;
    if (null != prevStyles) {
      for (var styleName in prevStyles)
        !prevStyles.hasOwnProperty(styleName) || null != styles2 && styles2.hasOwnProperty(styleName) || (0 === styleName.indexOf("--") ? node2.setProperty(styleName, "") : "float" === styleName ? node2.cssFloat = "" : node2[styleName] = "");
      for (var styleName$16 in styles2)
        styleName = styles2[styleName$16], styles2.hasOwnProperty(styleName$16) && prevStyles[styleName$16] !== styleName && setValueForStyle(node2, styleName$16, styleName);
    } else
      for (var styleName$17 in styles2)
        styles2.hasOwnProperty(styleName$17) && setValueForStyle(node2, styleName$17, styles2[styleName$17]);
  }
  function isCustomElement(tagName) {
    if (-1 === tagName.indexOf("-")) return false;
    switch (tagName) {
      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 aliases = /* @__PURE__ */ new Map([
    ["acceptCharset", "accept-charset"],
    ["htmlFor", "for"],
    ["httpEquiv", "http-equiv"],
    ["crossOrigin", "crossorigin"],
    ["accentHeight", "accent-height"],
    ["alignmentBaseline", "alignment-baseline"],
    ["arabicForm", "arabic-form"],
    ["baselineShift", "baseline-shift"],
    ["capHeight", "cap-height"],
    ["clipPath", "clip-path"],
    ["clipRule", "clip-rule"],
    ["colorInterpolation", "color-interpolation"],
    ["colorInterpolationFilters", "color-interpolation-filters"],
    ["colorProfile", "color-profile"],
    ["colorRendering", "color-rendering"],
    ["dominantBaseline", "dominant-baseline"],
    ["enableBackground", "enable-background"],
    ["fillOpacity", "fill-opacity"],
    ["fillRule", "fill-rule"],
    ["floodColor", "flood-color"],
    ["floodOpacity", "flood-opacity"],
    ["fontFamily", "font-family"],
    ["fontSize", "font-size"],
    ["fontSizeAdjust", "font-size-adjust"],
    ["fontStretch", "font-stretch"],
    ["fontStyle", "font-style"],
    ["fontVariant", "font-variant"],
    ["fontWeight", "font-weight"],
    ["glyphName", "glyph-name"],
    ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
    ["glyphOrientationVertical", "glyph-orientation-vertical"],
    ["horizAdvX", "horiz-adv-x"],
    ["horizOriginX", "horiz-origin-x"],
    ["imageRendering", "image-rendering"],
    ["letterSpacing", "letter-spacing"],
    ["lightingColor", "lighting-color"],
    ["markerEnd", "marker-end"],
    ["markerMid", "marker-mid"],
    ["markerStart", "marker-start"],
    ["overlinePosition", "overline-position"],
    ["overlineThickness", "overline-thickness"],
    ["paintOrder", "paint-order"],
    ["panose-1", "panose-1"],
    ["pointerEvents", "pointer-events"],
    ["renderingIntent", "rendering-intent"],
    ["shapeRendering", "shape-rendering"],
    ["stopColor", "stop-color"],
    ["stopOpacity", "stop-opacity"],
    ["strikethroughPosition", "strikethrough-position"],
    ["strikethroughThickness", "strikethrough-thickness"],
    ["strokeDasharray", "stroke-dasharray"],
    ["strokeDashoffset", "stroke-dashoffset"],
    ["strokeLinecap", "stroke-linecap"],
    ["strokeLinejoin", "stroke-linejoin"],
    ["strokeMiterlimit", "stroke-miterlimit"],
    ["strokeOpacity", "stroke-opacity"],
    ["strokeWidth", "stroke-width"],
    ["textAnchor", "text-anchor"],
    ["textDecoration", "text-decoration"],
    ["textRendering", "text-rendering"],
    ["transformOrigin", "transform-origin"],
    ["underlinePosition", "underline-position"],
    ["underlineThickness", "underline-thickness"],
    ["unicodeBidi", "unicode-bidi"],
    ["unicodeRange", "unicode-range"],
    ["unitsPerEm", "units-per-em"],
    ["vAlphabetic", "v-alphabetic"],
    ["vHanging", "v-hanging"],
    ["vIdeographic", "v-ideographic"],
    ["vMathematical", "v-mathematical"],
    ["vectorEffect", "vector-effect"],
    ["vertAdvY", "vert-adv-y"],
    ["vertOriginX", "vert-origin-x"],
    ["vertOriginY", "vert-origin-y"],
    ["wordSpacing", "word-spacing"],
    ["writingMode", "writing-mode"],
    ["xmlnsXlink", "xmlns:xlink"],
    ["xHeight", "x-height"]
  ]), isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
  function sanitizeURL(url) {
    return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
  }
  function noop$1() {
  }
  var currentReplayingEvent = null;
  function getEventTarget(nativeEvent) {
    nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;
    nativeEvent.correspondingUseElement && (nativeEvent = nativeEvent.correspondingUseElement);
    return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;
  }
  var restoreTarget = null, restoreQueue = null;
  function restoreStateOfTarget(target) {
    var internalInstance = getInstanceFromNode(target);
    if (internalInstance && (target = internalInstance.stateNode)) {
      var props = target[internalPropsKey] || null;
      a: switch (target = internalInstance.stateNode, internalInstance.type) {
        case "input":
          updateInput(
            target,
            props.value,
            props.defaultValue,
            props.defaultValue,
            props.checked,
            props.defaultChecked,
            props.type,
            props.name
          );
          internalInstance = props.name;
          if ("radio" === props.type && null != internalInstance) {
            for (props = target; props.parentNode; ) props = props.parentNode;
            props = props.querySelectorAll(
              'input[name="' + escapeSelectorAttributeValueInsideDoubleQuotes(
                "" + internalInstance
              ) + '"][type="radio"]'
            );
            for (internalInstance = 0; internalInstance < props.length; internalInstance++) {
              var otherNode = props[internalInstance];
              if (otherNode !== target && otherNode.form === target.form) {
                var otherProps = otherNode[internalPropsKey] || null;
                if (!otherProps) throw Error(formatProdErrorMessage(90));
                updateInput(
                  otherNode,
                  otherProps.value,
                  otherProps.defaultValue,
                  otherProps.defaultValue,
                  otherProps.checked,
                  otherProps.defaultChecked,
                  otherProps.type,
                  otherProps.name
                );
              }
            }
            for (internalInstance = 0; internalInstance < props.length; internalInstance++)
              otherNode = props[internalInstance], otherNode.form === target.form && updateValueIfChanged(otherNode);
          }
          break a;
        case "textarea":
          updateTextarea(target, props.value, props.defaultValue);
          break a;
        case "select":
          internalInstance = props.value, null != internalInstance && updateOptions(target, !!props.multiple, internalInstance, false);
      }
    }
  }
  var isInsideEventHandler = false;
  function batchedUpdates$1(fn, a, b2) {
    if (isInsideEventHandler) return fn(a, b2);
    isInsideEventHandler = true;
    try {
      var JSCompiler_inline_result = fn(a);
      return JSCompiler_inline_result;
    } finally {
      if (isInsideEventHandler = false, null !== restoreTarget || null !== restoreQueue) {
        if (flushSyncWork$1(), restoreTarget && (a = restoreTarget, fn = restoreQueue, restoreQueue = restoreTarget = null, restoreStateOfTarget(a), fn))
          for (a = 0; a < fn.length; a++) restoreStateOfTarget(fn[a]);
      }
    }
  }
  function getListener(inst, registrationName) {
    var stateNode = inst.stateNode;
    if (null === stateNode) return null;
    var props = stateNode[internalPropsKey] || null;
    if (null === props) return null;
    stateNode = props[registrationName];
    a: switch (registrationName) {
      case "onClick":
      case "onClickCapture":
      case "onDoubleClick":
      case "onDoubleClickCapture":
      case "onMouseDown":
      case "onMouseDownCapture":
      case "onMouseMove":
      case "onMouseMoveCapture":
      case "onMouseUp":
      case "onMouseUpCapture":
      case "onMouseEnter":
        (props = !props.disabled) || (inst = inst.type, props = !("button" === inst || "input" === inst || "select" === inst || "textarea" === inst));
        inst = !props;
        break a;
      default:
        inst = false;
    }
    if (inst) return null;
    if (stateNode && "function" !== typeof stateNode)
      throw Error(
        formatProdErrorMessage(231, registrationName, typeof stateNode)
      );
    return stateNode;
  }
  var canUseDOM = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), passiveBrowserEventsSupported = false;
  if (canUseDOM)
    try {
      var options = {};
      Object.defineProperty(options, "passive", {
        get: function() {
          passiveBrowserEventsSupported = true;
        }
      });
      window.addEventListener("test", options, options);
      window.removeEventListener("test", options, options);
    } catch (e) {
      passiveBrowserEventsSupported = false;
    }
  var root2 = null, startText = null, fallbackText = null;
  function getData() {
    if (fallbackText) return fallbackText;
    var start, startValue = startText, startLength = startValue.length, end, endValue = "value" in root2 ? root2.value : root2.textContent, endLength = endValue.length;
    for (start = 0; start < startLength && startValue[start] === endValue[start]; start++) ;
    var minEnd = startLength - start;
    for (end = 1; end <= minEnd && startValue[startLength - end] === endValue[endLength - end]; end++) ;
    return fallbackText = endValue.slice(start, 1 < end ? 1 - end : void 0);
  }
  function getEventCharCode(nativeEvent) {
    var keyCode = nativeEvent.keyCode;
    "charCode" in nativeEvent ? (nativeEvent = nativeEvent.charCode, 0 === nativeEvent && 13 === keyCode && (nativeEvent = 13)) : nativeEvent = keyCode;
    10 === nativeEvent && (nativeEvent = 13);
    return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;
  }
  function functionThatReturnsTrue() {
    return true;
  }
  function functionThatReturnsFalse() {
    return false;
  }
  function createSyntheticEvent(Interface) {
    function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
      this._reactName = reactName;
      this._targetInst = targetInst;
      this.type = reactEventType;
      this.nativeEvent = nativeEvent;
      this.target = nativeEventTarget;
      this.currentTarget = null;
      for (var propName in Interface)
        Interface.hasOwnProperty(propName) && (reactName = Interface[propName], this[propName] = reactName ? reactName(nativeEvent) : nativeEvent[propName]);
      this.isDefaultPrevented = (null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : false === nativeEvent.returnValue) ? functionThatReturnsTrue : functionThatReturnsFalse;
      this.isPropagationStopped = functionThatReturnsFalse;
      return this;
    }
    assign(SyntheticBaseEvent.prototype, {
      preventDefault: function() {
        this.defaultPrevented = true;
        var event = this.nativeEvent;
        event && (event.preventDefault ? event.preventDefault() : "unknown" !== typeof event.returnValue && (event.returnValue = false), this.isDefaultPrevented = functionThatReturnsTrue);
      },
      stopPropagation: function() {
        var event = this.nativeEvent;
        event && (event.stopPropagation ? event.stopPropagation() : "unknown" !== typeof event.cancelBubble && (event.cancelBubble = true), this.isPropagationStopped = functionThatReturnsTrue);
      },
      persist: function() {
      },
      isPersistent: functionThatReturnsTrue
    });
    return SyntheticBaseEvent;
  }
  var EventInterface = {
    eventPhase: 0,
    bubbles: 0,
    cancelable: 0,
    timeStamp: function(event) {
      return event.timeStamp || Date.now();
    },
    defaultPrevented: 0,
    isTrusted: 0
  }, SyntheticEvent = createSyntheticEvent(EventInterface), UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }), SyntheticUIEvent = createSyntheticEvent(UIEventInterface), lastMovementX, lastMovementY, lastMouseEvent, MouseEventInterface = assign({}, UIEventInterface, {
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    pageX: 0,
    pageY: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    getModifierState: getEventModifierState,
    button: 0,
    buttons: 0,
    relatedTarget: function(event) {
      return void 0 === event.relatedTarget ? event.fromElement === event.srcElement ? event.toElement : event.fromElement : event.relatedTarget;
    },
    movementX: function(event) {
      if ("movementX" in event) return event.movementX;
      event !== lastMouseEvent && (lastMouseEvent && "mousemove" === event.type ? (lastMovementX = event.screenX - lastMouseEvent.screenX, lastMovementY = event.screenY - lastMouseEvent.screenY) : lastMovementY = lastMovementX = 0, lastMouseEvent = event);
      return lastMovementX;
    },
    movementY: function(event) {
      return "movementY" in event ? event.movementY : lastMovementY;
    }
  }), SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface), DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }), SyntheticDragEvent = createSyntheticEvent(DragEventInterface), FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }), SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface), AnimationEventInterface = assign({}, EventInterface, {
    animationName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  }), SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface), ClipboardEventInterface = assign({}, EventInterface, {
    clipboardData: function(event) {
      return "clipboardData" in event ? event.clipboardData : window.clipboardData;
    }
  }), SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface), CompositionEventInterface = assign({}, EventInterface, { data: 0 }), SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface), normalizeKey = {
    Esc: "Escape",
    Spacebar: " ",
    Left: "ArrowLeft",
    Up: "ArrowUp",
    Right: "ArrowRight",
    Down: "ArrowDown",
    Del: "Delete",
    Win: "OS",
    Menu: "ContextMenu",
    Apps: "ContextMenu",
    Scroll: "ScrollLock",
    MozPrintableKey: "Unidentified"
  }, translateToKey = {
    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"
  }, modifierKeyToProp = {
    Alt: "altKey",
    Control: "ctrlKey",
    Meta: "metaKey",
    Shift: "shiftKey"
  };
  function modifierStateGetter(keyArg) {
    var nativeEvent = this.nativeEvent;
    return nativeEvent.getModifierState ? nativeEvent.getModifierState(keyArg) : (keyArg = modifierKeyToProp[keyArg]) ? !!nativeEvent[keyArg] : false;
  }
  function getEventModifierState() {
    return modifierStateGetter;
  }
  var KeyboardEventInterface = assign({}, UIEventInterface, {
    key: function(nativeEvent) {
      if (nativeEvent.key) {
        var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
        if ("Unidentified" !== key) return key;
      }
      return "keypress" === nativeEvent.type ? (nativeEvent = getEventCharCode(nativeEvent), 13 === nativeEvent ? "Enter" : String.fromCharCode(nativeEvent)) : "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : "";
    },
    code: 0,
    location: 0,
    ctrlKey: 0,
    shiftKey: 0,
    altKey: 0,
    metaKey: 0,
    repeat: 0,
    locale: 0,
    getModifierState: getEventModifierState,
    charCode: function(event) {
      return "keypress" === event.type ? getEventCharCode(event) : 0;
    },
    keyCode: function(event) {
      return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
    },
    which: function(event) {
      return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
    }
  }), SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface), PointerEventInterface = assign({}, MouseEventInterface, {
    pointerId: 0,
    width: 0,
    height: 0,
    pressure: 0,
    tangentialPressure: 0,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
    pointerType: 0,
    isPrimary: 0
  }), SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface), TouchEventInterface = assign({}, UIEventInterface, {
    touches: 0,
    targetTouches: 0,
    changedTouches: 0,
    altKey: 0,
    metaKey: 0,
    ctrlKey: 0,
    shiftKey: 0,
    getModifierState: getEventModifierState
  }), SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface), TransitionEventInterface = assign({}, EventInterface, {
    propertyName: 0,
    elapsedTime: 0,
    pseudoElement: 0
  }), SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface), WheelEventInterface = assign({}, MouseEventInterface, {
    deltaX: function(event) {
      return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
    },
    deltaY: function(event) {
      return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
    },
    deltaZ: 0,
    deltaMode: 0
  }), SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface), ToggleEventInterface = assign({}, EventInterface, {
    newState: 0,
    oldState: 0
  }), SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface), END_KEYCODES = [9, 13, 27, 32], canUseCompositionEvent = canUseDOM && "CompositionEvent" in window, documentMode = null;
  canUseDOM && "documentMode" in document && (documentMode = document.documentMode);
  var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode, useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && 8 < documentMode && 11 >= documentMode), SPACEBAR_CHAR = String.fromCharCode(32), hasSpaceKeypress = false;
  function isFallbackCompositionEnd(domEventName, nativeEvent) {
    switch (domEventName) {
      case "keyup":
        return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
      case "keydown":
        return 229 !== nativeEvent.keyCode;
      case "keypress":
      case "mousedown":
      case "focusout":
        return true;
      default:
        return false;
    }
  }
  function getDataFromCustomEvent(nativeEvent) {
    nativeEvent = nativeEvent.detail;
    return "object" === typeof nativeEvent && "data" in nativeEvent ? nativeEvent.data : null;
  }
  var isComposing = false;
  function getNativeBeforeInputChars(domEventName, nativeEvent) {
    switch (domEventName) {
      case "compositionend":
        return getDataFromCustomEvent(nativeEvent);
      case "keypress":
        if (32 !== nativeEvent.which) return null;
        hasSpaceKeypress = true;
        return SPACEBAR_CHAR;
      case "textInput":
        return domEventName = nativeEvent.data, domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName;
      default:
        return null;
    }
  }
  function getFallbackBeforeInputChars(domEventName, nativeEvent) {
    if (isComposing)
      return "compositionend" === domEventName || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent) ? (domEventName = getData(), fallbackText = startText = root2 = null, isComposing = false, domEventName) : null;
    switch (domEventName) {
      case "paste":
        return null;
      case "keypress":
        if (!(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) || nativeEvent.ctrlKey && nativeEvent.altKey) {
          if (nativeEvent.char && 1 < nativeEvent.char.length)
            return nativeEvent.char;
          if (nativeEvent.which) return String.fromCharCode(nativeEvent.which);
        }
        return null;
      case "compositionend":
        return useFallbackCompositionData && "ko" !== nativeEvent.locale ? null : nativeEvent.data;
      default:
        return null;
    }
  }
  var supportedInputTypes = {
    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 isTextInputElement(elem) {
    var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
    return "input" === nodeName ? !!supportedInputTypes[elem.type] : "textarea" === nodeName ? true : false;
  }
  function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
    restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [target] : restoreTarget = target;
    inst = accumulateTwoPhaseListeners(inst, "onChange");
    0 < inst.length && (nativeEvent = new SyntheticEvent(
      "onChange",
      "change",
      null,
      nativeEvent,
      target
    ), dispatchQueue.push({ event: nativeEvent, listeners: inst }));
  }
  var activeElement$1 = null, activeElementInst$1 = null;
  function runEventInBatch(dispatchQueue) {
    processDispatchQueue(dispatchQueue, 0);
  }
  function getInstIfValueChanged(targetInst) {
    var targetNode = getNodeFromInstance(targetInst);
    if (updateValueIfChanged(targetNode)) return targetInst;
  }
  function getTargetInstForChangeEvent(domEventName, targetInst) {
    if ("change" === domEventName) return targetInst;
  }
  var isInputEventSupported = false;
  if (canUseDOM) {
    var JSCompiler_inline_result$jscomp$286;
    if (canUseDOM) {
      var isSupported$jscomp$inline_427 = "oninput" in document;
      if (!isSupported$jscomp$inline_427) {
        var element$jscomp$inline_428 = document.createElement("div");
        element$jscomp$inline_428.setAttribute("oninput", "return;");
        isSupported$jscomp$inline_427 = "function" === typeof element$jscomp$inline_428.oninput;
      }
      JSCompiler_inline_result$jscomp$286 = isSupported$jscomp$inline_427;
    } else JSCompiler_inline_result$jscomp$286 = false;
    isInputEventSupported = JSCompiler_inline_result$jscomp$286 && (!document.documentMode || 9 < document.documentMode);
  }
  function stopWatchingForValueChange() {
    activeElement$1 && (activeElement$1.detachEvent("onpropertychange", handlePropertyChange), activeElementInst$1 = activeElement$1 = null);
  }
  function handlePropertyChange(nativeEvent) {
    if ("value" === nativeEvent.propertyName && getInstIfValueChanged(activeElementInst$1)) {
      var dispatchQueue = [];
      createAndAccumulateChangeEvent(
        dispatchQueue,
        activeElementInst$1,
        nativeEvent,
        getEventTarget(nativeEvent)
      );
      batchedUpdates$1(runEventInBatch, dispatchQueue);
    }
  }
  function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
    "focusin" === domEventName ? (stopWatchingForValueChange(), activeElement$1 = target, activeElementInst$1 = targetInst, activeElement$1.attachEvent("onpropertychange", handlePropertyChange)) : "focusout" === domEventName && stopWatchingForValueChange();
  }
  function getTargetInstForInputEventPolyfill(domEventName) {
    if ("selectionchange" === domEventName || "keyup" === domEventName || "keydown" === domEventName)
      return getInstIfValueChanged(activeElementInst$1);
  }
  function getTargetInstForClickEvent(domEventName, targetInst) {
    if ("click" === domEventName) return getInstIfValueChanged(targetInst);
  }
  function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
    if ("input" === domEventName || "change" === domEventName)
      return getInstIfValueChanged(targetInst);
  }
  function is(x2, y2) {
    return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
  }
  var objectIs = "function" === typeof Object.is ? Object.is : is;
  function shallowEqual(objA, objB) {
    if (objectIs(objA, objB)) return true;
    if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
      return false;
    var keysA = Object.keys(objA), keysB = Object.keys(objB);
    if (keysA.length !== keysB.length) return false;
    for (keysB = 0; keysB < keysA.length; keysB++) {
      var currentKey = keysA[keysB];
      if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
        return false;
    }
    return true;
  }
  function getLeafNode(node2) {
    for (; node2 && node2.firstChild; ) node2 = node2.firstChild;
    return node2;
  }
  function getNodeForCharacterOffset(root3, offset) {
    var node2 = getLeafNode(root3);
    root3 = 0;
    for (var nodeEnd; node2; ) {
      if (3 === node2.nodeType) {
        nodeEnd = root3 + node2.textContent.length;
        if (root3 <= offset && nodeEnd >= offset)
          return { node: node2, offset: offset - root3 };
        root3 = nodeEnd;
      }
      a: {
        for (; node2; ) {
          if (node2.nextSibling) {
            node2 = node2.nextSibling;
            break a;
          }
          node2 = node2.parentNode;
        }
        node2 = void 0;
      }
      node2 = getLeafNode(node2);
    }
  }
  function containsNode(outerNode, innerNode) {
    return outerNode && innerNode ? outerNode === innerNode ? true : outerNode && 3 === outerNode.nodeType ? false : innerNode && 3 === innerNode.nodeType ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(outerNode.compareDocumentPosition(innerNode) & 16) : false : false;
  }
  function getActiveElementDeep(containerInfo) {
    containerInfo = null != containerInfo && null != containerInfo.ownerDocument && null != containerInfo.ownerDocument.defaultView ? containerInfo.ownerDocument.defaultView : window;
    for (var element2 = getActiveElement(containerInfo.document); element2 instanceof containerInfo.HTMLIFrameElement; ) {
      try {
        var JSCompiler_inline_result = "string" === typeof element2.contentWindow.location.href;
      } catch (err) {
        JSCompiler_inline_result = false;
      }
      if (JSCompiler_inline_result) containerInfo = element2.contentWindow;
      else break;
      element2 = getActiveElement(containerInfo.document);
    }
    return element2;
  }
  function hasSelectionCapabilities(elem) {
    var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
    return nodeName && ("input" === nodeName && ("text" === elem.type || "search" === elem.type || "tel" === elem.type || "url" === elem.type || "password" === elem.type) || "textarea" === nodeName || "true" === elem.contentEditable);
  }
  var skipSelectionChangeEvent = canUseDOM && "documentMode" in document && 11 >= document.documentMode, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = false;
  function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
    var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : 9 === nativeEventTarget.nodeType ? nativeEventTarget : nativeEventTarget.ownerDocument;
    mouseDown || null == activeElement || activeElement !== getActiveElement(doc) || (doc = activeElement, "selectionStart" in doc && hasSelectionCapabilities(doc) ? doc = { start: doc.selectionStart, end: doc.selectionEnd } : (doc = (doc.ownerDocument && doc.ownerDocument.defaultView || window).getSelection(), doc = {
      anchorNode: doc.anchorNode,
      anchorOffset: doc.anchorOffset,
      focusNode: doc.focusNode,
      focusOffset: doc.focusOffset
    }), lastSelection && shallowEqual(lastSelection, doc) || (lastSelection = doc, doc = accumulateTwoPhaseListeners(activeElementInst, "onSelect"), 0 < doc.length && (nativeEvent = new SyntheticEvent(
      "onSelect",
      "select",
      null,
      nativeEvent,
      nativeEventTarget
    ), dispatchQueue.push({ event: nativeEvent, listeners: doc }), nativeEvent.target = activeElement)));
  }
  function makePrefixMap(styleProp, eventName) {
    var prefixes = {};
    prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
    prefixes["Webkit" + styleProp] = "webkit" + eventName;
    prefixes["Moz" + styleProp] = "moz" + eventName;
    return prefixes;
  }
  var vendorPrefixes = {
    animationend: makePrefixMap("Animation", "AnimationEnd"),
    animationiteration: makePrefixMap("Animation", "AnimationIteration"),
    animationstart: makePrefixMap("Animation", "AnimationStart"),
    transitionrun: makePrefixMap("Transition", "TransitionRun"),
    transitionstart: makePrefixMap("Transition", "TransitionStart"),
    transitioncancel: makePrefixMap("Transition", "TransitionCancel"),
    transitionend: makePrefixMap("Transition", "TransitionEnd")
  }, prefixedEventNames = {}, style = {};
  canUseDOM && (style = document.createElement("div").style, "AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation, delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition);
  function getVendorPrefixedEventName(eventName) {
    if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
    if (!vendorPrefixes[eventName]) return eventName;
    var prefixMap = vendorPrefixes[eventName], styleProp;
    for (styleProp in prefixMap)
      if (prefixMap.hasOwnProperty(styleProp) && styleProp in style)
        return prefixedEventNames[eventName] = prefixMap[styleProp];
    return eventName;
  }
  var ANIMATION_END = getVendorPrefixedEventName("animationend"), ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"), ANIMATION_START = getVendorPrefixedEventName("animationstart"), TRANSITION_RUN = getVendorPrefixedEventName("transitionrun"), TRANSITION_START = getVendorPrefixedEventName("transitionstart"), TRANSITION_CANCEL = getVendorPrefixedEventName("transitioncancel"), TRANSITION_END = getVendorPrefixedEventName("transitionend"), topLevelEventsToReactNames = /* @__PURE__ */ new Map(), simpleEventPluginEvents = "abort auxClick beforeToggle 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(
    " "
  );
  simpleEventPluginEvents.push("scrollEnd");
  function registerSimpleEvent(domEventName, reactName) {
    topLevelEventsToReactNames.set(domEventName, reactName);
    registerTwoPhaseEvent(reactName, [domEventName]);
  }
  var reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
    if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
      var event = new window.ErrorEvent("error", {
        bubbles: true,
        cancelable: true,
        message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
        error
      });
      if (!window.dispatchEvent(event)) return;
    } else if ("object" === typeof process && "function" === typeof process.emit) {
      process.emit("uncaughtException", error);
      return;
    }
    console.error(error);
  }, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0;
  function finishQueueingConcurrentUpdates() {
    for (var endIndex = concurrentQueuesIndex, i = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i < endIndex; ) {
      var fiber = concurrentQueues[i];
      concurrentQueues[i++] = null;
      var queue = concurrentQueues[i];
      concurrentQueues[i++] = null;
      var update = concurrentQueues[i];
      concurrentQueues[i++] = null;
      var lane = concurrentQueues[i];
      concurrentQueues[i++] = null;
      if (null !== queue && null !== update) {
        var pending = queue.pending;
        null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
        queue.pending = update;
      }
      0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);
    }
  }
  function enqueueUpdate$1(fiber, queue, update, lane) {
    concurrentQueues[concurrentQueuesIndex++] = fiber;
    concurrentQueues[concurrentQueuesIndex++] = queue;
    concurrentQueues[concurrentQueuesIndex++] = update;
    concurrentQueues[concurrentQueuesIndex++] = lane;
    concurrentlyUpdatedLanes |= lane;
    fiber.lanes |= lane;
    fiber = fiber.alternate;
    null !== fiber && (fiber.lanes |= lane);
  }
  function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
    enqueueUpdate$1(fiber, queue, update, lane);
    return getRootForUpdatedFiber(fiber);
  }
  function enqueueConcurrentRenderForLane(fiber, lane) {
    enqueueUpdate$1(fiber, null, null, lane);
    return getRootForUpdatedFiber(fiber);
  }
  function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
    sourceFiber.lanes |= lane;
    var alternate = sourceFiber.alternate;
    null !== alternate && (alternate.lanes |= lane);
    for (var isHidden = false, parent = sourceFiber.return; null !== parent; )
      parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & 1 || (isHidden = true)), sourceFiber = parent, parent = parent.return;
    return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden && null !== update && (isHidden = 31 - clz32(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden], null === alternate ? sourceFiber[isHidden] = [update] : alternate.push(update), update.lane = lane | 536870912), parent) : null;
  }
  function getRootForUpdatedFiber(sourceFiber) {
    if (50 < nestedUpdateCount)
      throw nestedUpdateCount = 0, rootWithNestedUpdates = null, Error(formatProdErrorMessage(185));
    for (var parent = sourceFiber.return; null !== parent; )
      sourceFiber = parent, parent = sourceFiber.return;
    return 3 === sourceFiber.tag ? sourceFiber.stateNode : null;
  }
  var emptyContextObject = {};
  function FiberNode(tag, pendingProps, key, mode) {
    this.tag = tag;
    this.key = key;
    this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
    this.index = 0;
    this.refCleanup = this.ref = null;
    this.pendingProps = pendingProps;
    this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
    this.mode = mode;
    this.subtreeFlags = this.flags = 0;
    this.deletions = null;
    this.childLanes = this.lanes = 0;
    this.alternate = null;
  }
  function createFiberImplClass(tag, pendingProps, key, mode) {
    return new FiberNode(tag, pendingProps, key, mode);
  }
  function shouldConstruct(Component) {
    Component = Component.prototype;
    return !(!Component || !Component.isReactComponent);
  }
  function createWorkInProgress(current, pendingProps) {
    var workInProgress2 = current.alternate;
    null === workInProgress2 ? (workInProgress2 = createFiberImplClass(
      current.tag,
      pendingProps,
      current.key,
      current.mode
    ), workInProgress2.elementType = current.elementType, workInProgress2.type = current.type, workInProgress2.stateNode = current.stateNode, workInProgress2.alternate = current, current.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null);
    workInProgress2.flags = current.flags & 65011712;
    workInProgress2.childLanes = current.childLanes;
    workInProgress2.lanes = current.lanes;
    workInProgress2.child = current.child;
    workInProgress2.memoizedProps = current.memoizedProps;
    workInProgress2.memoizedState = current.memoizedState;
    workInProgress2.updateQueue = current.updateQueue;
    pendingProps = current.dependencies;
    workInProgress2.dependencies = null === pendingProps ? null : { lanes: pendingProps.lanes, firstContext: pendingProps.firstContext };
    workInProgress2.sibling = current.sibling;
    workInProgress2.index = current.index;
    workInProgress2.ref = current.ref;
    workInProgress2.refCleanup = current.refCleanup;
    return workInProgress2;
  }
  function resetWorkInProgress(workInProgress2, renderLanes2) {
    workInProgress2.flags &= 65011714;
    var current = workInProgress2.alternate;
    null === current ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null) : (workInProgress2.childLanes = current.childLanes, workInProgress2.lanes = current.lanes, workInProgress2.child = current.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current.memoizedProps, workInProgress2.memoizedState = current.memoizedState, workInProgress2.updateQueue = current.updateQueue, workInProgress2.type = current.type, renderLanes2 = current.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
      lanes: renderLanes2.lanes,
      firstContext: renderLanes2.firstContext
    });
    return workInProgress2;
  }
  function createFiberFromTypeAndProps(type2, key, pendingProps, owner, mode, lanes) {
    var fiberTag = 0;
    owner = type2;
    if ("function" === typeof type2) shouldConstruct(type2) && (fiberTag = 1);
    else if ("string" === typeof type2)
      fiberTag = isHostHoistableType(
        type2,
        pendingProps,
        contextStackCursor.current
      ) ? 26 : "html" === type2 || "head" === type2 || "body" === type2 ? 27 : 5;
    else
      a: switch (type2) {
        case REACT_ACTIVITY_TYPE:
          return type2 = createFiberImplClass(31, pendingProps, key, mode), type2.elementType = REACT_ACTIVITY_TYPE, type2.lanes = lanes, type2;
        case REACT_FRAGMENT_TYPE:
          return createFiberFromFragment(pendingProps.children, mode, lanes, key);
        case REACT_STRICT_MODE_TYPE:
          fiberTag = 8;
          mode |= 24;
          break;
        case REACT_PROFILER_TYPE:
          return type2 = createFiberImplClass(12, pendingProps, key, mode | 2), type2.elementType = REACT_PROFILER_TYPE, type2.lanes = lanes, type2;
        case REACT_SUSPENSE_TYPE:
          return type2 = createFiberImplClass(13, pendingProps, key, mode), type2.elementType = REACT_SUSPENSE_TYPE, type2.lanes = lanes, type2;
        case REACT_SUSPENSE_LIST_TYPE:
          return type2 = createFiberImplClass(19, pendingProps, key, mode), type2.elementType = REACT_SUSPENSE_LIST_TYPE, type2.lanes = lanes, type2;
        default:
          if ("object" === typeof type2 && null !== type2)
            switch (type2.$$typeof) {
              case REACT_CONTEXT_TYPE:
                fiberTag = 10;
                break a;
              case REACT_CONSUMER_TYPE:
                fiberTag = 9;
                break a;
              case REACT_FORWARD_REF_TYPE:
                fiberTag = 11;
                break a;
              case REACT_MEMO_TYPE:
                fiberTag = 14;
                break a;
              case REACT_LAZY_TYPE:
                fiberTag = 16;
                owner = null;
                break a;
            }
          fiberTag = 29;
          pendingProps = Error(
            formatProdErrorMessage(130, null === type2 ? "null" : typeof type2, "")
          );
          owner = null;
      }
    key = createFiberImplClass(fiberTag, pendingProps, key, mode);
    key.elementType = type2;
    key.type = owner;
    key.lanes = lanes;
    return key;
  }
  function createFiberFromFragment(elements, mode, lanes, key) {
    elements = createFiberImplClass(7, elements, key, mode);
    elements.lanes = lanes;
    return elements;
  }
  function createFiberFromText(content2, mode, lanes) {
    content2 = createFiberImplClass(6, content2, null, mode);
    content2.lanes = lanes;
    return content2;
  }
  function createFiberFromDehydratedFragment(dehydratedNode) {
    var fiber = createFiberImplClass(18, null, null, 0);
    fiber.stateNode = dehydratedNode;
    return fiber;
  }
  function createFiberFromPortal(portal, mode, lanes) {
    mode = createFiberImplClass(
      4,
      null !== portal.children ? portal.children : [],
      portal.key,
      mode
    );
    mode.lanes = lanes;
    mode.stateNode = {
      containerInfo: portal.containerInfo,
      pendingChildren: null,
      implementation: portal.implementation
    };
    return mode;
  }
  var CapturedStacks = /* @__PURE__ */ new WeakMap();
  function createCapturedValueAtFiber(value, source) {
    if ("object" === typeof value && null !== value) {
      var existing = CapturedStacks.get(value);
      if (void 0 !== existing) return existing;
      source = {
        value,
        source,
        stack: getStackByFiberInDevAndProd(source)
      };
      CapturedStacks.set(value, source);
      return source;
    }
    return {
      value,
      source,
      stack: getStackByFiberInDevAndProd(source)
    };
  }
  var forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "";
  function pushTreeFork(workInProgress2, totalChildren) {
    forkStack[forkStackIndex++] = treeForkCount;
    forkStack[forkStackIndex++] = treeForkProvider;
    treeForkProvider = workInProgress2;
    treeForkCount = totalChildren;
  }
  function pushTreeId(workInProgress2, totalChildren, index3) {
    idStack[idStackIndex++] = treeContextId;
    idStack[idStackIndex++] = treeContextOverflow;
    idStack[idStackIndex++] = treeContextProvider;
    treeContextProvider = workInProgress2;
    var baseIdWithLeadingBit = treeContextId;
    workInProgress2 = treeContextOverflow;
    var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
    baseIdWithLeadingBit &= ~(1 << baseLength);
    index3 += 1;
    var length = 32 - clz32(totalChildren) + baseLength;
    if (30 < length) {
      var numberOfOverflowBits = baseLength - baseLength % 5;
      length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
      baseIdWithLeadingBit >>= numberOfOverflowBits;
      baseLength -= numberOfOverflowBits;
      treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index3 << baseLength | baseIdWithLeadingBit;
      treeContextOverflow = length + workInProgress2;
    } else
      treeContextId = 1 << length | index3 << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
  }
  function pushMaterializedTreeId(workInProgress2) {
    null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
  }
  function popTreeContext(workInProgress2) {
    for (; workInProgress2 === treeForkProvider; )
      treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
    for (; workInProgress2 === treeContextProvider; )
      treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
  }
  function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
    idStack[idStackIndex++] = treeContextId;
    idStack[idStackIndex++] = treeContextOverflow;
    idStack[idStackIndex++] = treeContextProvider;
    treeContextId = suspendedContext.id;
    treeContextOverflow = suspendedContext.overflow;
    treeContextProvider = workInProgress2;
  }
  var hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(formatProdErrorMessage(519));
  function throwOnHydrationMismatch(fiber) {
    var error = Error(
      formatProdErrorMessage(
        418,
        1 < arguments.length && void 0 !== arguments[1] && arguments[1] ? "text" : "HTML",
        ""
      )
    );
    queueHydrationError(createCapturedValueAtFiber(error, fiber));
    throw HydrationMismatchException;
  }
  function prepareToHydrateHostInstance(fiber) {
    var instance = fiber.stateNode, type2 = fiber.type, props = fiber.memoizedProps;
    instance[internalInstanceKey] = fiber;
    instance[internalPropsKey] = props;
    switch (type2) {
      case "dialog":
        listenToNonDelegatedEvent("cancel", instance);
        listenToNonDelegatedEvent("close", instance);
        break;
      case "iframe":
      case "object":
      case "embed":
        listenToNonDelegatedEvent("load", instance);
        break;
      case "video":
      case "audio":
        for (type2 = 0; type2 < mediaEventTypes.length; type2++)
          listenToNonDelegatedEvent(mediaEventTypes[type2], instance);
        break;
      case "source":
        listenToNonDelegatedEvent("error", instance);
        break;
      case "img":
      case "image":
      case "link":
        listenToNonDelegatedEvent("error", instance);
        listenToNonDelegatedEvent("load", instance);
        break;
      case "details":
        listenToNonDelegatedEvent("toggle", instance);
        break;
      case "input":
        listenToNonDelegatedEvent("invalid", instance);
        initInput(
          instance,
          props.value,
          props.defaultValue,
          props.checked,
          props.defaultChecked,
          props.type,
          props.name,
          true
        );
        break;
      case "select":
        listenToNonDelegatedEvent("invalid", instance);
        break;
      case "textarea":
        listenToNonDelegatedEvent("invalid", instance), initTextarea(instance, props.value, props.defaultValue, props.children);
    }
    type2 = props.children;
    "string" !== typeof type2 && "number" !== typeof type2 && "bigint" !== typeof type2 || instance.textContent === "" + type2 || true === props.suppressHydrationWarning || checkForUnmatchedText(instance.textContent, type2) ? (null != props.popover && (listenToNonDelegatedEvent("beforetoggle", instance), listenToNonDelegatedEvent("toggle", instance)), null != props.onScroll && listenToNonDelegatedEvent("scroll", instance), null != props.onScrollEnd && listenToNonDelegatedEvent("scrollend", instance), null != props.onClick && (instance.onclick = noop$1), instance = true) : instance = false;
    instance || throwOnHydrationMismatch(fiber, true);
  }
  function popToNextHostParent(fiber) {
    for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
      switch (hydrationParentFiber.tag) {
        case 5:
        case 31:
        case 13:
          rootOrSingletonContext = false;
          return;
        case 27:
        case 3:
          rootOrSingletonContext = true;
          return;
        default:
          hydrationParentFiber = hydrationParentFiber.return;
      }
  }
  function popHydrationState(fiber) {
    if (fiber !== hydrationParentFiber) return false;
    if (!isHydrating) return popToNextHostParent(fiber), isHydrating = true, false;
    var tag = fiber.tag, JSCompiler_temp;
    if (JSCompiler_temp = 3 !== tag && 27 !== tag) {
      if (JSCompiler_temp = 5 === tag)
        JSCompiler_temp = fiber.type, JSCompiler_temp = !("form" !== JSCompiler_temp && "button" !== JSCompiler_temp) || shouldSetTextContent(fiber.type, fiber.memoizedProps);
      JSCompiler_temp = !JSCompiler_temp;
    }
    JSCompiler_temp && nextHydratableInstance && throwOnHydrationMismatch(fiber);
    popToNextHostParent(fiber);
    if (13 === tag) {
      fiber = fiber.memoizedState;
      fiber = null !== fiber ? fiber.dehydrated : null;
      if (!fiber) throw Error(formatProdErrorMessage(317));
      nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
    } else if (31 === tag) {
      fiber = fiber.memoizedState;
      fiber = null !== fiber ? fiber.dehydrated : null;
      if (!fiber) throw Error(formatProdErrorMessage(317));
      nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
    } else
      27 === tag ? (tag = nextHydratableInstance, isSingletonScope(fiber.type) ? (fiber = previousHydratableOnEnteringScopedSingleton, previousHydratableOnEnteringScopedSingleton = null, nextHydratableInstance = fiber) : nextHydratableInstance = tag) : nextHydratableInstance = hydrationParentFiber ? getNextHydratable(fiber.stateNode.nextSibling) : null;
    return true;
  }
  function resetHydrationState() {
    nextHydratableInstance = hydrationParentFiber = null;
    isHydrating = false;
  }
  function upgradeHydrationErrorsToRecoverable() {
    var queuedErrors = hydrationErrors;
    null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
      workInProgressRootRecoverableErrors,
      queuedErrors
    ), hydrationErrors = null);
    return queuedErrors;
  }
  function queueHydrationError(error) {
    null === hydrationErrors ? hydrationErrors = [error] : hydrationErrors.push(error);
  }
  var valueCursor = createCursor(null), currentlyRenderingFiber$1 = null, lastContextDependency = null;
  function pushProvider(providerFiber, context, nextValue) {
    push2(valueCursor, context._currentValue);
    context._currentValue = nextValue;
  }
  function popProvider(context) {
    context._currentValue = valueCursor.current;
    pop(valueCursor);
  }
  function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
    for (; null !== parent; ) {
      var alternate = parent.alternate;
      (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
      if (parent === propagationRoot) break;
      parent = parent.return;
    }
  }
  function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
    var fiber = workInProgress2.child;
    null !== fiber && (fiber.return = workInProgress2);
    for (; null !== fiber; ) {
      var list2 = fiber.dependencies;
      if (null !== list2) {
        var nextFiber = fiber.child;
        list2 = list2.firstContext;
        a: for (; null !== list2; ) {
          var dependency = list2;
          list2 = fiber;
          for (var i = 0; i < contexts.length; i++)
            if (dependency.context === contexts[i]) {
              list2.lanes |= renderLanes2;
              dependency = list2.alternate;
              null !== dependency && (dependency.lanes |= renderLanes2);
              scheduleContextWorkOnParentPath(
                list2.return,
                renderLanes2,
                workInProgress2
              );
              forcePropagateEntireTree || (nextFiber = null);
              break a;
            }
          list2 = dependency.next;
        }
      } else if (18 === fiber.tag) {
        nextFiber = fiber.return;
        if (null === nextFiber) throw Error(formatProdErrorMessage(341));
        nextFiber.lanes |= renderLanes2;
        list2 = nextFiber.alternate;
        null !== list2 && (list2.lanes |= renderLanes2);
        scheduleContextWorkOnParentPath(nextFiber, renderLanes2, workInProgress2);
        nextFiber = null;
      } else nextFiber = fiber.child;
      if (null !== nextFiber) nextFiber.return = fiber;
      else
        for (nextFiber = fiber; null !== nextFiber; ) {
          if (nextFiber === workInProgress2) {
            nextFiber = null;
            break;
          }
          fiber = nextFiber.sibling;
          if (null !== fiber) {
            fiber.return = nextFiber.return;
            nextFiber = fiber;
            break;
          }
          nextFiber = nextFiber.return;
        }
      fiber = nextFiber;
    }
  }
  function propagateParentContextChanges(current, workInProgress2, renderLanes2, forcePropagateEntireTree) {
    current = null;
    for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
      if (!isInsidePropagationBailout) {
        if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
        else if (0 !== (parent.flags & 262144)) break;
      }
      if (10 === parent.tag) {
        var currentParent = parent.alternate;
        if (null === currentParent) throw Error(formatProdErrorMessage(387));
        currentParent = currentParent.memoizedProps;
        if (null !== currentParent) {
          var context = parent.type;
          objectIs(parent.pendingProps.value, currentParent.value) || (null !== current ? current.push(context) : current = [context]);
        }
      } else if (parent === hostTransitionProviderCursor.current) {
        currentParent = parent.alternate;
        if (null === currentParent) throw Error(formatProdErrorMessage(387));
        currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current ? current.push(HostTransitionContext) : current = [HostTransitionContext]);
      }
      parent = parent.return;
    }
    null !== current && propagateContextChanges(
      workInProgress2,
      current,
      renderLanes2,
      forcePropagateEntireTree
    );
    workInProgress2.flags |= 262144;
  }
  function checkIfContextChanged(currentDependencies) {
    for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
      if (!objectIs(
        currentDependencies.context._currentValue,
        currentDependencies.memoizedValue
      ))
        return true;
      currentDependencies = currentDependencies.next;
    }
    return false;
  }
  function prepareToReadContext(workInProgress2) {
    currentlyRenderingFiber$1 = workInProgress2;
    lastContextDependency = null;
    workInProgress2 = workInProgress2.dependencies;
    null !== workInProgress2 && (workInProgress2.firstContext = null);
  }
  function readContext(context) {
    return readContextForConsumer(currentlyRenderingFiber$1, context);
  }
  function readContextDuringReconciliation(consumer, context) {
    null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
    return readContextForConsumer(consumer, context);
  }
  function readContextForConsumer(consumer, context) {
    var value = context._currentValue;
    context = { context, memoizedValue: value, next: null };
    if (null === lastContextDependency) {
      if (null === consumer) throw Error(formatProdErrorMessage(308));
      lastContextDependency = context;
      consumer.dependencies = { lanes: 0, firstContext: context };
      consumer.flags |= 524288;
    } else lastContextDependency = lastContextDependency.next = context;
    return value;
  }
  var AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
    var listeners = [], signal = this.signal = {
      aborted: false,
      addEventListener: function(type2, listener) {
        listeners.push(listener);
      }
    };
    this.abort = function() {
      signal.aborted = true;
      listeners.forEach(function(listener) {
        return listener();
      });
    };
  }, scheduleCallback$2 = Scheduler.unstable_scheduleCallback, NormalPriority = Scheduler.unstable_NormalPriority, CacheContext = {
    $$typeof: REACT_CONTEXT_TYPE,
    Consumer: null,
    Provider: null,
    _currentValue: null,
    _currentValue2: null,
    _threadCount: 0
  };
  function createCache() {
    return {
      controller: new AbortControllerLocal(),
      data: /* @__PURE__ */ new Map(),
      refCount: 0
    };
  }
  function releaseCache(cache) {
    cache.refCount--;
    0 === cache.refCount && scheduleCallback$2(NormalPriority, function() {
      cache.controller.abort();
    });
  }
  var currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null;
  function entangleAsyncAction(transition, thenable) {
    if (null === currentEntangledListeners) {
      var entangledListeners = currentEntangledListeners = [];
      currentEntangledPendingCount = 0;
      currentEntangledLane = requestTransitionLane();
      currentEntangledActionThenable = {
        status: "pending",
        value: void 0,
        then: function(resolve) {
          entangledListeners.push(resolve);
        }
      };
    }
    currentEntangledPendingCount++;
    thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
    return thenable;
  }
  function pingEngtangledActionScope() {
    if (0 === --currentEntangledPendingCount && null !== currentEntangledListeners) {
      null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
      var listeners = currentEntangledListeners;
      currentEntangledListeners = null;
      currentEntangledLane = 0;
      currentEntangledActionThenable = null;
      for (var i = 0; i < listeners.length; i++) (0, listeners[i])();
    }
  }
  function chainThenableValue(thenable, result) {
    var listeners = [], thenableWithOverride = {
      status: "pending",
      value: null,
      reason: null,
      then: function(resolve) {
        listeners.push(resolve);
      }
    };
    thenable.then(
      function() {
        thenableWithOverride.status = "fulfilled";
        thenableWithOverride.value = result;
        for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);
      },
      function(error) {
        thenableWithOverride.status = "rejected";
        thenableWithOverride.reason = error;
        for (error = 0; error < listeners.length; error++)
          (0, listeners[error])(void 0);
      }
    );
    return thenableWithOverride;
  }
  var prevOnStartTransitionFinish = ReactSharedInternals.S;
  ReactSharedInternals.S = function(transition, returnValue) {
    globalMostRecentTransitionTime = now();
    "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && entangleAsyncAction(transition, returnValue);
    null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
  };
  var resumedCache = createCursor(null);
  function peekCacheFromPool() {
    var cacheResumedFromPreviousRender = resumedCache.current;
    return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
  }
  function pushTransition(offscreenWorkInProgress, prevCachePool) {
    null === prevCachePool ? push2(resumedCache, resumedCache.current) : push2(resumedCache, prevCachePool.pool);
  }
  function getSuspendedCache() {
    var cacheFromPool = peekCacheFromPool();
    return null === cacheFromPool ? null : { parent: CacheContext._currentValue, pool: cacheFromPool };
  }
  var SuspenseException = Error(formatProdErrorMessage(460)), SuspenseyCommitException = Error(formatProdErrorMessage(474)), SuspenseActionException = Error(formatProdErrorMessage(542)), noopSuspenseyCommitThenable = { then: function() {
  } };
  function isThenableResolved(thenable) {
    thenable = thenable.status;
    return "fulfilled" === thenable || "rejected" === thenable;
  }
  function trackUsedThenable(thenableState2, thenable, index3) {
    index3 = thenableState2[index3];
    void 0 === index3 ? thenableState2.push(thenable) : index3 !== thenable && (thenable.then(noop$1, noop$1), thenable = index3);
    switch (thenable.status) {
      case "fulfilled":
        return thenable.value;
      case "rejected":
        throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
      default:
        if ("string" === typeof thenable.status) thenable.then(noop$1, noop$1);
        else {
          thenableState2 = workInProgressRoot;
          if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
            throw Error(formatProdErrorMessage(482));
          thenableState2 = thenable;
          thenableState2.status = "pending";
          thenableState2.then(
            function(fulfilledValue) {
              if ("pending" === thenable.status) {
                var fulfilledThenable = thenable;
                fulfilledThenable.status = "fulfilled";
                fulfilledThenable.value = fulfilledValue;
              }
            },
            function(error) {
              if ("pending" === thenable.status) {
                var rejectedThenable = thenable;
                rejectedThenable.status = "rejected";
                rejectedThenable.reason = error;
              }
            }
          );
        }
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
        }
        suspendedThenable = thenable;
        throw SuspenseException;
    }
  }
  function resolveLazy(lazyType) {
    try {
      var init2 = lazyType._init;
      return init2(lazyType._payload);
    } catch (x2) {
      if (null !== x2 && "object" === typeof x2 && "function" === typeof x2.then)
        throw suspendedThenable = x2, SuspenseException;
      throw x2;
    }
  }
  var suspendedThenable = null;
  function getSuspendedThenable() {
    if (null === suspendedThenable) throw Error(formatProdErrorMessage(459));
    var thenable = suspendedThenable;
    suspendedThenable = null;
    return thenable;
  }
  function checkIfUseWrappedInAsyncCatch(rejectedReason) {
    if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
      throw Error(formatProdErrorMessage(483));
  }
  var thenableState$1 = null, thenableIndexCounter$1 = 0;
  function unwrapThenable(thenable) {
    var index3 = thenableIndexCounter$1;
    thenableIndexCounter$1 += 1;
    null === thenableState$1 && (thenableState$1 = []);
    return trackUsedThenable(thenableState$1, thenable, index3);
  }
  function coerceRef(workInProgress2, element2) {
    element2 = element2.props.ref;
    workInProgress2.ref = void 0 !== element2 ? element2 : null;
  }
  function throwOnInvalidObjectTypeImpl(returnFiber, newChild) {
    if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
      throw Error(formatProdErrorMessage(525));
    returnFiber = Object.prototype.toString.call(newChild);
    throw Error(
      formatProdErrorMessage(
        31,
        "[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber
      )
    );
  }
  function createChildReconciler(shouldTrackSideEffects) {
    function deleteChild(returnFiber, childToDelete) {
      if (shouldTrackSideEffects) {
        var deletions = returnFiber.deletions;
        null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
      }
    }
    function deleteRemainingChildren(returnFiber, currentFirstChild) {
      if (!shouldTrackSideEffects) return null;
      for (; null !== currentFirstChild; )
        deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
      return null;
    }
    function mapRemainingChildren(currentFirstChild) {
      for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
        null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
      return existingChildren;
    }
    function useFiber(fiber, pendingProps) {
      fiber = createWorkInProgress(fiber, pendingProps);
      fiber.index = 0;
      fiber.sibling = null;
      return fiber;
    }
    function placeChild(newFiber, lastPlacedIndex, newIndex) {
      newFiber.index = newIndex;
      if (!shouldTrackSideEffects)
        return newFiber.flags |= 1048576, lastPlacedIndex;
      newIndex = newFiber.alternate;
      if (null !== newIndex)
        return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
      newFiber.flags |= 67108866;
      return lastPlacedIndex;
    }
    function placeSingleChild(newFiber) {
      shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
      return newFiber;
    }
    function updateTextNode(returnFiber, current, textContent, lanes) {
      if (null === current || 6 !== current.tag)
        return current = createFiberFromText(textContent, returnFiber.mode, lanes), current.return = returnFiber, current;
      current = useFiber(current, textContent);
      current.return = returnFiber;
      return current;
    }
    function updateElement(returnFiber, current, element2, lanes) {
      var elementType = element2.type;
      if (elementType === REACT_FRAGMENT_TYPE)
        return updateFragment(
          returnFiber,
          current,
          element2.props.children,
          lanes,
          element2.key
        );
      if (null !== current && (current.elementType === elementType || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current.type))
        return current = useFiber(current, element2.props), coerceRef(current, element2), current.return = returnFiber, current;
      current = createFiberFromTypeAndProps(
        element2.type,
        element2.key,
        element2.props,
        null,
        returnFiber.mode,
        lanes
      );
      coerceRef(current, element2);
      current.return = returnFiber;
      return current;
    }
    function updatePortal(returnFiber, current, portal, lanes) {
      if (null === current || 4 !== current.tag || current.stateNode.containerInfo !== portal.containerInfo || current.stateNode.implementation !== portal.implementation)
        return current = createFiberFromPortal(portal, returnFiber.mode, lanes), current.return = returnFiber, current;
      current = useFiber(current, portal.children || []);
      current.return = returnFiber;
      return current;
    }
    function updateFragment(returnFiber, current, fragment, lanes, key) {
      if (null === current || 7 !== current.tag)
        return current = createFiberFromFragment(
          fragment,
          returnFiber.mode,
          lanes,
          key
        ), current.return = returnFiber, current;
      current = useFiber(current, fragment);
      current.return = returnFiber;
      return current;
    }
    function createChild(returnFiber, newChild, lanes) {
      if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
        return newChild = createFiberFromText(
          "" + newChild,
          returnFiber.mode,
          lanes
        ), newChild.return = returnFiber, newChild;
      if ("object" === typeof newChild && null !== newChild) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            return lanes = createFiberFromTypeAndProps(
              newChild.type,
              newChild.key,
              newChild.props,
              null,
              returnFiber.mode,
              lanes
            ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes;
          case REACT_PORTAL_TYPE:
            return newChild = createFiberFromPortal(
              newChild,
              returnFiber.mode,
              lanes
            ), newChild.return = returnFiber, newChild;
          case REACT_LAZY_TYPE:
            return newChild = resolveLazy(newChild), createChild(returnFiber, newChild, lanes);
        }
        if (isArrayImpl(newChild) || getIteratorFn(newChild))
          return newChild = createFiberFromFragment(
            newChild,
            returnFiber.mode,
            lanes,
            null
          ), newChild.return = returnFiber, newChild;
        if ("function" === typeof newChild.then)
          return createChild(returnFiber, unwrapThenable(newChild), lanes);
        if (newChild.$$typeof === REACT_CONTEXT_TYPE)
          return createChild(
            returnFiber,
            readContextDuringReconciliation(returnFiber, newChild),
            lanes
          );
        throwOnInvalidObjectTypeImpl(returnFiber, newChild);
      }
      return null;
    }
    function updateSlot(returnFiber, oldFiber, newChild, lanes) {
      var key = null !== oldFiber ? oldFiber.key : null;
      if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
        return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
      if ("object" === typeof newChild && null !== newChild) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            return newChild.key === key ? updateElement(returnFiber, oldFiber, newChild, lanes) : null;
          case REACT_PORTAL_TYPE:
            return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
          case REACT_LAZY_TYPE:
            return newChild = resolveLazy(newChild), updateSlot(returnFiber, oldFiber, newChild, lanes);
        }
        if (isArrayImpl(newChild) || getIteratorFn(newChild))
          return null !== key ? null : updateFragment(returnFiber, oldFiber, newChild, lanes, null);
        if ("function" === typeof newChild.then)
          return updateSlot(
            returnFiber,
            oldFiber,
            unwrapThenable(newChild),
            lanes
          );
        if (newChild.$$typeof === REACT_CONTEXT_TYPE)
          return updateSlot(
            returnFiber,
            oldFiber,
            readContextDuringReconciliation(returnFiber, newChild),
            lanes
          );
        throwOnInvalidObjectTypeImpl(returnFiber, newChild);
      }
      return null;
    }
    function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
      if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
        return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
      if ("object" === typeof newChild && null !== newChild) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            return existingChildren = existingChildren.get(
              null === newChild.key ? newIdx : newChild.key
            ) || null, updateElement(returnFiber, existingChildren, newChild, lanes);
          case REACT_PORTAL_TYPE:
            return existingChildren = existingChildren.get(
              null === newChild.key ? newIdx : newChild.key
            ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
          case REACT_LAZY_TYPE:
            return newChild = resolveLazy(newChild), updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              newChild,
              lanes
            );
        }
        if (isArrayImpl(newChild) || getIteratorFn(newChild))
          return existingChildren = existingChildren.get(newIdx) || null, updateFragment(returnFiber, existingChildren, newChild, lanes, null);
        if ("function" === typeof newChild.then)
          return updateFromMap(
            existingChildren,
            returnFiber,
            newIdx,
            unwrapThenable(newChild),
            lanes
          );
        if (newChild.$$typeof === REACT_CONTEXT_TYPE)
          return updateFromMap(
            existingChildren,
            returnFiber,
            newIdx,
            readContextDuringReconciliation(returnFiber, newChild),
            lanes
          );
        throwOnInvalidObjectTypeImpl(returnFiber, newChild);
      }
      return null;
    }
    function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
      for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
        oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
        var newFiber = updateSlot(
          returnFiber,
          oldFiber,
          newChildren[newIdx],
          lanes
        );
        if (null === newFiber) {
          null === oldFiber && (oldFiber = nextOldFiber);
          break;
        }
        shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
        currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
        null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
        previousNewFiber = newFiber;
        oldFiber = nextOldFiber;
      }
      if (newIdx === newChildren.length)
        return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
      if (null === oldFiber) {
        for (; newIdx < newChildren.length; newIdx++)
          oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (currentFirstChild = placeChild(
            oldFiber,
            currentFirstChild,
            newIdx
          ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
        nextOldFiber = updateFromMap(
          oldFiber,
          returnFiber,
          newIdx,
          newChildren[newIdx],
          lanes
        ), null !== nextOldFiber && (shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
          null === nextOldFiber.key ? newIdx : nextOldFiber.key
        ), currentFirstChild = placeChild(
          nextOldFiber,
          currentFirstChild,
          newIdx
        ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
      shouldTrackSideEffects && oldFiber.forEach(function(child) {
        return deleteChild(returnFiber, child);
      });
      isHydrating && pushTreeFork(returnFiber, newIdx);
      return resultingFirstChild;
    }
    function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
      if (null == newChildren) throw Error(formatProdErrorMessage(151));
      for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
        oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
        var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
        if (null === newFiber) {
          null === oldFiber && (oldFiber = nextOldFiber);
          break;
        }
        shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
        currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
        null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
        previousNewFiber = newFiber;
        oldFiber = nextOldFiber;
      }
      if (step.done)
        return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
      if (null === oldFiber) {
        for (; !step.done; newIdx++, step = newChildren.next())
          step = createChild(returnFiber, step.value, lanes), null !== step && (currentFirstChild = placeChild(step, currentFirstChild, newIdx), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
        step = updateFromMap(oldFiber, returnFiber, newIdx, step.value, lanes), null !== step && (shouldTrackSideEffects && null !== step.alternate && oldFiber.delete(null === step.key ? newIdx : step.key), currentFirstChild = placeChild(step, currentFirstChild, newIdx), null === previousNewFiber ? resultingFirstChild = step : previousNewFiber.sibling = step, previousNewFiber = step);
      shouldTrackSideEffects && oldFiber.forEach(function(child) {
        return deleteChild(returnFiber, child);
      });
      isHydrating && pushTreeFork(returnFiber, newIdx);
      return resultingFirstChild;
    }
    function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
      "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (newChild = newChild.props.children);
      if ("object" === typeof newChild && null !== newChild) {
        switch (newChild.$$typeof) {
          case REACT_ELEMENT_TYPE:
            a: {
              for (var key = newChild.key; null !== currentFirstChild; ) {
                if (currentFirstChild.key === key) {
                  key = newChild.type;
                  if (key === REACT_FRAGMENT_TYPE) {
                    if (7 === currentFirstChild.tag) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(
                        currentFirstChild,
                        newChild.props.children
                      );
                      lanes.return = returnFiber;
                      returnFiber = lanes;
                      break a;
                    }
                  } else if (currentFirstChild.elementType === key || "object" === typeof key && null !== key && key.$$typeof === REACT_LAZY_TYPE && resolveLazy(key) === currentFirstChild.type) {
                    deleteRemainingChildren(
                      returnFiber,
                      currentFirstChild.sibling
                    );
                    lanes = useFiber(currentFirstChild, newChild.props);
                    coerceRef(lanes, newChild);
                    lanes.return = returnFiber;
                    returnFiber = lanes;
                    break a;
                  }
                  deleteRemainingChildren(returnFiber, currentFirstChild);
                  break;
                } else deleteChild(returnFiber, currentFirstChild);
                currentFirstChild = currentFirstChild.sibling;
              }
              newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                newChild.props.children,
                returnFiber.mode,
                lanes,
                newChild.key
              ), lanes.return = returnFiber, returnFiber = lanes) : (lanes = createFiberFromTypeAndProps(
                newChild.type,
                newChild.key,
                newChild.props,
                null,
                returnFiber.mode,
                lanes
              ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = lanes);
            }
            return placeSingleChild(returnFiber);
          case REACT_PORTAL_TYPE:
            a: {
              for (key = newChild.key; null !== currentFirstChild; ) {
                if (currentFirstChild.key === key)
                  if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === newChild.containerInfo && currentFirstChild.stateNode.implementation === newChild.implementation) {
                    deleteRemainingChildren(
                      returnFiber,
                      currentFirstChild.sibling
                    );
                    lanes = useFiber(currentFirstChild, newChild.children || []);
                    lanes.return = returnFiber;
                    returnFiber = lanes;
                    break a;
                  } else {
                    deleteRemainingChildren(returnFiber, currentFirstChild);
                    break;
                  }
                else deleteChild(returnFiber, currentFirstChild);
                currentFirstChild = currentFirstChild.sibling;
              }
              lanes = createFiberFromPortal(newChild, returnFiber.mode, lanes);
              lanes.return = returnFiber;
              returnFiber = lanes;
            }
            return placeSingleChild(returnFiber);
          case REACT_LAZY_TYPE:
            return newChild = resolveLazy(newChild), reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            );
        }
        if (isArrayImpl(newChild))
          return reconcileChildrenArray(
            returnFiber,
            currentFirstChild,
            newChild,
            lanes
          );
        if (getIteratorFn(newChild)) {
          key = getIteratorFn(newChild);
          if ("function" !== typeof key) throw Error(formatProdErrorMessage(150));
          newChild = key.call(newChild);
          return reconcileChildrenIterator(
            returnFiber,
            currentFirstChild,
            newChild,
            lanes
          );
        }
        if ("function" === typeof newChild.then)
          return reconcileChildFibersImpl(
            returnFiber,
            currentFirstChild,
            unwrapThenable(newChild),
            lanes
          );
        if (newChild.$$typeof === REACT_CONTEXT_TYPE)
          return reconcileChildFibersImpl(
            returnFiber,
            currentFirstChild,
            readContextDuringReconciliation(returnFiber, newChild),
            lanes
          );
        throwOnInvalidObjectTypeImpl(returnFiber, newChild);
      }
      return "string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild ? (newChild = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(returnFiber, currentFirstChild.sibling), lanes = useFiber(currentFirstChild, newChild), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(newChild, returnFiber.mode, lanes), lanes.return = returnFiber, returnFiber = lanes), placeSingleChild(returnFiber)) : deleteRemainingChildren(returnFiber, currentFirstChild);
    }
    return function(returnFiber, currentFirstChild, newChild, lanes) {
      try {
        thenableIndexCounter$1 = 0;
        var firstChildFiber = reconcileChildFibersImpl(
          returnFiber,
          currentFirstChild,
          newChild,
          lanes
        );
        thenableState$1 = null;
        return firstChildFiber;
      } catch (x2) {
        if (x2 === SuspenseException || x2 === SuspenseActionException) throw x2;
        var fiber = createFiberImplClass(29, x2, null, returnFiber.mode);
        fiber.lanes = lanes;
        fiber.return = returnFiber;
        return fiber;
      } finally {
      }
    };
  }
  var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), hasForceUpdate = false;
  function initializeUpdateQueue(fiber) {
    fiber.updateQueue = {
      baseState: fiber.memoizedState,
      firstBaseUpdate: null,
      lastBaseUpdate: null,
      shared: { pending: null, lanes: 0, hiddenCallbacks: null },
      callbacks: null
    };
  }
  function cloneUpdateQueue(current, workInProgress2) {
    current = current.updateQueue;
    workInProgress2.updateQueue === current && (workInProgress2.updateQueue = {
      baseState: current.baseState,
      firstBaseUpdate: current.firstBaseUpdate,
      lastBaseUpdate: current.lastBaseUpdate,
      shared: current.shared,
      callbacks: null
    });
  }
  function createUpdate(lane) {
    return { lane, tag: 0, payload: null, callback: null, next: null };
  }
  function enqueueUpdate(fiber, update, lane) {
    var updateQueue = fiber.updateQueue;
    if (null === updateQueue) return null;
    updateQueue = updateQueue.shared;
    if (0 !== (executionContext & 2)) {
      var pending = updateQueue.pending;
      null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
      updateQueue.pending = update;
      update = getRootForUpdatedFiber(fiber);
      markUpdateLaneFromFiberToRoot(fiber, null, lane);
      return update;
    }
    enqueueUpdate$1(fiber, updateQueue, update, lane);
    return getRootForUpdatedFiber(fiber);
  }
  function entangleTransitions(root3, fiber, lane) {
    fiber = fiber.updateQueue;
    if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
      var queueLanes = fiber.lanes;
      queueLanes &= root3.pendingLanes;
      lane |= queueLanes;
      fiber.lanes = lane;
      markRootEntangled(root3, lane);
    }
  }
  function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
    var queue = workInProgress2.updateQueue, current = workInProgress2.alternate;
    if (null !== current && (current = current.updateQueue, queue === current)) {
      var newFirst = null, newLast = null;
      queue = queue.firstBaseUpdate;
      if (null !== queue) {
        do {
          var clone = {
            lane: queue.lane,
            tag: queue.tag,
            payload: queue.payload,
            callback: null,
            next: null
          };
          null === newLast ? newFirst = newLast = clone : newLast = newLast.next = clone;
          queue = queue.next;
        } while (null !== queue);
        null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
      } else newFirst = newLast = capturedUpdate;
      queue = {
        baseState: current.baseState,
        firstBaseUpdate: newFirst,
        lastBaseUpdate: newLast,
        shared: current.shared,
        callbacks: current.callbacks
      };
      workInProgress2.updateQueue = queue;
      return;
    }
    workInProgress2 = queue.lastBaseUpdate;
    null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
    queue.lastBaseUpdate = capturedUpdate;
  }
  var didReadFromEntangledAsyncAction = false;
  function suspendIfUpdateReadFromEntangledAsyncAction() {
    if (didReadFromEntangledAsyncAction) {
      var entangledActionThenable = currentEntangledActionThenable;
      if (null !== entangledActionThenable) throw entangledActionThenable;
    }
  }
  function processUpdateQueue(workInProgress$jscomp$0, props, instance$jscomp$0, renderLanes2) {
    didReadFromEntangledAsyncAction = false;
    var queue = workInProgress$jscomp$0.updateQueue;
    hasForceUpdate = false;
    var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
    if (null !== pendingQueue) {
      queue.shared.pending = null;
      var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
      lastPendingUpdate.next = null;
      null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
      lastBaseUpdate = lastPendingUpdate;
      var current = workInProgress$jscomp$0.alternate;
      null !== current && (current = current.updateQueue, pendingQueue = current.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current.lastBaseUpdate = lastPendingUpdate));
    }
    if (null !== firstBaseUpdate) {
      var newState = queue.baseState;
      lastBaseUpdate = 0;
      current = firstPendingUpdate = lastPendingUpdate = null;
      pendingQueue = firstBaseUpdate;
      do {
        var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
        if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
          0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
          null !== current && (current = current.next = {
            lane: 0,
            tag: pendingQueue.tag,
            payload: pendingQueue.payload,
            callback: null,
            next: null
          });
          a: {
            var workInProgress2 = workInProgress$jscomp$0, update = pendingQueue;
            updateLane = props;
            var instance = instance$jscomp$0;
            switch (update.tag) {
              case 1:
                workInProgress2 = update.payload;
                if ("function" === typeof workInProgress2) {
                  newState = workInProgress2.call(instance, newState, updateLane);
                  break a;
                }
                newState = workInProgress2;
                break a;
              case 3:
                workInProgress2.flags = workInProgress2.flags & -65537 | 128;
              case 0:
                workInProgress2 = update.payload;
                updateLane = "function" === typeof workInProgress2 ? workInProgress2.call(instance, newState, updateLane) : workInProgress2;
                if (null === updateLane || void 0 === updateLane) break a;
                newState = assign({}, newState, updateLane);
                break a;
              case 2:
                hasForceUpdate = true;
            }
          }
          updateLane = pendingQueue.callback;
          null !== updateLane && (workInProgress$jscomp$0.flags |= 64, isHiddenUpdate && (workInProgress$jscomp$0.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
        } else
          isHiddenUpdate = {
            lane: updateLane,
            tag: pendingQueue.tag,
            payload: pendingQueue.payload,
            callback: pendingQueue.callback,
            next: null
          }, null === current ? (firstPendingUpdate = current = isHiddenUpdate, lastPendingUpdate = newState) : current = current.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
        pendingQueue = pendingQueue.next;
        if (null === pendingQueue)
          if (pendingQueue = queue.shared.pending, null === pendingQueue)
            break;
          else
            isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
      } while (1);
      null === current && (lastPendingUpdate = newState);
      queue.baseState = lastPendingUpdate;
      queue.firstBaseUpdate = firstPendingUpdate;
      queue.lastBaseUpdate = current;
      null === firstBaseUpdate && (queue.shared.lanes = 0);
      workInProgressRootSkippedLanes |= lastBaseUpdate;
      workInProgress$jscomp$0.lanes = lastBaseUpdate;
      workInProgress$jscomp$0.memoizedState = newState;
    }
  }
  function callCallback(callback, context) {
    if ("function" !== typeof callback)
      throw Error(formatProdErrorMessage(191, callback));
    callback.call(context);
  }
  function commitCallbacks(updateQueue, context) {
    var callbacks = updateQueue.callbacks;
    if (null !== callbacks)
      for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
        callCallback(callbacks[updateQueue], context);
  }
  var currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0);
  function pushHiddenContext(fiber, context) {
    fiber = entangledRenderLanes;
    push2(prevEntangledRenderLanesCursor, fiber);
    push2(currentTreeHiddenStackCursor, context);
    entangledRenderLanes = fiber | context.baseLanes;
  }
  function reuseHiddenContextOnStack() {
    push2(prevEntangledRenderLanesCursor, entangledRenderLanes);
    push2(currentTreeHiddenStackCursor, currentTreeHiddenStackCursor.current);
  }
  function popHiddenContext() {
    entangledRenderLanes = prevEntangledRenderLanesCursor.current;
    pop(currentTreeHiddenStackCursor);
    pop(prevEntangledRenderLanesCursor);
  }
  var suspenseHandlerStackCursor = createCursor(null), shellBoundary = null;
  function pushPrimaryTreeSuspenseHandler(handler) {
    var current = handler.alternate;
    push2(suspenseStackCursor, suspenseStackCursor.current & 1);
    push2(suspenseHandlerStackCursor, handler);
    null === shellBoundary && (null === current || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current.memoizedState && (shellBoundary = handler));
  }
  function pushDehydratedActivitySuspenseHandler(fiber) {
    push2(suspenseStackCursor, suspenseStackCursor.current);
    push2(suspenseHandlerStackCursor, fiber);
    null === shellBoundary && (shellBoundary = fiber);
  }
  function pushOffscreenSuspenseHandler(fiber) {
    22 === fiber.tag ? (push2(suspenseStackCursor, suspenseStackCursor.current), push2(suspenseHandlerStackCursor, fiber), null === shellBoundary && (shellBoundary = fiber)) : reuseSuspenseHandlerOnStack();
  }
  function reuseSuspenseHandlerOnStack() {
    push2(suspenseStackCursor, suspenseStackCursor.current);
    push2(suspenseHandlerStackCursor, suspenseHandlerStackCursor.current);
  }
  function popSuspenseHandler(fiber) {
    pop(suspenseHandlerStackCursor);
    shellBoundary === fiber && (shellBoundary = null);
    pop(suspenseStackCursor);
  }
  var suspenseStackCursor = createCursor(0);
  function findFirstSuspended(row) {
    for (var node2 = row; null !== node2; ) {
      if (13 === node2.tag) {
        var state = node2.memoizedState;
        if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
          return node2;
      } else if (19 === node2.tag && ("forwards" === node2.memoizedProps.revealOrder || "backwards" === node2.memoizedProps.revealOrder || "unstable_legacy-backwards" === node2.memoizedProps.revealOrder || "together" === node2.memoizedProps.revealOrder)) {
        if (0 !== (node2.flags & 128)) return node2;
      } else if (null !== node2.child) {
        node2.child.return = node2;
        node2 = node2.child;
        continue;
      }
      if (node2 === row) break;
      for (; null === node2.sibling; ) {
        if (null === node2.return || node2.return === row) return null;
        node2 = node2.return;
      }
      node2.sibling.return = node2.return;
      node2 = node2.sibling;
    }
    return null;
  }
  var renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0;
  function throwInvalidHookError() {
    throw Error(formatProdErrorMessage(321));
  }
  function areHookInputsEqual(nextDeps, prevDeps) {
    if (null === prevDeps) return false;
    for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
      if (!objectIs(nextDeps[i], prevDeps[i])) return false;
    return true;
  }
  function renderWithHooks(current, workInProgress2, Component, props, secondArg, nextRenderLanes) {
    renderLanes = nextRenderLanes;
    currentlyRenderingFiber = workInProgress2;
    workInProgress2.memoizedState = null;
    workInProgress2.updateQueue = null;
    workInProgress2.lanes = 0;
    ReactSharedInternals.H = null === current || null === current.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate;
    shouldDoubleInvokeUserFnsInHooksDEV = false;
    nextRenderLanes = Component(props, secondArg);
    shouldDoubleInvokeUserFnsInHooksDEV = false;
    didScheduleRenderPhaseUpdateDuringThisPass && (nextRenderLanes = renderWithHooksAgain(
      workInProgress2,
      Component,
      props,
      secondArg
    ));
    finishRenderingHooks(current);
    return nextRenderLanes;
  }
  function finishRenderingHooks(current) {
    ReactSharedInternals.H = ContextOnlyDispatcher;
    var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
    renderLanes = 0;
    workInProgressHook = currentHook = currentlyRenderingFiber = null;
    didScheduleRenderPhaseUpdate = false;
    thenableIndexCounter = 0;
    thenableState = null;
    if (didRenderTooFewHooks) throw Error(formatProdErrorMessage(300));
    null === current || didReceiveUpdate || (current = current.dependencies, null !== current && checkIfContextChanged(current) && (didReceiveUpdate = true));
  }
  function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
    currentlyRenderingFiber = workInProgress2;
    var numberOfReRenders = 0;
    do {
      didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
      thenableIndexCounter = 0;
      didScheduleRenderPhaseUpdateDuringThisPass = false;
      if (25 <= numberOfReRenders) throw Error(formatProdErrorMessage(301));
      numberOfReRenders += 1;
      workInProgressHook = currentHook = null;
      if (null != workInProgress2.updateQueue) {
        var children = workInProgress2.updateQueue;
        children.lastEffect = null;
        children.events = null;
        children.stores = null;
        null != children.memoCache && (children.memoCache.index = 0);
      }
      ReactSharedInternals.H = HooksDispatcherOnRerender;
      children = Component(props, secondArg);
    } while (didScheduleRenderPhaseUpdateDuringThisPass);
    return children;
  }
  function TransitionAwareHostComponent() {
    var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
    maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
    dispatcher = dispatcher.useState()[0];
    (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
    return maybeThenable;
  }
  function checkDidRenderIdHook() {
    var didRenderIdHook = 0 !== localIdCounter;
    localIdCounter = 0;
    return didRenderIdHook;
  }
  function bailoutHooks(current, workInProgress2, lanes) {
    workInProgress2.updateQueue = current.updateQueue;
    workInProgress2.flags &= -2053;
    current.lanes &= ~lanes;
  }
  function resetHooksOnUnwind(workInProgress2) {
    if (didScheduleRenderPhaseUpdate) {
      for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
        var queue = workInProgress2.queue;
        null !== queue && (queue.pending = null);
        workInProgress2 = workInProgress2.next;
      }
      didScheduleRenderPhaseUpdate = false;
    }
    renderLanes = 0;
    workInProgressHook = currentHook = currentlyRenderingFiber = null;
    didScheduleRenderPhaseUpdateDuringThisPass = false;
    thenableIndexCounter = localIdCounter = 0;
    thenableState = null;
  }
  function mountWorkInProgressHook() {
    var hook = {
      memoizedState: null,
      baseState: null,
      baseQueue: null,
      queue: null,
      next: null
    };
    null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
    return workInProgressHook;
  }
  function updateWorkInProgressHook() {
    if (null === currentHook) {
      var nextCurrentHook = currentlyRenderingFiber.alternate;
      nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
    } else nextCurrentHook = currentHook.next;
    var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
    if (null !== nextWorkInProgressHook)
      workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
    else {
      if (null === nextCurrentHook) {
        if (null === currentlyRenderingFiber.alternate)
          throw Error(formatProdErrorMessage(467));
        throw Error(formatProdErrorMessage(310));
      }
      currentHook = nextCurrentHook;
      nextCurrentHook = {
        memoizedState: currentHook.memoizedState,
        baseState: currentHook.baseState,
        baseQueue: currentHook.baseQueue,
        queue: currentHook.queue,
        next: null
      };
      null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
    }
    return workInProgressHook;
  }
  function createFunctionComponentUpdateQueue() {
    return { lastEffect: null, events: null, stores: null, memoCache: null };
  }
  function useThenable(thenable) {
    var index3 = thenableIndexCounter;
    thenableIndexCounter += 1;
    null === thenableState && (thenableState = []);
    thenable = trackUsedThenable(thenableState, thenable, index3);
    index3 = currentlyRenderingFiber;
    null === (null === workInProgressHook ? index3.memoizedState : workInProgressHook.next) && (index3 = index3.alternate, ReactSharedInternals.H = null === index3 || null === index3.memoizedState ? HooksDispatcherOnMount : HooksDispatcherOnUpdate);
    return thenable;
  }
  function use(usable) {
    if (null !== usable && "object" === typeof usable) {
      if ("function" === typeof usable.then) return useThenable(usable);
      if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
    }
    throw Error(formatProdErrorMessage(438, String(usable)));
  }
  function useMemoCache(size) {
    var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
    null !== updateQueue && (memoCache = updateQueue.memoCache);
    if (null == memoCache) {
      var current = currentlyRenderingFiber.alternate;
      null !== current && (current = current.updateQueue, null !== current && (current = current.memoCache, null != current && (memoCache = {
        data: current.data.map(function(array) {
          return array.slice();
        }),
        index: 0
      })));
    }
    null == memoCache && (memoCache = { data: [], index: 0 });
    null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
    updateQueue.memoCache = memoCache;
    updateQueue = memoCache.data[memoCache.index];
    if (void 0 === updateQueue)
      for (updateQueue = memoCache.data[memoCache.index] = Array(size), current = 0; current < size; current++)
        updateQueue[current] = REACT_MEMO_CACHE_SENTINEL;
    memoCache.index++;
    return updateQueue;
  }
  function basicStateReducer(state, action) {
    return "function" === typeof action ? action(state) : action;
  }
  function updateReducer(reducer2) {
    var hook = updateWorkInProgressHook();
    return updateReducerImpl(hook, currentHook, reducer2);
  }
  function updateReducerImpl(hook, current, reducer2) {
    var queue = hook.queue;
    if (null === queue) throw Error(formatProdErrorMessage(311));
    queue.lastRenderedReducer = reducer2;
    var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
    if (null !== pendingQueue) {
      if (null !== baseQueue) {
        var baseFirst = baseQueue.next;
        baseQueue.next = pendingQueue.next;
        pendingQueue.next = baseFirst;
      }
      current.baseQueue = baseQueue = pendingQueue;
      queue.pending = null;
    }
    pendingQueue = hook.baseState;
    if (null === baseQueue) hook.memoizedState = pendingQueue;
    else {
      current = baseQueue.next;
      var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update = current, didReadFromEntangledAsyncAction$60 = false;
      do {
        var updateLane = update.lane & -536870913;
        if (updateLane !== update.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
          var revertLane = update.revertLane;
          if (0 === revertLane)
            null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
              lane: 0,
              revertLane: 0,
              gesture: null,
              action: update.action,
              hasEagerState: update.hasEagerState,
              eagerState: update.eagerState,
              next: null
            }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction$60 = true);
          else if ((renderLanes & revertLane) === revertLane) {
            update = update.next;
            revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction$60 = true);
            continue;
          } else
            updateLane = {
              lane: 0,
              revertLane: update.revertLane,
              gesture: null,
              action: update.action,
              hasEagerState: update.hasEagerState,
              eagerState: update.eagerState,
              next: null
            }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
          updateLane = update.action;
          shouldDoubleInvokeUserFnsInHooksDEV && reducer2(pendingQueue, updateLane);
          pendingQueue = update.hasEagerState ? update.eagerState : reducer2(pendingQueue, updateLane);
        } else
          revertLane = {
            lane: updateLane,
            revertLane: update.revertLane,
            gesture: update.gesture,
            action: update.action,
            hasEagerState: update.hasEagerState,
            eagerState: update.eagerState,
            next: null
          }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
        update = update.next;
      } while (null !== update && update !== current);
      null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
      if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction$60 && (reducer2 = currentEntangledActionThenable, null !== reducer2)))
        throw reducer2;
      hook.memoizedState = pendingQueue;
      hook.baseState = baseFirst;
      hook.baseQueue = newBaseQueueLast;
      queue.lastRenderedState = pendingQueue;
    }
    null === baseQueue && (queue.lanes = 0);
    return [hook.memoizedState, queue.dispatch];
  }
  function rerenderReducer(reducer2) {
    var hook = updateWorkInProgressHook(), queue = hook.queue;
    if (null === queue) throw Error(formatProdErrorMessage(311));
    queue.lastRenderedReducer = reducer2;
    var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
    if (null !== lastRenderPhaseUpdate) {
      queue.pending = null;
      var update = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
      do
        newState = reducer2(newState, update.action), update = update.next;
      while (update !== lastRenderPhaseUpdate);
      objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
      hook.memoizedState = newState;
      null === hook.baseQueue && (hook.baseState = newState);
      queue.lastRenderedState = newState;
    }
    return [newState, dispatch];
  }
  function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
    var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
    if (isHydrating$jscomp$0) {
      if (void 0 === getServerSnapshot) throw Error(formatProdErrorMessage(407));
      getServerSnapshot = getServerSnapshot();
    } else getServerSnapshot = getSnapshot();
    var snapshotChanged = !objectIs(
      (currentHook || hook).memoizedState,
      getServerSnapshot
    );
    snapshotChanged && (hook.memoizedState = getServerSnapshot, didReceiveUpdate = true);
    hook = hook.queue;
    updateEffect(subscribeToStore.bind(null, fiber, hook, subscribe), [
      subscribe
    ]);
    if (hook.getSnapshot !== getSnapshot || snapshotChanged || null !== workInProgressHook && workInProgressHook.memoizedState.tag & 1) {
      fiber.flags |= 2048;
      pushSimpleEffect(
        9,
        { destroy: void 0 },
        updateStoreInstance.bind(
          null,
          fiber,
          hook,
          getServerSnapshot,
          getSnapshot
        ),
        null
      );
      if (null === workInProgressRoot) throw Error(formatProdErrorMessage(349));
      isHydrating$jscomp$0 || 0 !== (renderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
    }
    return getServerSnapshot;
  }
  function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
    fiber.flags |= 16384;
    fiber = { getSnapshot, value: renderedSnapshot };
    getSnapshot = currentlyRenderingFiber.updateQueue;
    null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
  }
  function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
    inst.value = nextSnapshot;
    inst.getSnapshot = getSnapshot;
    checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
  }
  function subscribeToStore(fiber, inst, subscribe) {
    return subscribe(function() {
      checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
    });
  }
  function checkIfSnapshotChanged(inst) {
    var latestGetSnapshot = inst.getSnapshot;
    inst = inst.value;
    try {
      var nextValue = latestGetSnapshot();
      return !objectIs(inst, nextValue);
    } catch (error) {
      return true;
    }
  }
  function forceStoreRerender(fiber) {
    var root3 = enqueueConcurrentRenderForLane(fiber, 2);
    null !== root3 && scheduleUpdateOnFiber(root3, fiber, 2);
  }
  function mountStateImpl(initialState2) {
    var hook = mountWorkInProgressHook();
    if ("function" === typeof initialState2) {
      var initialStateInitializer = initialState2;
      initialState2 = initialStateInitializer();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          initialStateInitializer();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
    }
    hook.memoizedState = hook.baseState = initialState2;
    hook.queue = {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: basicStateReducer,
      lastRenderedState: initialState2
    };
    return hook;
  }
  function updateOptimisticImpl(hook, current, passthrough, reducer2) {
    hook.baseState = passthrough;
    return updateReducerImpl(
      hook,
      currentHook,
      "function" === typeof reducer2 ? reducer2 : basicStateReducer
    );
  }
  function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
    if (isRenderPhaseUpdate(fiber)) throw Error(formatProdErrorMessage(485));
    fiber = actionQueue.action;
    if (null !== fiber) {
      var actionNode = {
        payload,
        action: fiber,
        next: null,
        isTransition: true,
        status: "pending",
        value: null,
        reason: null,
        listeners: [],
        then: function(listener) {
          actionNode.listeners.push(listener);
        }
      };
      null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
      setState(actionNode);
      setPendingState = actionQueue.pending;
      null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
    }
  }
  function runActionStateAction(actionQueue, node2) {
    var action = node2.action, payload = node2.payload, prevState = actionQueue.state;
    if (node2.isTransition) {
      var prevTransition = ReactSharedInternals.T, currentTransition = {};
      ReactSharedInternals.T = currentTransition;
      try {
        var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        handleActionReturnValue(actionQueue, node2, returnValue);
      } catch (error) {
        onActionError(actionQueue, node2, error);
      } finally {
        null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
      }
    } else
      try {
        prevTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node2, prevTransition);
      } catch (error$66) {
        onActionError(actionQueue, node2, error$66);
      }
  }
  function handleActionReturnValue(actionQueue, node2, returnValue) {
    null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? returnValue.then(
      function(nextState) {
        onActionSuccess(actionQueue, node2, nextState);
      },
      function(error) {
        return onActionError(actionQueue, node2, error);
      }
    ) : onActionSuccess(actionQueue, node2, returnValue);
  }
  function onActionSuccess(actionQueue, actionNode, nextState) {
    actionNode.status = "fulfilled";
    actionNode.value = nextState;
    notifyActionListeners(actionNode);
    actionQueue.state = nextState;
    actionNode = actionQueue.pending;
    null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
  }
  function onActionError(actionQueue, actionNode, error) {
    var last = actionQueue.pending;
    actionQueue.pending = null;
    if (null !== last) {
      last = last.next;
      do
        actionNode.status = "rejected", actionNode.reason = error, notifyActionListeners(actionNode), actionNode = actionNode.next;
      while (actionNode !== last);
    }
    actionQueue.action = null;
  }
  function notifyActionListeners(actionNode) {
    actionNode = actionNode.listeners;
    for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
  }
  function actionStateReducer(oldState, newState) {
    return newState;
  }
  function mountActionState(action, initialStateProp) {
    if (isHydrating) {
      var ssrFormState = workInProgressRoot.formState;
      if (null !== ssrFormState) {
        a: {
          var JSCompiler_inline_result = currentlyRenderingFiber;
          if (isHydrating) {
            if (nextHydratableInstance) {
              b: {
                var JSCompiler_inline_result$jscomp$0 = nextHydratableInstance;
                for (var inRootOrSingleton = rootOrSingletonContext; 8 !== JSCompiler_inline_result$jscomp$0.nodeType; ) {
                  if (!inRootOrSingleton) {
                    JSCompiler_inline_result$jscomp$0 = null;
                    break b;
                  }
                  JSCompiler_inline_result$jscomp$0 = getNextHydratable(
                    JSCompiler_inline_result$jscomp$0.nextSibling
                  );
                  if (null === JSCompiler_inline_result$jscomp$0) {
                    JSCompiler_inline_result$jscomp$0 = null;
                    break b;
                  }
                }
                inRootOrSingleton = JSCompiler_inline_result$jscomp$0.data;
                JSCompiler_inline_result$jscomp$0 = "F!" === inRootOrSingleton || "F" === inRootOrSingleton ? JSCompiler_inline_result$jscomp$0 : null;
              }
              if (JSCompiler_inline_result$jscomp$0) {
                nextHydratableInstance = getNextHydratable(
                  JSCompiler_inline_result$jscomp$0.nextSibling
                );
                JSCompiler_inline_result = "F!" === JSCompiler_inline_result$jscomp$0.data;
                break a;
              }
            }
            throwOnHydrationMismatch(JSCompiler_inline_result);
          }
          JSCompiler_inline_result = false;
        }
        JSCompiler_inline_result && (initialStateProp = ssrFormState[0]);
      }
    }
    ssrFormState = mountWorkInProgressHook();
    ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
    JSCompiler_inline_result = {
      pending: null,
      lanes: 0,
      dispatch: null,
      lastRenderedReducer: actionStateReducer,
      lastRenderedState: initialStateProp
    };
    ssrFormState.queue = JSCompiler_inline_result;
    ssrFormState = dispatchSetState.bind(
      null,
      currentlyRenderingFiber,
      JSCompiler_inline_result
    );
    JSCompiler_inline_result.dispatch = ssrFormState;
    JSCompiler_inline_result = mountStateImpl(false);
    inRootOrSingleton = dispatchOptimisticSetState.bind(
      null,
      currentlyRenderingFiber,
      false,
      JSCompiler_inline_result.queue
    );
    JSCompiler_inline_result = mountWorkInProgressHook();
    JSCompiler_inline_result$jscomp$0 = {
      state: initialStateProp,
      dispatch: null,
      action,
      pending: null
    };
    JSCompiler_inline_result.queue = JSCompiler_inline_result$jscomp$0;
    ssrFormState = dispatchActionState.bind(
      null,
      currentlyRenderingFiber,
      JSCompiler_inline_result$jscomp$0,
      inRootOrSingleton,
      ssrFormState
    );
    JSCompiler_inline_result$jscomp$0.dispatch = ssrFormState;
    JSCompiler_inline_result.memoizedState = action;
    return [initialStateProp, ssrFormState, false];
  }
  function updateActionState(action) {
    var stateHook = updateWorkInProgressHook();
    return updateActionStateImpl(stateHook, currentHook, action);
  }
  function updateActionStateImpl(stateHook, currentStateHook, action) {
    currentStateHook = updateReducerImpl(
      stateHook,
      currentStateHook,
      actionStateReducer
    )[0];
    stateHook = updateReducer(basicStateReducer)[0];
    if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
      try {
        var state = useThenable(currentStateHook);
      } catch (x2) {
        if (x2 === SuspenseException) throw SuspenseActionException;
        throw x2;
      }
    else state = currentStateHook;
    currentStateHook = updateWorkInProgressHook();
    var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
    action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
      9,
      { destroy: void 0 },
      actionStateActionEffect.bind(null, actionQueue, action),
      null
    ));
    return [state, dispatch, stateHook];
  }
  function actionStateActionEffect(actionQueue, action) {
    actionQueue.action = action;
  }
  function rerenderActionState(action) {
    var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
    if (null !== currentStateHook)
      return updateActionStateImpl(stateHook, currentStateHook, action);
    updateWorkInProgressHook();
    stateHook = stateHook.memoizedState;
    currentStateHook = updateWorkInProgressHook();
    var dispatch = currentStateHook.queue.dispatch;
    currentStateHook.memoizedState = action;
    return [stateHook, dispatch, false];
  }
  function pushSimpleEffect(tag, inst, create2, deps) {
    tag = { tag, create: create2, deps, inst, next: null };
    inst = currentlyRenderingFiber.updateQueue;
    null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
    create2 = inst.lastEffect;
    null === create2 ? inst.lastEffect = tag.next = tag : (deps = create2.next, create2.next = tag, tag.next = deps, inst.lastEffect = tag);
    return tag;
  }
  function updateRef() {
    return updateWorkInProgressHook().memoizedState;
  }
  function mountEffectImpl(fiberFlags, hookFlags, create2, deps) {
    var hook = mountWorkInProgressHook();
    currentlyRenderingFiber.flags |= fiberFlags;
    hook.memoizedState = pushSimpleEffect(
      1 | hookFlags,
      { destroy: void 0 },
      create2,
      void 0 === deps ? null : deps
    );
  }
  function updateEffectImpl(fiberFlags, hookFlags, create2, deps) {
    var hook = updateWorkInProgressHook();
    deps = void 0 === deps ? null : deps;
    var inst = hook.memoizedState.inst;
    null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create2, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
      1 | hookFlags,
      inst,
      create2,
      deps
    ));
  }
  function mountEffect(create2, deps) {
    mountEffectImpl(8390656, 8, create2, deps);
  }
  function updateEffect(create2, deps) {
    updateEffectImpl(2048, 8, create2, deps);
  }
  function useEffectEventImpl(payload) {
    currentlyRenderingFiber.flags |= 4;
    var componentUpdateQueue = currentlyRenderingFiber.updateQueue;
    if (null === componentUpdateQueue)
      componentUpdateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = componentUpdateQueue, componentUpdateQueue.events = [payload];
    else {
      var events = componentUpdateQueue.events;
      null === events ? componentUpdateQueue.events = [payload] : events.push(payload);
    }
  }
  function updateEvent(callback) {
    var ref2 = updateWorkInProgressHook().memoizedState;
    useEffectEventImpl({ ref: ref2, nextImpl: callback });
    return function() {
      if (0 !== (executionContext & 2)) throw Error(formatProdErrorMessage(440));
      return ref2.impl.apply(void 0, arguments);
    };
  }
  function updateInsertionEffect(create2, deps) {
    return updateEffectImpl(4, 2, create2, deps);
  }
  function updateLayoutEffect(create2, deps) {
    return updateEffectImpl(4, 4, create2, deps);
  }
  function imperativeHandleEffect(create2, ref2) {
    if ("function" === typeof ref2) {
      create2 = create2();
      var refCleanup = ref2(create2);
      return function() {
        "function" === typeof refCleanup ? refCleanup() : ref2(null);
      };
    }
    if (null !== ref2 && void 0 !== ref2)
      return create2 = create2(), ref2.current = create2, function() {
        ref2.current = null;
      };
  }
  function updateImperativeHandle(ref2, create2, deps) {
    deps = null !== deps && void 0 !== deps ? deps.concat([ref2]) : null;
    updateEffectImpl(4, 4, imperativeHandleEffect.bind(null, create2, ref2), deps);
  }
  function mountDebugValue() {
  }
  function updateCallback(callback, deps) {
    var hook = updateWorkInProgressHook();
    deps = void 0 === deps ? null : deps;
    var prevState = hook.memoizedState;
    if (null !== deps && areHookInputsEqual(deps, prevState[1]))
      return prevState[0];
    hook.memoizedState = [callback, deps];
    return callback;
  }
  function updateMemo(nextCreate, deps) {
    var hook = updateWorkInProgressHook();
    deps = void 0 === deps ? null : deps;
    var prevState = hook.memoizedState;
    if (null !== deps && areHookInputsEqual(deps, prevState[1]))
      return prevState[0];
    prevState = nextCreate();
    if (shouldDoubleInvokeUserFnsInHooksDEV) {
      setIsStrictModeForDevtools(true);
      try {
        nextCreate();
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }
    hook.memoizedState = [prevState, deps];
    return prevState;
  }
  function mountDeferredValueImpl(hook, value, initialValue) {
    if (void 0 === initialValue || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
      return hook.memoizedState = value;
    hook.memoizedState = initialValue;
    hook = requestDeferredLane();
    currentlyRenderingFiber.lanes |= hook;
    workInProgressRootSkippedLanes |= hook;
    return initialValue;
  }
  function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
    if (objectIs(value, prevValue)) return value;
    if (null !== currentTreeHiddenStackCursor.current)
      return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
    if (0 === (renderLanes & 42) || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
      return didReceiveUpdate = true, hook.memoizedState = value;
    hook = requestDeferredLane();
    currentlyRenderingFiber.lanes |= hook;
    workInProgressRootSkippedLanes |= hook;
    return prevValue;
  }
  function startTransition(fiber, queue, pendingState, finishedState, callback) {
    var previousPriority = ReactDOMSharedInternals.p;
    ReactDOMSharedInternals.p = 0 !== previousPriority && 8 > previousPriority ? previousPriority : 8;
    var prevTransition = ReactSharedInternals.T, currentTransition = {};
    ReactSharedInternals.T = currentTransition;
    dispatchOptimisticSetState(fiber, false, queue, pendingState);
    try {
      var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
      null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
      if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
        var thenableForFinishedState = chainThenableValue(
          returnValue,
          finishedState
        );
        dispatchSetStateInternal(
          fiber,
          queue,
          thenableForFinishedState,
          requestUpdateLane(fiber)
        );
      } else
        dispatchSetStateInternal(
          fiber,
          queue,
          finishedState,
          requestUpdateLane(fiber)
        );
    } catch (error) {
      dispatchSetStateInternal(
        fiber,
        queue,
        { then: function() {
        }, status: "rejected", reason: error },
        requestUpdateLane()
      );
    } finally {
      ReactDOMSharedInternals.p = previousPriority, null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
    }
  }
  function noop2() {
  }
  function startHostTransition(formFiber, pendingState, action, formData) {
    if (5 !== formFiber.tag) throw Error(formatProdErrorMessage(476));
    var queue = ensureFormComponentIsStateful(formFiber).queue;
    startTransition(
      formFiber,
      queue,
      pendingState,
      sharedNotPendingObject,
      null === action ? noop2 : function() {
        requestFormReset$1(formFiber);
        return action(formData);
      }
    );
  }
  function ensureFormComponentIsStateful(formFiber) {
    var existingStateHook = formFiber.memoizedState;
    if (null !== existingStateHook) return existingStateHook;
    existingStateHook = {
      memoizedState: sharedNotPendingObject,
      baseState: sharedNotPendingObject,
      baseQueue: null,
      queue: {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: basicStateReducer,
        lastRenderedState: sharedNotPendingObject
      },
      next: null
    };
    var initialResetState = {};
    existingStateHook.next = {
      memoizedState: initialResetState,
      baseState: initialResetState,
      baseQueue: null,
      queue: {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: basicStateReducer,
        lastRenderedState: initialResetState
      },
      next: null
    };
    formFiber.memoizedState = existingStateHook;
    formFiber = formFiber.alternate;
    null !== formFiber && (formFiber.memoizedState = existingStateHook);
    return existingStateHook;
  }
  function requestFormReset$1(formFiber) {
    var stateHook = ensureFormComponentIsStateful(formFiber);
    null === stateHook.next && (stateHook = formFiber.alternate.memoizedState);
    dispatchSetStateInternal(
      formFiber,
      stateHook.next.queue,
      {},
      requestUpdateLane()
    );
  }
  function useHostTransitionStatus() {
    return readContext(HostTransitionContext);
  }
  function updateId() {
    return updateWorkInProgressHook().memoizedState;
  }
  function updateRefresh() {
    return updateWorkInProgressHook().memoizedState;
  }
  function refreshCache(fiber) {
    for (var provider = fiber.return; null !== provider; ) {
      switch (provider.tag) {
        case 24:
        case 3:
          var lane = requestUpdateLane();
          fiber = createUpdate(lane);
          var root$69 = enqueueUpdate(provider, fiber, lane);
          null !== root$69 && (scheduleUpdateOnFiber(root$69, provider, lane), entangleTransitions(root$69, provider, lane));
          provider = { cache: createCache() };
          fiber.payload = provider;
          return;
      }
      provider = provider.return;
    }
  }
  function dispatchReducerAction(fiber, queue, action) {
    var lane = requestUpdateLane();
    action = {
      lane,
      revertLane: 0,
      gesture: null,
      action,
      hasEagerState: false,
      eagerState: null,
      next: null
    };
    isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, action) : (action = enqueueConcurrentHookUpdate(fiber, queue, action, lane), null !== action && (scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane)));
  }
  function dispatchSetState(fiber, queue, action) {
    var lane = requestUpdateLane();
    dispatchSetStateInternal(fiber, queue, action, lane);
  }
  function dispatchSetStateInternal(fiber, queue, action, lane) {
    var update = {
      lane,
      revertLane: 0,
      gesture: null,
      action,
      hasEagerState: false,
      eagerState: null,
      next: null
    };
    if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);
    else {
      var alternate = fiber.alternate;
      if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate))
        try {
          var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
          update.hasEagerState = true;
          update.eagerState = eagerState;
          if (objectIs(eagerState, currentState))
            return enqueueUpdate$1(fiber, queue, update, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
        } catch (error) {
        } finally {
        }
      action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
      if (null !== action)
        return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
    }
    return false;
  }
  function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
    action = {
      lane: 2,
      revertLane: requestTransitionLane(),
      gesture: null,
      action,
      hasEagerState: false,
      eagerState: null,
      next: null
    };
    if (isRenderPhaseUpdate(fiber)) {
      if (throwIfDuringRender) throw Error(formatProdErrorMessage(479));
    } else
      throwIfDuringRender = enqueueConcurrentHookUpdate(
        fiber,
        queue,
        action,
        2
      ), null !== throwIfDuringRender && scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2);
  }
  function isRenderPhaseUpdate(fiber) {
    var alternate = fiber.alternate;
    return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
  }
  function enqueueRenderPhaseUpdate(queue, update) {
    didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
    var pending = queue.pending;
    null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
    queue.pending = update;
  }
  function entangleTransitionUpdate(root3, queue, lane) {
    if (0 !== (lane & 4194048)) {
      var queueLanes = queue.lanes;
      queueLanes &= root3.pendingLanes;
      lane |= queueLanes;
      queue.lanes = lane;
      markRootEntangled(root3, lane);
    }
  }
  var ContextOnlyDispatcher = {
    readContext,
    use,
    useCallback: throwInvalidHookError,
    useContext: throwInvalidHookError,
    useEffect: throwInvalidHookError,
    useImperativeHandle: throwInvalidHookError,
    useLayoutEffect: throwInvalidHookError,
    useInsertionEffect: throwInvalidHookError,
    useMemo: throwInvalidHookError,
    useReducer: throwInvalidHookError,
    useRef: throwInvalidHookError,
    useState: throwInvalidHookError,
    useDebugValue: throwInvalidHookError,
    useDeferredValue: throwInvalidHookError,
    useTransition: throwInvalidHookError,
    useSyncExternalStore: throwInvalidHookError,
    useId: throwInvalidHookError,
    useHostTransitionStatus: throwInvalidHookError,
    useFormState: throwInvalidHookError,
    useActionState: throwInvalidHookError,
    useOptimistic: throwInvalidHookError,
    useMemoCache: throwInvalidHookError,
    useCacheRefresh: throwInvalidHookError
  };
  ContextOnlyDispatcher.useEffectEvent = throwInvalidHookError;
  var HooksDispatcherOnMount = {
    readContext,
    use,
    useCallback: function(callback, deps) {
      mountWorkInProgressHook().memoizedState = [
        callback,
        void 0 === deps ? null : deps
      ];
      return callback;
    },
    useContext: readContext,
    useEffect: mountEffect,
    useImperativeHandle: function(ref2, create2, deps) {
      deps = null !== deps && void 0 !== deps ? deps.concat([ref2]) : null;
      mountEffectImpl(
        4194308,
        4,
        imperativeHandleEffect.bind(null, create2, ref2),
        deps
      );
    },
    useLayoutEffect: function(create2, deps) {
      return mountEffectImpl(4194308, 4, create2, deps);
    },
    useInsertionEffect: function(create2, deps) {
      mountEffectImpl(4, 2, create2, deps);
    },
    useMemo: function(nextCreate, deps) {
      var hook = mountWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var nextValue = nextCreate();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          nextCreate();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      hook.memoizedState = [nextValue, deps];
      return nextValue;
    },
    useReducer: function(reducer2, initialArg, init2) {
      var hook = mountWorkInProgressHook();
      if (void 0 !== init2) {
        var initialState2 = init2(initialArg);
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            init2(initialArg);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      } else initialState2 = initialArg;
      hook.memoizedState = hook.baseState = initialState2;
      reducer2 = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: reducer2,
        lastRenderedState: initialState2
      };
      hook.queue = reducer2;
      reducer2 = reducer2.dispatch = dispatchReducerAction.bind(
        null,
        currentlyRenderingFiber,
        reducer2
      );
      return [hook.memoizedState, reducer2];
    },
    useRef: function(initialValue) {
      var hook = mountWorkInProgressHook();
      initialValue = { current: initialValue };
      return hook.memoizedState = initialValue;
    },
    useState: function(initialState2) {
      initialState2 = mountStateImpl(initialState2);
      var queue = initialState2.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber, queue);
      queue.dispatch = dispatch;
      return [initialState2.memoizedState, dispatch];
    },
    useDebugValue: mountDebugValue,
    useDeferredValue: function(value, initialValue) {
      var hook = mountWorkInProgressHook();
      return mountDeferredValueImpl(hook, value, initialValue);
    },
    useTransition: function() {
      var stateHook = mountStateImpl(false);
      stateHook = startTransition.bind(
        null,
        currentlyRenderingFiber,
        stateHook.queue,
        true,
        false
      );
      mountWorkInProgressHook().memoizedState = stateHook;
      return [false, stateHook];
    },
    useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
      var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
      if (isHydrating) {
        if (void 0 === getServerSnapshot)
          throw Error(formatProdErrorMessage(407));
        getServerSnapshot = getServerSnapshot();
      } else {
        getServerSnapshot = getSnapshot();
        if (null === workInProgressRoot)
          throw Error(formatProdErrorMessage(349));
        0 !== (workInProgressRootRenderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
      }
      hook.memoizedState = getServerSnapshot;
      var inst = { value: getServerSnapshot, getSnapshot };
      hook.queue = inst;
      mountEffect(subscribeToStore.bind(null, fiber, inst, subscribe), [
        subscribe
      ]);
      fiber.flags |= 2048;
      pushSimpleEffect(
        9,
        { destroy: void 0 },
        updateStoreInstance.bind(
          null,
          fiber,
          inst,
          getServerSnapshot,
          getSnapshot
        ),
        null
      );
      return getServerSnapshot;
    },
    useId: function() {
      var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
      if (isHydrating) {
        var JSCompiler_inline_result = treeContextOverflow;
        var idWithLeadingBit = treeContextId;
        JSCompiler_inline_result = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + JSCompiler_inline_result;
        identifierPrefix = "_" + identifierPrefix + "R_" + JSCompiler_inline_result;
        JSCompiler_inline_result = localIdCounter++;
        0 < JSCompiler_inline_result && (identifierPrefix += "H" + JSCompiler_inline_result.toString(32));
        identifierPrefix += "_";
      } else
        JSCompiler_inline_result = globalClientIdCounter++, identifierPrefix = "_" + identifierPrefix + "r_" + JSCompiler_inline_result.toString(32) + "_";
      return hook.memoizedState = identifierPrefix;
    },
    useHostTransitionStatus,
    useFormState: mountActionState,
    useActionState: mountActionState,
    useOptimistic: function(passthrough) {
      var hook = mountWorkInProgressHook();
      hook.memoizedState = hook.baseState = passthrough;
      var queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: null,
        lastRenderedState: null
      };
      hook.queue = queue;
      hook = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber,
        true,
        queue
      );
      queue.dispatch = hook;
      return [passthrough, hook];
    },
    useMemoCache,
    useCacheRefresh: function() {
      return mountWorkInProgressHook().memoizedState = refreshCache.bind(
        null,
        currentlyRenderingFiber
      );
    },
    useEffectEvent: function(callback) {
      var hook = mountWorkInProgressHook(), ref2 = { impl: callback };
      hook.memoizedState = ref2;
      return function() {
        if (0 !== (executionContext & 2))
          throw Error(formatProdErrorMessage(440));
        return ref2.impl.apply(void 0, arguments);
      };
    }
  }, HooksDispatcherOnUpdate = {
    readContext,
    use,
    useCallback: updateCallback,
    useContext: readContext,
    useEffect: updateEffect,
    useImperativeHandle: updateImperativeHandle,
    useInsertionEffect: updateInsertionEffect,
    useLayoutEffect: updateLayoutEffect,
    useMemo: updateMemo,
    useReducer: updateReducer,
    useRef: updateRef,
    useState: function() {
      return updateReducer(basicStateReducer);
    },
    useDebugValue: mountDebugValue,
    useDeferredValue: function(value, initialValue) {
      var hook = updateWorkInProgressHook();
      return updateDeferredValueImpl(
        hook,
        currentHook.memoizedState,
        value,
        initialValue
      );
    },
    useTransition: function() {
      var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
      return [
        "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
        start
      ];
    },
    useSyncExternalStore: updateSyncExternalStore,
    useId: updateId,
    useHostTransitionStatus,
    useFormState: updateActionState,
    useActionState: updateActionState,
    useOptimistic: function(passthrough, reducer2) {
      var hook = updateWorkInProgressHook();
      return updateOptimisticImpl(hook, currentHook, passthrough, reducer2);
    },
    useMemoCache,
    useCacheRefresh: updateRefresh
  };
  HooksDispatcherOnUpdate.useEffectEvent = updateEvent;
  var HooksDispatcherOnRerender = {
    readContext,
    use,
    useCallback: updateCallback,
    useContext: readContext,
    useEffect: updateEffect,
    useImperativeHandle: updateImperativeHandle,
    useInsertionEffect: updateInsertionEffect,
    useLayoutEffect: updateLayoutEffect,
    useMemo: updateMemo,
    useReducer: rerenderReducer,
    useRef: updateRef,
    useState: function() {
      return rerenderReducer(basicStateReducer);
    },
    useDebugValue: mountDebugValue,
    useDeferredValue: function(value, initialValue) {
      var hook = updateWorkInProgressHook();
      return null === currentHook ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(
        hook,
        currentHook.memoizedState,
        value,
        initialValue
      );
    },
    useTransition: function() {
      var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
      return [
        "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
        start
      ];
    },
    useSyncExternalStore: updateSyncExternalStore,
    useId: updateId,
    useHostTransitionStatus,
    useFormState: rerenderActionState,
    useActionState: rerenderActionState,
    useOptimistic: function(passthrough, reducer2) {
      var hook = updateWorkInProgressHook();
      if (null !== currentHook)
        return updateOptimisticImpl(hook, currentHook, passthrough, reducer2);
      hook.baseState = passthrough;
      return [passthrough, hook.queue.dispatch];
    },
    useMemoCache,
    useCacheRefresh: updateRefresh
  };
  HooksDispatcherOnRerender.useEffectEvent = updateEvent;
  function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
    ctor = workInProgress2.memoizedState;
    getDerivedStateFromProps = getDerivedStateFromProps(nextProps, ctor);
    getDerivedStateFromProps = null === getDerivedStateFromProps || void 0 === getDerivedStateFromProps ? ctor : assign({}, ctor, getDerivedStateFromProps);
    workInProgress2.memoizedState = getDerivedStateFromProps;
    0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = getDerivedStateFromProps);
  }
  var classComponentUpdater = {
    enqueueSetState: function(inst, payload, callback) {
      inst = inst._reactInternals;
      var lane = requestUpdateLane(), update = createUpdate(lane);
      update.payload = payload;
      void 0 !== callback && null !== callback && (update.callback = callback);
      payload = enqueueUpdate(inst, update, lane);
      null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
    },
    enqueueReplaceState: function(inst, payload, callback) {
      inst = inst._reactInternals;
      var lane = requestUpdateLane(), update = createUpdate(lane);
      update.tag = 1;
      update.payload = payload;
      void 0 !== callback && null !== callback && (update.callback = callback);
      payload = enqueueUpdate(inst, update, lane);
      null !== payload && (scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
    },
    enqueueForceUpdate: function(inst, callback) {
      inst = inst._reactInternals;
      var lane = requestUpdateLane(), update = createUpdate(lane);
      update.tag = 2;
      void 0 !== callback && null !== callback && (update.callback = callback);
      callback = enqueueUpdate(inst, update, lane);
      null !== callback && (scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
    }
  };
  function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
    workInProgress2 = workInProgress2.stateNode;
    return "function" === typeof workInProgress2.shouldComponentUpdate ? workInProgress2.shouldComponentUpdate(newProps, newState, nextContext) : ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
  }
  function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
    workInProgress2 = instance.state;
    "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
    "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
    instance.state !== workInProgress2 && classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
  }
  function resolveClassComponentProps(Component, baseProps) {
    var newProps = baseProps;
    if ("ref" in baseProps) {
      newProps = {};
      for (var propName in baseProps)
        "ref" !== propName && (newProps[propName] = baseProps[propName]);
    }
    if (Component = Component.defaultProps) {
      newProps === baseProps && (newProps = assign({}, newProps));
      for (var propName$73 in Component)
        void 0 === newProps[propName$73] && (newProps[propName$73] = Component[propName$73]);
    }
    return newProps;
  }
  function defaultOnUncaughtError(error) {
    reportGlobalError(error);
  }
  function defaultOnCaughtError(error) {
    console.error(error);
  }
  function defaultOnRecoverableError(error) {
    reportGlobalError(error);
  }
  function logUncaughtError(root3, errorInfo) {
    try {
      var onUncaughtError = root3.onUncaughtError;
      onUncaughtError(errorInfo.value, { componentStack: errorInfo.stack });
    } catch (e$74) {
      setTimeout(function() {
        throw e$74;
      });
    }
  }
  function logCaughtError(root3, boundary, errorInfo) {
    try {
      var onCaughtError = root3.onCaughtError;
      onCaughtError(errorInfo.value, {
        componentStack: errorInfo.stack,
        errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
      });
    } catch (e$75) {
      setTimeout(function() {
        throw e$75;
      });
    }
  }
  function createRootErrorUpdate(root3, errorInfo, lane) {
    lane = createUpdate(lane);
    lane.tag = 3;
    lane.payload = { element: null };
    lane.callback = function() {
      logUncaughtError(root3, errorInfo);
    };
    return lane;
  }
  function createClassErrorUpdate(lane) {
    lane = createUpdate(lane);
    lane.tag = 3;
    return lane;
  }
  function initializeClassErrorUpdate(update, root3, fiber, errorInfo) {
    var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
    if ("function" === typeof getDerivedStateFromError) {
      var error = errorInfo.value;
      update.payload = function() {
        return getDerivedStateFromError(error);
      };
      update.callback = function() {
        logCaughtError(root3, fiber, errorInfo);
      };
    }
    var inst = fiber.stateNode;
    null !== inst && "function" === typeof inst.componentDidCatch && (update.callback = function() {
      logCaughtError(root3, fiber, errorInfo);
      "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
      var stack = errorInfo.stack;
      this.componentDidCatch(errorInfo.value, {
        componentStack: null !== stack ? stack : ""
      });
    });
  }
  function throwException(root3, returnFiber, sourceFiber, value, rootRenderLanes) {
    sourceFiber.flags |= 32768;
    if (null !== value && "object" === typeof value && "function" === typeof value.then) {
      returnFiber = sourceFiber.alternate;
      null !== returnFiber && propagateParentContextChanges(
        returnFiber,
        sourceFiber,
        rootRenderLanes,
        true
      );
      sourceFiber = suspenseHandlerStackCursor.current;
      if (null !== sourceFiber) {
        switch (sourceFiber.tag) {
          case 31:
          case 13:
            return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && 0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 3), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value]) : returnFiber.add(value), attachPingListener(root3, value, rootRenderLanes)), false;
          case 22:
            return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
              transitions: null,
              markerInstances: null,
              retryQueue: /* @__PURE__ */ new Set([value])
            }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value]) : sourceFiber.add(value)), attachPingListener(root3, value, rootRenderLanes)), false;
        }
        throw Error(formatProdErrorMessage(435, sourceFiber.tag));
      }
      attachPingListener(root3, value, rootRenderLanes);
      renderDidSuspendDelayIfPossible();
      return false;
    }
    if (isHydrating)
      return returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && (root3 = Error(formatProdErrorMessage(422), { cause: value }), queueHydrationError(createCapturedValueAtFiber(root3, sourceFiber)))) : (value !== HydrationMismatchException && (returnFiber = Error(formatProdErrorMessage(423), {
        cause: value
      }), queueHydrationError(
        createCapturedValueAtFiber(returnFiber, sourceFiber)
      )), root3 = root3.current.alternate, root3.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root3.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(
        root3.stateNode,
        value,
        rootRenderLanes
      ), enqueueCapturedUpdate(root3, rootRenderLanes), 4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2)), false;
    var wrapperError = Error(formatProdErrorMessage(520), { cause: value });
    wrapperError = createCapturedValueAtFiber(wrapperError, sourceFiber);
    null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [wrapperError] : workInProgressRootConcurrentErrors.push(wrapperError);
    4 !== workInProgressRootExitStatus && (workInProgressRootExitStatus = 2);
    if (null === returnFiber) return true;
    value = createCapturedValueAtFiber(value, sourceFiber);
    sourceFiber = returnFiber;
    do {
      switch (sourceFiber.tag) {
        case 3:
          return sourceFiber.flags |= 65536, root3 = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root3, root3 = createRootErrorUpdate(sourceFiber.stateNode, value, root3), enqueueCapturedUpdate(sourceFiber, root3), false;
        case 1:
          if (returnFiber = sourceFiber.type, wrapperError = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== wrapperError && "function" === typeof wrapperError.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(wrapperError))))
            return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
              rootRenderLanes,
              root3,
              sourceFiber,
              value
            ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
      }
      sourceFiber = sourceFiber.return;
    } while (null !== sourceFiber);
    return false;
  }
  var SelectiveHydrationException = Error(formatProdErrorMessage(461)), didReceiveUpdate = false;
  function reconcileChildren(current, workInProgress2, nextChildren, renderLanes2) {
    workInProgress2.child = null === current ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
      workInProgress2,
      current.child,
      nextChildren,
      renderLanes2
    );
  }
  function updateForwardRef(current, workInProgress2, Component, nextProps, renderLanes2) {
    Component = Component.render;
    var ref2 = workInProgress2.ref;
    if ("ref" in nextProps) {
      var propsWithoutRef = {};
      for (var key in nextProps)
        "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
    } else propsWithoutRef = nextProps;
    prepareToReadContext(workInProgress2);
    nextProps = renderWithHooks(
      current,
      workInProgress2,
      Component,
      propsWithoutRef,
      ref2,
      renderLanes2
    );
    key = checkDidRenderIdHook();
    if (null !== current && !didReceiveUpdate)
      return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
    isHydrating && key && pushMaterializedTreeId(workInProgress2);
    workInProgress2.flags |= 1;
    reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
    return workInProgress2.child;
  }
  function updateMemoComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
    if (null === current) {
      var type2 = Component.type;
      if ("function" === typeof type2 && !shouldConstruct(type2) && void 0 === type2.defaultProps && null === Component.compare)
        return workInProgress2.tag = 15, workInProgress2.type = type2, updateSimpleMemoComponent(
          current,
          workInProgress2,
          type2,
          nextProps,
          renderLanes2
        );
      current = createFiberFromTypeAndProps(
        Component.type,
        null,
        nextProps,
        workInProgress2,
        workInProgress2.mode,
        renderLanes2
      );
      current.ref = workInProgress2.ref;
      current.return = workInProgress2;
      return workInProgress2.child = current;
    }
    type2 = current.child;
    if (!checkScheduledUpdateOrContext(current, renderLanes2)) {
      var prevProps = type2.memoizedProps;
      Component = Component.compare;
      Component = null !== Component ? Component : shallowEqual;
      if (Component(prevProps, nextProps) && current.ref === workInProgress2.ref)
        return bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
    }
    workInProgress2.flags |= 1;
    current = createWorkInProgress(type2, nextProps);
    current.ref = workInProgress2.ref;
    current.return = workInProgress2;
    return workInProgress2.child = current;
  }
  function updateSimpleMemoComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
    if (null !== current) {
      var prevProps = current.memoizedProps;
      if (shallowEqual(prevProps, nextProps) && current.ref === workInProgress2.ref)
        if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current, renderLanes2))
          0 !== (current.flags & 131072) && (didReceiveUpdate = true);
        else
          return workInProgress2.lanes = current.lanes, bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
    }
    return updateFunctionComponent(
      current,
      workInProgress2,
      Component,
      nextProps,
      renderLanes2
    );
  }
  function updateOffscreenComponent(current, workInProgress2, renderLanes2, nextProps) {
    var nextChildren = nextProps.children, prevState = null !== current ? current.memoizedState : null;
    null === current && null === workInProgress2.stateNode && (workInProgress2.stateNode = {
      _visibility: 1,
      _pendingMarkers: null,
      _retryCache: null,
      _transitions: null
    });
    if ("hidden" === nextProps.mode) {
      if (0 !== (workInProgress2.flags & 128)) {
        prevState = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
        if (null !== current) {
          nextProps = workInProgress2.child = current.child;
          for (nextChildren = 0; null !== nextProps; )
            nextChildren = nextChildren | nextProps.lanes | nextProps.childLanes, nextProps = nextProps.sibling;
          nextProps = nextChildren & ~prevState;
        } else nextProps = 0, workInProgress2.child = null;
        return deferHiddenOffscreenComponent(
          current,
          workInProgress2,
          prevState,
          renderLanes2,
          nextProps
        );
      }
      if (0 !== (renderLanes2 & 536870912))
        workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current && pushTransition(
          workInProgress2,
          null !== prevState ? prevState.cachePool : null
        ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(), pushOffscreenSuspenseHandler(workInProgress2);
      else
        return nextProps = workInProgress2.lanes = 536870912, deferHiddenOffscreenComponent(
          current,
          workInProgress2,
          null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
          renderLanes2,
          nextProps
        );
    } else
      null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(), workInProgress2.memoizedState = null) : (null !== current && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(), reuseSuspenseHandlerOnStack());
    reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
    return workInProgress2.child;
  }
  function bailoutOffscreenComponent(current, workInProgress2) {
    null !== current && 22 === current.tag || null !== workInProgress2.stateNode || (workInProgress2.stateNode = {
      _visibility: 1,
      _pendingMarkers: null,
      _retryCache: null,
      _transitions: null
    });
    return workInProgress2.sibling;
  }
  function deferHiddenOffscreenComponent(current, workInProgress2, nextBaseLanes, renderLanes2, remainingChildLanes) {
    var JSCompiler_inline_result = peekCacheFromPool();
    JSCompiler_inline_result = null === JSCompiler_inline_result ? null : { parent: CacheContext._currentValue, pool: JSCompiler_inline_result };
    workInProgress2.memoizedState = {
      baseLanes: nextBaseLanes,
      cachePool: JSCompiler_inline_result
    };
    null !== current && pushTransition(workInProgress2, null);
    reuseHiddenContextOnStack();
    pushOffscreenSuspenseHandler(workInProgress2);
    null !== current && propagateParentContextChanges(current, workInProgress2, renderLanes2, true);
    workInProgress2.childLanes = remainingChildLanes;
    return null;
  }
  function mountActivityChildren(workInProgress2, nextProps) {
    nextProps = mountWorkInProgressOffscreenFiber(
      { mode: nextProps.mode, children: nextProps.children },
      workInProgress2.mode
    );
    nextProps.ref = workInProgress2.ref;
    workInProgress2.child = nextProps;
    nextProps.return = workInProgress2;
    return nextProps;
  }
  function retryActivityComponentWithoutHydrating(current, workInProgress2, renderLanes2) {
    reconcileChildFibers(workInProgress2, current.child, null, renderLanes2);
    current = mountActivityChildren(workInProgress2, workInProgress2.pendingProps);
    current.flags |= 2;
    popSuspenseHandler(workInProgress2);
    workInProgress2.memoizedState = null;
    return current;
  }
  function updateActivityComponent(current, workInProgress2, renderLanes2) {
    var nextProps = workInProgress2.pendingProps, didSuspend = 0 !== (workInProgress2.flags & 128);
    workInProgress2.flags &= -129;
    if (null === current) {
      if (isHydrating) {
        if ("hidden" === nextProps.mode)
          return current = mountActivityChildren(workInProgress2, nextProps), workInProgress2.lanes = 536870912, bailoutOffscreenComponent(null, current);
        pushDehydratedActivitySuspenseHandler(workInProgress2);
        (current = nextHydratableInstance) ? (current = canHydrateHydrationBoundary(
          current,
          rootOrSingletonContext
        ), current = null !== current && "&" === current.data ? current : null, null !== current && (workInProgress2.memoizedState = {
          dehydrated: current,
          treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
          retryLane: 536870912,
          hydrationErrors: null
        }, renderLanes2 = createFiberFromDehydratedFragment(current), renderLanes2.return = workInProgress2, workInProgress2.child = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : current = null;
        if (null === current) throw throwOnHydrationMismatch(workInProgress2);
        workInProgress2.lanes = 536870912;
        return null;
      }
      return mountActivityChildren(workInProgress2, nextProps);
    }
    var prevState = current.memoizedState;
    if (null !== prevState) {
      var dehydrated = prevState.dehydrated;
      pushDehydratedActivitySuspenseHandler(workInProgress2);
      if (didSuspend)
        if (workInProgress2.flags & 256)
          workInProgress2.flags &= -257, workInProgress2 = retryActivityComponentWithoutHydrating(
            current,
            workInProgress2,
            renderLanes2
          );
        else if (null !== workInProgress2.memoizedState)
          workInProgress2.child = current.child, workInProgress2.flags |= 128, workInProgress2 = null;
        else throw Error(formatProdErrorMessage(558));
      else if (didReceiveUpdate || propagateParentContextChanges(current, workInProgress2, renderLanes2, false), didSuspend = 0 !== (renderLanes2 & current.childLanes), didReceiveUpdate || didSuspend) {
        nextProps = workInProgressRoot;
        if (null !== nextProps && (dehydrated = getBumpedLaneForHydration(nextProps, renderLanes2), 0 !== dehydrated && dehydrated !== prevState.retryLane))
          throw prevState.retryLane = dehydrated, enqueueConcurrentRenderForLane(current, dehydrated), scheduleUpdateOnFiber(nextProps, current, dehydrated), SelectiveHydrationException;
        renderDidSuspendDelayIfPossible();
        workInProgress2 = retryActivityComponentWithoutHydrating(
          current,
          workInProgress2,
          renderLanes2
        );
      } else
        current = prevState.treeContext, nextHydratableInstance = getNextHydratable(dehydrated.nextSibling), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = false, null !== current && restoreSuspendedTreeContext(workInProgress2, current), workInProgress2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.flags |= 4096;
      return workInProgress2;
    }
    current = createWorkInProgress(current.child, {
      mode: nextProps.mode,
      children: nextProps.children
    });
    current.ref = workInProgress2.ref;
    workInProgress2.child = current;
    current.return = workInProgress2;
    return current;
  }
  function markRef(current, workInProgress2) {
    var ref2 = workInProgress2.ref;
    if (null === ref2)
      null !== current && null !== current.ref && (workInProgress2.flags |= 4194816);
    else {
      if ("function" !== typeof ref2 && "object" !== typeof ref2)
        throw Error(formatProdErrorMessage(284));
      if (null === current || current.ref !== ref2)
        workInProgress2.flags |= 4194816;
    }
  }
  function updateFunctionComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
    prepareToReadContext(workInProgress2);
    Component = renderWithHooks(
      current,
      workInProgress2,
      Component,
      nextProps,
      void 0,
      renderLanes2
    );
    nextProps = checkDidRenderIdHook();
    if (null !== current && !didReceiveUpdate)
      return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
    isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
    workInProgress2.flags |= 1;
    reconcileChildren(current, workInProgress2, Component, renderLanes2);
    return workInProgress2.child;
  }
  function replayFunctionComponent(current, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
    prepareToReadContext(workInProgress2);
    workInProgress2.updateQueue = null;
    nextProps = renderWithHooksAgain(
      workInProgress2,
      Component,
      nextProps,
      secondArg
    );
    finishRenderingHooks(current);
    Component = checkDidRenderIdHook();
    if (null !== current && !didReceiveUpdate)
      return bailoutHooks(current, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
    isHydrating && Component && pushMaterializedTreeId(workInProgress2);
    workInProgress2.flags |= 1;
    reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
    return workInProgress2.child;
  }
  function updateClassComponent(current, workInProgress2, Component, nextProps, renderLanes2) {
    prepareToReadContext(workInProgress2);
    if (null === workInProgress2.stateNode) {
      var context = emptyContextObject, contextType = Component.contextType;
      "object" === typeof contextType && null !== contextType && (context = readContext(contextType));
      context = new Component(nextProps, context);
      workInProgress2.memoizedState = null !== context.state && void 0 !== context.state ? context.state : null;
      context.updater = classComponentUpdater;
      workInProgress2.stateNode = context;
      context._reactInternals = workInProgress2;
      context = workInProgress2.stateNode;
      context.props = nextProps;
      context.state = workInProgress2.memoizedState;
      context.refs = {};
      initializeUpdateQueue(workInProgress2);
      contextType = Component.contextType;
      context.context = "object" === typeof contextType && null !== contextType ? readContext(contextType) : emptyContextObject;
      context.state = workInProgress2.memoizedState;
      contextType = Component.getDerivedStateFromProps;
      "function" === typeof contextType && (applyDerivedStateFromProps(
        workInProgress2,
        Component,
        contextType,
        nextProps
      ), context.state = workInProgress2.memoizedState);
      "function" === typeof Component.getDerivedStateFromProps || "function" === typeof context.getSnapshotBeforeUpdate || "function" !== typeof context.UNSAFE_componentWillMount && "function" !== typeof context.componentWillMount || (contextType = context.state, "function" === typeof context.componentWillMount && context.componentWillMount(), "function" === typeof context.UNSAFE_componentWillMount && context.UNSAFE_componentWillMount(), contextType !== context.state && classComponentUpdater.enqueueReplaceState(context, context.state, null), processUpdateQueue(workInProgress2, nextProps, context, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), context.state = workInProgress2.memoizedState);
      "function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308);
      nextProps = true;
    } else if (null === current) {
      context = workInProgress2.stateNode;
      var unresolvedOldProps = workInProgress2.memoizedProps, oldProps = resolveClassComponentProps(Component, unresolvedOldProps);
      context.props = oldProps;
      var oldContext = context.context, contextType$jscomp$0 = Component.contextType;
      contextType = emptyContextObject;
      "object" === typeof contextType$jscomp$0 && null !== contextType$jscomp$0 && (contextType = readContext(contextType$jscomp$0));
      var getDerivedStateFromProps = Component.getDerivedStateFromProps;
      contextType$jscomp$0 = "function" === typeof getDerivedStateFromProps || "function" === typeof context.getSnapshotBeforeUpdate;
      unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
      contextType$jscomp$0 || "function" !== typeof context.UNSAFE_componentWillReceiveProps && "function" !== typeof context.componentWillReceiveProps || (unresolvedOldProps || oldContext !== contextType) && callComponentWillReceiveProps(
        workInProgress2,
        context,
        nextProps,
        contextType
      );
      hasForceUpdate = false;
      var oldState = workInProgress2.memoizedState;
      context.state = oldState;
      processUpdateQueue(workInProgress2, nextProps, context, renderLanes2);
      suspendIfUpdateReadFromEntangledAsyncAction();
      oldContext = workInProgress2.memoizedState;
      unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof getDerivedStateFromProps && (applyDerivedStateFromProps(
        workInProgress2,
        Component,
        getDerivedStateFromProps,
        nextProps
      ), oldContext = workInProgress2.memoizedState), (oldProps = hasForceUpdate || checkShouldComponentUpdate(
        workInProgress2,
        Component,
        oldProps,
        nextProps,
        oldState,
        oldContext,
        contextType
      )) ? (contextType$jscomp$0 || "function" !== typeof context.UNSAFE_componentWillMount && "function" !== typeof context.componentWillMount || ("function" === typeof context.componentWillMount && context.componentWillMount(), "function" === typeof context.UNSAFE_componentWillMount && context.UNSAFE_componentWillMount()), "function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308)) : ("function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), context.props = nextProps, context.state = oldContext, context.context = contextType, nextProps = oldProps) : ("function" === typeof context.componentDidMount && (workInProgress2.flags |= 4194308), nextProps = false);
    } else {
      context = workInProgress2.stateNode;
      cloneUpdateQueue(current, workInProgress2);
      contextType = workInProgress2.memoizedProps;
      contextType$jscomp$0 = resolveClassComponentProps(Component, contextType);
      context.props = contextType$jscomp$0;
      getDerivedStateFromProps = workInProgress2.pendingProps;
      oldState = context.context;
      oldContext = Component.contextType;
      oldProps = emptyContextObject;
      "object" === typeof oldContext && null !== oldContext && (oldProps = readContext(oldContext));
      unresolvedOldProps = Component.getDerivedStateFromProps;
      (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof context.getSnapshotBeforeUpdate) || "function" !== typeof context.UNSAFE_componentWillReceiveProps && "function" !== typeof context.componentWillReceiveProps || (contextType !== getDerivedStateFromProps || oldState !== oldProps) && callComponentWillReceiveProps(
        workInProgress2,
        context,
        nextProps,
        oldProps
      );
      hasForceUpdate = false;
      oldState = workInProgress2.memoizedState;
      context.state = oldState;
      processUpdateQueue(workInProgress2, nextProps, context, renderLanes2);
      suspendIfUpdateReadFromEntangledAsyncAction();
      var newState = workInProgress2.memoizedState;
      contextType !== getDerivedStateFromProps || oldState !== newState || hasForceUpdate || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
        workInProgress2,
        Component,
        unresolvedOldProps,
        nextProps
      ), newState = workInProgress2.memoizedState), (contextType$jscomp$0 = hasForceUpdate || checkShouldComponentUpdate(
        workInProgress2,
        Component,
        contextType$jscomp$0,
        nextProps,
        oldState,
        newState,
        oldProps
      ) || null !== current && null !== current.dependencies && checkIfContextChanged(current.dependencies)) ? (oldContext || "function" !== typeof context.UNSAFE_componentWillUpdate && "function" !== typeof context.componentWillUpdate || ("function" === typeof context.componentWillUpdate && context.componentWillUpdate(nextProps, newState, oldProps), "function" === typeof context.UNSAFE_componentWillUpdate && context.UNSAFE_componentWillUpdate(
        nextProps,
        newState,
        oldProps
      )), "function" === typeof context.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof context.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof context.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), context.props = nextProps, context.state = newState, context.context = oldProps, nextProps = contextType$jscomp$0) : ("function" !== typeof context.componentDidUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof context.getSnapshotBeforeUpdate || contextType === current.memoizedProps && oldState === current.memoizedState || (workInProgress2.flags |= 1024), nextProps = false);
    }
    context = nextProps;
    markRef(current, workInProgress2);
    nextProps = 0 !== (workInProgress2.flags & 128);
    context || nextProps ? (context = workInProgress2.stateNode, Component = nextProps && "function" !== typeof Component.getDerivedStateFromError ? null : context.render(), workInProgress2.flags |= 1, null !== current && nextProps ? (workInProgress2.child = reconcileChildFibers(
      workInProgress2,
      current.child,
      null,
      renderLanes2
    ), workInProgress2.child = reconcileChildFibers(
      workInProgress2,
      null,
      Component,
      renderLanes2
    )) : reconcileChildren(current, workInProgress2, Component, renderLanes2), workInProgress2.memoizedState = context.state, current = workInProgress2.child) : current = bailoutOnAlreadyFinishedWork(
      current,
      workInProgress2,
      renderLanes2
    );
    return current;
  }
  function mountHostRootWithoutHydrating(current, workInProgress2, nextChildren, renderLanes2) {
    resetHydrationState();
    workInProgress2.flags |= 256;
    reconcileChildren(current, workInProgress2, nextChildren, renderLanes2);
    return workInProgress2.child;
  }
  var SUSPENDED_MARKER = {
    dehydrated: null,
    treeContext: null,
    retryLane: 0,
    hydrationErrors: null
  };
  function mountSuspenseOffscreenState(renderLanes2) {
    return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
  }
  function getRemainingWorkInPrimaryTree(current, primaryTreeDidDefer, renderLanes2) {
    current = null !== current ? current.childLanes & ~renderLanes2 : 0;
    primaryTreeDidDefer && (current |= workInProgressDeferredLane);
    return current;
  }
  function updateSuspenseComponent(current, workInProgress2, renderLanes2) {
    var nextProps = workInProgress2.pendingProps, showFallback = false, didSuspend = 0 !== (workInProgress2.flags & 128), JSCompiler_temp;
    (JSCompiler_temp = didSuspend) || (JSCompiler_temp = null !== current && null === current.memoizedState ? false : 0 !== (suspenseStackCursor.current & 2));
    JSCompiler_temp && (showFallback = true, workInProgress2.flags &= -129);
    JSCompiler_temp = 0 !== (workInProgress2.flags & 32);
    workInProgress2.flags &= -33;
    if (null === current) {
      if (isHydrating) {
        showFallback ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack();
        (current = nextHydratableInstance) ? (current = canHydrateHydrationBoundary(
          current,
          rootOrSingletonContext
        ), current = null !== current && "&" !== current.data ? current : null, null !== current && (workInProgress2.memoizedState = {
          dehydrated: current,
          treeContext: null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null,
          retryLane: 536870912,
          hydrationErrors: null
        }, renderLanes2 = createFiberFromDehydratedFragment(current), renderLanes2.return = workInProgress2, workInProgress2.child = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : current = null;
        if (null === current) throw throwOnHydrationMismatch(workInProgress2);
        isSuspenseInstanceFallback(current) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912;
        return null;
      }
      var nextPrimaryChildren = nextProps.children;
      nextProps = nextProps.fallback;
      if (showFallback)
        return reuseSuspenseHandlerOnStack(), showFallback = workInProgress2.mode, nextPrimaryChildren = mountWorkInProgressOffscreenFiber(
          { mode: "hidden", children: nextPrimaryChildren },
          showFallback
        ), nextProps = createFiberFromFragment(
          nextProps,
          showFallback,
          renderLanes2,
          null
        ), nextPrimaryChildren.return = workInProgress2, nextProps.return = workInProgress2, nextPrimaryChildren.sibling = nextProps, workInProgress2.child = nextPrimaryChildren, nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
          current,
          JSCompiler_temp,
          renderLanes2
        ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(null, nextProps);
      pushPrimaryTreeSuspenseHandler(workInProgress2);
      return mountSuspensePrimaryChildren(workInProgress2, nextPrimaryChildren);
    }
    var prevState = current.memoizedState;
    if (null !== prevState && (nextPrimaryChildren = prevState.dehydrated, null !== nextPrimaryChildren)) {
      if (didSuspend)
        workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
          current,
          workInProgress2,
          renderLanes2
        )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(), workInProgress2.child = current.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(), nextPrimaryChildren = nextProps.fallback, showFallback = workInProgress2.mode, nextProps = mountWorkInProgressOffscreenFiber(
          { mode: "visible", children: nextProps.children },
          showFallback
        ), nextPrimaryChildren = createFiberFromFragment(
          nextPrimaryChildren,
          showFallback,
          renderLanes2,
          null
        ), nextPrimaryChildren.flags |= 2, nextProps.return = workInProgress2, nextPrimaryChildren.return = workInProgress2, nextProps.sibling = nextPrimaryChildren, workInProgress2.child = nextProps, reconcileChildFibers(
          workInProgress2,
          current.child,
          null,
          renderLanes2
        ), nextProps = workInProgress2.child, nextProps.memoizedState = mountSuspenseOffscreenState(renderLanes2), nextProps.childLanes = getRemainingWorkInPrimaryTree(
          current,
          JSCompiler_temp,
          renderLanes2
        ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = bailoutOffscreenComponent(null, nextProps));
      else if (pushPrimaryTreeSuspenseHandler(workInProgress2), isSuspenseInstanceFallback(nextPrimaryChildren)) {
        JSCompiler_temp = nextPrimaryChildren.nextSibling && nextPrimaryChildren.nextSibling.dataset;
        if (JSCompiler_temp) var digest = JSCompiler_temp.dgst;
        JSCompiler_temp = digest;
        nextProps = Error(formatProdErrorMessage(419));
        nextProps.stack = "";
        nextProps.digest = JSCompiler_temp;
        queueHydrationError({ value: nextProps, source: null, stack: null });
        workInProgress2 = retrySuspenseComponentWithoutHydrating(
          current,
          workInProgress2,
          renderLanes2
        );
      } else if (didReceiveUpdate || propagateParentContextChanges(current, workInProgress2, renderLanes2, false), JSCompiler_temp = 0 !== (renderLanes2 & current.childLanes), didReceiveUpdate || JSCompiler_temp) {
        JSCompiler_temp = workInProgressRoot;
        if (null !== JSCompiler_temp && (nextProps = getBumpedLaneForHydration(JSCompiler_temp, renderLanes2), 0 !== nextProps && nextProps !== prevState.retryLane))
          throw prevState.retryLane = nextProps, enqueueConcurrentRenderForLane(current, nextProps), scheduleUpdateOnFiber(JSCompiler_temp, current, nextProps), SelectiveHydrationException;
        isSuspenseInstancePending(nextPrimaryChildren) || renderDidSuspendDelayIfPossible();
        workInProgress2 = retrySuspenseComponentWithoutHydrating(
          current,
          workInProgress2,
          renderLanes2
        );
      } else
        isSuspenseInstancePending(nextPrimaryChildren) ? (workInProgress2.flags |= 192, workInProgress2.child = current.child, workInProgress2 = null) : (current = prevState.treeContext, nextHydratableInstance = getNextHydratable(
          nextPrimaryChildren.nextSibling
        ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, rootOrSingletonContext = false, null !== current && restoreSuspendedTreeContext(workInProgress2, current), workInProgress2 = mountSuspensePrimaryChildren(
          workInProgress2,
          nextProps.children
        ), workInProgress2.flags |= 4096);
      return workInProgress2;
    }
    if (showFallback)
      return reuseSuspenseHandlerOnStack(), nextPrimaryChildren = nextProps.fallback, showFallback = workInProgress2.mode, prevState = current.child, digest = prevState.sibling, nextProps = createWorkInProgress(prevState, {
        mode: "hidden",
        children: nextProps.children
      }), nextProps.subtreeFlags = prevState.subtreeFlags & 65011712, null !== digest ? nextPrimaryChildren = createWorkInProgress(
        digest,
        nextPrimaryChildren
      ) : (nextPrimaryChildren = createFiberFromFragment(
        nextPrimaryChildren,
        showFallback,
        renderLanes2,
        null
      ), nextPrimaryChildren.flags |= 2), nextPrimaryChildren.return = workInProgress2, nextProps.return = workInProgress2, nextProps.sibling = nextPrimaryChildren, workInProgress2.child = nextProps, bailoutOffscreenComponent(null, nextProps), nextProps = workInProgress2.child, nextPrimaryChildren = current.child.memoizedState, null === nextPrimaryChildren ? nextPrimaryChildren = mountSuspenseOffscreenState(renderLanes2) : (showFallback = nextPrimaryChildren.cachePool, null !== showFallback ? (prevState = CacheContext._currentValue, showFallback = showFallback.parent !== prevState ? { parent: prevState, pool: prevState } : showFallback) : showFallback = getSuspendedCache(), nextPrimaryChildren = {
        baseLanes: nextPrimaryChildren.baseLanes | renderLanes2,
        cachePool: showFallback
      }), nextProps.memoizedState = nextPrimaryChildren, nextProps.childLanes = getRemainingWorkInPrimaryTree(
        current,
        JSCompiler_temp,
        renderLanes2
      ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(current.child, nextProps);
    pushPrimaryTreeSuspenseHandler(workInProgress2);
    renderLanes2 = current.child;
    current = renderLanes2.sibling;
    renderLanes2 = createWorkInProgress(renderLanes2, {
      mode: "visible",
      children: nextProps.children
    });
    renderLanes2.return = workInProgress2;
    renderLanes2.sibling = null;
    null !== current && (JSCompiler_temp = workInProgress2.deletions, null === JSCompiler_temp ? (workInProgress2.deletions = [current], workInProgress2.flags |= 16) : JSCompiler_temp.push(current));
    workInProgress2.child = renderLanes2;
    workInProgress2.memoizedState = null;
    return renderLanes2;
  }
  function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
    primaryChildren = mountWorkInProgressOffscreenFiber(
      { mode: "visible", children: primaryChildren },
      workInProgress2.mode
    );
    primaryChildren.return = workInProgress2;
    return workInProgress2.child = primaryChildren;
  }
  function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
    offscreenProps = createFiberImplClass(22, offscreenProps, null, mode);
    offscreenProps.lanes = 0;
    return offscreenProps;
  }
  function retrySuspenseComponentWithoutHydrating(current, workInProgress2, renderLanes2) {
    reconcileChildFibers(workInProgress2, current.child, null, renderLanes2);
    current = mountSuspensePrimaryChildren(
      workInProgress2,
      workInProgress2.pendingProps.children
    );
    current.flags |= 2;
    workInProgress2.memoizedState = null;
    return current;
  }
  function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
    fiber.lanes |= renderLanes2;
    var alternate = fiber.alternate;
    null !== alternate && (alternate.lanes |= renderLanes2);
    scheduleContextWorkOnParentPath(fiber.return, renderLanes2, propagationRoot);
  }
  function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode, treeForkCount2) {
    var renderState = workInProgress2.memoizedState;
    null === renderState ? workInProgress2.memoizedState = {
      isBackwards,
      rendering: null,
      renderingStartTime: 0,
      last: lastContentRow,
      tail,
      tailMode,
      treeForkCount: treeForkCount2
    } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode, renderState.treeForkCount = treeForkCount2);
  }
  function updateSuspenseListComponent(current, workInProgress2, renderLanes2) {
    var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail;
    nextProps = nextProps.children;
    var suspenseContext = suspenseStackCursor.current, shouldForceFallback = 0 !== (suspenseContext & 2);
    shouldForceFallback ? (suspenseContext = suspenseContext & 1 | 2, workInProgress2.flags |= 128) : suspenseContext &= 1;
    push2(suspenseStackCursor, suspenseContext);
    reconcileChildren(current, workInProgress2, nextProps, renderLanes2);
    nextProps = isHydrating ? treeForkCount : 0;
    if (!shouldForceFallback && null !== current && 0 !== (current.flags & 128))
      a: for (current = workInProgress2.child; null !== current; ) {
        if (13 === current.tag)
          null !== current.memoizedState && scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
        else if (19 === current.tag)
          scheduleSuspenseWorkOnFiber(current, renderLanes2, workInProgress2);
        else if (null !== current.child) {
          current.child.return = current;
          current = current.child;
          continue;
        }
        if (current === workInProgress2) break a;
        for (; null === current.sibling; ) {
          if (null === current.return || current.return === workInProgress2)
            break a;
          current = current.return;
        }
        current.sibling.return = current.return;
        current = current.sibling;
      }
    switch (revealOrder) {
      case "forwards":
        renderLanes2 = workInProgress2.child;
        for (revealOrder = null; null !== renderLanes2; )
          current = renderLanes2.alternate, null !== current && null === findFirstSuspended(current) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
        renderLanes2 = revealOrder;
        null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
        initSuspenseListRenderState(
          workInProgress2,
          false,
          revealOrder,
          renderLanes2,
          tailMode,
          nextProps
        );
        break;
      case "backwards":
      case "unstable_legacy-backwards":
        renderLanes2 = null;
        revealOrder = workInProgress2.child;
        for (workInProgress2.child = null; null !== revealOrder; ) {
          current = revealOrder.alternate;
          if (null !== current && null === findFirstSuspended(current)) {
            workInProgress2.child = revealOrder;
            break;
          }
          current = revealOrder.sibling;
          revealOrder.sibling = renderLanes2;
          renderLanes2 = revealOrder;
          revealOrder = current;
        }
        initSuspenseListRenderState(
          workInProgress2,
          true,
          renderLanes2,
          null,
          tailMode,
          nextProps
        );
        break;
      case "together":
        initSuspenseListRenderState(
          workInProgress2,
          false,
          null,
          null,
          void 0,
          nextProps
        );
        break;
      default:
        workInProgress2.memoizedState = null;
    }
    return workInProgress2.child;
  }
  function bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2) {
    null !== current && (workInProgress2.dependencies = current.dependencies);
    workInProgressRootSkippedLanes |= workInProgress2.lanes;
    if (0 === (renderLanes2 & workInProgress2.childLanes))
      if (null !== current) {
        if (propagateParentContextChanges(
          current,
          workInProgress2,
          renderLanes2,
          false
        ), 0 === (renderLanes2 & workInProgress2.childLanes))
          return null;
      } else return null;
    if (null !== current && workInProgress2.child !== current.child)
      throw Error(formatProdErrorMessage(153));
    if (null !== workInProgress2.child) {
      current = workInProgress2.child;
      renderLanes2 = createWorkInProgress(current, current.pendingProps);
      workInProgress2.child = renderLanes2;
      for (renderLanes2.return = workInProgress2; null !== current.sibling; )
        current = current.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current, current.pendingProps), renderLanes2.return = workInProgress2;
      renderLanes2.sibling = null;
    }
    return workInProgress2.child;
  }
  function checkScheduledUpdateOrContext(current, renderLanes2) {
    if (0 !== (current.lanes & renderLanes2)) return true;
    current = current.dependencies;
    return null !== current && checkIfContextChanged(current) ? true : false;
  }
  function attemptEarlyBailoutIfNoScheduledUpdate(current, workInProgress2, renderLanes2) {
    switch (workInProgress2.tag) {
      case 3:
        pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
        pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
        resetHydrationState();
        break;
      case 27:
      case 5:
        pushHostContext(workInProgress2);
        break;
      case 4:
        pushHostContainer(workInProgress2, workInProgress2.stateNode.containerInfo);
        break;
      case 10:
        pushProvider(
          workInProgress2,
          workInProgress2.type,
          workInProgress2.memoizedProps.value
        );
        break;
      case 31:
        if (null !== workInProgress2.memoizedState)
          return workInProgress2.flags |= 128, pushDehydratedActivitySuspenseHandler(workInProgress2), null;
        break;
      case 13:
        var state$102 = workInProgress2.memoizedState;
        if (null !== state$102) {
          if (null !== state$102.dehydrated)
            return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
          if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
            return updateSuspenseComponent(current, workInProgress2, renderLanes2);
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          current = bailoutOnAlreadyFinishedWork(
            current,
            workInProgress2,
            renderLanes2
          );
          return null !== current ? current.sibling : null;
        }
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        break;
      case 19:
        var didSuspendBefore = 0 !== (current.flags & 128);
        state$102 = 0 !== (renderLanes2 & workInProgress2.childLanes);
        state$102 || (propagateParentContextChanges(
          current,
          workInProgress2,
          renderLanes2,
          false
        ), state$102 = 0 !== (renderLanes2 & workInProgress2.childLanes));
        if (didSuspendBefore) {
          if (state$102)
            return updateSuspenseListComponent(
              current,
              workInProgress2,
              renderLanes2
            );
          workInProgress2.flags |= 128;
        }
        didSuspendBefore = workInProgress2.memoizedState;
        null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
        push2(suspenseStackCursor, suspenseStackCursor.current);
        if (state$102) break;
        else return null;
      case 22:
        return workInProgress2.lanes = 0, updateOffscreenComponent(
          current,
          workInProgress2,
          renderLanes2,
          workInProgress2.pendingProps
        );
      case 24:
        pushProvider(workInProgress2, CacheContext, current.memoizedState.cache);
    }
    return bailoutOnAlreadyFinishedWork(current, workInProgress2, renderLanes2);
  }
  function beginWork(current, workInProgress2, renderLanes2) {
    if (null !== current)
      if (current.memoizedProps !== workInProgress2.pendingProps)
        didReceiveUpdate = true;
      else {
        if (!checkScheduledUpdateOrContext(current, renderLanes2) && 0 === (workInProgress2.flags & 128))
          return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
            current,
            workInProgress2,
            renderLanes2
          );
        didReceiveUpdate = 0 !== (current.flags & 131072) ? true : false;
      }
    else
      didReceiveUpdate = false, isHydrating && 0 !== (workInProgress2.flags & 1048576) && pushTreeId(workInProgress2, treeForkCount, workInProgress2.index);
    workInProgress2.lanes = 0;
    switch (workInProgress2.tag) {
      case 16:
        a: {
          var props = workInProgress2.pendingProps;
          current = resolveLazy(workInProgress2.elementType);
          workInProgress2.type = current;
          if ("function" === typeof current)
            shouldConstruct(current) ? (props = resolveClassComponentProps(current, props), workInProgress2.tag = 1, workInProgress2 = updateClassComponent(
              null,
              workInProgress2,
              current,
              props,
              renderLanes2
            )) : (workInProgress2.tag = 0, workInProgress2 = updateFunctionComponent(
              null,
              workInProgress2,
              current,
              props,
              renderLanes2
            ));
          else {
            if (void 0 !== current && null !== current) {
              var $$typeof = current.$$typeof;
              if ($$typeof === REACT_FORWARD_REF_TYPE) {
                workInProgress2.tag = 11;
                workInProgress2 = updateForwardRef(
                  null,
                  workInProgress2,
                  current,
                  props,
                  renderLanes2
                );
                break a;
              } else if ($$typeof === REACT_MEMO_TYPE) {
                workInProgress2.tag = 14;
                workInProgress2 = updateMemoComponent(
                  null,
                  workInProgress2,
                  current,
                  props,
                  renderLanes2
                );
                break a;
              }
            }
            workInProgress2 = getComponentNameFromType(current) || current;
            throw Error(formatProdErrorMessage(306, workInProgress2, ""));
          }
        }
        return workInProgress2;
      case 0:
        return updateFunctionComponent(
          current,
          workInProgress2,
          workInProgress2.type,
          workInProgress2.pendingProps,
          renderLanes2
        );
      case 1:
        return props = workInProgress2.type, $$typeof = resolveClassComponentProps(
          props,
          workInProgress2.pendingProps
        ), updateClassComponent(
          current,
          workInProgress2,
          props,
          $$typeof,
          renderLanes2
        );
      case 3:
        a: {
          pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          );
          if (null === current) throw Error(formatProdErrorMessage(387));
          props = workInProgress2.pendingProps;
          var prevState = workInProgress2.memoizedState;
          $$typeof = prevState.element;
          cloneUpdateQueue(current, workInProgress2);
          processUpdateQueue(workInProgress2, props, null, renderLanes2);
          var nextState = workInProgress2.memoizedState;
          props = nextState.cache;
          pushProvider(workInProgress2, CacheContext, props);
          props !== prevState.cache && propagateContextChanges(
            workInProgress2,
            [CacheContext],
            renderLanes2,
            true
          );
          suspendIfUpdateReadFromEntangledAsyncAction();
          props = nextState.element;
          if (prevState.isDehydrated)
            if (prevState = {
              element: props,
              isDehydrated: false,
              cache: nextState.cache
            }, workInProgress2.updateQueue.baseState = prevState, workInProgress2.memoizedState = prevState, workInProgress2.flags & 256) {
              workInProgress2 = mountHostRootWithoutHydrating(
                current,
                workInProgress2,
                props,
                renderLanes2
              );
              break a;
            } else if (props !== $$typeof) {
              $$typeof = createCapturedValueAtFiber(
                Error(formatProdErrorMessage(424)),
                workInProgress2
              );
              queueHydrationError($$typeof);
              workInProgress2 = mountHostRootWithoutHydrating(
                current,
                workInProgress2,
                props,
                renderLanes2
              );
              break a;
            } else {
              current = workInProgress2.stateNode.containerInfo;
              switch (current.nodeType) {
                case 9:
                  current = current.body;
                  break;
                default:
                  current = "HTML" === current.nodeName ? current.ownerDocument.body : current;
              }
              nextHydratableInstance = getNextHydratable(current.firstChild);
              hydrationParentFiber = workInProgress2;
              isHydrating = true;
              hydrationErrors = null;
              rootOrSingletonContext = true;
              renderLanes2 = mountChildFibers(
                workInProgress2,
                null,
                props,
                renderLanes2
              );
              for (workInProgress2.child = renderLanes2; renderLanes2; )
                renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
            }
          else {
            resetHydrationState();
            if (props === $$typeof) {
              workInProgress2 = bailoutOnAlreadyFinishedWork(
                current,
                workInProgress2,
                renderLanes2
              );
              break a;
            }
            reconcileChildren(current, workInProgress2, props, renderLanes2);
          }
          workInProgress2 = workInProgress2.child;
        }
        return workInProgress2;
      case 26:
        return markRef(current, workInProgress2), null === current ? (renderLanes2 = getResource(
          workInProgress2.type,
          null,
          workInProgress2.pendingProps,
          null
        )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (renderLanes2 = workInProgress2.type, current = workInProgress2.pendingProps, props = getOwnerDocumentFromRootContainer(
          rootInstanceStackCursor.current
        ).createElement(renderLanes2), props[internalInstanceKey] = workInProgress2, props[internalPropsKey] = current, setInitialProperties(props, renderLanes2, current), markNodeAsHoistable(props), workInProgress2.stateNode = props) : workInProgress2.memoizedState = getResource(
          workInProgress2.type,
          current.memoizedProps,
          workInProgress2.pendingProps,
          current.memoizedState
        ), null;
      case 27:
        return pushHostContext(workInProgress2), null === current && isHydrating && (props = workInProgress2.stateNode = resolveSingletonInstance(
          workInProgress2.type,
          workInProgress2.pendingProps,
          rootInstanceStackCursor.current
        ), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, $$typeof = nextHydratableInstance, isSingletonScope(workInProgress2.type) ? (previousHydratableOnEnteringScopedSingleton = $$typeof, nextHydratableInstance = getNextHydratable(props.firstChild)) : nextHydratableInstance = $$typeof), reconcileChildren(
          current,
          workInProgress2,
          workInProgress2.pendingProps.children,
          renderLanes2
        ), markRef(current, workInProgress2), null === current && (workInProgress2.flags |= 4194304), workInProgress2.child;
      case 5:
        if (null === current && isHydrating) {
          if ($$typeof = props = nextHydratableInstance)
            props = canHydrateInstance(
              props,
              workInProgress2.type,
              workInProgress2.pendingProps,
              rootOrSingletonContext
            ), null !== props ? (workInProgress2.stateNode = props, hydrationParentFiber = workInProgress2, nextHydratableInstance = getNextHydratable(props.firstChild), rootOrSingletonContext = false, $$typeof = true) : $$typeof = false;
          $$typeof || throwOnHydrationMismatch(workInProgress2);
        }
        pushHostContext(workInProgress2);
        $$typeof = workInProgress2.type;
        prevState = workInProgress2.pendingProps;
        nextState = null !== current ? current.memoizedProps : null;
        props = prevState.children;
        shouldSetTextContent($$typeof, prevState) ? props = null : null !== nextState && shouldSetTextContent($$typeof, nextState) && (workInProgress2.flags |= 32);
        null !== workInProgress2.memoizedState && ($$typeof = renderWithHooks(
          current,
          workInProgress2,
          TransitionAwareHostComponent,
          null,
          null,
          renderLanes2
        ), HostTransitionContext._currentValue = $$typeof);
        markRef(current, workInProgress2);
        reconcileChildren(current, workInProgress2, props, renderLanes2);
        return workInProgress2.child;
      case 6:
        if (null === current && isHydrating) {
          if (current = renderLanes2 = nextHydratableInstance)
            renderLanes2 = canHydrateTextInstance(
              renderLanes2,
              workInProgress2.pendingProps,
              rootOrSingletonContext
            ), null !== renderLanes2 ? (workInProgress2.stateNode = renderLanes2, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, current = true) : current = false;
          current || throwOnHydrationMismatch(workInProgress2);
        }
        return null;
      case 13:
        return updateSuspenseComponent(current, workInProgress2, renderLanes2);
      case 4:
        return pushHostContainer(
          workInProgress2,
          workInProgress2.stateNode.containerInfo
        ), props = workInProgress2.pendingProps, null === current ? workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          null,
          props,
          renderLanes2
        ) : reconcileChildren(current, workInProgress2, props, renderLanes2), workInProgress2.child;
      case 11:
        return updateForwardRef(
          current,
          workInProgress2,
          workInProgress2.type,
          workInProgress2.pendingProps,
          renderLanes2
        );
      case 7:
        return reconcileChildren(
          current,
          workInProgress2,
          workInProgress2.pendingProps,
          renderLanes2
        ), workInProgress2.child;
      case 8:
        return reconcileChildren(
          current,
          workInProgress2,
          workInProgress2.pendingProps.children,
          renderLanes2
        ), workInProgress2.child;
      case 12:
        return reconcileChildren(
          current,
          workInProgress2,
          workInProgress2.pendingProps.children,
          renderLanes2
        ), workInProgress2.child;
      case 10:
        return props = workInProgress2.pendingProps, pushProvider(workInProgress2, workInProgress2.type, props.value), reconcileChildren(current, workInProgress2, props.children, renderLanes2), workInProgress2.child;
      case 9:
        return $$typeof = workInProgress2.type._context, props = workInProgress2.pendingProps.children, prepareToReadContext(workInProgress2), $$typeof = readContext($$typeof), props = props($$typeof), workInProgress2.flags |= 1, reconcileChildren(current, workInProgress2, props, renderLanes2), workInProgress2.child;
      case 14:
        return updateMemoComponent(
          current,
          workInProgress2,
          workInProgress2.type,
          workInProgress2.pendingProps,
          renderLanes2
        );
      case 15:
        return updateSimpleMemoComponent(
          current,
          workInProgress2,
          workInProgress2.type,
          workInProgress2.pendingProps,
          renderLanes2
        );
      case 19:
        return updateSuspenseListComponent(current, workInProgress2, renderLanes2);
      case 31:
        return updateActivityComponent(current, workInProgress2, renderLanes2);
      case 22:
        return updateOffscreenComponent(
          current,
          workInProgress2,
          renderLanes2,
          workInProgress2.pendingProps
        );
      case 24:
        return prepareToReadContext(workInProgress2), props = readContext(CacheContext), null === current ? ($$typeof = peekCacheFromPool(), null === $$typeof && ($$typeof = workInProgressRoot, prevState = createCache(), $$typeof.pooledCache = prevState, prevState.refCount++, null !== prevState && ($$typeof.pooledCacheLanes |= renderLanes2), $$typeof = prevState), workInProgress2.memoizedState = { parent: props, cache: $$typeof }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, $$typeof)) : (0 !== (current.lanes & renderLanes2) && (cloneUpdateQueue(current, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), $$typeof = current.memoizedState, prevState = workInProgress2.memoizedState, $$typeof.parent !== props ? ($$typeof = { parent: props, cache: props }, workInProgress2.memoizedState = $$typeof, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = $$typeof), pushProvider(workInProgress2, CacheContext, props)) : (props = prevState.cache, pushProvider(workInProgress2, CacheContext, props), props !== $$typeof.cache && propagateContextChanges(
          workInProgress2,
          [CacheContext],
          renderLanes2,
          true
        ))), reconcileChildren(
          current,
          workInProgress2,
          workInProgress2.pendingProps.children,
          renderLanes2
        ), workInProgress2.child;
      case 29:
        throw workInProgress2.pendingProps;
    }
    throw Error(formatProdErrorMessage(156, workInProgress2.tag));
  }
  function markUpdate(workInProgress2) {
    workInProgress2.flags |= 4;
  }
  function preloadInstanceAndSuspendIfNeeded(workInProgress2, type2, oldProps, newProps, renderLanes2) {
    if (type2 = 0 !== (workInProgress2.mode & 32)) type2 = false;
    if (type2) {
      if (workInProgress2.flags |= 16777216, (renderLanes2 & 335544128) === renderLanes2)
        if (workInProgress2.stateNode.complete) workInProgress2.flags |= 8192;
        else if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
        else
          throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
    } else workInProgress2.flags &= -16777217;
  }
  function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
    if ("stylesheet" !== resource.type || 0 !== (resource.state.loading & 4))
      workInProgress2.flags &= -16777217;
    else if (workInProgress2.flags |= 16777216, !preloadResource(resource))
      if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
      else
        throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
  }
  function scheduleRetryEffect(workInProgress2, retryQueue) {
    null !== retryQueue && (workInProgress2.flags |= 4);
    workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
  }
  function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
    if (!isHydrating)
      switch (renderState.tailMode) {
        case "hidden":
          hasRenderedATailFallback = renderState.tail;
          for (var lastTailNode = null; null !== hasRenderedATailFallback; )
            null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
          null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
          break;
        case "collapsed":
          lastTailNode = renderState.tail;
          for (var lastTailNode$106 = null; null !== lastTailNode; )
            null !== lastTailNode.alternate && (lastTailNode$106 = lastTailNode), lastTailNode = lastTailNode.sibling;
          null === lastTailNode$106 ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : lastTailNode$106.sibling = null;
      }
  }
  function bubbleProperties(completedWork) {
    var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
    if (didBailout)
      for (var child$107 = completedWork.child; null !== child$107; )
        newChildLanes |= child$107.lanes | child$107.childLanes, subtreeFlags |= child$107.subtreeFlags & 65011712, subtreeFlags |= child$107.flags & 65011712, child$107.return = completedWork, child$107 = child$107.sibling;
    else
      for (child$107 = completedWork.child; null !== child$107; )
        newChildLanes |= child$107.lanes | child$107.childLanes, subtreeFlags |= child$107.subtreeFlags, subtreeFlags |= child$107.flags, child$107.return = completedWork, child$107 = child$107.sibling;
    completedWork.subtreeFlags |= subtreeFlags;
    completedWork.childLanes = newChildLanes;
    return didBailout;
  }
  function completeWork(current, workInProgress2, renderLanes2) {
    var newProps = workInProgress2.pendingProps;
    popTreeContext(workInProgress2);
    switch (workInProgress2.tag) {
      case 16:
      case 15:
      case 0:
      case 11:
      case 7:
      case 8:
      case 12:
      case 9:
      case 14:
        return bubbleProperties(workInProgress2), null;
      case 1:
        return bubbleProperties(workInProgress2), null;
      case 3:
        renderLanes2 = workInProgress2.stateNode;
        newProps = null;
        null !== current && (newProps = current.memoizedState.cache);
        workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
        popProvider(CacheContext);
        popHostContainer();
        renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
        if (null === current || null === current.child)
          popHydrationState(workInProgress2) ? markUpdate(workInProgress2) : null === current || current.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
        bubbleProperties(workInProgress2);
        return null;
      case 26:
        var type2 = workInProgress2.type, nextResource = workInProgress2.memoizedState;
        null === current ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(workInProgress2, nextResource)) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
          workInProgress2,
          type2,
          null,
          newProps,
          renderLanes2
        ))) : nextResource ? nextResource !== current.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(workInProgress2, nextResource)) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (current = current.memoizedProps, current !== newProps && markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
          workInProgress2,
          type2,
          current,
          newProps,
          renderLanes2
        ));
        return null;
      case 27:
        popHostContext(workInProgress2);
        renderLanes2 = rootInstanceStackCursor.current;
        type2 = workInProgress2.type;
        if (null !== current && null != workInProgress2.stateNode)
          current.memoizedProps !== newProps && markUpdate(workInProgress2);
        else {
          if (!newProps) {
            if (null === workInProgress2.stateNode)
              throw Error(formatProdErrorMessage(166));
            bubbleProperties(workInProgress2);
            return null;
          }
          current = contextStackCursor.current;
          popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2) : (current = resolveSingletonInstance(type2, newProps, renderLanes2), workInProgress2.stateNode = current, markUpdate(workInProgress2));
        }
        bubbleProperties(workInProgress2);
        return null;
      case 5:
        popHostContext(workInProgress2);
        type2 = workInProgress2.type;
        if (null !== current && null != workInProgress2.stateNode)
          current.memoizedProps !== newProps && markUpdate(workInProgress2);
        else {
          if (!newProps) {
            if (null === workInProgress2.stateNode)
              throw Error(formatProdErrorMessage(166));
            bubbleProperties(workInProgress2);
            return null;
          }
          nextResource = contextStackCursor.current;
          if (popHydrationState(workInProgress2))
            prepareToHydrateHostInstance(workInProgress2);
          else {
            var ownerDocument = getOwnerDocumentFromRootContainer(
              rootInstanceStackCursor.current
            );
            switch (nextResource) {
              case 1:
                nextResource = ownerDocument.createElementNS(
                  "http://www.w3.org/2000/svg",
                  type2
                );
                break;
              case 2:
                nextResource = ownerDocument.createElementNS(
                  "http://www.w3.org/1998/Math/MathML",
                  type2
                );
                break;
              default:
                switch (type2) {
                  case "svg":
                    nextResource = ownerDocument.createElementNS(
                      "http://www.w3.org/2000/svg",
                      type2
                    );
                    break;
                  case "math":
                    nextResource = ownerDocument.createElementNS(
                      "http://www.w3.org/1998/Math/MathML",
                      type2
                    );
                    break;
                  case "script":
                    nextResource = ownerDocument.createElement("div");
                    nextResource.innerHTML = "<script><\/script>";
                    nextResource = nextResource.removeChild(
                      nextResource.firstChild
                    );
                    break;
                  case "select":
                    nextResource = "string" === typeof newProps.is ? ownerDocument.createElement("select", {
                      is: newProps.is
                    }) : ownerDocument.createElement("select");
                    newProps.multiple ? nextResource.multiple = true : newProps.size && (nextResource.size = newProps.size);
                    break;
                  default:
                    nextResource = "string" === typeof newProps.is ? ownerDocument.createElement(type2, { is: newProps.is }) : ownerDocument.createElement(type2);
                }
            }
            nextResource[internalInstanceKey] = workInProgress2;
            nextResource[internalPropsKey] = newProps;
            a: for (ownerDocument = workInProgress2.child; null !== ownerDocument; ) {
              if (5 === ownerDocument.tag || 6 === ownerDocument.tag)
                nextResource.appendChild(ownerDocument.stateNode);
              else if (4 !== ownerDocument.tag && 27 !== ownerDocument.tag && null !== ownerDocument.child) {
                ownerDocument.child.return = ownerDocument;
                ownerDocument = ownerDocument.child;
                continue;
              }
              if (ownerDocument === workInProgress2) break a;
              for (; null === ownerDocument.sibling; ) {
                if (null === ownerDocument.return || ownerDocument.return === workInProgress2)
                  break a;
                ownerDocument = ownerDocument.return;
              }
              ownerDocument.sibling.return = ownerDocument.return;
              ownerDocument = ownerDocument.sibling;
            }
            workInProgress2.stateNode = nextResource;
            a: switch (setInitialProperties(nextResource, type2, newProps), type2) {
              case "button":
              case "input":
              case "select":
              case "textarea":
                newProps = !!newProps.autoFocus;
                break a;
              case "img":
                newProps = true;
                break a;
              default:
                newProps = false;
            }
            newProps && markUpdate(workInProgress2);
          }
        }
        bubbleProperties(workInProgress2);
        preloadInstanceAndSuspendIfNeeded(
          workInProgress2,
          workInProgress2.type,
          null === current ? null : current.memoizedProps,
          workInProgress2.pendingProps,
          renderLanes2
        );
        return null;
      case 6:
        if (current && null != workInProgress2.stateNode)
          current.memoizedProps !== newProps && markUpdate(workInProgress2);
        else {
          if ("string" !== typeof newProps && null === workInProgress2.stateNode)
            throw Error(formatProdErrorMessage(166));
          current = rootInstanceStackCursor.current;
          if (popHydrationState(workInProgress2)) {
            current = workInProgress2.stateNode;
            renderLanes2 = workInProgress2.memoizedProps;
            newProps = null;
            type2 = hydrationParentFiber;
            if (null !== type2)
              switch (type2.tag) {
                case 27:
                case 5:
                  newProps = type2.memoizedProps;
              }
            current[internalInstanceKey] = workInProgress2;
            current = current.nodeValue === renderLanes2 || null !== newProps && true === newProps.suppressHydrationWarning || checkForUnmatchedText(current.nodeValue, renderLanes2) ? true : false;
            current || throwOnHydrationMismatch(workInProgress2, true);
          } else
            current = getOwnerDocumentFromRootContainer(current).createTextNode(
              newProps
            ), current[internalInstanceKey] = workInProgress2, workInProgress2.stateNode = current;
        }
        bubbleProperties(workInProgress2);
        return null;
      case 31:
        renderLanes2 = workInProgress2.memoizedState;
        if (null === current || null !== current.memoizedState) {
          newProps = popHydrationState(workInProgress2);
          if (null !== renderLanes2) {
            if (null === current) {
              if (!newProps) throw Error(formatProdErrorMessage(318));
              current = workInProgress2.memoizedState;
              current = null !== current ? current.dehydrated : null;
              if (!current) throw Error(formatProdErrorMessage(557));
              current[internalInstanceKey] = workInProgress2;
            } else
              resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4;
            bubbleProperties(workInProgress2);
            current = false;
          } else
            renderLanes2 = upgradeHydrationErrorsToRecoverable(), null !== current && null !== current.memoizedState && (current.memoizedState.hydrationErrors = renderLanes2), current = true;
          if (!current) {
            if (workInProgress2.flags & 256)
              return popSuspenseHandler(workInProgress2), workInProgress2;
            popSuspenseHandler(workInProgress2);
            return null;
          }
          if (0 !== (workInProgress2.flags & 128))
            throw Error(formatProdErrorMessage(558));
        }
        bubbleProperties(workInProgress2);
        return null;
      case 13:
        newProps = workInProgress2.memoizedState;
        if (null === current || null !== current.memoizedState && null !== current.memoizedState.dehydrated) {
          type2 = popHydrationState(workInProgress2);
          if (null !== newProps && null !== newProps.dehydrated) {
            if (null === current) {
              if (!type2) throw Error(formatProdErrorMessage(318));
              type2 = workInProgress2.memoizedState;
              type2 = null !== type2 ? type2.dehydrated : null;
              if (!type2) throw Error(formatProdErrorMessage(317));
              type2[internalInstanceKey] = workInProgress2;
            } else
              resetHydrationState(), 0 === (workInProgress2.flags & 128) && (workInProgress2.memoizedState = null), workInProgress2.flags |= 4;
            bubbleProperties(workInProgress2);
            type2 = false;
          } else
            type2 = upgradeHydrationErrorsToRecoverable(), null !== current && null !== current.memoizedState && (current.memoizedState.hydrationErrors = type2), type2 = true;
          if (!type2) {
            if (workInProgress2.flags & 256)
              return popSuspenseHandler(workInProgress2), workInProgress2;
            popSuspenseHandler(workInProgress2);
            return null;
          }
        }
        popSuspenseHandler(workInProgress2);
        if (0 !== (workInProgress2.flags & 128))
          return workInProgress2.lanes = renderLanes2, workInProgress2;
        renderLanes2 = null !== newProps;
        current = null !== current && null !== current.memoizedState;
        renderLanes2 && (newProps = workInProgress2.child, type2 = null, null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (type2 = newProps.alternate.memoizedState.cachePool.pool), nextResource = null, null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (nextResource = newProps.memoizedState.cachePool.pool), nextResource !== type2 && (newProps.flags |= 2048));
        renderLanes2 !== current && renderLanes2 && (workInProgress2.child.flags |= 8192);
        scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
        bubbleProperties(workInProgress2);
        return null;
      case 4:
        return popHostContainer(), null === current && listenToAllSupportedEvents(workInProgress2.stateNode.containerInfo), bubbleProperties(workInProgress2), null;
      case 10:
        return popProvider(workInProgress2.type), bubbleProperties(workInProgress2), null;
      case 19:
        pop(suspenseStackCursor);
        newProps = workInProgress2.memoizedState;
        if (null === newProps) return bubbleProperties(workInProgress2), null;
        type2 = 0 !== (workInProgress2.flags & 128);
        nextResource = newProps.rendering;
        if (null === nextResource)
          if (type2) cutOffTailIfNeeded(newProps, false);
          else {
            if (0 !== workInProgressRootExitStatus || null !== current && 0 !== (current.flags & 128))
              for (current = workInProgress2.child; null !== current; ) {
                nextResource = findFirstSuspended(current);
                if (null !== nextResource) {
                  workInProgress2.flags |= 128;
                  cutOffTailIfNeeded(newProps, false);
                  current = nextResource.updateQueue;
                  workInProgress2.updateQueue = current;
                  scheduleRetryEffect(workInProgress2, current);
                  workInProgress2.subtreeFlags = 0;
                  current = renderLanes2;
                  for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                    resetWorkInProgress(renderLanes2, current), renderLanes2 = renderLanes2.sibling;
                  push2(
                    suspenseStackCursor,
                    suspenseStackCursor.current & 1 | 2
                  );
                  isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount);
                  return workInProgress2.child;
                }
                current = current.sibling;
              }
            null !== newProps.tail && now() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, type2 = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
          }
        else {
          if (!type2)
            if (current = findFirstSuspended(nextResource), null !== current) {
              if (workInProgress2.flags |= 128, type2 = true, current = current.updateQueue, workInProgress2.updateQueue = current, scheduleRetryEffect(workInProgress2, current), cutOffTailIfNeeded(newProps, true), null === newProps.tail && "hidden" === newProps.tailMode && !nextResource.alternate && !isHydrating)
                return bubbleProperties(workInProgress2), null;
            } else
              2 * now() - newProps.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, type2 = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
          newProps.isBackwards ? (nextResource.sibling = workInProgress2.child, workInProgress2.child = nextResource) : (current = newProps.last, null !== current ? current.sibling = nextResource : workInProgress2.child = nextResource, newProps.last = nextResource);
        }
        if (null !== newProps.tail)
          return current = newProps.tail, newProps.rendering = current, newProps.tail = current.sibling, newProps.renderingStartTime = now(), current.sibling = null, renderLanes2 = suspenseStackCursor.current, push2(
            suspenseStackCursor,
            type2 ? renderLanes2 & 1 | 2 : renderLanes2 & 1
          ), isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount), current;
        bubbleProperties(workInProgress2);
        return null;
      case 22:
      case 23:
        return popSuspenseHandler(workInProgress2), popHiddenContext(), newProps = null !== workInProgress2.memoizedState, null !== current ? null !== current.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (renderLanes2 = current.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current && pop(resumedCache), null;
      case 24:
        return renderLanes2 = null, null !== current && (renderLanes2 = current.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext), bubbleProperties(workInProgress2), null;
      case 25:
        return null;
      case 30:
        return null;
    }
    throw Error(formatProdErrorMessage(156, workInProgress2.tag));
  }
  function unwindWork(current, workInProgress2) {
    popTreeContext(workInProgress2);
    switch (workInProgress2.tag) {
      case 1:
        return current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
      case 3:
        return popProvider(CacheContext), popHostContainer(), current = workInProgress2.flags, 0 !== (current & 65536) && 0 === (current & 128) ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
      case 26:
      case 27:
      case 5:
        return popHostContext(workInProgress2), null;
      case 31:
        if (null !== workInProgress2.memoizedState) {
          popSuspenseHandler(workInProgress2);
          if (null === workInProgress2.alternate)
            throw Error(formatProdErrorMessage(340));
          resetHydrationState();
        }
        current = workInProgress2.flags;
        return current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
      case 13:
        popSuspenseHandler(workInProgress2);
        current = workInProgress2.memoizedState;
        if (null !== current && null !== current.dehydrated) {
          if (null === workInProgress2.alternate)
            throw Error(formatProdErrorMessage(340));
          resetHydrationState();
        }
        current = workInProgress2.flags;
        return current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
      case 19:
        return pop(suspenseStackCursor), null;
      case 4:
        return popHostContainer(), null;
      case 10:
        return popProvider(workInProgress2.type), null;
      case 22:
      case 23:
        return popSuspenseHandler(workInProgress2), popHiddenContext(), null !== current && pop(resumedCache), current = workInProgress2.flags, current & 65536 ? (workInProgress2.flags = current & -65537 | 128, workInProgress2) : null;
      case 24:
        return popProvider(CacheContext), null;
      case 25:
        return null;
      default:
        return null;
    }
  }
  function unwindInterruptedWork(current, interruptedWork) {
    popTreeContext(interruptedWork);
    switch (interruptedWork.tag) {
      case 3:
        popProvider(CacheContext);
        popHostContainer();
        break;
      case 26:
      case 27:
      case 5:
        popHostContext(interruptedWork);
        break;
      case 4:
        popHostContainer();
        break;
      case 31:
        null !== interruptedWork.memoizedState && popSuspenseHandler(interruptedWork);
        break;
      case 13:
        popSuspenseHandler(interruptedWork);
        break;
      case 19:
        pop(suspenseStackCursor);
        break;
      case 10:
        popProvider(interruptedWork.type);
        break;
      case 22:
      case 23:
        popSuspenseHandler(interruptedWork);
        popHiddenContext();
        null !== current && pop(resumedCache);
        break;
      case 24:
        popProvider(CacheContext);
    }
  }
  function commitHookEffectListMount(flags, finishedWork) {
    try {
      var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
      if (null !== lastEffect) {
        var firstEffect = lastEffect.next;
        updateQueue = firstEffect;
        do {
          if ((updateQueue.tag & flags) === flags) {
            lastEffect = void 0;
            var create2 = updateQueue.create, inst = updateQueue.inst;
            lastEffect = create2();
            inst.destroy = lastEffect;
          }
          updateQueue = updateQueue.next;
        } while (updateQueue !== firstEffect);
      }
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
  }
  function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor$jscomp$0) {
    try {
      var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
      if (null !== lastEffect) {
        var firstEffect = lastEffect.next;
        updateQueue = firstEffect;
        do {
          if ((updateQueue.tag & flags) === flags) {
            var inst = updateQueue.inst, destroy = inst.destroy;
            if (void 0 !== destroy) {
              inst.destroy = void 0;
              lastEffect = finishedWork;
              var nearestMountedAncestor = nearestMountedAncestor$jscomp$0, destroy_ = destroy;
              try {
                destroy_();
              } catch (error) {
                captureCommitPhaseError(
                  lastEffect,
                  nearestMountedAncestor,
                  error
                );
              }
            }
          }
          updateQueue = updateQueue.next;
        } while (updateQueue !== firstEffect);
      }
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
  }
  function commitClassCallbacks(finishedWork) {
    var updateQueue = finishedWork.updateQueue;
    if (null !== updateQueue) {
      var instance = finishedWork.stateNode;
      try {
        commitCallbacks(updateQueue, instance);
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
  }
  function safelyCallComponentWillUnmount(current, nearestMountedAncestor, instance) {
    instance.props = resolveClassComponentProps(
      current.type,
      current.memoizedProps
    );
    instance.state = current.memoizedState;
    try {
      instance.componentWillUnmount();
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  }
  function safelyAttachRef(current, nearestMountedAncestor) {
    try {
      var ref2 = current.ref;
      if (null !== ref2) {
        switch (current.tag) {
          case 26:
          case 27:
          case 5:
            var instanceToUse = current.stateNode;
            break;
          case 30:
            instanceToUse = current.stateNode;
            break;
          default:
            instanceToUse = current.stateNode;
        }
        "function" === typeof ref2 ? current.refCleanup = ref2(instanceToUse) : ref2.current = instanceToUse;
      }
    } catch (error) {
      captureCommitPhaseError(current, nearestMountedAncestor, error);
    }
  }
  function safelyDetachRef(current, nearestMountedAncestor) {
    var ref2 = current.ref, refCleanup = current.refCleanup;
    if (null !== ref2)
      if ("function" === typeof refCleanup)
        try {
          refCleanup();
        } catch (error) {
          captureCommitPhaseError(current, nearestMountedAncestor, error);
        } finally {
          current.refCleanup = null, current = current.alternate, null != current && (current.refCleanup = null);
        }
      else if ("function" === typeof ref2)
        try {
          ref2(null);
        } catch (error$140) {
          captureCommitPhaseError(current, nearestMountedAncestor, error$140);
        }
      else ref2.current = null;
  }
  function commitHostMount(finishedWork) {
    var type2 = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
    try {
      a: switch (type2) {
        case "button":
        case "input":
        case "select":
        case "textarea":
          props.autoFocus && instance.focus();
          break a;
        case "img":
          props.src ? instance.src = props.src : props.srcSet && (instance.srcset = props.srcSet);
      }
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
  }
  function commitHostUpdate(finishedWork, newProps, oldProps) {
    try {
      var domElement = finishedWork.stateNode;
      updateProperties(domElement, finishedWork.type, oldProps, newProps);
      domElement[internalPropsKey] = newProps;
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
  }
  function isHostParent(fiber) {
    return 5 === fiber.tag || 3 === fiber.tag || 26 === fiber.tag || 27 === fiber.tag && isSingletonScope(fiber.type) || 4 === fiber.tag;
  }
  function getHostSibling(fiber) {
    a: for (; ; ) {
      for (; null === fiber.sibling; ) {
        if (null === fiber.return || isHostParent(fiber.return)) return null;
        fiber = fiber.return;
      }
      fiber.sibling.return = fiber.return;
      for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
        if (27 === fiber.tag && isSingletonScope(fiber.type)) continue a;
        if (fiber.flags & 2) continue a;
        if (null === fiber.child || 4 === fiber.tag) continue a;
        else fiber.child.return = fiber, fiber = fiber.child;
      }
      if (!(fiber.flags & 2)) return fiber.stateNode;
    }
  }
  function insertOrAppendPlacementNodeIntoContainer(node2, before, parent) {
    var tag = node2.tag;
    if (5 === tag || 6 === tag)
      node2 = node2.stateNode, before ? (9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent).insertBefore(node2, before) : (before = 9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent, before.appendChild(node2), parent = parent._reactRootContainer, null !== parent && void 0 !== parent || null !== before.onclick || (before.onclick = noop$1));
    else if (4 !== tag && (27 === tag && isSingletonScope(node2.type) && (parent = node2.stateNode, before = null), node2 = node2.child, null !== node2))
      for (insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling; null !== node2; )
        insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling;
  }
  function insertOrAppendPlacementNode(node2, before, parent) {
    var tag = node2.tag;
    if (5 === tag || 6 === tag)
      node2 = node2.stateNode, before ? parent.insertBefore(node2, before) : parent.appendChild(node2);
    else if (4 !== tag && (27 === tag && isSingletonScope(node2.type) && (parent = node2.stateNode), node2 = node2.child, null !== node2))
      for (insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling; null !== node2; )
        insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling;
  }
  function commitHostSingletonAcquisition(finishedWork) {
    var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
    try {
      for (var type2 = finishedWork.type, attributes = singleton.attributes; attributes.length; )
        singleton.removeAttributeNode(attributes[0]);
      setInitialProperties(singleton, type2, props);
      singleton[internalInstanceKey] = finishedWork;
      singleton[internalPropsKey] = props;
    } catch (error) {
      captureCommitPhaseError(finishedWork, finishedWork.return, error);
    }
  }
  var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null;
  function commitBeforeMutationEffects(root3, firstChild) {
    root3 = root3.containerInfo;
    eventsEnabled = _enabled;
    root3 = getActiveElementDeep(root3);
    if (hasSelectionCapabilities(root3)) {
      if ("selectionStart" in root3)
        var JSCompiler_temp = {
          start: root3.selectionStart,
          end: root3.selectionEnd
        };
      else
        a: {
          JSCompiler_temp = (JSCompiler_temp = root3.ownerDocument) && JSCompiler_temp.defaultView || window;
          var selection = JSCompiler_temp.getSelection && JSCompiler_temp.getSelection();
          if (selection && 0 !== selection.rangeCount) {
            JSCompiler_temp = selection.anchorNode;
            var anchorOffset = selection.anchorOffset, focusNode = selection.focusNode;
            selection = selection.focusOffset;
            try {
              JSCompiler_temp.nodeType, focusNode.nodeType;
            } catch (e$20) {
              JSCompiler_temp = null;
              break a;
            }
            var length = 0, start = -1, end = -1, indexWithinAnchor = 0, indexWithinFocus = 0, node2 = root3, parentNode = null;
            b: for (; ; ) {
              for (var next; ; ) {
                node2 !== JSCompiler_temp || 0 !== anchorOffset && 3 !== node2.nodeType || (start = length + anchorOffset);
                node2 !== focusNode || 0 !== selection && 3 !== node2.nodeType || (end = length + selection);
                3 === node2.nodeType && (length += node2.nodeValue.length);
                if (null === (next = node2.firstChild)) break;
                parentNode = node2;
                node2 = next;
              }
              for (; ; ) {
                if (node2 === root3) break b;
                parentNode === JSCompiler_temp && ++indexWithinAnchor === anchorOffset && (start = length);
                parentNode === focusNode && ++indexWithinFocus === selection && (end = length);
                if (null !== (next = node2.nextSibling)) break;
                node2 = parentNode;
                parentNode = node2.parentNode;
              }
              node2 = next;
            }
            JSCompiler_temp = -1 === start || -1 === end ? null : { start, end };
          } else JSCompiler_temp = null;
        }
      JSCompiler_temp = JSCompiler_temp || { start: 0, end: 0 };
    } else JSCompiler_temp = null;
    selectionInformation = { focusedElem: root3, selectionRange: JSCompiler_temp };
    _enabled = false;
    for (nextEffect = firstChild; null !== nextEffect; )
      if (firstChild = nextEffect, root3 = firstChild.child, 0 !== (firstChild.subtreeFlags & 1028) && null !== root3)
        root3.return = firstChild, nextEffect = root3;
      else
        for (; null !== nextEffect; ) {
          firstChild = nextEffect;
          focusNode = firstChild.alternate;
          root3 = firstChild.flags;
          switch (firstChild.tag) {
            case 0:
              if (0 !== (root3 & 4) && (root3 = firstChild.updateQueue, root3 = null !== root3 ? root3.events : null, null !== root3))
                for (JSCompiler_temp = 0; JSCompiler_temp < root3.length; JSCompiler_temp++)
                  anchorOffset = root3[JSCompiler_temp], anchorOffset.ref.impl = anchorOffset.nextImpl;
              break;
            case 11:
            case 15:
              break;
            case 1:
              if (0 !== (root3 & 1024) && null !== focusNode) {
                root3 = void 0;
                JSCompiler_temp = firstChild;
                anchorOffset = focusNode.memoizedProps;
                focusNode = focusNode.memoizedState;
                selection = JSCompiler_temp.stateNode;
                try {
                  var resolvedPrevProps = resolveClassComponentProps(
                    JSCompiler_temp.type,
                    anchorOffset
                  );
                  root3 = selection.getSnapshotBeforeUpdate(
                    resolvedPrevProps,
                    focusNode
                  );
                  selection.__reactInternalSnapshotBeforeUpdate = root3;
                } catch (error) {
                  captureCommitPhaseError(
                    JSCompiler_temp,
                    JSCompiler_temp.return,
                    error
                  );
                }
              }
              break;
            case 3:
              if (0 !== (root3 & 1024)) {
                if (root3 = firstChild.stateNode.containerInfo, JSCompiler_temp = root3.nodeType, 9 === JSCompiler_temp)
                  clearContainerSparingly(root3);
                else if (1 === JSCompiler_temp)
                  switch (root3.nodeName) {
                    case "HEAD":
                    case "HTML":
                    case "BODY":
                      clearContainerSparingly(root3);
                      break;
                    default:
                      root3.textContent = "";
                  }
              }
              break;
            case 5:
            case 26:
            case 27:
            case 6:
            case 4:
            case 17:
              break;
            default:
              if (0 !== (root3 & 1024)) throw Error(formatProdErrorMessage(163));
          }
          root3 = firstChild.sibling;
          if (null !== root3) {
            root3.return = firstChild.return;
            nextEffect = root3;
            break;
          }
          nextEffect = firstChild.return;
        }
  }
  function commitLayoutEffectOnFiber(finishedRoot, current, finishedWork) {
    var flags = finishedWork.flags;
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 15:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        flags & 4 && commitHookEffectListMount(5, finishedWork);
        break;
      case 1:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        if (flags & 4)
          if (finishedRoot = finishedWork.stateNode, null === current)
            try {
              finishedRoot.componentDidMount();
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          else {
            var prevProps = resolveClassComponentProps(
              finishedWork.type,
              current.memoizedProps
            );
            current = current.memoizedState;
            try {
              finishedRoot.componentDidUpdate(
                prevProps,
                current,
                finishedRoot.__reactInternalSnapshotBeforeUpdate
              );
            } catch (error$139) {
              captureCommitPhaseError(
                finishedWork,
                finishedWork.return,
                error$139
              );
            }
          }
        flags & 64 && commitClassCallbacks(finishedWork);
        flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
        break;
      case 3:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        if (flags & 64 && (finishedRoot = finishedWork.updateQueue, null !== finishedRoot)) {
          current = null;
          if (null !== finishedWork.child)
            switch (finishedWork.child.tag) {
              case 27:
              case 5:
                current = finishedWork.child.stateNode;
                break;
              case 1:
                current = finishedWork.child.stateNode;
            }
          try {
            commitCallbacks(finishedRoot, current);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
        break;
      case 27:
        null === current && flags & 4 && commitHostSingletonAcquisition(finishedWork);
      case 26:
      case 5:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        null === current && flags & 4 && commitHostMount(finishedWork);
        flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
        break;
      case 12:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        break;
      case 31:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
        break;
      case 13:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
        flags & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (finishedWork = retryDehydratedSuspenseBoundary.bind(
          null,
          finishedWork
        ), registerSuspenseInstanceRetry(finishedRoot, finishedWork))));
        break;
      case 22:
        flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
        if (!flags) {
          current = null !== current && null !== current.memoizedState || offscreenSubtreeWasHidden;
          prevProps = offscreenSubtreeIsHidden;
          var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
          offscreenSubtreeIsHidden = flags;
          (offscreenSubtreeWasHidden = current) && !prevOffscreenSubtreeWasHidden ? recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            0 !== (finishedWork.subtreeFlags & 8772)
          ) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          offscreenSubtreeIsHidden = prevProps;
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
        }
        break;
      case 30:
        break;
      default:
        recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
    }
  }
  function detachFiberAfterEffects(fiber) {
    var alternate = fiber.alternate;
    null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
    fiber.child = null;
    fiber.deletions = null;
    fiber.sibling = null;
    5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
    fiber.stateNode = null;
    fiber.return = null;
    fiber.dependencies = null;
    fiber.memoizedProps = null;
    fiber.memoizedState = null;
    fiber.pendingProps = null;
    fiber.stateNode = null;
    fiber.updateQueue = null;
  }
  var hostParent = null, hostParentIsContainer = false;
  function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
    for (parent = parent.child; null !== parent; )
      commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, parent), parent = parent.sibling;
  }
  function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
    if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
      try {
        injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
      } catch (err) {
      }
    switch (deletedFiber.tag) {
      case 26:
        offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        deletedFiber.memoizedState ? deletedFiber.memoizedState.count-- : deletedFiber.stateNode && (deletedFiber = deletedFiber.stateNode, deletedFiber.parentNode.removeChild(deletedFiber));
        break;
      case 27:
        offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
        var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
        isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        releaseSingletonInstance(deletedFiber.stateNode);
        hostParent = prevHostParent;
        hostParentIsContainer = prevHostParentIsContainer;
        break;
      case 5:
        offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
      case 6:
        prevHostParent = hostParent;
        prevHostParentIsContainer = hostParentIsContainer;
        hostParent = null;
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        hostParent = prevHostParent;
        hostParentIsContainer = prevHostParentIsContainer;
        if (null !== hostParent)
          if (hostParentIsContainer)
            try {
              (9 === hostParent.nodeType ? hostParent.body : "HTML" === hostParent.nodeName ? hostParent.ownerDocument.body : hostParent).removeChild(deletedFiber.stateNode);
            } catch (error) {
              captureCommitPhaseError(
                deletedFiber,
                nearestMountedAncestor,
                error
              );
            }
          else
            try {
              hostParent.removeChild(deletedFiber.stateNode);
            } catch (error) {
              captureCommitPhaseError(
                deletedFiber,
                nearestMountedAncestor,
                error
              );
            }
        break;
      case 18:
        null !== hostParent && (hostParentIsContainer ? (finishedRoot = hostParent, clearHydrationBoundary(
          9 === finishedRoot.nodeType ? finishedRoot.body : "HTML" === finishedRoot.nodeName ? finishedRoot.ownerDocument.body : finishedRoot,
          deletedFiber.stateNode
        ), retryIfBlockedOn(finishedRoot)) : clearHydrationBoundary(hostParent, deletedFiber.stateNode));
        break;
      case 4:
        prevHostParent = hostParent;
        prevHostParentIsContainer = hostParentIsContainer;
        hostParent = deletedFiber.stateNode.containerInfo;
        hostParentIsContainer = true;
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        hostParent = prevHostParent;
        hostParentIsContainer = prevHostParentIsContainer;
        break;
      case 0:
      case 11:
      case 14:
      case 15:
        commitHookEffectListUnmount(2, deletedFiber, nearestMountedAncestor);
        offscreenSubtreeWasHidden || commitHookEffectListUnmount(4, deletedFiber, nearestMountedAncestor);
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        break;
      case 1:
        offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
          deletedFiber,
          nearestMountedAncestor,
          prevHostParent
        ));
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        break;
      case 21:
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        break;
      case 22:
        offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
        offscreenSubtreeWasHidden = prevHostParent;
        break;
      default:
        recursivelyTraverseDeletionEffects(
          finishedRoot,
          nearestMountedAncestor,
          deletedFiber
        );
    }
  }
  function commitActivityHydrationCallbacks(finishedRoot, finishedWork) {
    if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot))) {
      finishedRoot = finishedRoot.dehydrated;
      try {
        retryIfBlockedOn(finishedRoot);
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
  }
  function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
    if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
      try {
        retryIfBlockedOn(finishedRoot);
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
  }
  function getRetryCache(finishedWork) {
    switch (finishedWork.tag) {
      case 31:
      case 13:
      case 19:
        var retryCache = finishedWork.stateNode;
        null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
        return retryCache;
      case 22:
        return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
      default:
        throw Error(formatProdErrorMessage(435, finishedWork.tag));
    }
  }
  function attachSuspenseRetryListeners(finishedWork, wakeables) {
    var retryCache = getRetryCache(finishedWork);
    wakeables.forEach(function(wakeable) {
      if (!retryCache.has(wakeable)) {
        retryCache.add(wakeable);
        var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
        wakeable.then(retry, retry);
      }
    });
  }
  function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
    var deletions = parentFiber.deletions;
    if (null !== deletions)
      for (var i = 0; i < deletions.length; i++) {
        var childToDelete = deletions[i], root3 = root$jscomp$0, returnFiber = parentFiber, parent = returnFiber;
        a: for (; null !== parent; ) {
          switch (parent.tag) {
            case 27:
              if (isSingletonScope(parent.type)) {
                hostParent = parent.stateNode;
                hostParentIsContainer = false;
                break a;
              }
              break;
            case 5:
              hostParent = parent.stateNode;
              hostParentIsContainer = false;
              break a;
            case 3:
            case 4:
              hostParent = parent.stateNode.containerInfo;
              hostParentIsContainer = true;
              break a;
          }
          parent = parent.return;
        }
        if (null === hostParent) throw Error(formatProdErrorMessage(160));
        commitDeletionEffectsOnFiber(root3, returnFiber, childToDelete);
        hostParent = null;
        hostParentIsContainer = false;
        root3 = childToDelete.alternate;
        null !== root3 && (root3.return = null);
        childToDelete.return = null;
      }
    if (parentFiber.subtreeFlags & 13886)
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
  }
  var currentHoistableRoot = null;
  function commitMutationEffectsOnFiber(finishedWork, root3) {
    var current = finishedWork.alternate, flags = finishedWork.flags;
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 14:
      case 15:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 4 && (commitHookEffectListUnmount(3, finishedWork, finishedWork.return), commitHookEffectListMount(3, finishedWork), commitHookEffectListUnmount(5, finishedWork, finishedWork.return));
        break;
      case 1:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
        flags & 64 && offscreenSubtreeIsHidden && (finishedWork = finishedWork.updateQueue, null !== finishedWork && (flags = finishedWork.callbacks, null !== flags && (current = finishedWork.shared.hiddenCallbacks, finishedWork.shared.hiddenCallbacks = null === current ? flags : current.concat(flags))));
        break;
      case 26:
        var hoistableRoot = currentHoistableRoot;
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
        if (flags & 4) {
          var currentResource = null !== current ? current.memoizedState : null;
          flags = finishedWork.memoizedState;
          if (null === current)
            if (null === flags)
              if (null === finishedWork.stateNode) {
                a: {
                  flags = finishedWork.type;
                  current = finishedWork.memoizedProps;
                  hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
                  b: switch (flags) {
                    case "title":
                      currentResource = hoistableRoot.getElementsByTagName("title")[0];
                      if (!currentResource || currentResource[internalHoistableMarker] || currentResource[internalInstanceKey] || "http://www.w3.org/2000/svg" === currentResource.namespaceURI || currentResource.hasAttribute("itemprop"))
                        currentResource = hoistableRoot.createElement(flags), hoistableRoot.head.insertBefore(
                          currentResource,
                          hoistableRoot.querySelector("head > title")
                        );
                      setInitialProperties(currentResource, flags, current);
                      currentResource[internalInstanceKey] = finishedWork;
                      markNodeAsHoistable(currentResource);
                      flags = currentResource;
                      break a;
                    case "link":
                      var maybeNodes = getHydratableHoistableCache(
                        "link",
                        "href",
                        hoistableRoot
                      ).get(flags + (current.href || ""));
                      if (maybeNodes) {
                        for (var i = 0; i < maybeNodes.length; i++)
                          if (currentResource = maybeNodes[i], currentResource.getAttribute("href") === (null == current.href || "" === current.href ? null : current.href) && currentResource.getAttribute("rel") === (null == current.rel ? null : current.rel) && currentResource.getAttribute("title") === (null == current.title ? null : current.title) && currentResource.getAttribute("crossorigin") === (null == current.crossOrigin ? null : current.crossOrigin)) {
                            maybeNodes.splice(i, 1);
                            break b;
                          }
                      }
                      currentResource = hoistableRoot.createElement(flags);
                      setInitialProperties(currentResource, flags, current);
                      hoistableRoot.head.appendChild(currentResource);
                      break;
                    case "meta":
                      if (maybeNodes = getHydratableHoistableCache(
                        "meta",
                        "content",
                        hoistableRoot
                      ).get(flags + (current.content || ""))) {
                        for (i = 0; i < maybeNodes.length; i++)
                          if (currentResource = maybeNodes[i], currentResource.getAttribute("content") === (null == current.content ? null : "" + current.content) && currentResource.getAttribute("name") === (null == current.name ? null : current.name) && currentResource.getAttribute("property") === (null == current.property ? null : current.property) && currentResource.getAttribute("http-equiv") === (null == current.httpEquiv ? null : current.httpEquiv) && currentResource.getAttribute("charset") === (null == current.charSet ? null : current.charSet)) {
                            maybeNodes.splice(i, 1);
                            break b;
                          }
                      }
                      currentResource = hoistableRoot.createElement(flags);
                      setInitialProperties(currentResource, flags, current);
                      hoistableRoot.head.appendChild(currentResource);
                      break;
                    default:
                      throw Error(formatProdErrorMessage(468, flags));
                  }
                  currentResource[internalInstanceKey] = finishedWork;
                  markNodeAsHoistable(currentResource);
                  flags = currentResource;
                }
                finishedWork.stateNode = flags;
              } else
                mountHoistable(
                  hoistableRoot,
                  finishedWork.type,
                  finishedWork.stateNode
                );
            else
              finishedWork.stateNode = acquireResource(
                hoistableRoot,
                flags,
                finishedWork.memoizedProps
              );
          else
            currentResource !== flags ? (null === currentResource ? null !== current.stateNode && (current = current.stateNode, current.parentNode.removeChild(current)) : currentResource.count--, null === flags ? mountHoistable(
              hoistableRoot,
              finishedWork.type,
              finishedWork.stateNode
            ) : acquireResource(
              hoistableRoot,
              flags,
              finishedWork.memoizedProps
            )) : null === flags && null !== finishedWork.stateNode && commitHostUpdate(
              finishedWork,
              finishedWork.memoizedProps,
              current.memoizedProps
            );
        }
        break;
      case 27:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
        null !== current && flags & 4 && commitHostUpdate(
          finishedWork,
          finishedWork.memoizedProps,
          current.memoizedProps
        );
        break;
      case 5:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 512 && (offscreenSubtreeWasHidden || null === current || safelyDetachRef(current, current.return));
        if (finishedWork.flags & 32) {
          hoistableRoot = finishedWork.stateNode;
          try {
            setTextContent(hoistableRoot, "");
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
        flags & 4 && null != finishedWork.stateNode && (hoistableRoot = finishedWork.memoizedProps, commitHostUpdate(
          finishedWork,
          hoistableRoot,
          null !== current ? current.memoizedProps : hoistableRoot
        ));
        flags & 1024 && (needsFormReset = true);
        break;
      case 6:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        if (flags & 4) {
          if (null === finishedWork.stateNode)
            throw Error(formatProdErrorMessage(162));
          flags = finishedWork.memoizedProps;
          current = finishedWork.stateNode;
          try {
            current.nodeValue = flags;
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
        break;
      case 3:
        tagCaches = null;
        hoistableRoot = currentHoistableRoot;
        currentHoistableRoot = getHoistableRoot(root3.containerInfo);
        recursivelyTraverseMutationEffects(root3, finishedWork);
        currentHoistableRoot = hoistableRoot;
        commitReconciliationEffects(finishedWork);
        if (flags & 4 && null !== current && current.memoizedState.isDehydrated)
          try {
            retryIfBlockedOn(root3.containerInfo);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
        break;
      case 4:
        flags = currentHoistableRoot;
        currentHoistableRoot = getHoistableRoot(
          finishedWork.stateNode.containerInfo
        );
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        currentHoistableRoot = flags;
        break;
      case 12:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        break;
      case 31:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
        break;
      case 13:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current && null !== current.memoizedState) && (globalMostRecentFallbackTime = now());
        flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
        break;
      case 22:
        hoistableRoot = null !== finishedWork.memoizedState;
        var wasHidden = null !== current && null !== current.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
        offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || hoistableRoot;
        offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
        recursivelyTraverseMutationEffects(root3, finishedWork);
        offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
        offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
        commitReconciliationEffects(finishedWork);
        if (flags & 8192)
          a: for (root3 = finishedWork.stateNode, root3._visibility = hoistableRoot ? root3._visibility & -2 : root3._visibility | 1, hoistableRoot && (null === current || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || recursivelyTraverseDisappearLayoutEffects(finishedWork)), current = null, root3 = finishedWork; ; ) {
            if (5 === root3.tag || 26 === root3.tag) {
              if (null === current) {
                wasHidden = current = root3;
                try {
                  if (currentResource = wasHidden.stateNode, hoistableRoot)
                    maybeNodes = currentResource.style, "function" === typeof maybeNodes.setProperty ? maybeNodes.setProperty("display", "none", "important") : maybeNodes.display = "none";
                  else {
                    i = wasHidden.stateNode;
                    var styleProp = wasHidden.memoizedProps.style, display = void 0 !== styleProp && null !== styleProp && styleProp.hasOwnProperty("display") ? styleProp.display : null;
                    i.style.display = null == display || "boolean" === typeof display ? "" : ("" + display).trim();
                  }
                } catch (error) {
                  captureCommitPhaseError(wasHidden, wasHidden.return, error);
                }
              }
            } else if (6 === root3.tag) {
              if (null === current) {
                wasHidden = root3;
                try {
                  wasHidden.stateNode.nodeValue = hoistableRoot ? "" : wasHidden.memoizedProps;
                } catch (error) {
                  captureCommitPhaseError(wasHidden, wasHidden.return, error);
                }
              }
            } else if (18 === root3.tag) {
              if (null === current) {
                wasHidden = root3;
                try {
                  var instance = wasHidden.stateNode;
                  hoistableRoot ? hideOrUnhideDehydratedBoundary(instance, true) : hideOrUnhideDehydratedBoundary(wasHidden.stateNode, false);
                } catch (error) {
                  captureCommitPhaseError(wasHidden, wasHidden.return, error);
                }
              }
            } else if ((22 !== root3.tag && 23 !== root3.tag || null === root3.memoizedState || root3 === finishedWork) && null !== root3.child) {
              root3.child.return = root3;
              root3 = root3.child;
              continue;
            }
            if (root3 === finishedWork) break a;
            for (; null === root3.sibling; ) {
              if (null === root3.return || root3.return === finishedWork) break a;
              current === root3 && (current = null);
              root3 = root3.return;
            }
            current === root3 && (current = null);
            root3.sibling.return = root3.return;
            root3 = root3.sibling;
          }
        flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current = flags.retryQueue, null !== current && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current))));
        break;
      case 19:
        recursivelyTraverseMutationEffects(root3, finishedWork);
        commitReconciliationEffects(finishedWork);
        flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
        break;
      case 30:
        break;
      case 21:
        break;
      default:
        recursivelyTraverseMutationEffects(root3, finishedWork), commitReconciliationEffects(finishedWork);
    }
  }
  function commitReconciliationEffects(finishedWork) {
    var flags = finishedWork.flags;
    if (flags & 2) {
      try {
        for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
          if (isHostParent(parentFiber)) {
            hostParentFiber = parentFiber;
            break;
          }
          parentFiber = parentFiber.return;
        }
        if (null == hostParentFiber) throw Error(formatProdErrorMessage(160));
        switch (hostParentFiber.tag) {
          case 27:
            var parent = hostParentFiber.stateNode, before = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(finishedWork, before, parent);
            break;
          case 5:
            var parent$141 = hostParentFiber.stateNode;
            hostParentFiber.flags & 32 && (setTextContent(parent$141, ""), hostParentFiber.flags &= -33);
            var before$142 = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(finishedWork, before$142, parent$141);
            break;
          case 3:
          case 4:
            var parent$143 = hostParentFiber.stateNode.containerInfo, before$144 = getHostSibling(finishedWork);
            insertOrAppendPlacementNodeIntoContainer(
              finishedWork,
              before$144,
              parent$143
            );
            break;
          default:
            throw Error(formatProdErrorMessage(161));
        }
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
      finishedWork.flags &= -3;
    }
    flags & 4096 && (finishedWork.flags &= -4097);
  }
  function recursivelyResetForms(parentFiber) {
    if (parentFiber.subtreeFlags & 1024)
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var fiber = parentFiber;
        recursivelyResetForms(fiber);
        5 === fiber.tag && fiber.flags & 1024 && fiber.stateNode.reset();
        parentFiber = parentFiber.sibling;
      }
  }
  function recursivelyTraverseLayoutEffects(root3, parentFiber) {
    if (parentFiber.subtreeFlags & 8772)
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        commitLayoutEffectOnFiber(root3, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
  }
  function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
    for (parentFiber = parentFiber.child; null !== parentFiber; ) {
      var finishedWork = parentFiber;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          commitHookEffectListUnmount(4, finishedWork, finishedWork.return);
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 1:
          safelyDetachRef(finishedWork, finishedWork.return);
          var instance = finishedWork.stateNode;
          "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
            finishedWork,
            finishedWork.return,
            instance
          );
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 27:
          releaseSingletonInstance(finishedWork.stateNode);
        case 26:
        case 5:
          safelyDetachRef(finishedWork, finishedWork.return);
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 22:
          null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 30:
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        default:
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
      }
      parentFiber = parentFiber.sibling;
    }
  }
  function recursivelyTraverseReappearLayoutEffects(finishedRoot$jscomp$0, parentFiber, includeWorkInProgressEffects) {
    includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
    for (parentFiber = parentFiber.child; null !== parentFiber; ) {
      var current = parentFiber.alternate, finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          commitHookEffectListMount(4, finishedWork);
          break;
        case 1:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          current = finishedWork;
          finishedRoot = current.stateNode;
          if ("function" === typeof finishedRoot.componentDidMount)
            try {
              finishedRoot.componentDidMount();
            } catch (error) {
              captureCommitPhaseError(current, current.return, error);
            }
          current = finishedWork;
          finishedRoot = current.updateQueue;
          if (null !== finishedRoot) {
            var instance = current.stateNode;
            try {
              var hiddenCallbacks = finishedRoot.shared.hiddenCallbacks;
              if (null !== hiddenCallbacks)
                for (finishedRoot.shared.hiddenCallbacks = null, finishedRoot = 0; finishedRoot < hiddenCallbacks.length; finishedRoot++)
                  callCallback(hiddenCallbacks[finishedRoot], instance);
            } catch (error) {
              captureCommitPhaseError(current, current.return, error);
            }
          }
          includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 27:
          commitHostSingletonAcquisition(finishedWork);
        case 26:
        case 5:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && null === current && flags & 4 && commitHostMount(finishedWork);
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 12:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          break;
        case 31:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 13:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 22:
          null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 30:
          break;
        default:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
      }
      parentFiber = parentFiber.sibling;
    }
  }
  function commitOffscreenPassiveMountEffects(current, finishedWork) {
    var previousCache = null;
    null !== current && null !== current.memoizedState && null !== current.memoizedState.cachePool && (previousCache = current.memoizedState.cachePool.pool);
    current = null;
    null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current = finishedWork.memoizedState.cachePool.pool);
    current !== previousCache && (null != current && current.refCount++, null != previousCache && releaseCache(previousCache));
  }
  function commitCachePassiveMountEffect(current, finishedWork) {
    current = null;
    null !== finishedWork.alternate && (current = finishedWork.alternate.memoizedState.cache);
    finishedWork = finishedWork.memoizedState.cache;
    finishedWork !== current && (finishedWork.refCount++, null != current && releaseCache(current));
  }
  function recursivelyTraversePassiveMountEffects(root3, parentFiber, committedLanes, committedTransitions) {
    if (parentFiber.subtreeFlags & 10256)
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        commitPassiveMountOnFiber(
          root3,
          parentFiber,
          committedLanes,
          committedTransitions
        ), parentFiber = parentFiber.sibling;
  }
  function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions) {
    var flags = finishedWork.flags;
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 15:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        flags & 2048 && commitHookEffectListMount(9, finishedWork);
        break;
      case 1:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        break;
      case 3:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        flags & 2048 && (finishedRoot = null, null !== finishedWork.alternate && (finishedRoot = finishedWork.alternate.memoizedState.cache), finishedWork = finishedWork.memoizedState.cache, finishedWork !== finishedRoot && (finishedWork.refCount++, null != finishedRoot && releaseCache(finishedRoot)));
        break;
      case 12:
        if (flags & 2048) {
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          );
          finishedRoot = finishedWork.stateNode;
          try {
            var _finishedWork$memoize2 = finishedWork.memoizedProps, id = _finishedWork$memoize2.id, onPostCommit = _finishedWork$memoize2.onPostCommit;
            "function" === typeof onPostCommit && onPostCommit(
              id,
              null === finishedWork.alternate ? "mount" : "update",
              finishedRoot.passiveEffectDuration,
              -0
            );
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        } else
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions
          );
        break;
      case 31:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        break;
      case 13:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        break;
      case 23:
        break;
      case 22:
        _finishedWork$memoize2 = finishedWork.stateNode;
        id = finishedWork.alternate;
        null !== finishedWork.memoizedState ? _finishedWork$memoize2._visibility & 2 ? recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        ) : recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork) : _finishedWork$memoize2._visibility & 2 ? recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        ) : (_finishedWork$memoize2._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions,
          0 !== (finishedWork.subtreeFlags & 10256) || false
        ));
        flags & 2048 && commitOffscreenPassiveMountEffects(id, finishedWork);
        break;
      case 24:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
        flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
        break;
      default:
        recursivelyTraversePassiveMountEffects(
          finishedRoot,
          finishedWork,
          committedLanes,
          committedTransitions
        );
    }
  }
  function recursivelyTraverseReconnectPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, includeWorkInProgressEffects) {
    includeWorkInProgressEffects = includeWorkInProgressEffects && (0 !== (parentFiber.subtreeFlags & 10256) || false);
    for (parentFiber = parentFiber.child; null !== parentFiber; ) {
      var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects
          );
          commitHookEffectListMount(8, finishedWork);
          break;
        case 23:
          break;
        case 22:
          var instance = finishedWork.stateNode;
          null !== finishedWork.memoizedState ? instance._visibility & 2 ? recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects
          ) : recursivelyTraverseAtomicPassiveEffects(
            finishedRoot,
            finishedWork
          ) : (instance._visibility |= 2, recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects
          ));
          includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
            finishedWork.alternate,
            finishedWork
          );
          break;
        case 24:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects
          );
      }
      parentFiber = parentFiber.sibling;
    }
  }
  function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber) {
    if (parentFiber.subtreeFlags & 10256)
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var finishedRoot = finishedRoot$jscomp$0, finishedWork = parentFiber, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 22:
            recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
            flags & 2048 && commitOffscreenPassiveMountEffects(
              finishedWork.alternate,
              finishedWork
            );
            break;
          case 24:
            recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
            flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraverseAtomicPassiveEffects(finishedRoot, finishedWork);
        }
        parentFiber = parentFiber.sibling;
      }
  }
  var suspenseyCommitFlag = 8192;
  function recursivelyAccumulateSuspenseyCommit(parentFiber, committedLanes, suspendedState) {
    if (parentFiber.subtreeFlags & suspenseyCommitFlag)
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        accumulateSuspenseyCommitOnFiber(
          parentFiber,
          committedLanes,
          suspendedState
        ), parentFiber = parentFiber.sibling;
  }
  function accumulateSuspenseyCommitOnFiber(fiber, committedLanes, suspendedState) {
    switch (fiber.tag) {
      case 26:
        recursivelyAccumulateSuspenseyCommit(
          fiber,
          committedLanes,
          suspendedState
        );
        fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState && suspendResource(
          suspendedState,
          currentHoistableRoot,
          fiber.memoizedState,
          fiber.memoizedProps
        );
        break;
      case 5:
        recursivelyAccumulateSuspenseyCommit(
          fiber,
          committedLanes,
          suspendedState
        );
        break;
      case 3:
      case 4:
        var previousHoistableRoot = currentHoistableRoot;
        currentHoistableRoot = getHoistableRoot(fiber.stateNode.containerInfo);
        recursivelyAccumulateSuspenseyCommit(
          fiber,
          committedLanes,
          suspendedState
        );
        currentHoistableRoot = previousHoistableRoot;
        break;
      case 22:
        null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(
          fiber,
          committedLanes,
          suspendedState
        ), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(
          fiber,
          committedLanes,
          suspendedState
        ));
        break;
      default:
        recursivelyAccumulateSuspenseyCommit(
          fiber,
          committedLanes,
          suspendedState
        );
    }
  }
  function detachAlternateSiblings(parentFiber) {
    var previousFiber = parentFiber.alternate;
    if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
      previousFiber.child = null;
      do
        previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
      while (null !== parentFiber);
    }
  }
  function recursivelyTraversePassiveUnmountEffects(parentFiber) {
    var deletions = parentFiber.deletions;
    if (0 !== (parentFiber.flags & 16)) {
      if (null !== deletions)
        for (var i = 0; i < deletions.length; i++) {
          var childToDelete = deletions[i];
          nextEffect = childToDelete;
          commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
            childToDelete,
            parentFiber
          );
        }
      detachAlternateSiblings(parentFiber);
    }
    if (parentFiber.subtreeFlags & 10256)
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
  }
  function commitPassiveUnmountOnFiber(finishedWork) {
    switch (finishedWork.tag) {
      case 0:
      case 11:
      case 15:
        recursivelyTraversePassiveUnmountEffects(finishedWork);
        finishedWork.flags & 2048 && commitHookEffectListUnmount(9, finishedWork, finishedWork.return);
        break;
      case 3:
        recursivelyTraversePassiveUnmountEffects(finishedWork);
        break;
      case 12:
        recursivelyTraversePassiveUnmountEffects(finishedWork);
        break;
      case 22:
        var instance = finishedWork.stateNode;
        null !== finishedWork.memoizedState && instance._visibility & 2 && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (instance._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(finishedWork)) : recursivelyTraversePassiveUnmountEffects(finishedWork);
        break;
      default:
        recursivelyTraversePassiveUnmountEffects(finishedWork);
    }
  }
  function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
    var deletions = parentFiber.deletions;
    if (0 !== (parentFiber.flags & 16)) {
      if (null !== deletions)
        for (var i = 0; i < deletions.length; i++) {
          var childToDelete = deletions[i];
          nextEffect = childToDelete;
          commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
            childToDelete,
            parentFiber
          );
        }
      detachAlternateSiblings(parentFiber);
    }
    for (parentFiber = parentFiber.child; null !== parentFiber; ) {
      deletions = parentFiber;
      switch (deletions.tag) {
        case 0:
        case 11:
        case 15:
          commitHookEffectListUnmount(8, deletions, deletions.return);
          recursivelyTraverseDisconnectPassiveEffects(deletions);
          break;
        case 22:
          i = deletions.stateNode;
          i._visibility & 2 && (i._visibility &= -3, recursivelyTraverseDisconnectPassiveEffects(deletions));
          break;
        default:
          recursivelyTraverseDisconnectPassiveEffects(deletions);
      }
      parentFiber = parentFiber.sibling;
    }
  }
  function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor) {
    for (; null !== nextEffect; ) {
      var fiber = nextEffect;
      switch (fiber.tag) {
        case 0:
        case 11:
        case 15:
          commitHookEffectListUnmount(8, fiber, nearestMountedAncestor);
          break;
        case 23:
        case 22:
          if (null !== fiber.memoizedState && null !== fiber.memoizedState.cachePool) {
            var cache = fiber.memoizedState.cachePool.pool;
            null != cache && cache.refCount++;
          }
          break;
        case 24:
          releaseCache(fiber.memoizedState.cache);
      }
      cache = fiber.child;
      if (null !== cache) cache.return = fiber, nextEffect = cache;
      else
        a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
          cache = nextEffect;
          var sibling = cache.sibling, returnFiber = cache.return;
          detachFiberAfterEffects(cache);
          if (cache === fiber) {
            nextEffect = null;
            break a;
          }
          if (null !== sibling) {
            sibling.return = returnFiber;
            nextEffect = sibling;
            break a;
          }
          nextEffect = returnFiber;
        }
    }
  }
  var DefaultAsyncDispatcher = {
    getCacheForType: function(resourceType) {
      var cache = readContext(CacheContext), cacheForType = cache.data.get(resourceType);
      void 0 === cacheForType && (cacheForType = resourceType(), cache.data.set(resourceType, cacheForType));
      return cacheForType;
    },
    cacheSignal: function() {
      return readContext(CacheContext).controller.signal;
    }
  }, PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, executionContext = 0, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = 0, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, globalMostRecentTransitionTime = 0, workInProgressRootRenderTargetTime = Infinity, workInProgressTransitions = null, legacyErrorBoundariesThatAlreadyFailed = null, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, nestedUpdateCount = 0, rootWithNestedUpdates = null;
  function requestUpdateLane() {
    return 0 !== (executionContext & 2) && 0 !== workInProgressRootRenderLanes ? workInProgressRootRenderLanes & -workInProgressRootRenderLanes : null !== ReactSharedInternals.T ? requestTransitionLane() : resolveUpdatePriority();
  }
  function requestDeferredLane() {
    if (0 === workInProgressDeferredLane)
      if (0 === (workInProgressRootRenderLanes & 536870912) || isHydrating) {
        var lane = nextTransitionDeferredLane;
        nextTransitionDeferredLane <<= 1;
        0 === (nextTransitionDeferredLane & 3932160) && (nextTransitionDeferredLane = 262144);
        workInProgressDeferredLane = lane;
      } else workInProgressDeferredLane = 536870912;
    lane = suspenseHandlerStackCursor.current;
    null !== lane && (lane.flags |= 32);
    return workInProgressDeferredLane;
  }
  function scheduleUpdateOnFiber(root3, fiber, lane) {
    if (root3 === workInProgressRoot && (2 === workInProgressSuspendedReason || 9 === workInProgressSuspendedReason) || null !== root3.cancelPendingCommit)
      prepareFreshStack(root3, 0), markRootSuspended(
        root3,
        workInProgressRootRenderLanes,
        workInProgressDeferredLane,
        false
      );
    markRootUpdated$1(root3, lane);
    if (0 === (executionContext & 2) || root3 !== workInProgressRoot)
      root3 === workInProgressRoot && (0 === (executionContext & 2) && (workInProgressRootInterleavedUpdatedLanes |= lane), 4 === workInProgressRootExitStatus && markRootSuspended(
        root3,
        workInProgressRootRenderLanes,
        workInProgressDeferredLane,
        false
      )), ensureRootIsScheduled(root3);
  }
  function performWorkOnRoot(root$jscomp$0, lanes, forceSync) {
    if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
    var shouldTimeSlice = !forceSync && 0 === (lanes & 127) && 0 === (lanes & root$jscomp$0.expiredLanes) || checkIfRootIsPrerendering(root$jscomp$0, lanes), exitStatus = shouldTimeSlice ? renderRootConcurrent(root$jscomp$0, lanes) : renderRootSync(root$jscomp$0, lanes, true), renderWasConcurrent = shouldTimeSlice;
    do {
      if (0 === exitStatus) {
        workInProgressRootIsPrerendering && !shouldTimeSlice && markRootSuspended(root$jscomp$0, lanes, 0, false);
        break;
      } else {
        forceSync = root$jscomp$0.current.alternate;
        if (renderWasConcurrent && !isRenderConsistentWithExternalStores(forceSync)) {
          exitStatus = renderRootSync(root$jscomp$0, lanes, false);
          renderWasConcurrent = false;
          continue;
        }
        if (2 === exitStatus) {
          renderWasConcurrent = lanes;
          if (root$jscomp$0.errorRecoveryDisabledLanes & renderWasConcurrent)
            var JSCompiler_inline_result = 0;
          else
            JSCompiler_inline_result = root$jscomp$0.pendingLanes & -536870913, JSCompiler_inline_result = 0 !== JSCompiler_inline_result ? JSCompiler_inline_result : JSCompiler_inline_result & 536870912 ? 536870912 : 0;
          if (0 !== JSCompiler_inline_result) {
            lanes = JSCompiler_inline_result;
            a: {
              var root3 = root$jscomp$0;
              exitStatus = workInProgressRootConcurrentErrors;
              var wasRootDehydrated = root3.current.memoizedState.isDehydrated;
              wasRootDehydrated && (prepareFreshStack(root3, JSCompiler_inline_result).flags |= 256);
              JSCompiler_inline_result = renderRootSync(
                root3,
                JSCompiler_inline_result,
                false
              );
              if (2 !== JSCompiler_inline_result) {
                if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                  root3.errorRecoveryDisabledLanes |= renderWasConcurrent;
                  workInProgressRootInterleavedUpdatedLanes |= renderWasConcurrent;
                  exitStatus = 4;
                  break a;
                }
                renderWasConcurrent = workInProgressRootRecoverableErrors;
                workInProgressRootRecoverableErrors = exitStatus;
                null !== renderWasConcurrent && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = renderWasConcurrent : workInProgressRootRecoverableErrors.push.apply(
                  workInProgressRootRecoverableErrors,
                  renderWasConcurrent
                ));
              }
              exitStatus = JSCompiler_inline_result;
            }
            renderWasConcurrent = false;
            if (2 !== exitStatus) continue;
          }
        }
        if (1 === exitStatus) {
          prepareFreshStack(root$jscomp$0, 0);
          markRootSuspended(root$jscomp$0, lanes, 0, true);
          break;
        }
        a: {
          shouldTimeSlice = root$jscomp$0;
          renderWasConcurrent = exitStatus;
          switch (renderWasConcurrent) {
            case 0:
            case 1:
              throw Error(formatProdErrorMessage(345));
            case 4:
              if ((lanes & 4194048) !== lanes) break;
            case 6:
              markRootSuspended(
                shouldTimeSlice,
                lanes,
                workInProgressDeferredLane,
                !workInProgressRootDidSkipSuspendedSiblings
              );
              break a;
            case 2:
              workInProgressRootRecoverableErrors = null;
              break;
            case 3:
            case 5:
              break;
            default:
              throw Error(formatProdErrorMessage(329));
          }
          if ((lanes & 62914560) === lanes && (exitStatus = globalMostRecentFallbackTime + 300 - now(), 10 < exitStatus)) {
            markRootSuspended(
              shouldTimeSlice,
              lanes,
              workInProgressDeferredLane,
              !workInProgressRootDidSkipSuspendedSiblings
            );
            if (0 !== getNextLanes(shouldTimeSlice, 0, true)) break a;
            pendingEffectsLanes = lanes;
            shouldTimeSlice.timeoutHandle = scheduleTimeout(
              commitRootWhenReady.bind(
                null,
                shouldTimeSlice,
                forceSync,
                workInProgressRootRecoverableErrors,
                workInProgressTransitions,
                workInProgressRootDidIncludeRecursiveRenderUpdate,
                lanes,
                workInProgressDeferredLane,
                workInProgressRootInterleavedUpdatedLanes,
                workInProgressSuspendedRetryLanes,
                workInProgressRootDidSkipSuspendedSiblings,
                renderWasConcurrent,
                "Throttled",
                -0,
                0
              ),
              exitStatus
            );
            break a;
          }
          commitRootWhenReady(
            shouldTimeSlice,
            forceSync,
            workInProgressRootRecoverableErrors,
            workInProgressTransitions,
            workInProgressRootDidIncludeRecursiveRenderUpdate,
            lanes,
            workInProgressDeferredLane,
            workInProgressRootInterleavedUpdatedLanes,
            workInProgressSuspendedRetryLanes,
            workInProgressRootDidSkipSuspendedSiblings,
            renderWasConcurrent,
            null,
            -0,
            0
          );
        }
      }
      break;
    } while (1);
    ensureRootIsScheduled(root$jscomp$0);
  }
  function commitRootWhenReady(root3, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
    root3.timeoutHandle = -1;
    suspendedCommitReason = finishedWork.subtreeFlags;
    if (suspendedCommitReason & 8192 || 16785408 === (suspendedCommitReason & 16785408)) {
      suspendedCommitReason = {
        stylesheets: null,
        count: 0,
        imgCount: 0,
        imgBytes: 0,
        suspenseyImages: [],
        waitingForImages: true,
        waitingForViewTransition: false,
        unsuspend: noop$1
      };
      accumulateSuspenseyCommitOnFiber(
        finishedWork,
        lanes,
        suspendedCommitReason
      );
      var timeoutOffset = (lanes & 62914560) === lanes ? globalMostRecentFallbackTime - now() : (lanes & 4194048) === lanes ? globalMostRecentTransitionTime - now() : 0;
      timeoutOffset = waitForCommitToBeReady(
        suspendedCommitReason,
        timeoutOffset
      );
      if (null !== timeoutOffset) {
        pendingEffectsLanes = lanes;
        root3.cancelPendingCommit = timeoutOffset(
          commitRoot.bind(
            null,
            root3,
            finishedWork,
            lanes,
            recoverableErrors,
            transitions,
            didIncludeRenderPhaseUpdate,
            spawnedLane,
            updatedLanes,
            suspendedRetryLanes,
            exitStatus,
            suspendedCommitReason,
            null,
            completedRenderStartTime,
            completedRenderEndTime
          )
        );
        markRootSuspended(root3, lanes, spawnedLane, !didSkipSuspendedSiblings);
        return;
      }
    }
    commitRoot(
      root3,
      finishedWork,
      lanes,
      recoverableErrors,
      transitions,
      didIncludeRenderPhaseUpdate,
      spawnedLane,
      updatedLanes,
      suspendedRetryLanes
    );
  }
  function isRenderConsistentWithExternalStores(finishedWork) {
    for (var node2 = finishedWork; ; ) {
      var tag = node2.tag;
      if ((0 === tag || 11 === tag || 15 === tag) && node2.flags & 16384 && (tag = node2.updateQueue, null !== tag && (tag = tag.stores, null !== tag)))
        for (var i = 0; i < tag.length; i++) {
          var check = tag[i], getSnapshot = check.getSnapshot;
          check = check.value;
          try {
            if (!objectIs(getSnapshot(), check)) return false;
          } catch (error) {
            return false;
          }
        }
      tag = node2.child;
      if (node2.subtreeFlags & 16384 && null !== tag)
        tag.return = node2, node2 = tag;
      else {
        if (node2 === finishedWork) break;
        for (; null === node2.sibling; ) {
          if (null === node2.return || node2.return === finishedWork) return true;
          node2 = node2.return;
        }
        node2.sibling.return = node2.return;
        node2 = node2.sibling;
      }
    }
    return true;
  }
  function markRootSuspended(root3, suspendedLanes, spawnedLane, didAttemptEntireTree) {
    suspendedLanes &= ~workInProgressRootPingedLanes;
    suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
    root3.suspendedLanes |= suspendedLanes;
    root3.pingedLanes &= ~suspendedLanes;
    didAttemptEntireTree && (root3.warmLanes |= suspendedLanes);
    didAttemptEntireTree = root3.expirationTimes;
    for (var lanes = suspendedLanes; 0 < lanes; ) {
      var index$6 = 31 - clz32(lanes), lane = 1 << index$6;
      didAttemptEntireTree[index$6] = -1;
      lanes &= ~lane;
    }
    0 !== spawnedLane && markSpawnedDeferredLane(root3, spawnedLane, suspendedLanes);
  }
  function flushSyncWork$1() {
    return 0 === (executionContext & 6) ? (flushSyncWorkAcrossRoots_impl(0), false) : true;
  }
  function resetWorkInProgressStack() {
    if (null !== workInProgress) {
      if (0 === workInProgressSuspendedReason)
        var interruptedWork = workInProgress.return;
      else
        interruptedWork = workInProgress, lastContextDependency = currentlyRenderingFiber$1 = null, resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
      for (; null !== interruptedWork; )
        unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
      workInProgress = null;
    }
  }
  function prepareFreshStack(root3, lanes) {
    var timeoutHandle = root3.timeoutHandle;
    -1 !== timeoutHandle && (root3.timeoutHandle = -1, cancelTimeout(timeoutHandle));
    timeoutHandle = root3.cancelPendingCommit;
    null !== timeoutHandle && (root3.cancelPendingCommit = null, timeoutHandle());
    pendingEffectsLanes = 0;
    resetWorkInProgressStack();
    workInProgressRoot = root3;
    workInProgress = timeoutHandle = createWorkInProgress(root3.current, null);
    workInProgressRootRenderLanes = lanes;
    workInProgressSuspendedReason = 0;
    workInProgressThrownValue = null;
    workInProgressRootDidSkipSuspendedSiblings = false;
    workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root3, lanes);
    workInProgressRootDidAttachPingListener = false;
    workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = workInProgressRootExitStatus = 0;
    workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
    workInProgressRootDidIncludeRecursiveRenderUpdate = false;
    0 !== (lanes & 8) && (lanes |= lanes & 32);
    var allEntangledLanes = root3.entangledLanes;
    if (0 !== allEntangledLanes)
      for (root3 = root3.entanglements, allEntangledLanes &= lanes; 0 < allEntangledLanes; ) {
        var index$4 = 31 - clz32(allEntangledLanes), lane = 1 << index$4;
        lanes |= root3[index$4];
        allEntangledLanes &= ~lane;
      }
    entangledRenderLanes = lanes;
    finishQueueingConcurrentUpdates();
    return timeoutHandle;
  }
  function handleThrow(root3, thrownValue) {
    currentlyRenderingFiber = null;
    ReactSharedInternals.H = ContextOnlyDispatcher;
    thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 3) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = 4) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? 8 : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? 6 : 1;
    workInProgressThrownValue = thrownValue;
    null === workInProgress && (workInProgressRootExitStatus = 1, logUncaughtError(
      root3,
      createCapturedValueAtFiber(thrownValue, root3.current)
    ));
  }
  function shouldRemainOnPreviousScreen() {
    var handler = suspenseHandlerStackCursor.current;
    return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
  }
  function pushDispatcher() {
    var prevDispatcher = ReactSharedInternals.H;
    ReactSharedInternals.H = ContextOnlyDispatcher;
    return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
  }
  function pushAsyncDispatcher() {
    var prevAsyncDispatcher = ReactSharedInternals.A;
    ReactSharedInternals.A = DefaultAsyncDispatcher;
    return prevAsyncDispatcher;
  }
  function renderDidSuspendDelayIfPossible() {
    workInProgressRootExitStatus = 4;
    workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
    0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
      workInProgressRoot,
      workInProgressRootRenderLanes,
      workInProgressDeferredLane,
      false
    );
  }
  function renderRootSync(root3, lanes, shouldYieldForPrerendering) {
    var prevExecutionContext = executionContext;
    executionContext |= 2;
    var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
    if (workInProgressRoot !== root3 || workInProgressRootRenderLanes !== lanes)
      workInProgressTransitions = null, prepareFreshStack(root3, lanes);
    lanes = false;
    var exitStatus = workInProgressRootExitStatus;
    a: do
      try {
        if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
          var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
          switch (workInProgressSuspendedReason) {
            case 8:
              resetWorkInProgressStack();
              exitStatus = 6;
              break a;
            case 3:
            case 2:
            case 9:
            case 6:
              null === suspenseHandlerStackCursor.current && (lanes = true);
              var reason = workInProgressSuspendedReason;
              workInProgressSuspendedReason = 0;
              workInProgressThrownValue = null;
              throwAndUnwindWorkLoop(root3, unitOfWork, thrownValue, reason);
              if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                exitStatus = 0;
                break a;
              }
              break;
            default:
              reason = workInProgressSuspendedReason, workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root3, unitOfWork, thrownValue, reason);
          }
        }
        workLoopSync();
        exitStatus = workInProgressRootExitStatus;
        break;
      } catch (thrownValue$165) {
        handleThrow(root3, thrownValue$165);
      }
    while (1);
    lanes && root3.shellSuspendCounter++;
    lastContextDependency = currentlyRenderingFiber$1 = null;
    executionContext = prevExecutionContext;
    ReactSharedInternals.H = prevDispatcher;
    ReactSharedInternals.A = prevAsyncDispatcher;
    null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
    return exitStatus;
  }
  function workLoopSync() {
    for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
  }
  function renderRootConcurrent(root3, lanes) {
    var prevExecutionContext = executionContext;
    executionContext |= 2;
    var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
    workInProgressRoot !== root3 || workInProgressRootRenderLanes !== lanes ? (workInProgressTransitions = null, workInProgressRootRenderTargetTime = now() + 500, prepareFreshStack(root3, lanes)) : workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
      root3,
      lanes
    );
    a: do
      try {
        if (0 !== workInProgressSuspendedReason && null !== workInProgress) {
          lanes = workInProgress;
          var thrownValue = workInProgressThrownValue;
          b: switch (workInProgressSuspendedReason) {
            case 1:
              workInProgressSuspendedReason = 0;
              workInProgressThrownValue = null;
              throwAndUnwindWorkLoop(root3, lanes, thrownValue, 1);
              break;
            case 2:
            case 9:
              if (isThenableResolved(thrownValue)) {
                workInProgressSuspendedReason = 0;
                workInProgressThrownValue = null;
                replaySuspendedUnitOfWork(lanes);
                break;
              }
              lanes = function() {
                2 !== workInProgressSuspendedReason && 9 !== workInProgressSuspendedReason || workInProgressRoot !== root3 || (workInProgressSuspendedReason = 7);
                ensureRootIsScheduled(root3);
              };
              thrownValue.then(lanes, lanes);
              break a;
            case 3:
              workInProgressSuspendedReason = 7;
              break a;
            case 4:
              workInProgressSuspendedReason = 5;
              break a;
            case 7:
              isThenableResolved(thrownValue) ? (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = 0, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root3, lanes, thrownValue, 7));
              break;
            case 5:
              var resource = null;
              switch (workInProgress.tag) {
                case 26:
                  resource = workInProgress.memoizedState;
                case 5:
                case 27:
                  var hostFiber = workInProgress;
                  if (resource ? preloadResource(resource) : hostFiber.stateNode.complete) {
                    workInProgressSuspendedReason = 0;
                    workInProgressThrownValue = null;
                    var sibling = hostFiber.sibling;
                    if (null !== sibling) workInProgress = sibling;
                    else {
                      var returnFiber = hostFiber.return;
                      null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                    }
                    break b;
                  }
              }
              workInProgressSuspendedReason = 0;
              workInProgressThrownValue = null;
              throwAndUnwindWorkLoop(root3, lanes, thrownValue, 5);
              break;
            case 6:
              workInProgressSuspendedReason = 0;
              workInProgressThrownValue = null;
              throwAndUnwindWorkLoop(root3, lanes, thrownValue, 6);
              break;
            case 8:
              resetWorkInProgressStack();
              workInProgressRootExitStatus = 6;
              break a;
            default:
              throw Error(formatProdErrorMessage(462));
          }
        }
        workLoopConcurrentByScheduler();
        break;
      } catch (thrownValue$167) {
        handleThrow(root3, thrownValue$167);
      }
    while (1);
    lastContextDependency = currentlyRenderingFiber$1 = null;
    ReactSharedInternals.H = prevDispatcher;
    ReactSharedInternals.A = prevAsyncDispatcher;
    executionContext = prevExecutionContext;
    if (null !== workInProgress) return 0;
    workInProgressRoot = null;
    workInProgressRootRenderLanes = 0;
    finishQueueingConcurrentUpdates();
    return workInProgressRootExitStatus;
  }
  function workLoopConcurrentByScheduler() {
    for (; null !== workInProgress && !shouldYield(); )
      performUnitOfWork(workInProgress);
  }
  function performUnitOfWork(unitOfWork) {
    var next = beginWork(unitOfWork.alternate, unitOfWork, entangledRenderLanes);
    unitOfWork.memoizedProps = unitOfWork.pendingProps;
    null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
  }
  function replaySuspendedUnitOfWork(unitOfWork) {
    var next = unitOfWork;
    var current = next.alternate;
    switch (next.tag) {
      case 15:
      case 0:
        next = replayFunctionComponent(
          current,
          next,
          next.pendingProps,
          next.type,
          void 0,
          workInProgressRootRenderLanes
        );
        break;
      case 11:
        next = replayFunctionComponent(
          current,
          next,
          next.pendingProps,
          next.type.render,
          next.ref,
          workInProgressRootRenderLanes
        );
        break;
      case 5:
        resetHooksOnUnwind(next);
      default:
        unwindInterruptedWork(current, next), next = workInProgress = resetWorkInProgress(next, entangledRenderLanes), next = beginWork(current, next, entangledRenderLanes);
    }
    unitOfWork.memoizedProps = unitOfWork.pendingProps;
    null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
  }
  function throwAndUnwindWorkLoop(root3, unitOfWork, thrownValue, suspendedReason) {
    lastContextDependency = currentlyRenderingFiber$1 = null;
    resetHooksOnUnwind(unitOfWork);
    thenableState$1 = null;
    thenableIndexCounter$1 = 0;
    var returnFiber = unitOfWork.return;
    try {
      if (throwException(
        root3,
        returnFiber,
        unitOfWork,
        thrownValue,
        workInProgressRootRenderLanes
      )) {
        workInProgressRootExitStatus = 1;
        logUncaughtError(
          root3,
          createCapturedValueAtFiber(thrownValue, root3.current)
        );
        workInProgress = null;
        return;
      }
    } catch (error) {
      if (null !== returnFiber) throw workInProgress = returnFiber, error;
      workInProgressRootExitStatus = 1;
      logUncaughtError(
        root3,
        createCapturedValueAtFiber(thrownValue, root3.current)
      );
      workInProgress = null;
      return;
    }
    if (unitOfWork.flags & 32768) {
      if (isHydrating || 1 === suspendedReason) root3 = true;
      else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
        root3 = false;
      else if (workInProgressRootDidSkipSuspendedSiblings = root3 = true, 2 === suspendedReason || 9 === suspendedReason || 3 === suspendedReason || 6 === suspendedReason)
        suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
      unwindUnitOfWork(unitOfWork, root3);
    } else completeUnitOfWork(unitOfWork);
  }
  function completeUnitOfWork(unitOfWork) {
    var completedWork = unitOfWork;
    do {
      if (0 !== (completedWork.flags & 32768)) {
        unwindUnitOfWork(
          completedWork,
          workInProgressRootDidSkipSuspendedSiblings
        );
        return;
      }
      unitOfWork = completedWork.return;
      var next = completeWork(
        completedWork.alternate,
        completedWork,
        entangledRenderLanes
      );
      if (null !== next) {
        workInProgress = next;
        return;
      }
      completedWork = completedWork.sibling;
      if (null !== completedWork) {
        workInProgress = completedWork;
        return;
      }
      workInProgress = completedWork = unitOfWork;
    } while (null !== completedWork);
    0 === workInProgressRootExitStatus && (workInProgressRootExitStatus = 5);
  }
  function unwindUnitOfWork(unitOfWork, skipSiblings) {
    do {
      var next = unwindWork(unitOfWork.alternate, unitOfWork);
      if (null !== next) {
        next.flags &= 32767;
        workInProgress = next;
        return;
      }
      next = unitOfWork.return;
      null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
      if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
        workInProgress = unitOfWork;
        return;
      }
      workInProgress = unitOfWork = next;
    } while (null !== unitOfWork);
    workInProgressRootExitStatus = 6;
    workInProgress = null;
  }
  function commitRoot(root3, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes) {
    root3.cancelPendingCommit = null;
    do
      flushPendingEffects();
    while (0 !== pendingEffectsStatus);
    if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(327));
    if (null !== finishedWork) {
      if (finishedWork === root3.current) throw Error(formatProdErrorMessage(177));
      didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
      didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
      markRootFinished(
        root3,
        lanes,
        didIncludeRenderPhaseUpdate,
        spawnedLane,
        updatedLanes,
        suspendedRetryLanes
      );
      root3 === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
      pendingFinishedWork = finishedWork;
      pendingEffectsRoot = root3;
      pendingEffectsLanes = lanes;
      pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
      pendingPassiveTransitions = transitions;
      pendingRecoverableErrors = recoverableErrors;
      0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root3.callbackNode = null, root3.callbackPriority = 0, scheduleCallback$1(NormalPriority$1, function() {
        flushPassiveEffects();
        return null;
      })) : (root3.callbackNode = null, root3.callbackPriority = 0);
      recoverableErrors = 0 !== (finishedWork.flags & 13878);
      if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
        recoverableErrors = ReactSharedInternals.T;
        ReactSharedInternals.T = null;
        transitions = ReactDOMSharedInternals.p;
        ReactDOMSharedInternals.p = 2;
        spawnedLane = executionContext;
        executionContext |= 4;
        try {
          commitBeforeMutationEffects(root3, finishedWork, lanes);
        } finally {
          executionContext = spawnedLane, ReactDOMSharedInternals.p = transitions, ReactSharedInternals.T = recoverableErrors;
        }
      }
      pendingEffectsStatus = 1;
      flushMutationEffects();
      flushLayoutEffects();
      flushSpawnedWork();
    }
  }
  function flushMutationEffects() {
    if (1 === pendingEffectsStatus) {
      pendingEffectsStatus = 0;
      var root3 = pendingEffectsRoot, finishedWork = pendingFinishedWork, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
      if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
        rootMutationHasEffect = ReactSharedInternals.T;
        ReactSharedInternals.T = null;
        var previousPriority = ReactDOMSharedInternals.p;
        ReactDOMSharedInternals.p = 2;
        var prevExecutionContext = executionContext;
        executionContext |= 4;
        try {
          commitMutationEffectsOnFiber(finishedWork, root3);
          var priorSelectionInformation = selectionInformation, curFocusedElem = getActiveElementDeep(root3.containerInfo), priorFocusedElem = priorSelectionInformation.focusedElem, priorSelectionRange = priorSelectionInformation.selectionRange;
          if (curFocusedElem !== priorFocusedElem && priorFocusedElem && priorFocusedElem.ownerDocument && containsNode(
            priorFocusedElem.ownerDocument.documentElement,
            priorFocusedElem
          )) {
            if (null !== priorSelectionRange && hasSelectionCapabilities(priorFocusedElem)) {
              var start = priorSelectionRange.start, end = priorSelectionRange.end;
              void 0 === end && (end = start);
              if ("selectionStart" in priorFocusedElem)
                priorFocusedElem.selectionStart = start, priorFocusedElem.selectionEnd = Math.min(
                  end,
                  priorFocusedElem.value.length
                );
              else {
                var doc = priorFocusedElem.ownerDocument || document, win = doc && doc.defaultView || window;
                if (win.getSelection) {
                  var selection = win.getSelection(), length = priorFocusedElem.textContent.length, start$jscomp$0 = Math.min(priorSelectionRange.start, length), end$jscomp$0 = void 0 === priorSelectionRange.end ? start$jscomp$0 : Math.min(priorSelectionRange.end, length);
                  !selection.extend && start$jscomp$0 > end$jscomp$0 && (curFocusedElem = end$jscomp$0, end$jscomp$0 = start$jscomp$0, start$jscomp$0 = curFocusedElem);
                  var startMarker = getNodeForCharacterOffset(
                    priorFocusedElem,
                    start$jscomp$0
                  ), endMarker = getNodeForCharacterOffset(
                    priorFocusedElem,
                    end$jscomp$0
                  );
                  if (startMarker && endMarker && (1 !== selection.rangeCount || selection.anchorNode !== startMarker.node || selection.anchorOffset !== startMarker.offset || selection.focusNode !== endMarker.node || selection.focusOffset !== endMarker.offset)) {
                    var range2 = doc.createRange();
                    range2.setStart(startMarker.node, startMarker.offset);
                    selection.removeAllRanges();
                    start$jscomp$0 > end$jscomp$0 ? (selection.addRange(range2), selection.extend(endMarker.node, endMarker.offset)) : (range2.setEnd(endMarker.node, endMarker.offset), selection.addRange(range2));
                  }
                }
              }
            }
            doc = [];
            for (selection = priorFocusedElem; selection = selection.parentNode; )
              1 === selection.nodeType && doc.push({
                element: selection,
                left: selection.scrollLeft,
                top: selection.scrollTop
              });
            "function" === typeof priorFocusedElem.focus && priorFocusedElem.focus();
            for (priorFocusedElem = 0; priorFocusedElem < doc.length; priorFocusedElem++) {
              var info = doc[priorFocusedElem];
              info.element.scrollLeft = info.left;
              info.element.scrollTop = info.top;
            }
          }
          _enabled = !!eventsEnabled;
          selectionInformation = eventsEnabled = null;
        } finally {
          executionContext = prevExecutionContext, ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = rootMutationHasEffect;
        }
      }
      root3.current = finishedWork;
      pendingEffectsStatus = 2;
    }
  }
  function flushLayoutEffects() {
    if (2 === pendingEffectsStatus) {
      pendingEffectsStatus = 0;
      var root3 = pendingEffectsRoot, finishedWork = pendingFinishedWork, rootHasLayoutEffect = 0 !== (finishedWork.flags & 8772);
      if (0 !== (finishedWork.subtreeFlags & 8772) || rootHasLayoutEffect) {
        rootHasLayoutEffect = ReactSharedInternals.T;
        ReactSharedInternals.T = null;
        var previousPriority = ReactDOMSharedInternals.p;
        ReactDOMSharedInternals.p = 2;
        var prevExecutionContext = executionContext;
        executionContext |= 4;
        try {
          commitLayoutEffectOnFiber(root3, finishedWork.alternate, finishedWork);
        } finally {
          executionContext = prevExecutionContext, ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = rootHasLayoutEffect;
        }
      }
      pendingEffectsStatus = 3;
    }
  }
  function flushSpawnedWork() {
    if (4 === pendingEffectsStatus || 3 === pendingEffectsStatus) {
      pendingEffectsStatus = 0;
      requestPaint();
      var root3 = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, recoverableErrors = pendingRecoverableErrors;
      0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? pendingEffectsStatus = 5 : (pendingEffectsStatus = 0, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(root3, root3.pendingLanes));
      var remainingLanes = root3.pendingLanes;
      0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
      lanesToEventPriority(lanes);
      finishedWork = finishedWork.stateNode;
      if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
        try {
          injectedHook.onCommitFiberRoot(
            rendererID,
            finishedWork,
            void 0,
            128 === (finishedWork.current.flags & 128)
          );
        } catch (err) {
        }
      if (null !== recoverableErrors) {
        finishedWork = ReactSharedInternals.T;
        remainingLanes = ReactDOMSharedInternals.p;
        ReactDOMSharedInternals.p = 2;
        ReactSharedInternals.T = null;
        try {
          for (var onRecoverableError = root3.onRecoverableError, i = 0; i < recoverableErrors.length; i++) {
            var recoverableError = recoverableErrors[i];
            onRecoverableError(recoverableError.value, {
              componentStack: recoverableError.stack
            });
          }
        } finally {
          ReactSharedInternals.T = finishedWork, ReactDOMSharedInternals.p = remainingLanes;
        }
      }
      0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
      ensureRootIsScheduled(root3);
      remainingLanes = root3.pendingLanes;
      0 !== (lanes & 261930) && 0 !== (remainingLanes & 42) ? root3 === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = root3) : nestedUpdateCount = 0;
      flushSyncWorkAcrossRoots_impl(0);
    }
  }
  function releaseRootPooledCache(root3, remainingLanes) {
    0 === (root3.pooledCacheLanes &= remainingLanes) && (remainingLanes = root3.pooledCache, null != remainingLanes && (root3.pooledCache = null, releaseCache(remainingLanes)));
  }
  function flushPendingEffects() {
    flushMutationEffects();
    flushLayoutEffects();
    flushSpawnedWork();
    return flushPassiveEffects();
  }
  function flushPassiveEffects() {
    if (5 !== pendingEffectsStatus) return false;
    var root3 = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
    pendingEffectsRemainingLanes = 0;
    var renderPriority = lanesToEventPriority(pendingEffectsLanes), prevTransition = ReactSharedInternals.T, previousPriority = ReactDOMSharedInternals.p;
    try {
      ReactDOMSharedInternals.p = 32 > renderPriority ? 32 : renderPriority;
      ReactSharedInternals.T = null;
      renderPriority = pendingPassiveTransitions;
      pendingPassiveTransitions = null;
      var root$jscomp$0 = pendingEffectsRoot, lanes = pendingEffectsLanes;
      pendingEffectsStatus = 0;
      pendingFinishedWork = pendingEffectsRoot = null;
      pendingEffectsLanes = 0;
      if (0 !== (executionContext & 6)) throw Error(formatProdErrorMessage(331));
      var prevExecutionContext = executionContext;
      executionContext |= 4;
      commitPassiveUnmountOnFiber(root$jscomp$0.current);
      commitPassiveMountOnFiber(
        root$jscomp$0,
        root$jscomp$0.current,
        lanes,
        renderPriority
      );
      executionContext = prevExecutionContext;
      flushSyncWorkAcrossRoots_impl(0, false);
      if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
        try {
          injectedHook.onPostCommitFiberRoot(rendererID, root$jscomp$0);
        } catch (err) {
        }
      return true;
    } finally {
      ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition, releaseRootPooledCache(root3, remainingLanes);
    }
  }
  function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
    sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
    sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
    rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
    null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
  }
  function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) {
    if (3 === sourceFiber.tag)
      captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
    else
      for (; null !== nearestMountedAncestor; ) {
        if (3 === nearestMountedAncestor.tag) {
          captureCommitPhaseErrorOnRoot(
            nearestMountedAncestor,
            sourceFiber,
            error
          );
          break;
        } else if (1 === nearestMountedAncestor.tag) {
          var instance = nearestMountedAncestor.stateNode;
          if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
            sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
            error = createClassErrorUpdate(2);
            instance = enqueueUpdate(nearestMountedAncestor, error, 2);
            null !== instance && (initializeClassErrorUpdate(
              error,
              instance,
              nearestMountedAncestor,
              sourceFiber
            ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
            break;
          }
        }
        nearestMountedAncestor = nearestMountedAncestor.return;
      }
  }
  function attachPingListener(root3, wakeable, lanes) {
    var pingCache = root3.pingCache;
    if (null === pingCache) {
      pingCache = root3.pingCache = new PossiblyWeakMap();
      var threadIDs = /* @__PURE__ */ new Set();
      pingCache.set(wakeable, threadIDs);
    } else
      threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
    threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), root3 = pingSuspendedRoot.bind(null, root3, wakeable, lanes), wakeable.then(root3, root3));
  }
  function pingSuspendedRoot(root3, wakeable, pingedLanes) {
    var pingCache = root3.pingCache;
    null !== pingCache && pingCache.delete(wakeable);
    root3.pingedLanes |= root3.suspendedLanes & pingedLanes;
    root3.warmLanes &= ~pingedLanes;
    workInProgressRoot === root3 && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (4 === workInProgressRootExitStatus || 3 === workInProgressRootExitStatus && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && 300 > now() - globalMostRecentFallbackTime ? 0 === (executionContext & 2) && prepareFreshStack(root3, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
    ensureRootIsScheduled(root3);
  }
  function retryTimedOutBoundary(boundaryFiber, retryLane) {
    0 === retryLane && (retryLane = claimNextRetryLane());
    boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
    null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
  }
  function retryDehydratedSuspenseBoundary(boundaryFiber) {
    var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
    null !== suspenseState && (retryLane = suspenseState.retryLane);
    retryTimedOutBoundary(boundaryFiber, retryLane);
  }
  function resolveRetryWakeable(boundaryFiber, wakeable) {
    var retryLane = 0;
    switch (boundaryFiber.tag) {
      case 31:
      case 13:
        var retryCache = boundaryFiber.stateNode;
        var suspenseState = boundaryFiber.memoizedState;
        null !== suspenseState && (retryLane = suspenseState.retryLane);
        break;
      case 19:
        retryCache = boundaryFiber.stateNode;
        break;
      case 22:
        retryCache = boundaryFiber.stateNode._retryCache;
        break;
      default:
        throw Error(formatProdErrorMessage(314));
    }
    null !== retryCache && retryCache.delete(wakeable);
    retryTimedOutBoundary(boundaryFiber, retryLane);
  }
  function scheduleCallback$1(priorityLevel, callback) {
    return scheduleCallback$3(priorityLevel, callback);
  }
  var firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0;
  function ensureRootIsScheduled(root3) {
    root3 !== lastScheduledRoot && null === root3.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root3 : lastScheduledRoot = lastScheduledRoot.next = root3);
    mightHavePendingSyncWork = true;
    didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
  }
  function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
    if (!isFlushingWork && mightHavePendingSyncWork) {
      isFlushingWork = true;
      do {
        var didPerformSomeWork = false;
        for (var root$170 = firstScheduledRoot; null !== root$170; ) {
          if (0 !== syncTransitionLanes) {
            var pendingLanes = root$170.pendingLanes;
            if (0 === pendingLanes) var JSCompiler_inline_result = 0;
            else {
              var suspendedLanes = root$170.suspendedLanes, pingedLanes = root$170.pingedLanes;
              JSCompiler_inline_result = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
              JSCompiler_inline_result &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
              JSCompiler_inline_result = JSCompiler_inline_result & 201326741 ? JSCompiler_inline_result & 201326741 | 1 : JSCompiler_inline_result ? JSCompiler_inline_result | 2 : 0;
            }
            0 !== JSCompiler_inline_result && (didPerformSomeWork = true, performSyncWorkOnRoot(root$170, JSCompiler_inline_result));
          } else
            JSCompiler_inline_result = workInProgressRootRenderLanes, JSCompiler_inline_result = getNextLanes(
              root$170,
              root$170 === workInProgressRoot ? JSCompiler_inline_result : 0,
              null !== root$170.cancelPendingCommit || -1 !== root$170.timeoutHandle
            ), 0 === (JSCompiler_inline_result & 3) || checkIfRootIsPrerendering(root$170, JSCompiler_inline_result) || (didPerformSomeWork = true, performSyncWorkOnRoot(root$170, JSCompiler_inline_result));
          root$170 = root$170.next;
        }
      } while (didPerformSomeWork);
      isFlushingWork = false;
    }
  }
  function processRootScheduleInImmediateTask() {
    processRootScheduleInMicrotask();
  }
  function processRootScheduleInMicrotask() {
    mightHavePendingSyncWork = didScheduleMicrotask = false;
    var syncTransitionLanes = 0;
    0 !== currentEventTransitionLane && shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane);
    for (var currentTime = now(), prev = null, root3 = firstScheduledRoot; null !== root3; ) {
      var next = root3.next, nextLanes = scheduleTaskForRootDuringMicrotask(root3, currentTime);
      if (0 === nextLanes)
        root3.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
      else if (prev = root3, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
        mightHavePendingSyncWork = true;
      root3 = next;
    }
    0 !== pendingEffectsStatus && 5 !== pendingEffectsStatus || flushSyncWorkAcrossRoots_impl(syncTransitionLanes);
    0 !== currentEventTransitionLane && (currentEventTransitionLane = 0);
  }
  function scheduleTaskForRootDuringMicrotask(root3, currentTime) {
    for (var suspendedLanes = root3.suspendedLanes, pingedLanes = root3.pingedLanes, expirationTimes = root3.expirationTimes, lanes = root3.pendingLanes & -62914561; 0 < lanes; ) {
      var index$5 = 31 - clz32(lanes), lane = 1 << index$5, expirationTime = expirationTimes[index$5];
      if (-1 === expirationTime) {
        if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
          expirationTimes[index$5] = computeExpirationTime(lane, currentTime);
      } else expirationTime <= currentTime && (root3.expiredLanes |= lane);
      lanes &= ~lane;
    }
    currentTime = workInProgressRoot;
    suspendedLanes = workInProgressRootRenderLanes;
    suspendedLanes = getNextLanes(
      root3,
      root3 === currentTime ? suspendedLanes : 0,
      null !== root3.cancelPendingCommit || -1 !== root3.timeoutHandle
    );
    pingedLanes = root3.callbackNode;
    if (0 === suspendedLanes || root3 === currentTime && (2 === workInProgressSuspendedReason || 9 === workInProgressSuspendedReason) || null !== root3.cancelPendingCommit)
      return null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes), root3.callbackNode = null, root3.callbackPriority = 0;
    if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root3, suspendedLanes)) {
      currentTime = suspendedLanes & -suspendedLanes;
      if (currentTime === root3.callbackPriority) return currentTime;
      null !== pingedLanes && cancelCallback$1(pingedLanes);
      switch (lanesToEventPriority(suspendedLanes)) {
        case 2:
        case 8:
          suspendedLanes = UserBlockingPriority;
          break;
        case 32:
          suspendedLanes = NormalPriority$1;
          break;
        case 268435456:
          suspendedLanes = IdlePriority;
          break;
        default:
          suspendedLanes = NormalPriority$1;
      }
      pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root3);
      suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
      root3.callbackPriority = currentTime;
      root3.callbackNode = suspendedLanes;
      return currentTime;
    }
    null !== pingedLanes && null !== pingedLanes && cancelCallback$1(pingedLanes);
    root3.callbackPriority = 2;
    root3.callbackNode = null;
    return 2;
  }
  function performWorkOnRootViaSchedulerTask(root3, didTimeout) {
    if (0 !== pendingEffectsStatus && 5 !== pendingEffectsStatus)
      return root3.callbackNode = null, root3.callbackPriority = 0, null;
    var originalCallbackNode = root3.callbackNode;
    if (flushPendingEffects() && root3.callbackNode !== originalCallbackNode)
      return null;
    var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
    workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
      root3,
      root3 === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
      null !== root3.cancelPendingCommit || -1 !== root3.timeoutHandle
    );
    if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
    performWorkOnRoot(root3, workInProgressRootRenderLanes$jscomp$0, didTimeout);
    scheduleTaskForRootDuringMicrotask(root3, now());
    return null != root3.callbackNode && root3.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root3) : null;
  }
  function performSyncWorkOnRoot(root3, lanes) {
    if (flushPendingEffects()) return null;
    performWorkOnRoot(root3, lanes, true);
  }
  function scheduleImmediateRootScheduleTask() {
    scheduleMicrotask(function() {
      0 !== (executionContext & 6) ? scheduleCallback$3(
        ImmediatePriority,
        processRootScheduleInImmediateTask
      ) : processRootScheduleInMicrotask();
    });
  }
  function requestTransitionLane() {
    if (0 === currentEventTransitionLane) {
      var actionScopeLane = currentEntangledLane;
      0 === actionScopeLane && (actionScopeLane = nextTransitionUpdateLane, nextTransitionUpdateLane <<= 1, 0 === (nextTransitionUpdateLane & 261888) && (nextTransitionUpdateLane = 256));
      currentEventTransitionLane = actionScopeLane;
    }
    return currentEventTransitionLane;
  }
  function coerceFormActionProp(actionProp) {
    return null == actionProp || "symbol" === typeof actionProp || "boolean" === typeof actionProp ? null : "function" === typeof actionProp ? actionProp : sanitizeURL("" + actionProp);
  }
  function createFormDataWithSubmitter(form, submitter) {
    var temp = submitter.ownerDocument.createElement("input");
    temp.name = submitter.name;
    temp.value = submitter.value;
    form.id && temp.setAttribute("form", form.id);
    submitter.parentNode.insertBefore(temp, submitter);
    form = new FormData(form);
    temp.parentNode.removeChild(temp);
    return form;
  }
  function extractEvents$1(dispatchQueue, domEventName, maybeTargetInst, nativeEvent, nativeEventTarget) {
    if ("submit" === domEventName && maybeTargetInst && maybeTargetInst.stateNode === nativeEventTarget) {
      var action = coerceFormActionProp(
        (nativeEventTarget[internalPropsKey] || null).action
      ), submitter = nativeEvent.submitter;
      submitter && (domEventName = (domEventName = submitter[internalPropsKey] || null) ? coerceFormActionProp(domEventName.formAction) : submitter.getAttribute("formAction"), null !== domEventName && (action = domEventName, submitter = null));
      var event = new SyntheticEvent(
        "action",
        "action",
        null,
        nativeEvent,
        nativeEventTarget
      );
      dispatchQueue.push({
        event,
        listeners: [
          {
            instance: null,
            listener: function() {
              if (nativeEvent.defaultPrevented) {
                if (0 !== currentEventTransitionLane) {
                  var formData = submitter ? createFormDataWithSubmitter(nativeEventTarget, submitter) : new FormData(nativeEventTarget);
                  startHostTransition(
                    maybeTargetInst,
                    {
                      pending: true,
                      data: formData,
                      method: nativeEventTarget.method,
                      action
                    },
                    null,
                    formData
                  );
                }
              } else
                "function" === typeof action && (event.preventDefault(), formData = submitter ? createFormDataWithSubmitter(nativeEventTarget, submitter) : new FormData(nativeEventTarget), startHostTransition(
                  maybeTargetInst,
                  {
                    pending: true,
                    data: formData,
                    method: nativeEventTarget.method,
                    action
                  },
                  action,
                  formData
                ));
            },
            currentTarget: nativeEventTarget
          }
        ]
      });
    }
  }
  for (var i$jscomp$inline_1577 = 0; i$jscomp$inline_1577 < simpleEventPluginEvents.length; i$jscomp$inline_1577++) {
    var eventName$jscomp$inline_1578 = simpleEventPluginEvents[i$jscomp$inline_1577], domEventName$jscomp$inline_1579 = eventName$jscomp$inline_1578.toLowerCase(), capitalizedEvent$jscomp$inline_1580 = eventName$jscomp$inline_1578[0].toUpperCase() + eventName$jscomp$inline_1578.slice(1);
    registerSimpleEvent(
      domEventName$jscomp$inline_1579,
      "on" + capitalizedEvent$jscomp$inline_1580
    );
  }
  registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
  registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
  registerSimpleEvent(ANIMATION_START, "onAnimationStart");
  registerSimpleEvent("dblclick", "onDoubleClick");
  registerSimpleEvent("focusin", "onFocus");
  registerSimpleEvent("focusout", "onBlur");
  registerSimpleEvent(TRANSITION_RUN, "onTransitionRun");
  registerSimpleEvent(TRANSITION_START, "onTransitionStart");
  registerSimpleEvent(TRANSITION_CANCEL, "onTransitionCancel");
  registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
  registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
  registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
  registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
  registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
  registerTwoPhaseEvent(
    "onChange",
    "change click focusin focusout input keydown keyup selectionchange".split(" ")
  );
  registerTwoPhaseEvent(
    "onSelect",
    "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
      " "
    )
  );
  registerTwoPhaseEvent("onBeforeInput", [
    "compositionend",
    "keypress",
    "textInput",
    "paste"
  ]);
  registerTwoPhaseEvent(
    "onCompositionEnd",
    "compositionend focusout keydown keypress keyup mousedown".split(" ")
  );
  registerTwoPhaseEvent(
    "onCompositionStart",
    "compositionstart focusout keydown keypress keyup mousedown".split(" ")
  );
  registerTwoPhaseEvent(
    "onCompositionUpdate",
    "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
  );
  var mediaEventTypes = "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(
    " "
  ), nonDelegatedEvents = new Set(
    "beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mediaEventTypes)
  );
  function processDispatchQueue(dispatchQueue, eventSystemFlags) {
    eventSystemFlags = 0 !== (eventSystemFlags & 4);
    for (var i = 0; i < dispatchQueue.length; i++) {
      var _dispatchQueue$i = dispatchQueue[i], event = _dispatchQueue$i.event;
      _dispatchQueue$i = _dispatchQueue$i.listeners;
      a: {
        var previousInstance = void 0;
        if (eventSystemFlags)
          for (var i$jscomp$0 = _dispatchQueue$i.length - 1; 0 <= i$jscomp$0; i$jscomp$0--) {
            var _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget;
            _dispatchListeners$i = _dispatchListeners$i.listener;
            if (instance !== previousInstance && event.isPropagationStopped())
              break a;
            previousInstance = _dispatchListeners$i;
            event.currentTarget = currentTarget;
            try {
              previousInstance(event);
            } catch (error) {
              reportGlobalError(error);
            }
            event.currentTarget = null;
            previousInstance = instance;
          }
        else
          for (i$jscomp$0 = 0; i$jscomp$0 < _dispatchQueue$i.length; i$jscomp$0++) {
            _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0];
            instance = _dispatchListeners$i.instance;
            currentTarget = _dispatchListeners$i.currentTarget;
            _dispatchListeners$i = _dispatchListeners$i.listener;
            if (instance !== previousInstance && event.isPropagationStopped())
              break a;
            previousInstance = _dispatchListeners$i;
            event.currentTarget = currentTarget;
            try {
              previousInstance(event);
            } catch (error) {
              reportGlobalError(error);
            }
            event.currentTarget = null;
            previousInstance = instance;
          }
      }
    }
  }
  function listenToNonDelegatedEvent(domEventName, targetElement) {
    var JSCompiler_inline_result = targetElement[internalEventHandlersKey];
    void 0 === JSCompiler_inline_result && (JSCompiler_inline_result = targetElement[internalEventHandlersKey] = /* @__PURE__ */ new Set());
    var listenerSetKey = domEventName + "__bubble";
    JSCompiler_inline_result.has(listenerSetKey) || (addTrappedEventListener(targetElement, domEventName, 2, false), JSCompiler_inline_result.add(listenerSetKey));
  }
  function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
    var eventSystemFlags = 0;
    isCapturePhaseListener && (eventSystemFlags |= 4);
    addTrappedEventListener(
      target,
      domEventName,
      eventSystemFlags,
      isCapturePhaseListener
    );
  }
  var listeningMarker = "_reactListening" + Math.random().toString(36).slice(2);
  function listenToAllSupportedEvents(rootContainerElement) {
    if (!rootContainerElement[listeningMarker]) {
      rootContainerElement[listeningMarker] = true;
      allNativeEvents.forEach(function(domEventName) {
        "selectionchange" !== domEventName && (nonDelegatedEvents.has(domEventName) || listenToNativeEvent(domEventName, false, rootContainerElement), listenToNativeEvent(domEventName, true, rootContainerElement));
      });
      var ownerDocument = 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
      null === ownerDocument || ownerDocument[listeningMarker] || (ownerDocument[listeningMarker] = true, listenToNativeEvent("selectionchange", false, ownerDocument));
    }
  }
  function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener) {
    switch (getEventPriority(domEventName)) {
      case 2:
        var listenerWrapper = dispatchDiscreteEvent;
        break;
      case 8:
        listenerWrapper = dispatchContinuousEvent;
        break;
      default:
        listenerWrapper = dispatchEvent;
    }
    eventSystemFlags = listenerWrapper.bind(
      null,
      domEventName,
      eventSystemFlags,
      targetContainer
    );
    listenerWrapper = void 0;
    !passiveBrowserEventsSupported || "touchstart" !== domEventName && "touchmove" !== domEventName && "wheel" !== domEventName || (listenerWrapper = true);
    isCapturePhaseListener ? void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
      capture: true,
      passive: listenerWrapper
    }) : targetContainer.addEventListener(domEventName, eventSystemFlags, true) : void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
      passive: listenerWrapper
    }) : targetContainer.addEventListener(domEventName, eventSystemFlags, false);
  }
  function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst$jscomp$0, targetContainer) {
    var ancestorInst = targetInst$jscomp$0;
    if (0 === (eventSystemFlags & 1) && 0 === (eventSystemFlags & 2) && null !== targetInst$jscomp$0)
      a: for (; ; ) {
        if (null === targetInst$jscomp$0) return;
        var nodeTag = targetInst$jscomp$0.tag;
        if (3 === nodeTag || 4 === nodeTag) {
          var container = targetInst$jscomp$0.stateNode.containerInfo;
          if (container === targetContainer) break;
          if (4 === nodeTag)
            for (nodeTag = targetInst$jscomp$0.return; null !== nodeTag; ) {
              var grandTag = nodeTag.tag;
              if ((3 === grandTag || 4 === grandTag) && nodeTag.stateNode.containerInfo === targetContainer)
                return;
              nodeTag = nodeTag.return;
            }
          for (; null !== container; ) {
            nodeTag = getClosestInstanceFromNode(container);
            if (null === nodeTag) return;
            grandTag = nodeTag.tag;
            if (5 === grandTag || 6 === grandTag || 26 === grandTag || 27 === grandTag) {
              targetInst$jscomp$0 = ancestorInst = nodeTag;
              continue a;
            }
            container = container.parentNode;
          }
        }
        targetInst$jscomp$0 = targetInst$jscomp$0.return;
      }
    batchedUpdates$1(function() {
      var targetInst = ancestorInst, nativeEventTarget = getEventTarget(nativeEvent), dispatchQueue = [];
      a: {
        var reactName = topLevelEventsToReactNames.get(domEventName);
        if (void 0 !== reactName) {
          var SyntheticEventCtor = SyntheticEvent, reactEventType = domEventName;
          switch (domEventName) {
            case "keypress":
              if (0 === getEventCharCode(nativeEvent)) break a;
            case "keydown":
            case "keyup":
              SyntheticEventCtor = SyntheticKeyboardEvent;
              break;
            case "focusin":
              reactEventType = "focus";
              SyntheticEventCtor = SyntheticFocusEvent;
              break;
            case "focusout":
              reactEventType = "blur";
              SyntheticEventCtor = SyntheticFocusEvent;
              break;
            case "beforeblur":
            case "afterblur":
              SyntheticEventCtor = SyntheticFocusEvent;
              break;
            case "click":
              if (2 === nativeEvent.button) break a;
            case "auxclick":
            case "dblclick":
            case "mousedown":
            case "mousemove":
            case "mouseup":
            case "mouseout":
            case "mouseover":
            case "contextmenu":
              SyntheticEventCtor = SyntheticMouseEvent;
              break;
            case "drag":
            case "dragend":
            case "dragenter":
            case "dragexit":
            case "dragleave":
            case "dragover":
            case "dragstart":
            case "drop":
              SyntheticEventCtor = SyntheticDragEvent;
              break;
            case "touchcancel":
            case "touchend":
            case "touchmove":
            case "touchstart":
              SyntheticEventCtor = SyntheticTouchEvent;
              break;
            case ANIMATION_END:
            case ANIMATION_ITERATION:
            case ANIMATION_START:
              SyntheticEventCtor = SyntheticAnimationEvent;
              break;
            case TRANSITION_END:
              SyntheticEventCtor = SyntheticTransitionEvent;
              break;
            case "scroll":
            case "scrollend":
              SyntheticEventCtor = SyntheticUIEvent;
              break;
            case "wheel":
              SyntheticEventCtor = SyntheticWheelEvent;
              break;
            case "copy":
            case "cut":
            case "paste":
              SyntheticEventCtor = SyntheticClipboardEvent;
              break;
            case "gotpointercapture":
            case "lostpointercapture":
            case "pointercancel":
            case "pointerdown":
            case "pointermove":
            case "pointerout":
            case "pointerover":
            case "pointerup":
              SyntheticEventCtor = SyntheticPointerEvent;
              break;
            case "toggle":
            case "beforetoggle":
              SyntheticEventCtor = SyntheticToggleEvent;
          }
          var inCapturePhase = 0 !== (eventSystemFlags & 4), accumulateTargetOnly = !inCapturePhase && ("scroll" === domEventName || "scrollend" === domEventName), reactEventName = inCapturePhase ? null !== reactName ? reactName + "Capture" : null : reactName;
          inCapturePhase = [];
          for (var instance = targetInst, lastHostComponent; null !== instance; ) {
            var _instance = instance;
            lastHostComponent = _instance.stateNode;
            _instance = _instance.tag;
            5 !== _instance && 26 !== _instance && 27 !== _instance || null === lastHostComponent || null === reactEventName || (_instance = getListener(instance, reactEventName), null != _instance && inCapturePhase.push(
              createDispatchListener(instance, _instance, lastHostComponent)
            ));
            if (accumulateTargetOnly) break;
            instance = instance.return;
          }
          0 < inCapturePhase.length && (reactName = new SyntheticEventCtor(
            reactName,
            reactEventType,
            null,
            nativeEvent,
            nativeEventTarget
          ), dispatchQueue.push({ event: reactName, listeners: inCapturePhase }));
        }
      }
      if (0 === (eventSystemFlags & 7)) {
        a: {
          reactName = "mouseover" === domEventName || "pointerover" === domEventName;
          SyntheticEventCtor = "mouseout" === domEventName || "pointerout" === domEventName;
          if (reactName && nativeEvent !== currentReplayingEvent && (reactEventType = nativeEvent.relatedTarget || nativeEvent.fromElement) && (getClosestInstanceFromNode(reactEventType) || reactEventType[internalContainerInstanceKey]))
            break a;
          if (SyntheticEventCtor || reactName) {
            reactName = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget : (reactName = nativeEventTarget.ownerDocument) ? reactName.defaultView || reactName.parentWindow : window;
            if (SyntheticEventCtor) {
              if (reactEventType = nativeEvent.relatedTarget || nativeEvent.toElement, SyntheticEventCtor = targetInst, reactEventType = reactEventType ? getClosestInstanceFromNode(reactEventType) : null, null !== reactEventType && (accumulateTargetOnly = getNearestMountedFiber(reactEventType), inCapturePhase = reactEventType.tag, reactEventType !== accumulateTargetOnly || 5 !== inCapturePhase && 27 !== inCapturePhase && 6 !== inCapturePhase))
                reactEventType = null;
            } else SyntheticEventCtor = null, reactEventType = targetInst;
            if (SyntheticEventCtor !== reactEventType) {
              inCapturePhase = SyntheticMouseEvent;
              _instance = "onMouseLeave";
              reactEventName = "onMouseEnter";
              instance = "mouse";
              if ("pointerout" === domEventName || "pointerover" === domEventName)
                inCapturePhase = SyntheticPointerEvent, _instance = "onPointerLeave", reactEventName = "onPointerEnter", instance = "pointer";
              accumulateTargetOnly = null == SyntheticEventCtor ? reactName : getNodeFromInstance(SyntheticEventCtor);
              lastHostComponent = null == reactEventType ? reactName : getNodeFromInstance(reactEventType);
              reactName = new inCapturePhase(
                _instance,
                instance + "leave",
                SyntheticEventCtor,
                nativeEvent,
                nativeEventTarget
              );
              reactName.target = accumulateTargetOnly;
              reactName.relatedTarget = lastHostComponent;
              _instance = null;
              getClosestInstanceFromNode(nativeEventTarget) === targetInst && (inCapturePhase = new inCapturePhase(
                reactEventName,
                instance + "enter",
                reactEventType,
                nativeEvent,
                nativeEventTarget
              ), inCapturePhase.target = lastHostComponent, inCapturePhase.relatedTarget = accumulateTargetOnly, _instance = inCapturePhase);
              accumulateTargetOnly = _instance;
              if (SyntheticEventCtor && reactEventType)
                b: {
                  inCapturePhase = getParent;
                  reactEventName = SyntheticEventCtor;
                  instance = reactEventType;
                  lastHostComponent = 0;
                  for (_instance = reactEventName; _instance; _instance = inCapturePhase(_instance))
                    lastHostComponent++;
                  _instance = 0;
                  for (var tempB = instance; tempB; tempB = inCapturePhase(tempB))
                    _instance++;
                  for (; 0 < lastHostComponent - _instance; )
                    reactEventName = inCapturePhase(reactEventName), lastHostComponent--;
                  for (; 0 < _instance - lastHostComponent; )
                    instance = inCapturePhase(instance), _instance--;
                  for (; lastHostComponent--; ) {
                    if (reactEventName === instance || null !== instance && reactEventName === instance.alternate) {
                      inCapturePhase = reactEventName;
                      break b;
                    }
                    reactEventName = inCapturePhase(reactEventName);
                    instance = inCapturePhase(instance);
                  }
                  inCapturePhase = null;
                }
              else inCapturePhase = null;
              null !== SyntheticEventCtor && accumulateEnterLeaveListenersForEvent(
                dispatchQueue,
                reactName,
                SyntheticEventCtor,
                inCapturePhase,
                false
              );
              null !== reactEventType && null !== accumulateTargetOnly && accumulateEnterLeaveListenersForEvent(
                dispatchQueue,
                accumulateTargetOnly,
                reactEventType,
                inCapturePhase,
                true
              );
            }
          }
        }
        a: {
          reactName = targetInst ? getNodeFromInstance(targetInst) : window;
          SyntheticEventCtor = reactName.nodeName && reactName.nodeName.toLowerCase();
          if ("select" === SyntheticEventCtor || "input" === SyntheticEventCtor && "file" === reactName.type)
            var getTargetInstFunc = getTargetInstForChangeEvent;
          else if (isTextInputElement(reactName))
            if (isInputEventSupported)
              getTargetInstFunc = getTargetInstForInputOrChangeEvent;
            else {
              getTargetInstFunc = getTargetInstForInputEventPolyfill;
              var handleEventFunc = handleEventsForInputEventPolyfill;
            }
          else
            SyntheticEventCtor = reactName.nodeName, !SyntheticEventCtor || "input" !== SyntheticEventCtor.toLowerCase() || "checkbox" !== reactName.type && "radio" !== reactName.type ? targetInst && isCustomElement(targetInst.elementType) && (getTargetInstFunc = getTargetInstForChangeEvent) : getTargetInstFunc = getTargetInstForClickEvent;
          if (getTargetInstFunc && (getTargetInstFunc = getTargetInstFunc(domEventName, targetInst))) {
            createAndAccumulateChangeEvent(
              dispatchQueue,
              getTargetInstFunc,
              nativeEvent,
              nativeEventTarget
            );
            break a;
          }
          handleEventFunc && handleEventFunc(domEventName, reactName, targetInst);
          "focusout" === domEventName && targetInst && "number" === reactName.type && null != targetInst.memoizedProps.value && setDefaultValue(reactName, "number", reactName.value);
        }
        handleEventFunc = targetInst ? getNodeFromInstance(targetInst) : window;
        switch (domEventName) {
          case "focusin":
            if (isTextInputElement(handleEventFunc) || "true" === handleEventFunc.contentEditable)
              activeElement = handleEventFunc, activeElementInst = targetInst, lastSelection = null;
            break;
          case "focusout":
            lastSelection = activeElementInst = activeElement = null;
            break;
          case "mousedown":
            mouseDown = true;
            break;
          case "contextmenu":
          case "mouseup":
          case "dragend":
            mouseDown = false;
            constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
            break;
          case "selectionchange":
            if (skipSelectionChangeEvent) break;
          case "keydown":
          case "keyup":
            constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget);
        }
        var fallbackData;
        if (canUseCompositionEvent)
          b: {
            switch (domEventName) {
              case "compositionstart":
                var eventType = "onCompositionStart";
                break b;
              case "compositionend":
                eventType = "onCompositionEnd";
                break b;
              case "compositionupdate":
                eventType = "onCompositionUpdate";
                break b;
            }
            eventType = void 0;
          }
        else
          isComposing ? isFallbackCompositionEnd(domEventName, nativeEvent) && (eventType = "onCompositionEnd") : "keydown" === domEventName && 229 === nativeEvent.keyCode && (eventType = "onCompositionStart");
        eventType && (useFallbackCompositionData && "ko" !== nativeEvent.locale && (isComposing || "onCompositionStart" !== eventType ? "onCompositionEnd" === eventType && isComposing && (fallbackData = getData()) : (root2 = nativeEventTarget, startText = "value" in root2 ? root2.value : root2.textContent, isComposing = true)), handleEventFunc = accumulateTwoPhaseListeners(targetInst, eventType), 0 < handleEventFunc.length && (eventType = new SyntheticCompositionEvent(
          eventType,
          domEventName,
          null,
          nativeEvent,
          nativeEventTarget
        ), dispatchQueue.push({ event: eventType, listeners: handleEventFunc }), fallbackData ? eventType.data = fallbackData : (fallbackData = getDataFromCustomEvent(nativeEvent), null !== fallbackData && (eventType.data = fallbackData))));
        if (fallbackData = canUseTextInputEvent ? getNativeBeforeInputChars(domEventName, nativeEvent) : getFallbackBeforeInputChars(domEventName, nativeEvent))
          eventType = accumulateTwoPhaseListeners(targetInst, "onBeforeInput"), 0 < eventType.length && (handleEventFunc = new SyntheticCompositionEvent(
            "onBeforeInput",
            "beforeinput",
            null,
            nativeEvent,
            nativeEventTarget
          ), dispatchQueue.push({
            event: handleEventFunc,
            listeners: eventType
          }), handleEventFunc.data = fallbackData);
        extractEvents$1(
          dispatchQueue,
          domEventName,
          targetInst,
          nativeEvent,
          nativeEventTarget
        );
      }
      processDispatchQueue(dispatchQueue, eventSystemFlags);
    });
  }
  function createDispatchListener(instance, listener, currentTarget) {
    return {
      instance,
      listener,
      currentTarget
    };
  }
  function accumulateTwoPhaseListeners(targetFiber, reactName) {
    for (var captureName = reactName + "Capture", listeners = []; null !== targetFiber; ) {
      var _instance2 = targetFiber, stateNode = _instance2.stateNode;
      _instance2 = _instance2.tag;
      5 !== _instance2 && 26 !== _instance2 && 27 !== _instance2 || null === stateNode || (_instance2 = getListener(targetFiber, captureName), null != _instance2 && listeners.unshift(
        createDispatchListener(targetFiber, _instance2, stateNode)
      ), _instance2 = getListener(targetFiber, reactName), null != _instance2 && listeners.push(
        createDispatchListener(targetFiber, _instance2, stateNode)
      ));
      if (3 === targetFiber.tag) return listeners;
      targetFiber = targetFiber.return;
    }
    return [];
  }
  function getParent(inst) {
    if (null === inst) return null;
    do
      inst = inst.return;
    while (inst && 5 !== inst.tag && 27 !== inst.tag);
    return inst ? inst : null;
  }
  function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common2, inCapturePhase) {
    for (var registrationName = event._reactName, listeners = []; null !== target && target !== common2; ) {
      var _instance3 = target, alternate = _instance3.alternate, stateNode = _instance3.stateNode;
      _instance3 = _instance3.tag;
      if (null !== alternate && alternate === common2) break;
      5 !== _instance3 && 26 !== _instance3 && 27 !== _instance3 || null === stateNode || (alternate = stateNode, inCapturePhase ? (stateNode = getListener(target, registrationName), null != stateNode && listeners.unshift(
        createDispatchListener(target, stateNode, alternate)
      )) : inCapturePhase || (stateNode = getListener(target, registrationName), null != stateNode && listeners.push(
        createDispatchListener(target, stateNode, alternate)
      )));
      target = target.return;
    }
    0 !== listeners.length && dispatchQueue.push({ event, listeners });
  }
  var NORMALIZE_NEWLINES_REGEX = /\r\n?/g, NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g;
  function normalizeMarkupForTextOrAttribute(markup) {
    return ("string" === typeof markup ? markup : "" + markup).replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
  }
  function checkForUnmatchedText(serverText, clientText) {
    clientText = normalizeMarkupForTextOrAttribute(clientText);
    return normalizeMarkupForTextOrAttribute(serverText) === clientText ? true : false;
  }
  function setProp(domElement, tag, key, value, props, prevValue) {
    switch (key) {
      case "children":
        "string" === typeof value ? "body" === tag || "textarea" === tag && "" === value || setTextContent(domElement, value) : ("number" === typeof value || "bigint" === typeof value) && "body" !== tag && setTextContent(domElement, "" + value);
        break;
      case "className":
        setValueForKnownAttribute(domElement, "class", value);
        break;
      case "tabIndex":
        setValueForKnownAttribute(domElement, "tabindex", value);
        break;
      case "dir":
      case "role":
      case "viewBox":
      case "width":
      case "height":
        setValueForKnownAttribute(domElement, key, value);
        break;
      case "style":
        setValueForStyles(domElement, value, prevValue);
        break;
      case "data":
        if ("object" !== tag) {
          setValueForKnownAttribute(domElement, "data", value);
          break;
        }
      case "src":
      case "href":
        if ("" === value && ("a" !== tag || "href" !== key)) {
          domElement.removeAttribute(key);
          break;
        }
        if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value) {
          domElement.removeAttribute(key);
          break;
        }
        value = sanitizeURL("" + value);
        domElement.setAttribute(key, value);
        break;
      case "action":
      case "formAction":
        if ("function" === typeof value) {
          domElement.setAttribute(
            key,
            "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
          );
          break;
        } else
          "function" === typeof prevValue && ("formAction" === key ? ("input" !== tag && setProp(domElement, tag, "name", props.name, props, null), setProp(
            domElement,
            tag,
            "formEncType",
            props.formEncType,
            props,
            null
          ), setProp(
            domElement,
            tag,
            "formMethod",
            props.formMethod,
            props,
            null
          ), setProp(
            domElement,
            tag,
            "formTarget",
            props.formTarget,
            props,
            null
          )) : (setProp(domElement, tag, "encType", props.encType, props, null), setProp(domElement, tag, "method", props.method, props, null), setProp(domElement, tag, "target", props.target, props, null)));
        if (null == value || "symbol" === typeof value || "boolean" === typeof value) {
          domElement.removeAttribute(key);
          break;
        }
        value = sanitizeURL("" + value);
        domElement.setAttribute(key, value);
        break;
      case "onClick":
        null != value && (domElement.onclick = noop$1);
        break;
      case "onScroll":
        null != value && listenToNonDelegatedEvent("scroll", domElement);
        break;
      case "onScrollEnd":
        null != value && listenToNonDelegatedEvent("scrollend", domElement);
        break;
      case "dangerouslySetInnerHTML":
        if (null != value) {
          if ("object" !== typeof value || !("__html" in value))
            throw Error(formatProdErrorMessage(61));
          key = value.__html;
          if (null != key) {
            if (null != props.children) throw Error(formatProdErrorMessage(60));
            domElement.innerHTML = key;
          }
        }
        break;
      case "multiple":
        domElement.multiple = value && "function" !== typeof value && "symbol" !== typeof value;
        break;
      case "muted":
        domElement.muted = value && "function" !== typeof value && "symbol" !== typeof value;
        break;
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "defaultValue":
      case "defaultChecked":
      case "innerHTML":
      case "ref":
        break;
      case "autoFocus":
        break;
      case "xlinkHref":
        if (null == value || "function" === typeof value || "boolean" === typeof value || "symbol" === typeof value) {
          domElement.removeAttribute("xlink:href");
          break;
        }
        key = sanitizeURL("" + value);
        domElement.setAttributeNS(
          "http://www.w3.org/1999/xlink",
          "xlink:href",
          key
        );
        break;
      case "contentEditable":
      case "spellCheck":
      case "draggable":
      case "value":
      case "autoReverse":
      case "externalResourcesRequired":
      case "focusable":
      case "preserveAlpha":
        null != value && "function" !== typeof value && "symbol" !== typeof value ? domElement.setAttribute(key, "" + value) : domElement.removeAttribute(key);
        break;
      case "inert":
      case "allowFullScreen":
      case "async":
      case "autoPlay":
      case "controls":
      case "default":
      case "defer":
      case "disabled":
      case "disablePictureInPicture":
      case "disableRemotePlayback":
      case "formNoValidate":
      case "hidden":
      case "loop":
      case "noModule":
      case "noValidate":
      case "open":
      case "playsInline":
      case "readOnly":
      case "required":
      case "reversed":
      case "scoped":
      case "seamless":
      case "itemScope":
        value && "function" !== typeof value && "symbol" !== typeof value ? domElement.setAttribute(key, "") : domElement.removeAttribute(key);
        break;
      case "capture":
      case "download":
        true === value ? domElement.setAttribute(key, "") : false !== value && null != value && "function" !== typeof value && "symbol" !== typeof value ? domElement.setAttribute(key, value) : domElement.removeAttribute(key);
        break;
      case "cols":
      case "rows":
      case "size":
      case "span":
        null != value && "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value ? domElement.setAttribute(key, value) : domElement.removeAttribute(key);
        break;
      case "rowSpan":
      case "start":
        null == value || "function" === typeof value || "symbol" === typeof value || isNaN(value) ? domElement.removeAttribute(key) : domElement.setAttribute(key, value);
        break;
      case "popover":
        listenToNonDelegatedEvent("beforetoggle", domElement);
        listenToNonDelegatedEvent("toggle", domElement);
        setValueForAttribute(domElement, "popover", value);
        break;
      case "xlinkActuate":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/1999/xlink",
          "xlink:actuate",
          value
        );
        break;
      case "xlinkArcrole":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/1999/xlink",
          "xlink:arcrole",
          value
        );
        break;
      case "xlinkRole":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/1999/xlink",
          "xlink:role",
          value
        );
        break;
      case "xlinkShow":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/1999/xlink",
          "xlink:show",
          value
        );
        break;
      case "xlinkTitle":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/1999/xlink",
          "xlink:title",
          value
        );
        break;
      case "xlinkType":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/1999/xlink",
          "xlink:type",
          value
        );
        break;
      case "xmlBase":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/XML/1998/namespace",
          "xml:base",
          value
        );
        break;
      case "xmlLang":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/XML/1998/namespace",
          "xml:lang",
          value
        );
        break;
      case "xmlSpace":
        setValueForNamespacedAttribute(
          domElement,
          "http://www.w3.org/XML/1998/namespace",
          "xml:space",
          value
        );
        break;
      case "is":
        setValueForAttribute(domElement, "is", value);
        break;
      case "innerText":
      case "textContent":
        break;
      default:
        if (!(2 < key.length) || "o" !== key[0] && "O" !== key[0] || "n" !== key[1] && "N" !== key[1])
          key = aliases.get(key) || key, setValueForAttribute(domElement, key, value);
    }
  }
  function setPropOnCustomElement(domElement, tag, key, value, props, prevValue) {
    switch (key) {
      case "style":
        setValueForStyles(domElement, value, prevValue);
        break;
      case "dangerouslySetInnerHTML":
        if (null != value) {
          if ("object" !== typeof value || !("__html" in value))
            throw Error(formatProdErrorMessage(61));
          key = value.__html;
          if (null != key) {
            if (null != props.children) throw Error(formatProdErrorMessage(60));
            domElement.innerHTML = key;
          }
        }
        break;
      case "children":
        "string" === typeof value ? setTextContent(domElement, value) : ("number" === typeof value || "bigint" === typeof value) && setTextContent(domElement, "" + value);
        break;
      case "onScroll":
        null != value && listenToNonDelegatedEvent("scroll", domElement);
        break;
      case "onScrollEnd":
        null != value && listenToNonDelegatedEvent("scrollend", domElement);
        break;
      case "onClick":
        null != value && (domElement.onclick = noop$1);
        break;
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "innerHTML":
      case "ref":
        break;
      case "innerText":
      case "textContent":
        break;
      default:
        if (!registrationNameDependencies.hasOwnProperty(key))
          a: {
            if ("o" === key[0] && "n" === key[1] && (props = key.endsWith("Capture"), tag = key.slice(2, props ? key.length - 7 : void 0), prevValue = domElement[internalPropsKey] || null, prevValue = null != prevValue ? prevValue[key] : null, "function" === typeof prevValue && domElement.removeEventListener(tag, prevValue, props), "function" === typeof value)) {
              "function" !== typeof prevValue && null !== prevValue && (key in domElement ? domElement[key] = null : domElement.hasAttribute(key) && domElement.removeAttribute(key));
              domElement.addEventListener(tag, value, props);
              break a;
            }
            key in domElement ? domElement[key] = value : true === value ? domElement.setAttribute(key, "") : setValueForAttribute(domElement, key, value);
          }
    }
  }
  function setInitialProperties(domElement, tag, props) {
    switch (tag) {
      case "div":
      case "span":
      case "svg":
      case "path":
      case "a":
      case "g":
      case "p":
      case "li":
        break;
      case "img":
        listenToNonDelegatedEvent("error", domElement);
        listenToNonDelegatedEvent("load", domElement);
        var hasSrc = false, hasSrcSet = false, propKey;
        for (propKey in props)
          if (props.hasOwnProperty(propKey)) {
            var propValue = props[propKey];
            if (null != propValue)
              switch (propKey) {
                case "src":
                  hasSrc = true;
                  break;
                case "srcSet":
                  hasSrcSet = true;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(formatProdErrorMessage(137, tag));
                default:
                  setProp(domElement, tag, propKey, propValue, props, null);
              }
          }
        hasSrcSet && setProp(domElement, tag, "srcSet", props.srcSet, props, null);
        hasSrc && setProp(domElement, tag, "src", props.src, props, null);
        return;
      case "input":
        listenToNonDelegatedEvent("invalid", domElement);
        var defaultValue = propKey = propValue = hasSrcSet = null, checked = null, defaultChecked = null;
        for (hasSrc in props)
          if (props.hasOwnProperty(hasSrc)) {
            var propValue$184 = props[hasSrc];
            if (null != propValue$184)
              switch (hasSrc) {
                case "name":
                  hasSrcSet = propValue$184;
                  break;
                case "type":
                  propValue = propValue$184;
                  break;
                case "checked":
                  checked = propValue$184;
                  break;
                case "defaultChecked":
                  defaultChecked = propValue$184;
                  break;
                case "value":
                  propKey = propValue$184;
                  break;
                case "defaultValue":
                  defaultValue = propValue$184;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != propValue$184)
                    throw Error(formatProdErrorMessage(137, tag));
                  break;
                default:
                  setProp(domElement, tag, hasSrc, propValue$184, props, null);
              }
          }
        initInput(
          domElement,
          propKey,
          defaultValue,
          checked,
          defaultChecked,
          propValue,
          hasSrcSet,
          false
        );
        return;
      case "select":
        listenToNonDelegatedEvent("invalid", domElement);
        hasSrc = propValue = propKey = null;
        for (hasSrcSet in props)
          if (props.hasOwnProperty(hasSrcSet) && (defaultValue = props[hasSrcSet], null != defaultValue))
            switch (hasSrcSet) {
              case "value":
                propKey = defaultValue;
                break;
              case "defaultValue":
                propValue = defaultValue;
                break;
              case "multiple":
                hasSrc = defaultValue;
              default:
                setProp(domElement, tag, hasSrcSet, defaultValue, props, null);
            }
        tag = propKey;
        props = propValue;
        domElement.multiple = !!hasSrc;
        null != tag ? updateOptions(domElement, !!hasSrc, tag, false) : null != props && updateOptions(domElement, !!hasSrc, props, true);
        return;
      case "textarea":
        listenToNonDelegatedEvent("invalid", domElement);
        propKey = hasSrcSet = hasSrc = null;
        for (propValue in props)
          if (props.hasOwnProperty(propValue) && (defaultValue = props[propValue], null != defaultValue))
            switch (propValue) {
              case "value":
                hasSrc = defaultValue;
                break;
              case "defaultValue":
                hasSrcSet = defaultValue;
                break;
              case "children":
                propKey = defaultValue;
                break;
              case "dangerouslySetInnerHTML":
                if (null != defaultValue) throw Error(formatProdErrorMessage(91));
                break;
              default:
                setProp(domElement, tag, propValue, defaultValue, props, null);
            }
        initTextarea(domElement, hasSrc, hasSrcSet, propKey);
        return;
      case "option":
        for (checked in props)
          if (props.hasOwnProperty(checked) && (hasSrc = props[checked], null != hasSrc))
            switch (checked) {
              case "selected":
                domElement.selected = hasSrc && "function" !== typeof hasSrc && "symbol" !== typeof hasSrc;
                break;
              default:
                setProp(domElement, tag, checked, hasSrc, props, null);
            }
        return;
      case "dialog":
        listenToNonDelegatedEvent("beforetoggle", domElement);
        listenToNonDelegatedEvent("toggle", domElement);
        listenToNonDelegatedEvent("cancel", domElement);
        listenToNonDelegatedEvent("close", domElement);
        break;
      case "iframe":
      case "object":
        listenToNonDelegatedEvent("load", domElement);
        break;
      case "video":
      case "audio":
        for (hasSrc = 0; hasSrc < mediaEventTypes.length; hasSrc++)
          listenToNonDelegatedEvent(mediaEventTypes[hasSrc], domElement);
        break;
      case "image":
        listenToNonDelegatedEvent("error", domElement);
        listenToNonDelegatedEvent("load", domElement);
        break;
      case "details":
        listenToNonDelegatedEvent("toggle", domElement);
        break;
      case "embed":
      case "source":
      case "link":
        listenToNonDelegatedEvent("error", domElement), listenToNonDelegatedEvent("load", domElement);
      case "area":
      case "base":
      case "br":
      case "col":
      case "hr":
      case "keygen":
      case "meta":
      case "param":
      case "track":
      case "wbr":
      case "menuitem":
        for (defaultChecked in props)
          if (props.hasOwnProperty(defaultChecked) && (hasSrc = props[defaultChecked], null != hasSrc))
            switch (defaultChecked) {
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(formatProdErrorMessage(137, tag));
              default:
                setProp(domElement, tag, defaultChecked, hasSrc, props, null);
            }
        return;
      default:
        if (isCustomElement(tag)) {
          for (propValue$184 in props)
            props.hasOwnProperty(propValue$184) && (hasSrc = props[propValue$184], void 0 !== hasSrc && setPropOnCustomElement(
              domElement,
              tag,
              propValue$184,
              hasSrc,
              props,
              void 0
            ));
          return;
        }
    }
    for (defaultValue in props)
      props.hasOwnProperty(defaultValue) && (hasSrc = props[defaultValue], null != hasSrc && setProp(domElement, tag, defaultValue, hasSrc, props, null));
  }
  function updateProperties(domElement, tag, lastProps, nextProps) {
    switch (tag) {
      case "div":
      case "span":
      case "svg":
      case "path":
      case "a":
      case "g":
      case "p":
      case "li":
        break;
      case "input":
        var name2 = null, type2 = null, value = null, defaultValue = null, lastDefaultValue = null, checked = null, defaultChecked = null;
        for (propKey in lastProps) {
          var lastProp = lastProps[propKey];
          if (lastProps.hasOwnProperty(propKey) && null != lastProp)
            switch (propKey) {
              case "checked":
                break;
              case "value":
                break;
              case "defaultValue":
                lastDefaultValue = lastProp;
              default:
                nextProps.hasOwnProperty(propKey) || setProp(domElement, tag, propKey, null, nextProps, lastProp);
            }
        }
        for (var propKey$201 in nextProps) {
          var propKey = nextProps[propKey$201];
          lastProp = lastProps[propKey$201];
          if (nextProps.hasOwnProperty(propKey$201) && (null != propKey || null != lastProp))
            switch (propKey$201) {
              case "type":
                type2 = propKey;
                break;
              case "name":
                name2 = propKey;
                break;
              case "checked":
                checked = propKey;
                break;
              case "defaultChecked":
                defaultChecked = propKey;
                break;
              case "value":
                value = propKey;
                break;
              case "defaultValue":
                defaultValue = propKey;
                break;
              case "children":
              case "dangerouslySetInnerHTML":
                if (null != propKey)
                  throw Error(formatProdErrorMessage(137, tag));
                break;
              default:
                propKey !== lastProp && setProp(
                  domElement,
                  tag,
                  propKey$201,
                  propKey,
                  nextProps,
                  lastProp
                );
            }
        }
        updateInput(
          domElement,
          value,
          defaultValue,
          lastDefaultValue,
          checked,
          defaultChecked,
          type2,
          name2
        );
        return;
      case "select":
        propKey = value = defaultValue = propKey$201 = null;
        for (type2 in lastProps)
          if (lastDefaultValue = lastProps[type2], lastProps.hasOwnProperty(type2) && null != lastDefaultValue)
            switch (type2) {
              case "value":
                break;
              case "multiple":
                propKey = lastDefaultValue;
              default:
                nextProps.hasOwnProperty(type2) || setProp(
                  domElement,
                  tag,
                  type2,
                  null,
                  nextProps,
                  lastDefaultValue
                );
            }
        for (name2 in nextProps)
          if (type2 = nextProps[name2], lastDefaultValue = lastProps[name2], nextProps.hasOwnProperty(name2) && (null != type2 || null != lastDefaultValue))
            switch (name2) {
              case "value":
                propKey$201 = type2;
                break;
              case "defaultValue":
                defaultValue = type2;
                break;
              case "multiple":
                value = type2;
              default:
                type2 !== lastDefaultValue && setProp(
                  domElement,
                  tag,
                  name2,
                  type2,
                  nextProps,
                  lastDefaultValue
                );
            }
        tag = defaultValue;
        lastProps = value;
        nextProps = propKey;
        null != propKey$201 ? updateOptions(domElement, !!lastProps, propKey$201, false) : !!nextProps !== !!lastProps && (null != tag ? updateOptions(domElement, !!lastProps, tag, true) : updateOptions(domElement, !!lastProps, lastProps ? [] : "", false));
        return;
      case "textarea":
        propKey = propKey$201 = null;
        for (defaultValue in lastProps)
          if (name2 = lastProps[defaultValue], lastProps.hasOwnProperty(defaultValue) && null != name2 && !nextProps.hasOwnProperty(defaultValue))
            switch (defaultValue) {
              case "value":
                break;
              case "children":
                break;
              default:
                setProp(domElement, tag, defaultValue, null, nextProps, name2);
            }
        for (value in nextProps)
          if (name2 = nextProps[value], type2 = lastProps[value], nextProps.hasOwnProperty(value) && (null != name2 || null != type2))
            switch (value) {
              case "value":
                propKey$201 = name2;
                break;
              case "defaultValue":
                propKey = name2;
                break;
              case "children":
                break;
              case "dangerouslySetInnerHTML":
                if (null != name2) throw Error(formatProdErrorMessage(91));
                break;
              default:
                name2 !== type2 && setProp(domElement, tag, value, name2, nextProps, type2);
            }
        updateTextarea(domElement, propKey$201, propKey);
        return;
      case "option":
        for (var propKey$217 in lastProps)
          if (propKey$201 = lastProps[propKey$217], lastProps.hasOwnProperty(propKey$217) && null != propKey$201 && !nextProps.hasOwnProperty(propKey$217))
            switch (propKey$217) {
              case "selected":
                domElement.selected = false;
                break;
              default:
                setProp(
                  domElement,
                  tag,
                  propKey$217,
                  null,
                  nextProps,
                  propKey$201
                );
            }
        for (lastDefaultValue in nextProps)
          if (propKey$201 = nextProps[lastDefaultValue], propKey = lastProps[lastDefaultValue], nextProps.hasOwnProperty(lastDefaultValue) && propKey$201 !== propKey && (null != propKey$201 || null != propKey))
            switch (lastDefaultValue) {
              case "selected":
                domElement.selected = propKey$201 && "function" !== typeof propKey$201 && "symbol" !== typeof propKey$201;
                break;
              default:
                setProp(
                  domElement,
                  tag,
                  lastDefaultValue,
                  propKey$201,
                  nextProps,
                  propKey
                );
            }
        return;
      case "img":
      case "link":
      case "area":
      case "base":
      case "br":
      case "col":
      case "embed":
      case "hr":
      case "keygen":
      case "meta":
      case "param":
      case "source":
      case "track":
      case "wbr":
      case "menuitem":
        for (var propKey$222 in lastProps)
          propKey$201 = lastProps[propKey$222], lastProps.hasOwnProperty(propKey$222) && null != propKey$201 && !nextProps.hasOwnProperty(propKey$222) && setProp(domElement, tag, propKey$222, null, nextProps, propKey$201);
        for (checked in nextProps)
          if (propKey$201 = nextProps[checked], propKey = lastProps[checked], nextProps.hasOwnProperty(checked) && propKey$201 !== propKey && (null != propKey$201 || null != propKey))
            switch (checked) {
              case "children":
              case "dangerouslySetInnerHTML":
                if (null != propKey$201)
                  throw Error(formatProdErrorMessage(137, tag));
                break;
              default:
                setProp(
                  domElement,
                  tag,
                  checked,
                  propKey$201,
                  nextProps,
                  propKey
                );
            }
        return;
      default:
        if (isCustomElement(tag)) {
          for (var propKey$227 in lastProps)
            propKey$201 = lastProps[propKey$227], lastProps.hasOwnProperty(propKey$227) && void 0 !== propKey$201 && !nextProps.hasOwnProperty(propKey$227) && setPropOnCustomElement(
              domElement,
              tag,
              propKey$227,
              void 0,
              nextProps,
              propKey$201
            );
          for (defaultChecked in nextProps)
            propKey$201 = nextProps[defaultChecked], propKey = lastProps[defaultChecked], !nextProps.hasOwnProperty(defaultChecked) || propKey$201 === propKey || void 0 === propKey$201 && void 0 === propKey || setPropOnCustomElement(
              domElement,
              tag,
              defaultChecked,
              propKey$201,
              nextProps,
              propKey
            );
          return;
        }
    }
    for (var propKey$232 in lastProps)
      propKey$201 = lastProps[propKey$232], lastProps.hasOwnProperty(propKey$232) && null != propKey$201 && !nextProps.hasOwnProperty(propKey$232) && setProp(domElement, tag, propKey$232, null, nextProps, propKey$201);
    for (lastProp in nextProps)
      propKey$201 = nextProps[lastProp], propKey = lastProps[lastProp], !nextProps.hasOwnProperty(lastProp) || propKey$201 === propKey || null == propKey$201 && null == propKey || setProp(domElement, tag, lastProp, propKey$201, nextProps, propKey);
  }
  function isLikelyStaticResource(initiatorType) {
    switch (initiatorType) {
      case "css":
      case "script":
      case "font":
      case "img":
      case "image":
      case "input":
      case "link":
        return true;
      default:
        return false;
    }
  }
  function estimateBandwidth() {
    if ("function" === typeof performance.getEntriesByType) {
      for (var count = 0, bits = 0, resourceEntries = performance.getEntriesByType("resource"), i = 0; i < resourceEntries.length; i++) {
        var entry = resourceEntries[i], transferSize = entry.transferSize, initiatorType = entry.initiatorType, duration = entry.duration;
        if (transferSize && duration && isLikelyStaticResource(initiatorType)) {
          initiatorType = 0;
          duration = entry.responseEnd;
          for (i += 1; i < resourceEntries.length; i++) {
            var overlapEntry = resourceEntries[i], overlapStartTime = overlapEntry.startTime;
            if (overlapStartTime > duration) break;
            var overlapTransferSize = overlapEntry.transferSize, overlapInitiatorType = overlapEntry.initiatorType;
            overlapTransferSize && isLikelyStaticResource(overlapInitiatorType) && (overlapEntry = overlapEntry.responseEnd, initiatorType += overlapTransferSize * (overlapEntry < duration ? 1 : (duration - overlapStartTime) / (overlapEntry - overlapStartTime)));
          }
          --i;
          bits += 8 * (transferSize + initiatorType) / (entry.duration / 1e3);
          count++;
          if (10 < count) break;
        }
      }
      if (0 < count) return bits / count / 1e6;
    }
    return navigator.connection && (count = navigator.connection.downlink, "number" === typeof count) ? count : 5;
  }
  var eventsEnabled = null, selectionInformation = null;
  function getOwnerDocumentFromRootContainer(rootContainerElement) {
    return 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
  }
  function getOwnHostContext(namespaceURI) {
    switch (namespaceURI) {
      case "http://www.w3.org/2000/svg":
        return 1;
      case "http://www.w3.org/1998/Math/MathML":
        return 2;
      default:
        return 0;
    }
  }
  function getChildHostContextProd(parentNamespace, type2) {
    if (0 === parentNamespace)
      switch (type2) {
        case "svg":
          return 1;
        case "math":
          return 2;
        default:
          return 0;
      }
    return 1 === parentNamespace && "foreignObject" === type2 ? 0 : parentNamespace;
  }
  function shouldSetTextContent(type2, props) {
    return "textarea" === type2 || "noscript" === type2 || "string" === typeof props.children || "number" === typeof props.children || "bigint" === typeof props.children || "object" === typeof props.dangerouslySetInnerHTML && null !== props.dangerouslySetInnerHTML && null != props.dangerouslySetInnerHTML.__html;
  }
  var currentPopstateTransitionEvent = null;
  function shouldAttemptEagerTransition() {
    var event = window.event;
    if (event && "popstate" === event.type) {
      if (event === currentPopstateTransitionEvent) return false;
      currentPopstateTransitionEvent = event;
      return true;
    }
    currentPopstateTransitionEvent = null;
    return false;
  }
  var scheduleTimeout = "function" === typeof setTimeout ? setTimeout : void 0, cancelTimeout = "function" === typeof clearTimeout ? clearTimeout : void 0, localPromise = "function" === typeof Promise ? Promise : void 0, scheduleMicrotask = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof localPromise ? function(callback) {
    return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
  } : scheduleTimeout;
  function handleErrorInNextTick(error) {
    setTimeout(function() {
      throw error;
    });
  }
  function isSingletonScope(type2) {
    return "head" === type2;
  }
  function clearHydrationBoundary(parentInstance, hydrationInstance) {
    var node2 = hydrationInstance, depth = 0;
    do {
      var nextNode = node2.nextSibling;
      parentInstance.removeChild(node2);
      if (nextNode && 8 === nextNode.nodeType)
        if (node2 = nextNode.data, "/$" === node2 || "/&" === node2) {
          if (0 === depth) {
            parentInstance.removeChild(nextNode);
            retryIfBlockedOn(hydrationInstance);
            return;
          }
          depth--;
        } else if ("$" === node2 || "$?" === node2 || "$~" === node2 || "$!" === node2 || "&" === node2)
          depth++;
        else if ("html" === node2)
          releaseSingletonInstance(parentInstance.ownerDocument.documentElement);
        else if ("head" === node2) {
          node2 = parentInstance.ownerDocument.head;
          releaseSingletonInstance(node2);
          for (var node$jscomp$0 = node2.firstChild; node$jscomp$0; ) {
            var nextNode$jscomp$0 = node$jscomp$0.nextSibling, nodeName = node$jscomp$0.nodeName;
            node$jscomp$0[internalHoistableMarker] || "SCRIPT" === nodeName || "STYLE" === nodeName || "LINK" === nodeName && "stylesheet" === node$jscomp$0.rel.toLowerCase() || node2.removeChild(node$jscomp$0);
            node$jscomp$0 = nextNode$jscomp$0;
          }
        } else
          "body" === node2 && releaseSingletonInstance(parentInstance.ownerDocument.body);
      node2 = nextNode;
    } while (node2);
    retryIfBlockedOn(hydrationInstance);
  }
  function hideOrUnhideDehydratedBoundary(suspenseInstance, isHidden) {
    var node2 = suspenseInstance;
    suspenseInstance = 0;
    do {
      var nextNode = node2.nextSibling;
      1 === node2.nodeType ? isHidden ? (node2._stashedDisplay = node2.style.display, node2.style.display = "none") : (node2.style.display = node2._stashedDisplay || "", "" === node2.getAttribute("style") && node2.removeAttribute("style")) : 3 === node2.nodeType && (isHidden ? (node2._stashedText = node2.nodeValue, node2.nodeValue = "") : node2.nodeValue = node2._stashedText || "");
      if (nextNode && 8 === nextNode.nodeType)
        if (node2 = nextNode.data, "/$" === node2)
          if (0 === suspenseInstance) break;
          else suspenseInstance--;
        else
          "$" !== node2 && "$?" !== node2 && "$~" !== node2 && "$!" !== node2 || suspenseInstance++;
      node2 = nextNode;
    } while (node2);
  }
  function clearContainerSparingly(container) {
    var nextNode = container.firstChild;
    nextNode && 10 === nextNode.nodeType && (nextNode = nextNode.nextSibling);
    for (; nextNode; ) {
      var node2 = nextNode;
      nextNode = nextNode.nextSibling;
      switch (node2.nodeName) {
        case "HTML":
        case "HEAD":
        case "BODY":
          clearContainerSparingly(node2);
          detachDeletedInstance(node2);
          continue;
        case "SCRIPT":
        case "STYLE":
          continue;
        case "LINK":
          if ("stylesheet" === node2.rel.toLowerCase()) continue;
      }
      container.removeChild(node2);
    }
  }
  function canHydrateInstance(instance, type2, props, inRootOrSingleton) {
    for (; 1 === instance.nodeType; ) {
      var anyProps = props;
      if (instance.nodeName.toLowerCase() !== type2.toLowerCase()) {
        if (!inRootOrSingleton && ("INPUT" !== instance.nodeName || "hidden" !== instance.type))
          break;
      } else if (!inRootOrSingleton)
        if ("input" === type2 && "hidden" === instance.type) {
          var name2 = null == anyProps.name ? null : "" + anyProps.name;
          if ("hidden" === anyProps.type && instance.getAttribute("name") === name2)
            return instance;
        } else return instance;
      else if (!instance[internalHoistableMarker])
        switch (type2) {
          case "meta":
            if (!instance.hasAttribute("itemprop")) break;
            return instance;
          case "link":
            name2 = instance.getAttribute("rel");
            if ("stylesheet" === name2 && instance.hasAttribute("data-precedence"))
              break;
            else if (name2 !== anyProps.rel || instance.getAttribute("href") !== (null == anyProps.href || "" === anyProps.href ? null : anyProps.href) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin) || instance.getAttribute("title") !== (null == anyProps.title ? null : anyProps.title))
              break;
            return instance;
          case "style":
            if (instance.hasAttribute("data-precedence")) break;
            return instance;
          case "script":
            name2 = instance.getAttribute("src");
            if ((name2 !== (null == anyProps.src ? null : anyProps.src) || instance.getAttribute("type") !== (null == anyProps.type ? null : anyProps.type) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin)) && name2 && instance.hasAttribute("async") && !instance.hasAttribute("itemprop"))
              break;
            return instance;
          default:
            return instance;
        }
      instance = getNextHydratable(instance.nextSibling);
      if (null === instance) break;
    }
    return null;
  }
  function canHydrateTextInstance(instance, text2, inRootOrSingleton) {
    if ("" === text2) return null;
    for (; 3 !== instance.nodeType; ) {
      if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
        return null;
      instance = getNextHydratable(instance.nextSibling);
      if (null === instance) return null;
    }
    return instance;
  }
  function canHydrateHydrationBoundary(instance, inRootOrSingleton) {
    for (; 8 !== instance.nodeType; ) {
      if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
        return null;
      instance = getNextHydratable(instance.nextSibling);
      if (null === instance) return null;
    }
    return instance;
  }
  function isSuspenseInstancePending(instance) {
    return "$?" === instance.data || "$~" === instance.data;
  }
  function isSuspenseInstanceFallback(instance) {
    return "$!" === instance.data || "$?" === instance.data && "loading" !== instance.ownerDocument.readyState;
  }
  function registerSuspenseInstanceRetry(instance, callback) {
    var ownerDocument = instance.ownerDocument;
    if ("$~" === instance.data) instance._reactRetry = callback;
    else if ("$?" !== instance.data || "loading" !== ownerDocument.readyState)
      callback();
    else {
      var listener = function() {
        callback();
        ownerDocument.removeEventListener("DOMContentLoaded", listener);
      };
      ownerDocument.addEventListener("DOMContentLoaded", listener);
      instance._reactRetry = listener;
    }
  }
  function getNextHydratable(node2) {
    for (; null != node2; node2 = node2.nextSibling) {
      var nodeType = node2.nodeType;
      if (1 === nodeType || 3 === nodeType) break;
      if (8 === nodeType) {
        nodeType = node2.data;
        if ("$" === nodeType || "$!" === nodeType || "$?" === nodeType || "$~" === nodeType || "&" === nodeType || "F!" === nodeType || "F" === nodeType)
          break;
        if ("/$" === nodeType || "/&" === nodeType) return null;
      }
    }
    return node2;
  }
  var previousHydratableOnEnteringScopedSingleton = null;
  function getNextHydratableInstanceAfterHydrationBoundary(hydrationInstance) {
    hydrationInstance = hydrationInstance.nextSibling;
    for (var depth = 0; hydrationInstance; ) {
      if (8 === hydrationInstance.nodeType) {
        var data = hydrationInstance.data;
        if ("/$" === data || "/&" === data) {
          if (0 === depth)
            return getNextHydratable(hydrationInstance.nextSibling);
          depth--;
        } else
          "$" !== data && "$!" !== data && "$?" !== data && "$~" !== data && "&" !== data || depth++;
      }
      hydrationInstance = hydrationInstance.nextSibling;
    }
    return null;
  }
  function getParentHydrationBoundary(targetInstance) {
    targetInstance = targetInstance.previousSibling;
    for (var depth = 0; targetInstance; ) {
      if (8 === targetInstance.nodeType) {
        var data = targetInstance.data;
        if ("$" === data || "$!" === data || "$?" === data || "$~" === data || "&" === data) {
          if (0 === depth) return targetInstance;
          depth--;
        } else "/$" !== data && "/&" !== data || depth++;
      }
      targetInstance = targetInstance.previousSibling;
    }
    return null;
  }
  function resolveSingletonInstance(type2, props, rootContainerInstance) {
    props = getOwnerDocumentFromRootContainer(rootContainerInstance);
    switch (type2) {
      case "html":
        type2 = props.documentElement;
        if (!type2) throw Error(formatProdErrorMessage(452));
        return type2;
      case "head":
        type2 = props.head;
        if (!type2) throw Error(formatProdErrorMessage(453));
        return type2;
      case "body":
        type2 = props.body;
        if (!type2) throw Error(formatProdErrorMessage(454));
        return type2;
      default:
        throw Error(formatProdErrorMessage(451));
    }
  }
  function releaseSingletonInstance(instance) {
    for (var attributes = instance.attributes; attributes.length; )
      instance.removeAttributeNode(attributes[0]);
    detachDeletedInstance(instance);
  }
  var preloadPropsMap = /* @__PURE__ */ new Map(), preconnectsSet = /* @__PURE__ */ new Set();
  function getHoistableRoot(container) {
    return "function" === typeof container.getRootNode ? container.getRootNode() : 9 === container.nodeType ? container : container.ownerDocument;
  }
  var previousDispatcher = ReactDOMSharedInternals.d;
  ReactDOMSharedInternals.d = {
    f: flushSyncWork,
    r: requestFormReset,
    D: prefetchDNS,
    C: preconnect,
    L: preload,
    m: preloadModule,
    X: preinitScript,
    S: preinitStyle,
    M: preinitModuleScript
  };
  function flushSyncWork() {
    var previousWasRendering = previousDispatcher.f(), wasRendering = flushSyncWork$1();
    return previousWasRendering || wasRendering;
  }
  function requestFormReset(form) {
    var formInst = getInstanceFromNode(form);
    null !== formInst && 5 === formInst.tag && "form" === formInst.type ? requestFormReset$1(formInst) : previousDispatcher.r(form);
  }
  var globalDocument = "undefined" === typeof document ? null : document;
  function preconnectAs(rel, href, crossOrigin) {
    var ownerDocument = globalDocument;
    if (ownerDocument && "string" === typeof href && href) {
      var limitedEscapedHref = escapeSelectorAttributeValueInsideDoubleQuotes(href);
      limitedEscapedHref = 'link[rel="' + rel + '"][href="' + limitedEscapedHref + '"]';
      "string" === typeof crossOrigin && (limitedEscapedHref += '[crossorigin="' + crossOrigin + '"]');
      preconnectsSet.has(limitedEscapedHref) || (preconnectsSet.add(limitedEscapedHref), rel = { rel, crossOrigin, href }, null === ownerDocument.querySelector(limitedEscapedHref) && (href = ownerDocument.createElement("link"), setInitialProperties(href, "link", rel), markNodeAsHoistable(href), ownerDocument.head.appendChild(href)));
    }
  }
  function prefetchDNS(href) {
    previousDispatcher.D(href);
    preconnectAs("dns-prefetch", href, null);
  }
  function preconnect(href, crossOrigin) {
    previousDispatcher.C(href, crossOrigin);
    preconnectAs("preconnect", href, crossOrigin);
  }
  function preload(href, as, options2) {
    previousDispatcher.L(href, as, options2);
    var ownerDocument = globalDocument;
    if (ownerDocument && href && as) {
      var preloadSelector = 'link[rel="preload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"]';
      "image" === as ? options2 && options2.imageSrcSet ? (preloadSelector += '[imagesrcset="' + escapeSelectorAttributeValueInsideDoubleQuotes(
        options2.imageSrcSet
      ) + '"]', "string" === typeof options2.imageSizes && (preloadSelector += '[imagesizes="' + escapeSelectorAttributeValueInsideDoubleQuotes(
        options2.imageSizes
      ) + '"]')) : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]' : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]';
      var key = preloadSelector;
      switch (as) {
        case "style":
          key = getStyleKey(href);
          break;
        case "script":
          key = getScriptKey(href);
      }
      preloadPropsMap.has(key) || (href = assign(
        {
          rel: "preload",
          href: "image" === as && options2 && options2.imageSrcSet ? void 0 : href,
          as
        },
        options2
      ), preloadPropsMap.set(key, href), null !== ownerDocument.querySelector(preloadSelector) || "style" === as && ownerDocument.querySelector(getStylesheetSelectorFromKey(key)) || "script" === as && ownerDocument.querySelector(getScriptSelectorFromKey(key)) || (as = ownerDocument.createElement("link"), setInitialProperties(as, "link", href), markNodeAsHoistable(as), ownerDocument.head.appendChild(as)));
    }
  }
  function preloadModule(href, options2) {
    previousDispatcher.m(href, options2);
    var ownerDocument = globalDocument;
    if (ownerDocument && href) {
      var as = options2 && "string" === typeof options2.as ? options2.as : "script", preloadSelector = 'link[rel="modulepreload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"][href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]', key = preloadSelector;
      switch (as) {
        case "audioworklet":
        case "paintworklet":
        case "serviceworker":
        case "sharedworker":
        case "worker":
        case "script":
          key = getScriptKey(href);
      }
      if (!preloadPropsMap.has(key) && (href = assign({ rel: "modulepreload", href }, options2), preloadPropsMap.set(key, href), null === ownerDocument.querySelector(preloadSelector))) {
        switch (as) {
          case "audioworklet":
          case "paintworklet":
          case "serviceworker":
          case "sharedworker":
          case "worker":
          case "script":
            if (ownerDocument.querySelector(getScriptSelectorFromKey(key)))
              return;
        }
        as = ownerDocument.createElement("link");
        setInitialProperties(as, "link", href);
        markNodeAsHoistable(as);
        ownerDocument.head.appendChild(as);
      }
    }
  }
  function preinitStyle(href, precedence, options2) {
    previousDispatcher.S(href, precedence, options2);
    var ownerDocument = globalDocument;
    if (ownerDocument && href) {
      var styles2 = getResourcesFromRoot(ownerDocument).hoistableStyles, key = getStyleKey(href);
      precedence = precedence || "default";
      var resource = styles2.get(key);
      if (!resource) {
        var state = { loading: 0, preload: null };
        if (resource = ownerDocument.querySelector(
          getStylesheetSelectorFromKey(key)
        ))
          state.loading = 5;
        else {
          href = assign(
            { rel: "stylesheet", href, "data-precedence": precedence },
            options2
          );
          (options2 = preloadPropsMap.get(key)) && adoptPreloadPropsForStylesheet(href, options2);
          var link2 = resource = ownerDocument.createElement("link");
          markNodeAsHoistable(link2);
          setInitialProperties(link2, "link", href);
          link2._p = new Promise(function(resolve, reject) {
            link2.onload = resolve;
            link2.onerror = reject;
          });
          link2.addEventListener("load", function() {
            state.loading |= 1;
          });
          link2.addEventListener("error", function() {
            state.loading |= 2;
          });
          state.loading |= 4;
          insertStylesheet(resource, precedence, ownerDocument);
        }
        resource = {
          type: "stylesheet",
          instance: resource,
          count: 1,
          state
        };
        styles2.set(key, resource);
      }
    }
  }
  function preinitScript(src2, options2) {
    previousDispatcher.X(src2, options2);
    var ownerDocument = globalDocument;
    if (ownerDocument && src2) {
      var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key = getScriptKey(src2), resource = scripts.get(key);
      resource || (resource = ownerDocument.querySelector(getScriptSelectorFromKey(key)), resource || (src2 = assign({ src: src2, async: true }, options2), (options2 = preloadPropsMap.get(key)) && adoptPreloadPropsForScript(src2, options2), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src2), ownerDocument.head.appendChild(resource)), resource = {
        type: "script",
        instance: resource,
        count: 1,
        state: null
      }, scripts.set(key, resource));
    }
  }
  function preinitModuleScript(src2, options2) {
    previousDispatcher.M(src2, options2);
    var ownerDocument = globalDocument;
    if (ownerDocument && src2) {
      var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key = getScriptKey(src2), resource = scripts.get(key);
      resource || (resource = ownerDocument.querySelector(getScriptSelectorFromKey(key)), resource || (src2 = assign({ src: src2, async: true, type: "module" }, options2), (options2 = preloadPropsMap.get(key)) && adoptPreloadPropsForScript(src2, options2), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src2), ownerDocument.head.appendChild(resource)), resource = {
        type: "script",
        instance: resource,
        count: 1,
        state: null
      }, scripts.set(key, resource));
    }
  }
  function getResource(type2, currentProps, pendingProps, currentResource) {
    var JSCompiler_inline_result = (JSCompiler_inline_result = rootInstanceStackCursor.current) ? getHoistableRoot(JSCompiler_inline_result) : null;
    if (!JSCompiler_inline_result) throw Error(formatProdErrorMessage(446));
    switch (type2) {
      case "meta":
      case "title":
        return null;
      case "style":
        return "string" === typeof pendingProps.precedence && "string" === typeof pendingProps.href ? (currentProps = getStyleKey(pendingProps.href), pendingProps = getResourcesFromRoot(
          JSCompiler_inline_result
        ).hoistableStyles, currentResource = pendingProps.get(currentProps), currentResource || (currentResource = {
          type: "style",
          instance: null,
          count: 0,
          state: null
        }, pendingProps.set(currentProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
      case "link":
        if ("stylesheet" === pendingProps.rel && "string" === typeof pendingProps.href && "string" === typeof pendingProps.precedence) {
          type2 = getStyleKey(pendingProps.href);
          var styles$243 = getResourcesFromRoot(
            JSCompiler_inline_result
          ).hoistableStyles, resource$244 = styles$243.get(type2);
          resource$244 || (JSCompiler_inline_result = JSCompiler_inline_result.ownerDocument || JSCompiler_inline_result, resource$244 = {
            type: "stylesheet",
            instance: null,
            count: 0,
            state: { loading: 0, preload: null }
          }, styles$243.set(type2, resource$244), (styles$243 = JSCompiler_inline_result.querySelector(
            getStylesheetSelectorFromKey(type2)
          )) && !styles$243._p && (resource$244.instance = styles$243, resource$244.state.loading = 5), preloadPropsMap.has(type2) || (pendingProps = {
            rel: "preload",
            as: "style",
            href: pendingProps.href,
            crossOrigin: pendingProps.crossOrigin,
            integrity: pendingProps.integrity,
            media: pendingProps.media,
            hrefLang: pendingProps.hrefLang,
            referrerPolicy: pendingProps.referrerPolicy
          }, preloadPropsMap.set(type2, pendingProps), styles$243 || preloadStylesheet(
            JSCompiler_inline_result,
            type2,
            pendingProps,
            resource$244.state
          )));
          if (currentProps && null === currentResource)
            throw Error(formatProdErrorMessage(528, ""));
          return resource$244;
        }
        if (currentProps && null !== currentResource)
          throw Error(formatProdErrorMessage(529, ""));
        return null;
      case "script":
        return currentProps = pendingProps.async, pendingProps = pendingProps.src, "string" === typeof pendingProps && currentProps && "function" !== typeof currentProps && "symbol" !== typeof currentProps ? (currentProps = getScriptKey(pendingProps), pendingProps = getResourcesFromRoot(
          JSCompiler_inline_result
        ).hoistableScripts, currentResource = pendingProps.get(currentProps), currentResource || (currentResource = {
          type: "script",
          instance: null,
          count: 0,
          state: null
        }, pendingProps.set(currentProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
      default:
        throw Error(formatProdErrorMessage(444, type2));
    }
  }
  function getStyleKey(href) {
    return 'href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"';
  }
  function getStylesheetSelectorFromKey(key) {
    return 'link[rel="stylesheet"][' + key + "]";
  }
  function stylesheetPropsFromRawProps(rawProps) {
    return assign({}, rawProps, {
      "data-precedence": rawProps.precedence,
      precedence: null
    });
  }
  function preloadStylesheet(ownerDocument, key, preloadProps, state) {
    ownerDocument.querySelector('link[rel="preload"][as="style"][' + key + "]") ? state.loading = 1 : (key = ownerDocument.createElement("link"), state.preload = key, key.addEventListener("load", function() {
      return state.loading |= 1;
    }), key.addEventListener("error", function() {
      return state.loading |= 2;
    }), setInitialProperties(key, "link", preloadProps), markNodeAsHoistable(key), ownerDocument.head.appendChild(key));
  }
  function getScriptKey(src2) {
    return '[src="' + escapeSelectorAttributeValueInsideDoubleQuotes(src2) + '"]';
  }
  function getScriptSelectorFromKey(key) {
    return "script[async]" + key;
  }
  function acquireResource(hoistableRoot, resource, props) {
    resource.count++;
    if (null === resource.instance)
      switch (resource.type) {
        case "style":
          var instance = hoistableRoot.querySelector(
            'style[data-href~="' + escapeSelectorAttributeValueInsideDoubleQuotes(props.href) + '"]'
          );
          if (instance)
            return resource.instance = instance, markNodeAsHoistable(instance), instance;
          var styleProps = assign({}, props, {
            "data-href": props.href,
            "data-precedence": props.precedence,
            href: null,
            precedence: null
          });
          instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement(
            "style"
          );
          markNodeAsHoistable(instance);
          setInitialProperties(instance, "style", styleProps);
          insertStylesheet(instance, props.precedence, hoistableRoot);
          return resource.instance = instance;
        case "stylesheet":
          styleProps = getStyleKey(props.href);
          var instance$249 = hoistableRoot.querySelector(
            getStylesheetSelectorFromKey(styleProps)
          );
          if (instance$249)
            return resource.state.loading |= 4, resource.instance = instance$249, markNodeAsHoistable(instance$249), instance$249;
          instance = stylesheetPropsFromRawProps(props);
          (styleProps = preloadPropsMap.get(styleProps)) && adoptPreloadPropsForStylesheet(instance, styleProps);
          instance$249 = (hoistableRoot.ownerDocument || hoistableRoot).createElement("link");
          markNodeAsHoistable(instance$249);
          var linkInstance = instance$249;
          linkInstance._p = new Promise(function(resolve, reject) {
            linkInstance.onload = resolve;
            linkInstance.onerror = reject;
          });
          setInitialProperties(instance$249, "link", instance);
          resource.state.loading |= 4;
          insertStylesheet(instance$249, props.precedence, hoistableRoot);
          return resource.instance = instance$249;
        case "script":
          instance$249 = getScriptKey(props.src);
          if (styleProps = hoistableRoot.querySelector(
            getScriptSelectorFromKey(instance$249)
          ))
            return resource.instance = styleProps, markNodeAsHoistable(styleProps), styleProps;
          instance = props;
          if (styleProps = preloadPropsMap.get(instance$249))
            instance = assign({}, props), adoptPreloadPropsForScript(instance, styleProps);
          hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
          styleProps = hoistableRoot.createElement("script");
          markNodeAsHoistable(styleProps);
          setInitialProperties(styleProps, "link", instance);
          hoistableRoot.head.appendChild(styleProps);
          return resource.instance = styleProps;
        case "void":
          return null;
        default:
          throw Error(formatProdErrorMessage(443, resource.type));
      }
    else
      "stylesheet" === resource.type && 0 === (resource.state.loading & 4) && (instance = resource.instance, resource.state.loading |= 4, insertStylesheet(instance, props.precedence, hoistableRoot));
    return resource.instance;
  }
  function insertStylesheet(instance, precedence, root3) {
    for (var nodes = root3.querySelectorAll(
      'link[rel="stylesheet"][data-precedence],style[data-precedence]'
    ), last = nodes.length ? nodes[nodes.length - 1] : null, prior = last, i = 0; i < nodes.length; i++) {
      var node2 = nodes[i];
      if (node2.dataset.precedence === precedence) prior = node2;
      else if (prior !== last) break;
    }
    prior ? prior.parentNode.insertBefore(instance, prior.nextSibling) : (precedence = 9 === root3.nodeType ? root3.head : root3, precedence.insertBefore(instance, precedence.firstChild));
  }
  function adoptPreloadPropsForStylesheet(stylesheetProps, preloadProps) {
    null == stylesheetProps.crossOrigin && (stylesheetProps.crossOrigin = preloadProps.crossOrigin);
    null == stylesheetProps.referrerPolicy && (stylesheetProps.referrerPolicy = preloadProps.referrerPolicy);
    null == stylesheetProps.title && (stylesheetProps.title = preloadProps.title);
  }
  function adoptPreloadPropsForScript(scriptProps, preloadProps) {
    null == scriptProps.crossOrigin && (scriptProps.crossOrigin = preloadProps.crossOrigin);
    null == scriptProps.referrerPolicy && (scriptProps.referrerPolicy = preloadProps.referrerPolicy);
    null == scriptProps.integrity && (scriptProps.integrity = preloadProps.integrity);
  }
  var tagCaches = null;
  function getHydratableHoistableCache(type2, keyAttribute, ownerDocument) {
    if (null === tagCaches) {
      var cache = /* @__PURE__ */ new Map();
      var caches = tagCaches = /* @__PURE__ */ new Map();
      caches.set(ownerDocument, cache);
    } else
      caches = tagCaches, cache = caches.get(ownerDocument), cache || (cache = /* @__PURE__ */ new Map(), caches.set(ownerDocument, cache));
    if (cache.has(type2)) return cache;
    cache.set(type2, null);
    ownerDocument = ownerDocument.getElementsByTagName(type2);
    for (caches = 0; caches < ownerDocument.length; caches++) {
      var node2 = ownerDocument[caches];
      if (!(node2[internalHoistableMarker] || node2[internalInstanceKey] || "link" === type2 && "stylesheet" === node2.getAttribute("rel")) && "http://www.w3.org/2000/svg" !== node2.namespaceURI) {
        var nodeKey = node2.getAttribute(keyAttribute) || "";
        nodeKey = type2 + nodeKey;
        var existing = cache.get(nodeKey);
        existing ? existing.push(node2) : cache.set(nodeKey, [node2]);
      }
    }
    return cache;
  }
  function mountHoistable(hoistableRoot, type2, instance) {
    hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
    hoistableRoot.head.insertBefore(
      instance,
      "title" === type2 ? hoistableRoot.querySelector("head > title") : null
    );
  }
  function isHostHoistableType(type2, props, hostContext) {
    if (1 === hostContext || null != props.itemProp) return false;
    switch (type2) {
      case "meta":
      case "title":
        return true;
      case "style":
        if ("string" !== typeof props.precedence || "string" !== typeof props.href || "" === props.href)
          break;
        return true;
      case "link":
        if ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href || props.onLoad || props.onError)
          break;
        switch (props.rel) {
          case "stylesheet":
            return type2 = props.disabled, "string" === typeof props.precedence && null == type2;
          default:
            return true;
        }
      case "script":
        if (props.async && "function" !== typeof props.async && "symbol" !== typeof props.async && !props.onLoad && !props.onError && props.src && "string" === typeof props.src)
          return true;
    }
    return false;
  }
  function preloadResource(resource) {
    return "stylesheet" === resource.type && 0 === (resource.state.loading & 3) ? false : true;
  }
  function suspendResource(state, hoistableRoot, resource, props) {
    if ("stylesheet" === resource.type && ("string" !== typeof props.media || false !== matchMedia(props.media).matches) && 0 === (resource.state.loading & 4)) {
      if (null === resource.instance) {
        var key = getStyleKey(props.href), instance = hoistableRoot.querySelector(
          getStylesheetSelectorFromKey(key)
        );
        if (instance) {
          hoistableRoot = instance._p;
          null !== hoistableRoot && "object" === typeof hoistableRoot && "function" === typeof hoistableRoot.then && (state.count++, state = onUnsuspend.bind(state), hoistableRoot.then(state, state));
          resource.state.loading |= 4;
          resource.instance = instance;
          markNodeAsHoistable(instance);
          return;
        }
        instance = hoistableRoot.ownerDocument || hoistableRoot;
        props = stylesheetPropsFromRawProps(props);
        (key = preloadPropsMap.get(key)) && adoptPreloadPropsForStylesheet(props, key);
        instance = instance.createElement("link");
        markNodeAsHoistable(instance);
        var linkInstance = instance;
        linkInstance._p = new Promise(function(resolve, reject) {
          linkInstance.onload = resolve;
          linkInstance.onerror = reject;
        });
        setInitialProperties(instance, "link", props);
        resource.instance = instance;
      }
      null === state.stylesheets && (state.stylesheets = /* @__PURE__ */ new Map());
      state.stylesheets.set(resource, hoistableRoot);
      (hoistableRoot = resource.state.preload) && 0 === (resource.state.loading & 3) && (state.count++, resource = onUnsuspend.bind(state), hoistableRoot.addEventListener("load", resource), hoistableRoot.addEventListener("error", resource));
    }
  }
  var estimatedBytesWithinLimit = 0;
  function waitForCommitToBeReady(state, timeoutOffset) {
    state.stylesheets && 0 === state.count && insertSuspendedStylesheets(state, state.stylesheets);
    return 0 < state.count || 0 < state.imgCount ? function(commit) {
      var stylesheetTimer = setTimeout(function() {
        state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets);
        if (state.unsuspend) {
          var unsuspend = state.unsuspend;
          state.unsuspend = null;
          unsuspend();
        }
      }, 6e4 + timeoutOffset);
      0 < state.imgBytes && 0 === estimatedBytesWithinLimit && (estimatedBytesWithinLimit = 62500 * estimateBandwidth());
      var imgTimer = setTimeout(
        function() {
          state.waitingForImages = false;
          if (0 === state.count && (state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets), state.unsuspend)) {
            var unsuspend = state.unsuspend;
            state.unsuspend = null;
            unsuspend();
          }
        },
        (state.imgBytes > estimatedBytesWithinLimit ? 50 : 800) + timeoutOffset
      );
      state.unsuspend = commit;
      return function() {
        state.unsuspend = null;
        clearTimeout(stylesheetTimer);
        clearTimeout(imgTimer);
      };
    } : null;
  }
  function onUnsuspend() {
    this.count--;
    if (0 === this.count && (0 === this.imgCount || !this.waitingForImages)) {
      if (this.stylesheets) insertSuspendedStylesheets(this, this.stylesheets);
      else if (this.unsuspend) {
        var unsuspend = this.unsuspend;
        this.unsuspend = null;
        unsuspend();
      }
    }
  }
  var precedencesByRoot = null;
  function insertSuspendedStylesheets(state, resources) {
    state.stylesheets = null;
    null !== state.unsuspend && (state.count++, precedencesByRoot = /* @__PURE__ */ new Map(), resources.forEach(insertStylesheetIntoRoot, state), precedencesByRoot = null, onUnsuspend.call(state));
  }
  function insertStylesheetIntoRoot(root3, resource) {
    if (!(resource.state.loading & 4)) {
      var precedences = precedencesByRoot.get(root3);
      if (precedences) var last = precedences.get(null);
      else {
        precedences = /* @__PURE__ */ new Map();
        precedencesByRoot.set(root3, precedences);
        for (var nodes = root3.querySelectorAll(
          "link[data-precedence],style[data-precedence]"
        ), i = 0; i < nodes.length; i++) {
          var node2 = nodes[i];
          if ("LINK" === node2.nodeName || "not all" !== node2.getAttribute("media"))
            precedences.set(node2.dataset.precedence, node2), last = node2;
        }
        last && precedences.set(null, last);
      }
      nodes = resource.instance;
      node2 = nodes.getAttribute("data-precedence");
      i = precedences.get(node2) || last;
      i === last && precedences.set(null, nodes);
      precedences.set(node2, nodes);
      this.count++;
      last = onUnsuspend.bind(this);
      nodes.addEventListener("load", last);
      nodes.addEventListener("error", last);
      i ? i.parentNode.insertBefore(nodes, i.nextSibling) : (root3 = 9 === root3.nodeType ? root3.head : root3, root3.insertBefore(nodes, root3.firstChild));
      resource.state.loading |= 4;
    }
  }
  var HostTransitionContext = {
    $$typeof: REACT_CONTEXT_TYPE,
    Provider: null,
    Consumer: null,
    _currentValue: sharedNotPendingObject,
    _currentValue2: sharedNotPendingObject,
    _threadCount: 0
  };
  function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator, formState) {
    this.tag = 1;
    this.containerInfo = containerInfo;
    this.pingCache = this.current = this.pendingChildren = null;
    this.timeoutHandle = -1;
    this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
    this.callbackPriority = 0;
    this.expirationTimes = createLaneMap(-1);
    this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
    this.entanglements = createLaneMap(0);
    this.hiddenUpdates = createLaneMap(null);
    this.identifierPrefix = identifierPrefix;
    this.onUncaughtError = onUncaughtError;
    this.onCaughtError = onCaughtError;
    this.onRecoverableError = onRecoverableError;
    this.pooledCache = null;
    this.pooledCacheLanes = 0;
    this.formState = formState;
    this.incompleteTransitions = /* @__PURE__ */ new Map();
  }
  function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, formState, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator) {
    containerInfo = new FiberRootNode(
      containerInfo,
      tag,
      hydrate,
      identifierPrefix,
      onUncaughtError,
      onCaughtError,
      onRecoverableError,
      onDefaultTransitionIndicator,
      formState
    );
    tag = 1;
    true === isStrictMode && (tag |= 24);
    isStrictMode = createFiberImplClass(3, null, null, tag);
    containerInfo.current = isStrictMode;
    isStrictMode.stateNode = containerInfo;
    tag = createCache();
    tag.refCount++;
    containerInfo.pooledCache = tag;
    tag.refCount++;
    isStrictMode.memoizedState = {
      element: initialChildren,
      isDehydrated: hydrate,
      cache: tag
    };
    initializeUpdateQueue(isStrictMode);
    return containerInfo;
  }
  function getContextForSubtree(parentComponent) {
    if (!parentComponent) return emptyContextObject;
    parentComponent = emptyContextObject;
    return parentComponent;
  }
  function updateContainerImpl(rootFiber, lane, element2, container, parentComponent, callback) {
    parentComponent = getContextForSubtree(parentComponent);
    null === container.context ? container.context = parentComponent : container.pendingContext = parentComponent;
    container = createUpdate(lane);
    container.payload = { element: element2 };
    callback = void 0 === callback ? null : callback;
    null !== callback && (container.callback = callback);
    element2 = enqueueUpdate(rootFiber, container, lane);
    null !== element2 && (scheduleUpdateOnFiber(element2, rootFiber, lane), entangleTransitions(element2, rootFiber, lane));
  }
  function markRetryLaneImpl(fiber, retryLane) {
    fiber = fiber.memoizedState;
    if (null !== fiber && null !== fiber.dehydrated) {
      var a = fiber.retryLane;
      fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
    }
  }
  function markRetryLaneIfNotHydrated(fiber, retryLane) {
    markRetryLaneImpl(fiber, retryLane);
    (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
  }
  function attemptContinuousHydration(fiber) {
    if (13 === fiber.tag || 31 === fiber.tag) {
      var root3 = enqueueConcurrentRenderForLane(fiber, 67108864);
      null !== root3 && scheduleUpdateOnFiber(root3, fiber, 67108864);
      markRetryLaneIfNotHydrated(fiber, 67108864);
    }
  }
  function attemptHydrationAtCurrentPriority(fiber) {
    if (13 === fiber.tag || 31 === fiber.tag) {
      var lane = requestUpdateLane();
      lane = getBumpedLaneForHydrationByLane(lane);
      var root3 = enqueueConcurrentRenderForLane(fiber, lane);
      null !== root3 && scheduleUpdateOnFiber(root3, fiber, lane);
      markRetryLaneIfNotHydrated(fiber, lane);
    }
  }
  var _enabled = true;
  function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
    var prevTransition = ReactSharedInternals.T;
    ReactSharedInternals.T = null;
    var previousPriority = ReactDOMSharedInternals.p;
    try {
      ReactDOMSharedInternals.p = 2, dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
    } finally {
      ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
    }
  }
  function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
    var prevTransition = ReactSharedInternals.T;
    ReactSharedInternals.T = null;
    var previousPriority = ReactDOMSharedInternals.p;
    try {
      ReactDOMSharedInternals.p = 8, dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
    } finally {
      ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
    }
  }
  function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    if (_enabled) {
      var blockedOn = findInstanceBlockingEvent(nativeEvent);
      if (null === blockedOn)
        dispatchEventForPluginEventSystem(
          domEventName,
          eventSystemFlags,
          nativeEvent,
          return_targetInst,
          targetContainer
        ), clearIfContinuousEvent(domEventName, nativeEvent);
      else if (queueIfContinuousEvent(
        blockedOn,
        domEventName,
        eventSystemFlags,
        targetContainer,
        nativeEvent
      ))
        nativeEvent.stopPropagation();
      else if (clearIfContinuousEvent(domEventName, nativeEvent), eventSystemFlags & 4 && -1 < discreteReplayableEvents.indexOf(domEventName)) {
        for (; null !== blockedOn; ) {
          var fiber = getInstanceFromNode(blockedOn);
          if (null !== fiber)
            switch (fiber.tag) {
              case 3:
                fiber = fiber.stateNode;
                if (fiber.current.memoizedState.isDehydrated) {
                  var lanes = getHighestPriorityLanes(fiber.pendingLanes);
                  if (0 !== lanes) {
                    var root3 = fiber;
                    root3.pendingLanes |= 2;
                    for (root3.entangledLanes |= 2; lanes; ) {
                      var lane = 1 << 31 - clz32(lanes);
                      root3.entanglements[1] |= lane;
                      lanes &= ~lane;
                    }
                    ensureRootIsScheduled(fiber);
                    0 === (executionContext & 6) && (workInProgressRootRenderTargetTime = now() + 500, flushSyncWorkAcrossRoots_impl(0));
                  }
                }
                break;
              case 31:
              case 13:
                root3 = enqueueConcurrentRenderForLane(fiber, 2), null !== root3 && scheduleUpdateOnFiber(root3, fiber, 2), flushSyncWork$1(), markRetryLaneIfNotHydrated(fiber, 2);
            }
          fiber = findInstanceBlockingEvent(nativeEvent);
          null === fiber && dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            return_targetInst,
            targetContainer
          );
          if (fiber === blockedOn) break;
          blockedOn = fiber;
        }
        null !== blockedOn && nativeEvent.stopPropagation();
      } else
        dispatchEventForPluginEventSystem(
          domEventName,
          eventSystemFlags,
          nativeEvent,
          null,
          targetContainer
        );
    }
  }
  function findInstanceBlockingEvent(nativeEvent) {
    nativeEvent = getEventTarget(nativeEvent);
    return findInstanceBlockingTarget(nativeEvent);
  }
  var return_targetInst = null;
  function findInstanceBlockingTarget(targetNode) {
    return_targetInst = null;
    targetNode = getClosestInstanceFromNode(targetNode);
    if (null !== targetNode) {
      var nearestMounted = getNearestMountedFiber(targetNode);
      if (null === nearestMounted) targetNode = null;
      else {
        var tag = nearestMounted.tag;
        if (13 === tag) {
          targetNode = getSuspenseInstanceFromFiber(nearestMounted);
          if (null !== targetNode) return targetNode;
          targetNode = null;
        } else if (31 === tag) {
          targetNode = getActivityInstanceFromFiber(nearestMounted);
          if (null !== targetNode) return targetNode;
          targetNode = null;
        } else if (3 === tag) {
          if (nearestMounted.stateNode.current.memoizedState.isDehydrated)
            return 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
          targetNode = null;
        } else nearestMounted !== targetNode && (targetNode = null);
      }
    }
    return_targetInst = targetNode;
    return null;
  }
  function getEventPriority(domEventName) {
    switch (domEventName) {
      case "beforetoggle":
      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 "toggle":
      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 2;
      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 "touchmove":
      case "wheel":
      case "mouseenter":
      case "mouseleave":
      case "pointerenter":
      case "pointerleave":
        return 8;
      case "message":
        switch (getCurrentPriorityLevel()) {
          case ImmediatePriority:
            return 2;
          case UserBlockingPriority:
            return 8;
          case NormalPriority$1:
          case LowPriority:
            return 32;
          case IdlePriority:
            return 268435456;
          default:
            return 32;
        }
      default:
        return 32;
    }
  }
  var hasScheduledReplayAttempt = false, queuedFocus = null, queuedDrag = null, queuedMouse = null, queuedPointers = /* @__PURE__ */ new Map(), queuedPointerCaptures = /* @__PURE__ */ new Map(), queuedExplicitHydrationTargets = [], discreteReplayableEvents = "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".split(
    " "
  );
  function clearIfContinuousEvent(domEventName, nativeEvent) {
    switch (domEventName) {
      case "focusin":
      case "focusout":
        queuedFocus = null;
        break;
      case "dragenter":
      case "dragleave":
        queuedDrag = null;
        break;
      case "mouseover":
      case "mouseout":
        queuedMouse = null;
        break;
      case "pointerover":
      case "pointerout":
        queuedPointers.delete(nativeEvent.pointerId);
        break;
      case "gotpointercapture":
      case "lostpointercapture":
        queuedPointerCaptures.delete(nativeEvent.pointerId);
    }
  }
  function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    if (null === existingQueuedEvent || existingQueuedEvent.nativeEvent !== nativeEvent)
      return existingQueuedEvent = {
        blockedOn,
        domEventName,
        eventSystemFlags,
        nativeEvent,
        targetContainers: [targetContainer]
      }, null !== blockedOn && (blockedOn = getInstanceFromNode(blockedOn), null !== blockedOn && attemptContinuousHydration(blockedOn)), existingQueuedEvent;
    existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
    blockedOn = existingQueuedEvent.targetContainers;
    null !== targetContainer && -1 === blockedOn.indexOf(targetContainer) && blockedOn.push(targetContainer);
    return existingQueuedEvent;
  }
  function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
    switch (domEventName) {
      case "focusin":
        return queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedFocus,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        ), true;
      case "dragenter":
        return queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedDrag,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        ), true;
      case "mouseover":
        return queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
          queuedMouse,
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        ), true;
      case "pointerover":
        var pointerId = nativeEvent.pointerId;
        queuedPointers.set(
          pointerId,
          accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedPointers.get(pointerId) || null,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          )
        );
        return true;
      case "gotpointercapture":
        return pointerId = nativeEvent.pointerId, queuedPointerCaptures.set(
          pointerId,
          accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedPointerCaptures.get(pointerId) || null,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          )
        ), true;
    }
    return false;
  }
  function attemptExplicitHydrationTarget(queuedTarget) {
    var targetInst = getClosestInstanceFromNode(queuedTarget.target);
    if (null !== targetInst) {
      var nearestMounted = getNearestMountedFiber(targetInst);
      if (null !== nearestMounted) {
        if (targetInst = nearestMounted.tag, 13 === targetInst) {
          if (targetInst = getSuspenseInstanceFromFiber(nearestMounted), null !== targetInst) {
            queuedTarget.blockedOn = targetInst;
            runWithPriority(queuedTarget.priority, function() {
              attemptHydrationAtCurrentPriority(nearestMounted);
            });
            return;
          }
        } else if (31 === targetInst) {
          if (targetInst = getActivityInstanceFromFiber(nearestMounted), null !== targetInst) {
            queuedTarget.blockedOn = targetInst;
            runWithPriority(queuedTarget.priority, function() {
              attemptHydrationAtCurrentPriority(nearestMounted);
            });
            return;
          }
        } else if (3 === targetInst && nearestMounted.stateNode.current.memoizedState.isDehydrated) {
          queuedTarget.blockedOn = 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
          return;
        }
      }
    }
    queuedTarget.blockedOn = null;
  }
  function attemptReplayContinuousQueuedEvent(queuedEvent) {
    if (null !== queuedEvent.blockedOn) return false;
    for (var targetContainers = queuedEvent.targetContainers; 0 < targetContainers.length; ) {
      var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent);
      if (null === nextBlockedOn) {
        nextBlockedOn = queuedEvent.nativeEvent;
        var nativeEventClone = new nextBlockedOn.constructor(
          nextBlockedOn.type,
          nextBlockedOn
        );
        currentReplayingEvent = nativeEventClone;
        nextBlockedOn.target.dispatchEvent(nativeEventClone);
        currentReplayingEvent = null;
      } else
        return targetContainers = getInstanceFromNode(nextBlockedOn), null !== targetContainers && attemptContinuousHydration(targetContainers), queuedEvent.blockedOn = nextBlockedOn, false;
      targetContainers.shift();
    }
    return true;
  }
  function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
    attemptReplayContinuousQueuedEvent(queuedEvent) && map.delete(key);
  }
  function replayUnblockedEvents() {
    hasScheduledReplayAttempt = false;
    null !== queuedFocus && attemptReplayContinuousQueuedEvent(queuedFocus) && (queuedFocus = null);
    null !== queuedDrag && attemptReplayContinuousQueuedEvent(queuedDrag) && (queuedDrag = null);
    null !== queuedMouse && attemptReplayContinuousQueuedEvent(queuedMouse) && (queuedMouse = null);
    queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
    queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
  }
  function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
    queuedEvent.blockedOn === unblocked && (queuedEvent.blockedOn = null, hasScheduledReplayAttempt || (hasScheduledReplayAttempt = true, Scheduler.unstable_scheduleCallback(
      Scheduler.unstable_NormalPriority,
      replayUnblockedEvents
    )));
  }
  var lastScheduledReplayQueue = null;
  function scheduleReplayQueueIfNeeded(formReplayingQueue) {
    lastScheduledReplayQueue !== formReplayingQueue && (lastScheduledReplayQueue = formReplayingQueue, Scheduler.unstable_scheduleCallback(
      Scheduler.unstable_NormalPriority,
      function() {
        lastScheduledReplayQueue === formReplayingQueue && (lastScheduledReplayQueue = null);
        for (var i = 0; i < formReplayingQueue.length; i += 3) {
          var form = formReplayingQueue[i], submitterOrAction = formReplayingQueue[i + 1], formData = formReplayingQueue[i + 2];
          if ("function" !== typeof submitterOrAction)
            if (null === findInstanceBlockingTarget(submitterOrAction || form))
              continue;
            else break;
          var formInst = getInstanceFromNode(form);
          null !== formInst && (formReplayingQueue.splice(i, 3), i -= 3, startHostTransition(
            formInst,
            {
              pending: true,
              data: formData,
              method: form.method,
              action: submitterOrAction
            },
            submitterOrAction,
            formData
          ));
        }
      }
    ));
  }
  function retryIfBlockedOn(unblocked) {
    function unblock(queuedEvent) {
      return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
    }
    null !== queuedFocus && scheduleCallbackIfUnblocked(queuedFocus, unblocked);
    null !== queuedDrag && scheduleCallbackIfUnblocked(queuedDrag, unblocked);
    null !== queuedMouse && scheduleCallbackIfUnblocked(queuedMouse, unblocked);
    queuedPointers.forEach(unblock);
    queuedPointerCaptures.forEach(unblock);
    for (var i = 0; i < queuedExplicitHydrationTargets.length; i++) {
      var queuedTarget = queuedExplicitHydrationTargets[i];
      queuedTarget.blockedOn === unblocked && (queuedTarget.blockedOn = null);
    }
    for (; 0 < queuedExplicitHydrationTargets.length && (i = queuedExplicitHydrationTargets[0], null === i.blockedOn); )
      attemptExplicitHydrationTarget(i), null === i.blockedOn && queuedExplicitHydrationTargets.shift();
    i = (unblocked.ownerDocument || unblocked).$$reactFormReplay;
    if (null != i)
      for (queuedTarget = 0; queuedTarget < i.length; queuedTarget += 3) {
        var form = i[queuedTarget], submitterOrAction = i[queuedTarget + 1], formProps = form[internalPropsKey] || null;
        if ("function" === typeof submitterOrAction)
          formProps || scheduleReplayQueueIfNeeded(i);
        else if (formProps) {
          var action = null;
          if (submitterOrAction && submitterOrAction.hasAttribute("formAction"))
            if (form = submitterOrAction, formProps = submitterOrAction[internalPropsKey] || null)
              action = formProps.formAction;
            else {
              if (null !== findInstanceBlockingTarget(form)) continue;
            }
          else action = formProps.action;
          "function" === typeof action ? i[queuedTarget + 1] = action : (i.splice(queuedTarget, 3), queuedTarget -= 3);
          scheduleReplayQueueIfNeeded(i);
        }
      }
  }
  function defaultOnDefaultTransitionIndicator() {
    function handleNavigate(event) {
      event.canIntercept && "react-transition" === event.info && event.intercept({
        handler: function() {
          return new Promise(function(resolve) {
            return pendingResolve = resolve;
          });
        },
        focusReset: "manual",
        scroll: "manual"
      });
    }
    function handleNavigateComplete() {
      null !== pendingResolve && (pendingResolve(), pendingResolve = null);
      isCancelled || setTimeout(startFakeNavigation, 20);
    }
    function startFakeNavigation() {
      if (!isCancelled && !navigation.transition) {
        var currentEntry = navigation.currentEntry;
        currentEntry && null != currentEntry.url && navigation.navigate(currentEntry.url, {
          state: currentEntry.getState(),
          info: "react-transition",
          history: "replace"
        });
      }
    }
    if ("object" === typeof navigation) {
      var isCancelled = false, pendingResolve = null;
      navigation.addEventListener("navigate", handleNavigate);
      navigation.addEventListener("navigatesuccess", handleNavigateComplete);
      navigation.addEventListener("navigateerror", handleNavigateComplete);
      setTimeout(startFakeNavigation, 100);
      return function() {
        isCancelled = true;
        navigation.removeEventListener("navigate", handleNavigate);
        navigation.removeEventListener("navigatesuccess", handleNavigateComplete);
        navigation.removeEventListener("navigateerror", handleNavigateComplete);
        null !== pendingResolve && (pendingResolve(), pendingResolve = null);
      };
    }
  }
  function ReactDOMRoot(internalRoot) {
    this._internalRoot = internalRoot;
  }
  ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children) {
    var root3 = this._internalRoot;
    if (null === root3) throw Error(formatProdErrorMessage(409));
    var current = root3.current, lane = requestUpdateLane();
    updateContainerImpl(current, lane, children, root3, null, null);
  };
  ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
    var root3 = this._internalRoot;
    if (null !== root3) {
      this._internalRoot = null;
      var container = root3.containerInfo;
      updateContainerImpl(root3.current, 2, null, root3, null, null);
      flushSyncWork$1();
      container[internalContainerInstanceKey] = null;
    }
  };
  function ReactDOMHydrationRoot(internalRoot) {
    this._internalRoot = internalRoot;
  }
  ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = function(target) {
    if (target) {
      var updatePriority = resolveUpdatePriority();
      target = { blockedOn: null, target, priority: updatePriority };
      for (var i = 0; i < queuedExplicitHydrationTargets.length && 0 !== updatePriority && updatePriority < queuedExplicitHydrationTargets[i].priority; i++) ;
      queuedExplicitHydrationTargets.splice(i, 0, target);
      0 === i && attemptExplicitHydrationTarget(target);
    }
  };
  var isomorphicReactPackageVersion$jscomp$inline_1840 = React2.version;
  if ("19.2.4" !== isomorphicReactPackageVersion$jscomp$inline_1840)
    throw Error(
      formatProdErrorMessage(
        527,
        isomorphicReactPackageVersion$jscomp$inline_1840,
        "19.2.4"
      )
    );
  ReactDOMSharedInternals.findDOMNode = function(componentOrElement) {
    var fiber = componentOrElement._reactInternals;
    if (void 0 === fiber) {
      if ("function" === typeof componentOrElement.render)
        throw Error(formatProdErrorMessage(188));
      componentOrElement = Object.keys(componentOrElement).join(",");
      throw Error(formatProdErrorMessage(268, componentOrElement));
    }
    componentOrElement = findCurrentFiberUsingSlowPath(fiber);
    componentOrElement = null !== componentOrElement ? findCurrentHostFiberImpl(componentOrElement) : null;
    componentOrElement = null === componentOrElement ? null : componentOrElement.stateNode;
    return componentOrElement;
  };
  var internals$jscomp$inline_2347 = {
    bundleType: 0,
    version: "19.2.4",
    rendererPackageName: "react-dom",
    currentDispatcherRef: ReactSharedInternals,
    reconcilerVersion: "19.2.4"
  };
  if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
    var hook$jscomp$inline_2348 = __REACT_DEVTOOLS_GLOBAL_HOOK__;
    if (!hook$jscomp$inline_2348.isDisabled && hook$jscomp$inline_2348.supportsFiber)
      try {
        rendererID = hook$jscomp$inline_2348.inject(
          internals$jscomp$inline_2347
        ), injectedHook = hook$jscomp$inline_2348;
      } catch (err) {
      }
  }
  reactDomClient_production.createRoot = function(container, options2) {
    if (!isValidContainer(container)) throw Error(formatProdErrorMessage(299));
    var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError;
    null !== options2 && void 0 !== options2 && (true === options2.unstable_strictMode && (isStrictMode = true), void 0 !== options2.identifierPrefix && (identifierPrefix = options2.identifierPrefix), void 0 !== options2.onUncaughtError && (onUncaughtError = options2.onUncaughtError), void 0 !== options2.onCaughtError && (onCaughtError = options2.onCaughtError), void 0 !== options2.onRecoverableError && (onRecoverableError = options2.onRecoverableError));
    options2 = createFiberRoot(
      container,
      1,
      false,
      null,
      null,
      isStrictMode,
      identifierPrefix,
      null,
      onUncaughtError,
      onCaughtError,
      onRecoverableError,
      defaultOnDefaultTransitionIndicator
    );
    container[internalContainerInstanceKey] = options2.current;
    listenToAllSupportedEvents(container);
    return new ReactDOMRoot(options2);
  };
  reactDomClient_production.hydrateRoot = function(container, initialChildren, options2) {
    if (!isValidContainer(container)) throw Error(formatProdErrorMessage(299));
    var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError, formState = null;
    null !== options2 && void 0 !== options2 && (true === options2.unstable_strictMode && (isStrictMode = true), void 0 !== options2.identifierPrefix && (identifierPrefix = options2.identifierPrefix), void 0 !== options2.onUncaughtError && (onUncaughtError = options2.onUncaughtError), void 0 !== options2.onCaughtError && (onCaughtError = options2.onCaughtError), void 0 !== options2.onRecoverableError && (onRecoverableError = options2.onRecoverableError), void 0 !== options2.formState && (formState = options2.formState));
    initialChildren = createFiberRoot(
      container,
      1,
      true,
      initialChildren,
      null != options2 ? options2 : null,
      isStrictMode,
      identifierPrefix,
      formState,
      onUncaughtError,
      onCaughtError,
      onRecoverableError,
      defaultOnDefaultTransitionIndicator
    );
    initialChildren.context = getContextForSubtree(null);
    options2 = initialChildren.current;
    isStrictMode = requestUpdateLane();
    isStrictMode = getBumpedLaneForHydrationByLane(isStrictMode);
    identifierPrefix = createUpdate(isStrictMode);
    identifierPrefix.callback = null;
    enqueueUpdate(options2, identifierPrefix, isStrictMode);
    options2 = isStrictMode;
    initialChildren.current.lanes = options2;
    markRootUpdated$1(initialChildren, options2);
    ensureRootIsScheduled(initialChildren);
    container[internalContainerInstanceKey] = initialChildren.current;
    listenToAllSupportedEvents(container);
    return new ReactDOMHydrationRoot(initialChildren);
  };
  reactDomClient_production.version = "19.2.4";
  return reactDomClient_production;
}
var reactDomClient_development = {};
var hasRequiredReactDomClient_development;
function requireReactDomClient_development() {
  if (hasRequiredReactDomClient_development) return reactDomClient_development;
  hasRequiredReactDomClient_development = 1;
  "production" !== process.env.NODE_ENV && (function() {
    function findHook(fiber, id) {
      for (fiber = fiber.memoizedState; null !== fiber && 0 < id; )
        fiber = fiber.next, id--;
      return fiber;
    }
    function copyWithSetImpl(obj, path, index2, value) {
      if (index2 >= path.length) return value;
      var key = path[index2], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
      updated[key] = copyWithSetImpl(obj[key], path, index2 + 1, value);
      return updated;
    }
    function copyWithRename(obj, oldPath, newPath) {
      if (oldPath.length !== newPath.length)
        console.warn("copyWithRename() expects paths of the same length");
      else {
        for (var i = 0; i < newPath.length - 1; i++)
          if (oldPath[i] !== newPath[i]) {
            console.warn(
              "copyWithRename() expects paths to be the same except for the deepest key"
            );
            return;
          }
        return copyWithRenameImpl(obj, oldPath, newPath, 0);
      }
    }
    function copyWithRenameImpl(obj, oldPath, newPath, index2) {
      var oldKey = oldPath[index2], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
      index2 + 1 === oldPath.length ? (updated[newPath[index2]] = updated[oldKey], isArrayImpl(updated) ? updated.splice(oldKey, 1) : delete updated[oldKey]) : updated[oldKey] = copyWithRenameImpl(
        obj[oldKey],
        oldPath,
        newPath,
        index2 + 1
      );
      return updated;
    }
    function copyWithDeleteImpl(obj, path, index2) {
      var key = path[index2], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
      if (index2 + 1 === path.length)
        return isArrayImpl(updated) ? updated.splice(key, 1) : delete updated[key], updated;
      updated[key] = copyWithDeleteImpl(obj[key], path, index2 + 1);
      return updated;
    }
    function shouldSuspendImpl() {
      return false;
    }
    function shouldErrorImpl() {
      return null;
    }
    function warnInvalidHookAccess() {
      console.error(
        "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks"
      );
    }
    function warnInvalidContextAccess() {
      console.error(
        "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
      );
    }
    function noop2() {
    }
    function warnForMissingKey() {
    }
    function setToSortedString(set) {
      var array = [];
      set.forEach(function(value) {
        array.push(value);
      });
      return array.sort().join(", ");
    }
    function createFiber(tag, pendingProps, key, mode) {
      return new FiberNode(tag, pendingProps, key, mode);
    }
    function scheduleRoot(root3, element2) {
      root3.context === emptyContextObject && (updateContainerImpl(root3.current, 2, element2, root3, null, null), flushSyncWork$1());
    }
    function scheduleRefresh(root3, update) {
      if (null !== resolveFamily2) {
        var staleFamilies = update.staleFamilies;
        update = update.updatedFamilies;
        flushPendingEffects();
        scheduleFibersWithFamiliesRecursively(
          root3.current,
          update,
          staleFamilies
        );
        flushSyncWork$1();
      }
    }
    function setRefreshHandler(handler) {
      resolveFamily2 = handler;
    }
    function isValidContainer(node2) {
      return !(!node2 || 1 !== node2.nodeType && 9 !== node2.nodeType && 11 !== node2.nodeType);
    }
    function getNearestMountedFiber(fiber) {
      var node2 = fiber, nearestMounted = fiber;
      if (fiber.alternate) for (; node2.return; ) node2 = node2.return;
      else {
        fiber = node2;
        do
          node2 = fiber, 0 !== (node2.flags & 4098) && (nearestMounted = node2.return), fiber = node2.return;
        while (fiber);
      }
      return 3 === node2.tag ? nearestMounted : null;
    }
    function getSuspenseInstanceFromFiber(fiber) {
      if (13 === fiber.tag) {
        var suspenseState = fiber.memoizedState;
        null === suspenseState && (fiber = fiber.alternate, null !== fiber && (suspenseState = fiber.memoizedState));
        if (null !== suspenseState) return suspenseState.dehydrated;
      }
      return null;
    }
    function getActivityInstanceFromFiber(fiber) {
      if (31 === fiber.tag) {
        var activityState = fiber.memoizedState;
        null === activityState && (fiber = fiber.alternate, null !== fiber && (activityState = fiber.memoizedState));
        if (null !== activityState) return activityState.dehydrated;
      }
      return null;
    }
    function assertIsMounted(fiber) {
      if (getNearestMountedFiber(fiber) !== fiber)
        throw Error("Unable to find node on an unmounted component.");
    }
    function findCurrentFiberUsingSlowPath(fiber) {
      var alternate = fiber.alternate;
      if (!alternate) {
        alternate = getNearestMountedFiber(fiber);
        if (null === alternate)
          throw Error("Unable to find node on an unmounted component.");
        return alternate !== fiber ? null : fiber;
      }
      for (var a = fiber, b2 = alternate; ; ) {
        var parentA = a.return;
        if (null === parentA) break;
        var parentB = parentA.alternate;
        if (null === parentB) {
          b2 = parentA.return;
          if (null !== b2) {
            a = b2;
            continue;
          }
          break;
        }
        if (parentA.child === parentB.child) {
          for (parentB = parentA.child; parentB; ) {
            if (parentB === a) return assertIsMounted(parentA), fiber;
            if (parentB === b2) return assertIsMounted(parentA), alternate;
            parentB = parentB.sibling;
          }
          throw Error("Unable to find node on an unmounted component.");
        }
        if (a.return !== b2.return) a = parentA, b2 = parentB;
        else {
          for (var didFindChild = false, _child = parentA.child; _child; ) {
            if (_child === a) {
              didFindChild = true;
              a = parentA;
              b2 = parentB;
              break;
            }
            if (_child === b2) {
              didFindChild = true;
              b2 = parentA;
              a = parentB;
              break;
            }
            _child = _child.sibling;
          }
          if (!didFindChild) {
            for (_child = parentB.child; _child; ) {
              if (_child === a) {
                didFindChild = true;
                a = parentB;
                b2 = parentA;
                break;
              }
              if (_child === b2) {
                didFindChild = true;
                b2 = parentB;
                a = parentA;
                break;
              }
              _child = _child.sibling;
            }
            if (!didFindChild)
              throw Error(
                "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."
              );
          }
        }
        if (a.alternate !== b2)
          throw Error(
            "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."
          );
      }
      if (3 !== a.tag)
        throw Error("Unable to find node on an unmounted component.");
      return a.stateNode.current === a ? fiber : alternate;
    }
    function findCurrentHostFiberImpl(node2) {
      var tag = node2.tag;
      if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node2;
      for (node2 = node2.child; null !== node2; ) {
        tag = findCurrentHostFiberImpl(node2);
        if (null !== tag) return tag;
        node2 = node2.sibling;
      }
      return null;
    }
    function getIteratorFn(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable)
        return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    function getComponentNameFromType(type2) {
      if (null == type2) return null;
      if ("function" === typeof type2)
        return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
      if ("string" === typeof type2) return type2;
      switch (type2) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
        case REACT_ACTIVITY_TYPE:
          return "Activity";
      }
      if ("object" === typeof type2)
        switch ("number" === typeof type2.tag && console.error(
          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
        ), type2.$$typeof) {
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_CONTEXT_TYPE:
            return type2.displayName || "Context";
          case REACT_CONSUMER_TYPE:
            return (type2._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type2.render;
            type2 = type2.displayName;
            type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
            return type2;
          case REACT_MEMO_TYPE:
            return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type2._payload;
            type2 = type2._init;
            try {
              return getComponentNameFromType(type2(innerType));
            } catch (x2) {
            }
        }
      return null;
    }
    function getComponentNameFromOwner(owner) {
      return "number" === typeof owner.tag ? getComponentNameFromFiber(owner) : "string" === typeof owner.name ? owner.name : null;
    }
    function getComponentNameFromFiber(fiber) {
      var type2 = fiber.type;
      switch (fiber.tag) {
        case 31:
          return "Activity";
        case 24:
          return "Cache";
        case 9:
          return (type2._context.displayName || "Context") + ".Consumer";
        case 10:
          return type2.displayName || "Context";
        case 18:
          return "DehydratedFragment";
        case 11:
          return fiber = type2.render, fiber = fiber.displayName || fiber.name || "", type2.displayName || ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef");
        case 7:
          return "Fragment";
        case 26:
        case 27:
        case 5:
          return type2;
        case 4:
          return "Portal";
        case 3:
          return "Root";
        case 6:
          return "Text";
        case 16:
          return getComponentNameFromType(type2);
        case 8:
          return type2 === REACT_STRICT_MODE_TYPE ? "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 14:
        case 15:
          if ("function" === typeof type2)
            return type2.displayName || type2.name || null;
          if ("string" === typeof type2) return type2;
          break;
        case 29:
          type2 = fiber._debugInfo;
          if (null != type2) {
            for (var i = type2.length - 1; 0 <= i; i--)
              if ("string" === typeof type2[i].name) return type2[i].name;
          }
          if (null !== fiber.return)
            return getComponentNameFromFiber(fiber.return);
      }
      return null;
    }
    function createCursor(defaultValue) {
      return { current: defaultValue };
    }
    function pop(cursor, fiber) {
      0 > index$jscomp$0 ? console.error("Unexpected pop.") : (fiber !== fiberStack[index$jscomp$0] && console.error("Unexpected Fiber popped."), cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, fiberStack[index$jscomp$0] = null, index$jscomp$0--);
    }
    function push2(cursor, value, fiber) {
      index$jscomp$0++;
      valueStack[index$jscomp$0] = cursor.current;
      fiberStack[index$jscomp$0] = fiber;
      cursor.current = value;
    }
    function requiredContext(c) {
      null === c && console.error(
        "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."
      );
      return c;
    }
    function pushHostContainer(fiber, nextRootInstance) {
      push2(rootInstanceStackCursor, nextRootInstance, fiber);
      push2(contextFiberStackCursor, fiber, fiber);
      push2(contextStackCursor, null, fiber);
      var nextRootContext = nextRootInstance.nodeType;
      switch (nextRootContext) {
        case 9:
        case 11:
          nextRootContext = 9 === nextRootContext ? "#document" : "#fragment";
          nextRootInstance = (nextRootInstance = nextRootInstance.documentElement) ? (nextRootInstance = nextRootInstance.namespaceURI) ? getOwnHostContext(nextRootInstance) : HostContextNamespaceNone : HostContextNamespaceNone;
          break;
        default:
          if (nextRootContext = nextRootInstance.tagName, nextRootInstance = nextRootInstance.namespaceURI)
            nextRootInstance = getOwnHostContext(nextRootInstance), nextRootInstance = getChildHostContextProd(
              nextRootInstance,
              nextRootContext
            );
          else
            switch (nextRootContext) {
              case "svg":
                nextRootInstance = HostContextNamespaceSvg;
                break;
              case "math":
                nextRootInstance = HostContextNamespaceMath;
                break;
              default:
                nextRootInstance = HostContextNamespaceNone;
            }
      }
      nextRootContext = nextRootContext.toLowerCase();
      nextRootContext = updatedAncestorInfoDev(null, nextRootContext);
      nextRootContext = {
        context: nextRootInstance,
        ancestorInfo: nextRootContext
      };
      pop(contextStackCursor, fiber);
      push2(contextStackCursor, nextRootContext, fiber);
    }
    function popHostContainer(fiber) {
      pop(contextStackCursor, fiber);
      pop(contextFiberStackCursor, fiber);
      pop(rootInstanceStackCursor, fiber);
    }
    function getHostContext() {
      return requiredContext(contextStackCursor.current);
    }
    function pushHostContext(fiber) {
      null !== fiber.memoizedState && push2(hostTransitionProviderCursor, fiber, fiber);
      var context = requiredContext(contextStackCursor.current);
      var type2 = fiber.type;
      var nextContext = getChildHostContextProd(context.context, type2);
      type2 = updatedAncestorInfoDev(context.ancestorInfo, type2);
      nextContext = { context: nextContext, ancestorInfo: type2 };
      context !== nextContext && (push2(contextFiberStackCursor, fiber, fiber), push2(contextStackCursor, nextContext, fiber));
    }
    function popHostContext(fiber) {
      contextFiberStackCursor.current === fiber && (pop(contextStackCursor, fiber), pop(contextFiberStackCursor, fiber));
      hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor, fiber), HostTransitionContext._currentValue = NotPendingTransition);
    }
    function disabledLog() {
    }
    function disableLogs() {
      if (0 === disabledDepth) {
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd;
        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        };
        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
      }
      disabledDepth++;
    }
    function reenableLogs() {
      disabledDepth--;
      if (0 === disabledDepth) {
        var props = { configurable: true, enumerable: true, writable: true };
        Object.defineProperties(console, {
          log: assign({}, props, { value: prevLog }),
          info: assign({}, props, { value: prevInfo }),
          warn: assign({}, props, { value: prevWarn }),
          error: assign({}, props, { value: prevError }),
          group: assign({}, props, { value: prevGroup }),
          groupCollapsed: assign({}, props, { value: prevGroupCollapsed }),
          groupEnd: assign({}, props, { value: prevGroupEnd })
        });
      }
      0 > disabledDepth && console.error(
        "disabledDepth fell below zero. This is a bug in React. Please file an issue."
      );
    }
    function formatOwnerStack(error) {
      var prevPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      error = error.stack;
      Error.prepareStackTrace = prevPrepareStackTrace;
      error.startsWith("Error: react-stack-top-frame\n") && (error = error.slice(29));
      prevPrepareStackTrace = error.indexOf("\n");
      -1 !== prevPrepareStackTrace && (error = error.slice(prevPrepareStackTrace + 1));
      prevPrepareStackTrace = error.indexOf("react_stack_bottom_frame");
      -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error.lastIndexOf(
        "\n",
        prevPrepareStackTrace
      ));
      if (-1 !== prevPrepareStackTrace)
        error = error.slice(0, prevPrepareStackTrace);
      else return "";
      return error;
    }
    function describeBuiltInComponentFrame(name2) {
      if (void 0 === prefix)
        try {
          throw Error();
        } catch (x2) {
          var match = x2.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || "";
          suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
        }
      return "\n" + prefix + name2 + suffix;
    }
    function describeNativeComponentFrame(fn, construct) {
      if (!fn || reentry) return "";
      var frame = componentFrameCache.get(fn);
      if (void 0 !== frame) return frame;
      reentry = true;
      frame = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      var previousDispatcher2 = null;
      previousDispatcher2 = ReactSharedInternals.H;
      ReactSharedInternals.H = null;
      disableLogs();
      try {
        var RunInRootFrame = {
          DetermineComponentFrameRoot: function() {
            try {
              if (construct) {
                var Fake = function() {
                  throw Error();
                };
                Object.defineProperty(Fake.prototype, "props", {
                  set: function() {
                    throw Error();
                  }
                });
                if ("object" === typeof Reflect && Reflect.construct) {
                  try {
                    Reflect.construct(Fake, []);
                  } catch (x2) {
                    var control = x2;
                  }
                  Reflect.construct(fn, [], Fake);
                } else {
                  try {
                    Fake.call();
                  } catch (x$0) {
                    control = x$0;
                  }
                  fn.call(Fake.prototype);
                }
              } else {
                try {
                  throw Error();
                } catch (x$1) {
                  control = x$1;
                }
                (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
                });
              }
            } catch (sample) {
              if (sample && control && "string" === typeof sample.stack)
                return [sample.stack, control.stack];
            }
            return [null, null];
          }
        };
        RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
        var namePropDescriptor = Object.getOwnPropertyDescriptor(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name"
        );
        namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name",
          { value: "DetermineComponentFrameRoot" }
        );
        var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
        if (sampleStack && controlStack) {
          var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
          for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes(
            "DetermineComponentFrameRoot"
          ); )
            namePropDescriptor++;
          for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes(
            "DetermineComponentFrameRoot"
          ); )
            _RunInRootFrame$Deter++;
          if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
            for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
              _RunInRootFrame$Deter--;
          for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
            if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
              if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) {
                do
                  if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                    var _frame = "\n" + sampleLines[namePropDescriptor].replace(
                      " at new ",
                      " at "
                    );
                    fn.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn.displayName));
                    "function" === typeof fn && componentFrameCache.set(fn, _frame);
                    return _frame;
                  }
                while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
              }
              break;
            }
        }
      } finally {
        reentry = false, ReactSharedInternals.H = previousDispatcher2, reenableLogs(), Error.prepareStackTrace = frame;
      }
      sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
      "function" === typeof fn && componentFrameCache.set(fn, sampleLines);
      return sampleLines;
    }
    function describeFiber(fiber, childFiber) {
      switch (fiber.tag) {
        case 26:
        case 27:
        case 5:
          return describeBuiltInComponentFrame(fiber.type);
        case 16:
          return describeBuiltInComponentFrame("Lazy");
        case 13:
          return fiber.child !== childFiber && null !== childFiber ? describeBuiltInComponentFrame("Suspense Fallback") : describeBuiltInComponentFrame("Suspense");
        case 19:
          return describeBuiltInComponentFrame("SuspenseList");
        case 0:
        case 15:
          return describeNativeComponentFrame(fiber.type, false);
        case 11:
          return describeNativeComponentFrame(fiber.type.render, false);
        case 1:
          return describeNativeComponentFrame(fiber.type, true);
        case 31:
          return describeBuiltInComponentFrame("Activity");
        default:
          return "";
      }
    }
    function getStackByFiberInDevAndProd(workInProgress2) {
      try {
        var info = "", previous2 = null;
        do {
          info += describeFiber(workInProgress2, previous2);
          var debugInfo = workInProgress2._debugInfo;
          if (debugInfo)
            for (var i = debugInfo.length - 1; 0 <= i; i--) {
              var entry = debugInfo[i];
              if ("string" === typeof entry.name) {
                var JSCompiler_temp_const = info;
                a: {
                  var name2 = entry.name, env2 = entry.env, location = entry.debugLocation;
                  if (null != location) {
                    var childStack = formatOwnerStack(location), idx = childStack.lastIndexOf("\n"), lastLine = -1 === idx ? childStack : childStack.slice(idx + 1);
                    if (-1 !== lastLine.indexOf(name2)) {
                      var JSCompiler_inline_result = "\n" + lastLine;
                      break a;
                    }
                  }
                  JSCompiler_inline_result = describeBuiltInComponentFrame(
                    name2 + (env2 ? " [" + env2 + "]" : "")
                  );
                }
                info = JSCompiler_temp_const + JSCompiler_inline_result;
              }
            }
          previous2 = workInProgress2;
          workInProgress2 = workInProgress2.return;
        } while (workInProgress2);
        return info;
      } catch (x2) {
        return "\nError generating stack: " + x2.message + "\n" + x2.stack;
      }
    }
    function describeFunctionComponentFrameWithoutLineNumber(fn) {
      return (fn = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(fn) : "";
    }
    function getCurrentFiberOwnerNameInDevOrNull() {
      if (null === current) return null;
      var owner = current._debugOwner;
      return null != owner ? getComponentNameFromOwner(owner) : null;
    }
    function getCurrentFiberStackInDev() {
      if (null === current) return "";
      var workInProgress2 = current;
      try {
        var info = "";
        6 === workInProgress2.tag && (workInProgress2 = workInProgress2.return);
        switch (workInProgress2.tag) {
          case 26:
          case 27:
          case 5:
            info += describeBuiltInComponentFrame(workInProgress2.type);
            break;
          case 13:
            info += describeBuiltInComponentFrame("Suspense");
            break;
          case 19:
            info += describeBuiltInComponentFrame("SuspenseList");
            break;
          case 31:
            info += describeBuiltInComponentFrame("Activity");
            break;
          case 30:
          case 0:
          case 15:
          case 1:
            workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
              workInProgress2.type
            ));
            break;
          case 11:
            workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
              workInProgress2.type.render
            ));
        }
        for (; workInProgress2; )
          if ("number" === typeof workInProgress2.tag) {
            var fiber = workInProgress2;
            workInProgress2 = fiber._debugOwner;
            var debugStack = fiber._debugStack;
            if (workInProgress2 && debugStack) {
              var formattedStack = formatOwnerStack(debugStack);
              "" !== formattedStack && (info += "\n" + formattedStack);
            }
          } else if (null != workInProgress2.debugStack) {
            var ownerStack = workInProgress2.debugStack;
            (workInProgress2 = workInProgress2.owner) && ownerStack && (info += "\n" + formatOwnerStack(ownerStack));
          } else break;
        var JSCompiler_inline_result = info;
      } catch (x2) {
        JSCompiler_inline_result = "\nError generating stack: " + x2.message + "\n" + x2.stack;
      }
      return JSCompiler_inline_result;
    }
    function runWithFiberInDEV(fiber, callback, arg0, arg1, arg2, arg3, arg4) {
      var previousFiber = current;
      setCurrentFiber(fiber);
      try {
        return null !== fiber && fiber._debugTask ? fiber._debugTask.run(
          callback.bind(null, arg0, arg1, arg2, arg3, arg4)
        ) : callback(arg0, arg1, arg2, arg3, arg4);
      } finally {
        setCurrentFiber(previousFiber);
      }
      throw Error(
        "runWithFiberInDEV should never be called in production. This is a bug in React."
      );
    }
    function setCurrentFiber(fiber) {
      ReactSharedInternals.getCurrentStack = null === fiber ? null : getCurrentFiberStackInDev;
      isRendering = false;
      current = fiber;
    }
    function typeName(value) {
      return "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
    }
    function willCoercionThrow(value) {
      try {
        return testStringCoercion(value), false;
      } catch (e) {
        return true;
      }
    }
    function testStringCoercion(value) {
      return "" + value;
    }
    function checkAttributeStringCoercion(value, attributeName) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before using it here.",
          attributeName,
          typeName(value)
        ), testStringCoercion(value);
    }
    function checkCSSPropertyStringCoercion(value, propName) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before using it here.",
          propName,
          typeName(value)
        ), testStringCoercion(value);
    }
    function checkFormFieldValueStringCoercion(value) {
      if (willCoercionThrow(value))
        return console.error(
          "Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before using it here.",
          typeName(value)
        ), testStringCoercion(value);
    }
    function injectInternals(internals) {
      if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) return false;
      var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
      if (hook.isDisabled) return true;
      if (!hook.supportsFiber)
        return console.error(
          "The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://react.dev/link/react-devtools"
        ), true;
      try {
        rendererID = hook.inject(internals), injectedHook = hook;
      } catch (err) {
        console.error("React instrumentation encountered an error: %o.", err);
      }
      return hook.checkDCE ? true : false;
    }
    function setIsStrictModeForDevtools(newIsStrictMode) {
      "function" === typeof log$1 && unstable_setDisableYieldValue(newIsStrictMode);
      if (injectedHook && "function" === typeof injectedHook.setStrictMode)
        try {
          injectedHook.setStrictMode(rendererID, newIsStrictMode);
        } catch (err) {
          hasLoggedError || (hasLoggedError = true, console.error(
            "React instrumentation encountered an error: %o",
            err
          ));
        }
    }
    function clz32Fallback(x2) {
      x2 >>>= 0;
      return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
    }
    function getHighestPriorityLanes(lanes) {
      var pendingSyncLanes = lanes & 42;
      if (0 !== pendingSyncLanes) return pendingSyncLanes;
      switch (lanes & -lanes) {
        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:
          return 64;
        case 128:
          return 128;
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
          return lanes & 261888;
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return lanes & 3932160;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          return lanes & 62914560;
        case 67108864:
          return 67108864;
        case 134217728:
          return 134217728;
        case 268435456:
          return 268435456;
        case 536870912:
          return 536870912;
        case 1073741824:
          return 0;
        default:
          return console.error(
            "Should have found matching lanes. This is a bug in React."
          ), lanes;
      }
    }
    function getNextLanes(root3, wipLanes, rootHasPendingCommit) {
      var pendingLanes = root3.pendingLanes;
      if (0 === pendingLanes) return 0;
      var nextLanes = 0, suspendedLanes = root3.suspendedLanes, pingedLanes = root3.pingedLanes;
      root3 = root3.warmLanes;
      var nonIdlePendingLanes = pendingLanes & 134217727;
      0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root3, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root3, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
      return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
    }
    function checkIfRootIsPrerendering(root3, renderLanes2) {
      return 0 === (root3.pendingLanes & ~(root3.suspendedLanes & ~root3.pingedLanes) & renderLanes2);
    }
    function computeExpirationTime(lane, currentTime) {
      switch (lane) {
        case 1:
        case 2:
        case 4:
        case 8:
        case 64:
          return currentTime + 250;
        case 16:
        case 32:
        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 currentTime + 5e3;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
          return -1;
        case 67108864:
        case 134217728:
        case 268435456:
        case 536870912:
        case 1073741824:
          return -1;
        default:
          return console.error(
            "Should have found matching lanes. This is a bug in React."
          ), -1;
      }
    }
    function claimNextRetryLane() {
      var lane = nextRetryLane;
      nextRetryLane <<= 1;
      0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
      return lane;
    }
    function createLaneMap(initial) {
      for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
      return laneMap;
    }
    function markRootUpdated$1(root3, updateLane) {
      root3.pendingLanes |= updateLane;
      268435456 !== updateLane && (root3.suspendedLanes = 0, root3.pingedLanes = 0, root3.warmLanes = 0);
    }
    function markRootFinished(root3, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
      var previouslyPendingLanes = root3.pendingLanes;
      root3.pendingLanes = remainingLanes;
      root3.suspendedLanes = 0;
      root3.pingedLanes = 0;
      root3.warmLanes = 0;
      root3.expiredLanes &= remainingLanes;
      root3.entangledLanes &= remainingLanes;
      root3.errorRecoveryDisabledLanes &= remainingLanes;
      root3.shellSuspendCounter = 0;
      var entanglements = root3.entanglements, expirationTimes = root3.expirationTimes, hiddenUpdates = root3.hiddenUpdates;
      for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
        var index2 = 31 - clz32(remainingLanes), lane = 1 << index2;
        entanglements[index2] = 0;
        expirationTimes[index2] = -1;
        var hiddenUpdatesForLane = hiddenUpdates[index2];
        if (null !== hiddenUpdatesForLane)
          for (hiddenUpdates[index2] = null, index2 = 0; index2 < hiddenUpdatesForLane.length; index2++) {
            var update = hiddenUpdatesForLane[index2];
            null !== update && (update.lane &= -536870913);
          }
        remainingLanes &= ~lane;
      }
      0 !== spawnedLane && markSpawnedDeferredLane(root3, spawnedLane, 0);
      0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root3.tag && (root3.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
    }
    function markSpawnedDeferredLane(root3, spawnedLane, entangledLanes) {
      root3.pendingLanes |= spawnedLane;
      root3.suspendedLanes &= ~spawnedLane;
      var spawnedLaneIndex = 31 - clz32(spawnedLane);
      root3.entangledLanes |= spawnedLane;
      root3.entanglements[spawnedLaneIndex] = root3.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 261930;
    }
    function markRootEntangled(root3, entangledLanes) {
      var rootEntangledLanes = root3.entangledLanes |= entangledLanes;
      for (root3 = root3.entanglements; rootEntangledLanes; ) {
        var index2 = 31 - clz32(rootEntangledLanes), lane = 1 << index2;
        lane & entangledLanes | root3[index2] & entangledLanes && (root3[index2] |= entangledLanes);
        rootEntangledLanes &= ~lane;
      }
    }
    function getBumpedLaneForHydration(root3, renderLanes2) {
      var renderLane = renderLanes2 & -renderLanes2;
      renderLane = 0 !== (renderLane & 42) ? 1 : getBumpedLaneForHydrationByLane(renderLane);
      return 0 !== (renderLane & (root3.suspendedLanes | renderLanes2)) ? 0 : renderLane;
    }
    function getBumpedLaneForHydrationByLane(lane) {
      switch (lane) {
        case 2:
          lane = 1;
          break;
        case 8:
          lane = 4;
          break;
        case 32:
          lane = 16;
          break;
        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:
          lane = 128;
          break;
        case 268435456:
          lane = 134217728;
          break;
        default:
          lane = 0;
      }
      return lane;
    }
    function addFiberToLanesMap(root3, fiber, lanes) {
      if (isDevToolsPresent)
        for (root3 = root3.pendingUpdatersLaneMap; 0 < lanes; ) {
          var index2 = 31 - clz32(lanes), lane = 1 << index2;
          root3[index2].add(fiber);
          lanes &= ~lane;
        }
    }
    function movePendingFibersToMemoized(root3, lanes) {
      if (isDevToolsPresent)
        for (var pendingUpdatersLaneMap = root3.pendingUpdatersLaneMap, memoizedUpdaters = root3.memoizedUpdaters; 0 < lanes; ) {
          var index2 = 31 - clz32(lanes);
          root3 = 1 << index2;
          index2 = pendingUpdatersLaneMap[index2];
          0 < index2.size && (index2.forEach(function(fiber) {
            var alternate = fiber.alternate;
            null !== alternate && memoizedUpdaters.has(alternate) || memoizedUpdaters.add(fiber);
          }), index2.clear());
          lanes &= ~root3;
        }
    }
    function lanesToEventPriority(lanes) {
      lanes &= -lanes;
      return DiscreteEventPriority < lanes ? ContinuousEventPriority < lanes ? 0 !== (lanes & 134217727) ? DefaultEventPriority : IdleEventPriority : ContinuousEventPriority : DiscreteEventPriority;
    }
    function resolveUpdatePriority() {
      var updatePriority = ReactDOMSharedInternals.p;
      if (0 !== updatePriority) return updatePriority;
      updatePriority = window.event;
      return void 0 === updatePriority ? DefaultEventPriority : getEventPriority(updatePriority.type);
    }
    function runWithPriority(priority, fn) {
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        return ReactDOMSharedInternals.p = priority, fn();
      } finally {
        ReactDOMSharedInternals.p = previousPriority;
      }
    }
    function detachDeletedInstance(node2) {
      delete node2[internalInstanceKey];
      delete node2[internalPropsKey];
      delete node2[internalEventHandlersKey];
      delete node2[internalEventHandlerListenersKey];
      delete node2[internalEventHandlesSetKey];
    }
    function getClosestInstanceFromNode(targetNode) {
      var targetInst = targetNode[internalInstanceKey];
      if (targetInst) return targetInst;
      for (var parentNode = targetNode.parentNode; parentNode; ) {
        if (targetInst = parentNode[internalContainerInstanceKey] || parentNode[internalInstanceKey]) {
          parentNode = targetInst.alternate;
          if (null !== targetInst.child || null !== parentNode && null !== parentNode.child)
            for (targetNode = getParentHydrationBoundary(targetNode); null !== targetNode; ) {
              if (parentNode = targetNode[internalInstanceKey])
                return parentNode;
              targetNode = getParentHydrationBoundary(targetNode);
            }
          return targetInst;
        }
        targetNode = parentNode;
        parentNode = targetNode.parentNode;
      }
      return null;
    }
    function getInstanceFromNode(node2) {
      if (node2 = node2[internalInstanceKey] || node2[internalContainerInstanceKey]) {
        var tag = node2.tag;
        if (5 === tag || 6 === tag || 13 === tag || 31 === tag || 26 === tag || 27 === tag || 3 === tag)
          return node2;
      }
      return null;
    }
    function getNodeFromInstance(inst) {
      var tag = inst.tag;
      if (5 === tag || 26 === tag || 27 === tag || 6 === tag)
        return inst.stateNode;
      throw Error("getNodeFromInstance: Invalid argument.");
    }
    function getResourcesFromRoot(root3) {
      var resources = root3[internalRootNodeResourcesKey];
      resources || (resources = root3[internalRootNodeResourcesKey] = { hoistableStyles: /* @__PURE__ */ new Map(), hoistableScripts: /* @__PURE__ */ new Map() });
      return resources;
    }
    function markNodeAsHoistable(node2) {
      node2[internalHoistableMarker] = true;
    }
    function registerTwoPhaseEvent(registrationName, dependencies) {
      registerDirectEvent(registrationName, dependencies);
      registerDirectEvent(registrationName + "Capture", dependencies);
    }
    function registerDirectEvent(registrationName, dependencies) {
      registrationNameDependencies[registrationName] && console.error(
        "EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.",
        registrationName
      );
      registrationNameDependencies[registrationName] = dependencies;
      var lowerCasedName = registrationName.toLowerCase();
      possibleRegistrationNames[lowerCasedName] = registrationName;
      "onDoubleClick" === registrationName && (possibleRegistrationNames.ondblclick = registrationName);
      for (registrationName = 0; registrationName < dependencies.length; registrationName++)
        allNativeEvents.add(dependencies[registrationName]);
    }
    function checkControlledValueProps(tagName, props) {
      hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || null == props.value || ("select" === tagName ? console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set `onChange`."
      ) : console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."
      ));
      props.onChange || props.readOnly || props.disabled || null == props.checked || console.error(
        "You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."
      );
    }
    function isAttributeNameSafe(attributeName) {
      if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
        return true;
      if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName))
        return false;
      if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
        return validatedAttributeNameCache[attributeName] = true;
      illegalAttributeNameCache[attributeName] = true;
      console.error("Invalid attribute name: `%s`", attributeName);
      return false;
    }
    function getValueForAttributeOnCustomComponent(node2, name2, expected) {
      if (isAttributeNameSafe(name2)) {
        if (!node2.hasAttribute(name2)) {
          switch (typeof expected) {
            case "symbol":
            case "object":
              return expected;
            case "function":
              return expected;
            case "boolean":
              if (false === expected) return expected;
          }
          return void 0 === expected ? void 0 : null;
        }
        node2 = node2.getAttribute(name2);
        if ("" === node2 && true === expected) return true;
        checkAttributeStringCoercion(expected, name2);
        return node2 === "" + expected ? expected : node2;
      }
    }
    function setValueForAttribute(node2, name2, value) {
      if (isAttributeNameSafe(name2))
        if (null === value) node2.removeAttribute(name2);
        else {
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
              node2.removeAttribute(name2);
              return;
            case "boolean":
              var prefix2 = name2.toLowerCase().slice(0, 5);
              if ("data-" !== prefix2 && "aria-" !== prefix2) {
                node2.removeAttribute(name2);
                return;
              }
          }
          checkAttributeStringCoercion(value, name2);
          node2.setAttribute(name2, "" + value);
        }
    }
    function setValueForKnownAttribute(node2, name2, value) {
      if (null === value) node2.removeAttribute(name2);
      else {
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            node2.removeAttribute(name2);
            return;
        }
        checkAttributeStringCoercion(value, name2);
        node2.setAttribute(name2, "" + value);
      }
    }
    function setValueForNamespacedAttribute(node2, namespace, name2, value) {
      if (null === value) node2.removeAttribute(name2);
      else {
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            node2.removeAttribute(name2);
            return;
        }
        checkAttributeStringCoercion(value, name2);
        node2.setAttributeNS(namespace, name2, "" + value);
      }
    }
    function getToStringValue(value) {
      switch (typeof value) {
        case "bigint":
        case "boolean":
        case "number":
        case "string":
        case "undefined":
          return value;
        case "object":
          return checkFormFieldValueStringCoercion(value), value;
        default:
          return "";
      }
    }
    function isCheckable(elem) {
      var type2 = elem.type;
      return (elem = elem.nodeName) && "input" === elem.toLowerCase() && ("checkbox" === type2 || "radio" === type2);
    }
    function trackValueOnNode(node2, valueField, currentValue) {
      var descriptor = Object.getOwnPropertyDescriptor(
        node2.constructor.prototype,
        valueField
      );
      if (!node2.hasOwnProperty(valueField) && "undefined" !== typeof descriptor && "function" === typeof descriptor.get && "function" === typeof descriptor.set) {
        var get2 = descriptor.get, set = descriptor.set;
        Object.defineProperty(node2, valueField, {
          configurable: true,
          get: function() {
            return get2.call(this);
          },
          set: function(value) {
            checkFormFieldValueStringCoercion(value);
            currentValue = "" + value;
            set.call(this, value);
          }
        });
        Object.defineProperty(node2, valueField, {
          enumerable: descriptor.enumerable
        });
        return {
          getValue: function() {
            return currentValue;
          },
          setValue: function(value) {
            checkFormFieldValueStringCoercion(value);
            currentValue = "" + value;
          },
          stopTracking: function() {
            node2._valueTracker = null;
            delete node2[valueField];
          }
        };
      }
    }
    function track(node2) {
      if (!node2._valueTracker) {
        var valueField = isCheckable(node2) ? "checked" : "value";
        node2._valueTracker = trackValueOnNode(
          node2,
          valueField,
          "" + node2[valueField]
        );
      }
    }
    function updateValueIfChanged(node2) {
      if (!node2) return false;
      var tracker = node2._valueTracker;
      if (!tracker) return true;
      var lastValue = tracker.getValue();
      var value = "";
      node2 && (value = isCheckable(node2) ? node2.checked ? "true" : "false" : node2.value);
      node2 = value;
      return node2 !== lastValue ? (tracker.setValue(node2), true) : false;
    }
    function getActiveElement(doc) {
      doc = doc || ("undefined" !== typeof document ? document : void 0);
      if ("undefined" === typeof doc) return null;
      try {
        return doc.activeElement || doc.body;
      } catch (e) {
        return doc.body;
      }
    }
    function escapeSelectorAttributeValueInsideDoubleQuotes(value) {
      return value.replace(
        escapeSelectorAttributeValueInsideDoubleQuotesRegex,
        function(ch) {
          return "\\" + ch.charCodeAt(0).toString(16) + " ";
        }
      );
    }
    function validateInputProps(element2, props) {
      void 0 === props.checked || void 0 === props.defaultChecked || didWarnCheckedDefaultChecked || (console.error(
        "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
        getCurrentFiberOwnerNameInDevOrNull() || "A component",
        props.type
      ), didWarnCheckedDefaultChecked = true);
      void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue$1 || (console.error(
        "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
        getCurrentFiberOwnerNameInDevOrNull() || "A component",
        props.type
      ), didWarnValueDefaultValue$1 = true);
    }
    function updateInput(element2, value, defaultValue, lastDefaultValue, checked, defaultChecked, type2, name2) {
      element2.name = "";
      null != type2 && "function" !== typeof type2 && "symbol" !== typeof type2 && "boolean" !== typeof type2 ? (checkAttributeStringCoercion(type2, "type"), element2.type = type2) : element2.removeAttribute("type");
      if (null != value)
        if ("number" === type2) {
          if (0 === value && "" === element2.value || element2.value != value)
            element2.value = "" + getToStringValue(value);
        } else
          element2.value !== "" + getToStringValue(value) && (element2.value = "" + getToStringValue(value));
      else
        "submit" !== type2 && "reset" !== type2 || element2.removeAttribute("value");
      null != value ? setDefaultValue(element2, type2, getToStringValue(value)) : null != defaultValue ? setDefaultValue(element2, type2, getToStringValue(defaultValue)) : null != lastDefaultValue && element2.removeAttribute("value");
      null == checked && null != defaultChecked && (element2.defaultChecked = !!defaultChecked);
      null != checked && (element2.checked = checked && "function" !== typeof checked && "symbol" !== typeof checked);
      null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 ? (checkAttributeStringCoercion(name2, "name"), element2.name = "" + getToStringValue(name2)) : element2.removeAttribute("name");
    }
    function initInput(element2, value, defaultValue, checked, defaultChecked, type2, name2, isHydrating2) {
      null != type2 && "function" !== typeof type2 && "symbol" !== typeof type2 && "boolean" !== typeof type2 && (checkAttributeStringCoercion(type2, "type"), element2.type = type2);
      if (null != value || null != defaultValue) {
        if (!("submit" !== type2 && "reset" !== type2 || void 0 !== value && null !== value)) {
          track(element2);
          return;
        }
        defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
        value = null != value ? "" + getToStringValue(value) : defaultValue;
        isHydrating2 || value === element2.value || (element2.value = value);
        element2.defaultValue = value;
      }
      checked = null != checked ? checked : defaultChecked;
      checked = "function" !== typeof checked && "symbol" !== typeof checked && !!checked;
      element2.checked = isHydrating2 ? element2.checked : !!checked;
      element2.defaultChecked = !!checked;
      null != name2 && "function" !== typeof name2 && "symbol" !== typeof name2 && "boolean" !== typeof name2 && (checkAttributeStringCoercion(name2, "name"), element2.name = name2);
      track(element2);
    }
    function setDefaultValue(node2, type2, value) {
      "number" === type2 && getActiveElement(node2.ownerDocument) === node2 || node2.defaultValue === "" + value || (node2.defaultValue = "" + value);
    }
    function validateOptionProps(element2, props) {
      null == props.value && ("object" === typeof props.children && null !== props.children ? React2.Children.forEach(props.children, function(child) {
        null == child || "string" === typeof child || "number" === typeof child || "bigint" === typeof child || didWarnInvalidChild || (didWarnInvalidChild = true, console.error(
          "Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>."
        ));
      }) : null == props.dangerouslySetInnerHTML || didWarnInvalidInnerHTML || (didWarnInvalidInnerHTML = true, console.error(
        "Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."
      )));
      null == props.selected || didWarnSelectedSetOnOption || (console.error(
        "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."
      ), didWarnSelectedSetOnOption = true);
    }
    function getDeclarationErrorAddendum() {
      var ownerName = getCurrentFiberOwnerNameInDevOrNull();
      return ownerName ? "\n\nCheck the render method of `" + ownerName + "`." : "";
    }
    function updateOptions(node2, multiple, propValue, setDefaultSelected) {
      node2 = node2.options;
      if (multiple) {
        multiple = {};
        for (var i = 0; i < propValue.length; i++)
          multiple["$" + propValue[i]] = true;
        for (propValue = 0; propValue < node2.length; propValue++)
          i = multiple.hasOwnProperty("$" + node2[propValue].value), node2[propValue].selected !== i && (node2[propValue].selected = i), i && setDefaultSelected && (node2[propValue].defaultSelected = true);
      } else {
        propValue = "" + getToStringValue(propValue);
        multiple = null;
        for (i = 0; i < node2.length; i++) {
          if (node2[i].value === propValue) {
            node2[i].selected = true;
            setDefaultSelected && (node2[i].defaultSelected = true);
            return;
          }
          null !== multiple || node2[i].disabled || (multiple = node2[i]);
        }
        null !== multiple && (multiple.selected = true);
      }
    }
    function validateSelectProps(element2, props) {
      for (element2 = 0; element2 < valuePropNames.length; element2++) {
        var propName = valuePropNames[element2];
        if (null != props[propName]) {
          var propNameIsArray = isArrayImpl(props[propName]);
          props.multiple && !propNameIsArray ? console.error(
            "The `%s` prop supplied to <select> must be an array if `multiple` is true.%s",
            propName,
            getDeclarationErrorAddendum()
          ) : !props.multiple && propNameIsArray && console.error(
            "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s",
            propName,
            getDeclarationErrorAddendum()
          );
        }
      }
      void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || (console.error(
        "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://react.dev/link/controlled-components"
      ), didWarnValueDefaultValue = true);
    }
    function validateTextareaProps(element2, props) {
      void 0 === props.value || void 0 === props.defaultValue || didWarnValDefaultVal || (console.error(
        "%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://react.dev/link/controlled-components",
        getCurrentFiberOwnerNameInDevOrNull() || "A component"
      ), didWarnValDefaultVal = true);
      null != props.children && null == props.value && console.error(
        "Use the `defaultValue` or `value` props instead of setting children on <textarea>."
      );
    }
    function updateTextarea(element2, value, defaultValue) {
      if (null != value && (value = "" + getToStringValue(value), value !== element2.value && (element2.value = value), null == defaultValue)) {
        element2.defaultValue !== value && (element2.defaultValue = value);
        return;
      }
      element2.defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
    }
    function initTextarea(element2, value, defaultValue, children) {
      if (null == value) {
        if (null != children) {
          if (null != defaultValue)
            throw Error(
              "If you supply `defaultValue` on a <textarea>, do not pass children."
            );
          if (isArrayImpl(children)) {
            if (1 < children.length)
              throw Error("<textarea> can only have at most one child.");
            children = children[0];
          }
          defaultValue = children;
        }
        null == defaultValue && (defaultValue = "");
        value = defaultValue;
      }
      defaultValue = getToStringValue(value);
      element2.defaultValue = defaultValue;
      children = element2.textContent;
      children === defaultValue && "" !== children && null !== children && (element2.value = children);
      track(element2);
    }
    function findNotableNode(node2, indent) {
      return void 0 === node2.serverProps && 0 === node2.serverTail.length && 1 === node2.children.length && 3 < node2.distanceFromLeaf && node2.distanceFromLeaf > 15 - indent ? findNotableNode(node2.children[0], indent) : node2;
    }
    function indentation(indent) {
      return "  " + "  ".repeat(indent);
    }
    function added(indent) {
      return "+ " + "  ".repeat(indent);
    }
    function removed(indent) {
      return "- " + "  ".repeat(indent);
    }
    function describeFiberType(fiber) {
      switch (fiber.tag) {
        case 26:
        case 27:
        case 5:
          return fiber.type;
        case 16:
          return "Lazy";
        case 31:
          return "Activity";
        case 13:
          return "Suspense";
        case 19:
          return "SuspenseList";
        case 0:
        case 15:
          return fiber = fiber.type, fiber.displayName || fiber.name || null;
        case 11:
          return fiber = fiber.type.render, fiber.displayName || fiber.name || null;
        case 1:
          return fiber = fiber.type, fiber.displayName || fiber.name || null;
        default:
          return null;
      }
    }
    function describeTextNode(content2, maxLength) {
      return needsEscaping.test(content2) ? (content2 = JSON.stringify(content2), content2.length > maxLength - 2 ? 8 > maxLength ? '{"..."}' : "{" + content2.slice(0, maxLength - 7) + '..."}' : "{" + content2 + "}") : content2.length > maxLength ? 5 > maxLength ? '{"..."}' : content2.slice(0, maxLength - 3) + "..." : content2;
    }
    function describeTextDiff(clientText, serverProps, indent) {
      var maxLength = 120 - 2 * indent;
      if (null === serverProps)
        return added(indent) + describeTextNode(clientText, maxLength) + "\n";
      if ("string" === typeof serverProps) {
        for (var firstDiff = 0; firstDiff < serverProps.length && firstDiff < clientText.length && serverProps.charCodeAt(firstDiff) === clientText.charCodeAt(firstDiff); firstDiff++) ;
        firstDiff > maxLength - 8 && 10 < firstDiff && (clientText = "..." + clientText.slice(firstDiff - 8), serverProps = "..." + serverProps.slice(firstDiff - 8));
        return added(indent) + describeTextNode(clientText, maxLength) + "\n" + removed(indent) + describeTextNode(serverProps, maxLength) + "\n";
      }
      return indentation(indent) + describeTextNode(clientText, maxLength) + "\n";
    }
    function objectName(object) {
      return Object.prototype.toString.call(object).replace(/^\[object (.*)\]$/, function(m2, p0) {
        return p0;
      });
    }
    function describeValue(value, maxLength) {
      switch (typeof value) {
        case "string":
          return value = JSON.stringify(value), value.length > maxLength ? 5 > maxLength ? '"..."' : value.slice(0, maxLength - 4) + '..."' : value;
        case "object":
          if (null === value) return "null";
          if (isArrayImpl(value)) return "[...]";
          if (value.$$typeof === REACT_ELEMENT_TYPE)
            return (maxLength = getComponentNameFromType(value.type)) ? "<" + maxLength + ">" : "<...>";
          var name2 = objectName(value);
          if ("Object" === name2) {
            name2 = "";
            maxLength -= 2;
            for (var propName in value)
              if (value.hasOwnProperty(propName)) {
                var jsonPropName = JSON.stringify(propName);
                jsonPropName !== '"' + propName + '"' && (propName = jsonPropName);
                maxLength -= propName.length - 2;
                jsonPropName = describeValue(
                  value[propName],
                  15 > maxLength ? maxLength : 15
                );
                maxLength -= jsonPropName.length;
                if (0 > maxLength) {
                  name2 += "" === name2 ? "..." : ", ...";
                  break;
                }
                name2 += ("" === name2 ? "" : ",") + propName + ":" + jsonPropName;
              }
            return "{" + name2 + "}";
          }
          return name2;
        case "function":
          return (maxLength = value.displayName || value.name) ? "function " + maxLength : "function";
        default:
          return String(value);
      }
    }
    function describePropValue(value, maxLength) {
      return "string" !== typeof value || needsEscaping.test(value) ? "{" + describeValue(value, maxLength - 2) + "}" : value.length > maxLength - 2 ? 5 > maxLength ? '"..."' : '"' + value.slice(0, maxLength - 5) + '..."' : '"' + value + '"';
    }
    function describeExpandedElement(type2, props, rowPrefix) {
      var remainingRowLength = 120 - rowPrefix.length - type2.length, properties = [], propName;
      for (propName in props)
        if (props.hasOwnProperty(propName) && "children" !== propName) {
          var propValue = describePropValue(
            props[propName],
            120 - rowPrefix.length - propName.length - 1
          );
          remainingRowLength -= propName.length + propValue.length + 2;
          properties.push(propName + "=" + propValue);
        }
      return 0 === properties.length ? rowPrefix + "<" + type2 + ">\n" : 0 < remainingRowLength ? rowPrefix + "<" + type2 + " " + properties.join(" ") + ">\n" : rowPrefix + "<" + type2 + "\n" + rowPrefix + "  " + properties.join("\n" + rowPrefix + "  ") + "\n" + rowPrefix + ">\n";
    }
    function describePropertiesDiff(clientObject, serverObject, indent) {
      var properties = "", remainingServerProperties = assign({}, serverObject), propName;
      for (propName in clientObject)
        if (clientObject.hasOwnProperty(propName)) {
          delete remainingServerProperties[propName];
          var maxLength = 120 - 2 * indent - propName.length - 2, clientPropValue = describeValue(clientObject[propName], maxLength);
          serverObject.hasOwnProperty(propName) ? (maxLength = describeValue(serverObject[propName], maxLength), properties += added(indent) + propName + ": " + clientPropValue + "\n", properties += removed(indent) + propName + ": " + maxLength + "\n") : properties += added(indent) + propName + ": " + clientPropValue + "\n";
        }
      for (var _propName in remainingServerProperties)
        remainingServerProperties.hasOwnProperty(_propName) && (clientObject = describeValue(
          remainingServerProperties[_propName],
          120 - 2 * indent - _propName.length - 2
        ), properties += removed(indent) + _propName + ": " + clientObject + "\n");
      return properties;
    }
    function describeElementDiff(type2, clientProps, serverProps, indent) {
      var content2 = "", serverPropNames = /* @__PURE__ */ new Map();
      for (propName$jscomp$0 in serverProps)
        serverProps.hasOwnProperty(propName$jscomp$0) && serverPropNames.set(
          propName$jscomp$0.toLowerCase(),
          propName$jscomp$0
        );
      if (1 === serverPropNames.size && serverPropNames.has("children"))
        content2 += describeExpandedElement(
          type2,
          clientProps,
          indentation(indent)
        );
      else {
        for (var _propName2 in clientProps)
          if (clientProps.hasOwnProperty(_propName2) && "children" !== _propName2) {
            var maxLength$jscomp$0 = 120 - 2 * (indent + 1) - _propName2.length - 1, serverPropName = serverPropNames.get(_propName2.toLowerCase());
            if (void 0 !== serverPropName) {
              serverPropNames.delete(_propName2.toLowerCase());
              var propName$jscomp$0 = clientProps[_propName2];
              serverPropName = serverProps[serverPropName];
              var clientPropValue = describePropValue(
                propName$jscomp$0,
                maxLength$jscomp$0
              );
              maxLength$jscomp$0 = describePropValue(
                serverPropName,
                maxLength$jscomp$0
              );
              "object" === typeof propName$jscomp$0 && null !== propName$jscomp$0 && "object" === typeof serverPropName && null !== serverPropName && "Object" === objectName(propName$jscomp$0) && "Object" === objectName(serverPropName) && (2 < Object.keys(propName$jscomp$0).length || 2 < Object.keys(serverPropName).length || -1 < clientPropValue.indexOf("...") || -1 < maxLength$jscomp$0.indexOf("...")) ? content2 += indentation(indent + 1) + _propName2 + "={{\n" + describePropertiesDiff(
                propName$jscomp$0,
                serverPropName,
                indent + 2
              ) + indentation(indent + 1) + "}}\n" : (content2 += added(indent + 1) + _propName2 + "=" + clientPropValue + "\n", content2 += removed(indent + 1) + _propName2 + "=" + maxLength$jscomp$0 + "\n");
            } else
              content2 += indentation(indent + 1) + _propName2 + "=" + describePropValue(clientProps[_propName2], maxLength$jscomp$0) + "\n";
          }
        serverPropNames.forEach(function(propName) {
          if ("children" !== propName) {
            var maxLength = 120 - 2 * (indent + 1) - propName.length - 1;
            content2 += removed(indent + 1) + propName + "=" + describePropValue(serverProps[propName], maxLength) + "\n";
          }
        });
        content2 = "" === content2 ? indentation(indent) + "<" + type2 + ">\n" : indentation(indent) + "<" + type2 + "\n" + content2 + indentation(indent) + ">\n";
      }
      type2 = serverProps.children;
      clientProps = clientProps.children;
      if ("string" === typeof type2 || "number" === typeof type2 || "bigint" === typeof type2) {
        serverPropNames = "";
        if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
          serverPropNames = "" + clientProps;
        content2 += describeTextDiff(serverPropNames, "" + type2, indent + 1);
      } else if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
        content2 = null == type2 ? content2 + describeTextDiff("" + clientProps, null, indent + 1) : content2 + describeTextDiff("" + clientProps, void 0, indent + 1);
      return content2;
    }
    function describeSiblingFiber(fiber, indent) {
      var type2 = describeFiberType(fiber);
      if (null === type2) {
        type2 = "";
        for (fiber = fiber.child; fiber; )
          type2 += describeSiblingFiber(fiber, indent), fiber = fiber.sibling;
        return type2;
      }
      return indentation(indent) + "<" + type2 + ">\n";
    }
    function describeNode(node2, indent) {
      var skipToNode = findNotableNode(node2, indent);
      if (skipToNode !== node2 && (1 !== node2.children.length || node2.children[0] !== skipToNode))
        return indentation(indent) + "...\n" + describeNode(skipToNode, indent + 1);
      skipToNode = "";
      var debugInfo = node2.fiber._debugInfo;
      if (debugInfo)
        for (var i = 0; i < debugInfo.length; i++) {
          var serverComponentName = debugInfo[i].name;
          "string" === typeof serverComponentName && (skipToNode += indentation(indent) + "<" + serverComponentName + ">\n", indent++);
        }
      debugInfo = "";
      i = node2.fiber.pendingProps;
      if (6 === node2.fiber.tag)
        debugInfo = describeTextDiff(i, node2.serverProps, indent), indent++;
      else if (serverComponentName = describeFiberType(node2.fiber), null !== serverComponentName)
        if (void 0 === node2.serverProps) {
          debugInfo = indent;
          var maxLength = 120 - 2 * debugInfo - serverComponentName.length - 2, content2 = "";
          for (propName in i)
            if (i.hasOwnProperty(propName) && "children" !== propName) {
              var propValue = describePropValue(i[propName], 15);
              maxLength -= propName.length + propValue.length + 2;
              if (0 > maxLength) {
                content2 += " ...";
                break;
              }
              content2 += " " + propName + "=" + propValue;
            }
          debugInfo = indentation(debugInfo) + "<" + serverComponentName + content2 + ">\n";
          indent++;
        } else
          null === node2.serverProps ? (debugInfo = describeExpandedElement(
            serverComponentName,
            i,
            added(indent)
          ), indent++) : "string" === typeof node2.serverProps ? console.error(
            "Should not have matched a non HostText fiber to a Text node. This is a bug in React."
          ) : (debugInfo = describeElementDiff(
            serverComponentName,
            i,
            node2.serverProps,
            indent
          ), indent++);
      var propName = "";
      i = node2.fiber.child;
      for (serverComponentName = 0; i && serverComponentName < node2.children.length; )
        maxLength = node2.children[serverComponentName], maxLength.fiber === i ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i, indent), i = i.sibling;
      i && 0 < node2.children.length && (propName += indentation(indent) + "...\n");
      i = node2.serverTail;
      null === node2.serverProps && indent--;
      for (node2 = 0; node2 < i.length; node2++)
        serverComponentName = i[node2], propName = "string" === typeof serverComponentName ? propName + (removed(indent) + describeTextNode(serverComponentName, 120 - 2 * indent) + "\n") : propName + describeExpandedElement(
          serverComponentName.type,
          serverComponentName.props,
          removed(indent)
        );
      return skipToNode + debugInfo + propName;
    }
    function describeDiff(rootNode) {
      try {
        return "\n\n" + describeNode(rootNode, 0);
      } catch (x2) {
        return "";
      }
    }
    function describeAncestors(ancestor, child, props) {
      for (var fiber = child, node2 = null, distanceFromLeaf = 0; fiber; )
        fiber === ancestor && (distanceFromLeaf = 0), node2 = {
          fiber,
          children: null !== node2 ? [node2] : [],
          serverProps: fiber === child ? props : fiber === ancestor ? null : void 0,
          serverTail: [],
          distanceFromLeaf
        }, distanceFromLeaf++, fiber = fiber.return;
      return null !== node2 ? describeDiff(node2).replaceAll(/^[+-]/gm, ">") : "";
    }
    function updatedAncestorInfoDev(oldInfo, tag) {
      var ancestorInfo = assign({}, oldInfo || emptyAncestorInfoDev), info = { tag };
      -1 !== inScopeTags.indexOf(tag) && (ancestorInfo.aTagInScope = null, ancestorInfo.buttonTagInScope = null, ancestorInfo.nobrTagInScope = null);
      -1 !== buttonScopeTags.indexOf(tag) && (ancestorInfo.pTagInButtonScope = null);
      -1 !== specialTags.indexOf(tag) && "address" !== tag && "div" !== tag && "p" !== tag && (ancestorInfo.listItemTagAutoclosing = null, ancestorInfo.dlItemTagAutoclosing = null);
      ancestorInfo.current = info;
      "form" === tag && (ancestorInfo.formTag = info);
      "a" === tag && (ancestorInfo.aTagInScope = info);
      "button" === tag && (ancestorInfo.buttonTagInScope = info);
      "nobr" === tag && (ancestorInfo.nobrTagInScope = info);
      "p" === tag && (ancestorInfo.pTagInButtonScope = info);
      "li" === tag && (ancestorInfo.listItemTagAutoclosing = info);
      if ("dd" === tag || "dt" === tag)
        ancestorInfo.dlItemTagAutoclosing = info;
      "#document" === tag || "html" === tag ? ancestorInfo.containerTagInScope = null : ancestorInfo.containerTagInScope || (ancestorInfo.containerTagInScope = info);
      null !== oldInfo || "#document" !== tag && "html" !== tag && "body" !== tag ? true === ancestorInfo.implicitRootScope && (ancestorInfo.implicitRootScope = false) : ancestorInfo.implicitRootScope = true;
      return ancestorInfo;
    }
    function isTagValidWithParent(tag, parentTag, implicitRootScope) {
      switch (parentTag) {
        case "select":
          return "hr" === tag || "option" === tag || "optgroup" === tag || "script" === tag || "template" === tag || "#text" === tag;
        case "optgroup":
          return "option" === tag || "#text" === tag;
        case "option":
          return "#text" === tag;
        case "tr":
          return "th" === tag || "td" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "tbody":
        case "thead":
        case "tfoot":
          return "tr" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "colgroup":
          return "col" === tag || "template" === tag;
        case "table":
          return "caption" === tag || "colgroup" === tag || "tbody" === tag || "tfoot" === tag || "thead" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "head":
          return "base" === tag || "basefont" === tag || "bgsound" === tag || "link" === tag || "meta" === tag || "title" === tag || "noscript" === tag || "noframes" === tag || "style" === tag || "script" === tag || "template" === tag;
        case "html":
          if (implicitRootScope) break;
          return "head" === tag || "body" === tag || "frameset" === tag;
        case "frameset":
          return "frame" === tag;
        case "#document":
          if (!implicitRootScope) return "html" === tag;
      }
      switch (tag) {
        case "h1":
        case "h2":
        case "h3":
        case "h4":
        case "h5":
        case "h6":
          return "h1" !== parentTag && "h2" !== parentTag && "h3" !== parentTag && "h4" !== parentTag && "h5" !== parentTag && "h6" !== parentTag;
        case "rp":
        case "rt":
          return -1 === impliedEndTags.indexOf(parentTag);
        case "caption":
        case "col":
        case "colgroup":
        case "frameset":
        case "frame":
        case "tbody":
        case "td":
        case "tfoot":
        case "th":
        case "thead":
        case "tr":
          return null == parentTag;
        case "head":
          return implicitRootScope || null === parentTag;
        case "html":
          return implicitRootScope && "#document" === parentTag || null === parentTag;
        case "body":
          return implicitRootScope && ("#document" === parentTag || "html" === parentTag) || null === parentTag;
      }
      return true;
    }
    function findInvalidAncestorForTag(tag, ancestorInfo) {
      switch (tag) {
        case "address":
        case "article":
        case "aside":
        case "blockquote":
        case "center":
        case "details":
        case "dialog":
        case "dir":
        case "div":
        case "dl":
        case "fieldset":
        case "figcaption":
        case "figure":
        case "footer":
        case "header":
        case "hgroup":
        case "main":
        case "menu":
        case "nav":
        case "ol":
        case "p":
        case "section":
        case "summary":
        case "ul":
        case "pre":
        case "listing":
        case "table":
        case "hr":
        case "xmp":
        case "h1":
        case "h2":
        case "h3":
        case "h4":
        case "h5":
        case "h6":
          return ancestorInfo.pTagInButtonScope;
        case "form":
          return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
        case "li":
          return ancestorInfo.listItemTagAutoclosing;
        case "dd":
        case "dt":
          return ancestorInfo.dlItemTagAutoclosing;
        case "button":
          return ancestorInfo.buttonTagInScope;
        case "a":
          return ancestorInfo.aTagInScope;
        case "nobr":
          return ancestorInfo.nobrTagInScope;
      }
      return null;
    }
    function findAncestor(parent, tagName) {
      for (; parent; ) {
        switch (parent.tag) {
          case 5:
          case 26:
          case 27:
            if (parent.type === tagName) return parent;
        }
        parent = parent.return;
      }
      return null;
    }
    function validateDOMNesting(childTag, ancestorInfo) {
      ancestorInfo = ancestorInfo || emptyAncestorInfoDev;
      var parentInfo = ancestorInfo.current;
      ancestorInfo = (parentInfo = isTagValidWithParent(
        childTag,
        parentInfo && parentInfo.tag,
        ancestorInfo.implicitRootScope
      ) ? null : parentInfo) ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
      ancestorInfo = parentInfo || ancestorInfo;
      if (!ancestorInfo) return true;
      var ancestorTag = ancestorInfo.tag;
      ancestorInfo = String(!!parentInfo) + "|" + childTag + "|" + ancestorTag;
      if (didWarn[ancestorInfo]) return false;
      didWarn[ancestorInfo] = true;
      var ancestor = (ancestorInfo = current) ? findAncestor(ancestorInfo.return, ancestorTag) : null, ancestorDescription = null !== ancestorInfo && null !== ancestor ? describeAncestors(ancestor, ancestorInfo, null) : "", tagDisplayName = "<" + childTag + ">";
      parentInfo ? (parentInfo = "", "table" === ancestorTag && "tr" === childTag && (parentInfo += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser."), console.error(
        "In HTML, %s cannot be a child of <%s>.%s\nThis will cause a hydration error.%s",
        tagDisplayName,
        ancestorTag,
        parentInfo,
        ancestorDescription
      )) : console.error(
        "In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s",
        tagDisplayName,
        ancestorTag,
        ancestorDescription
      );
      ancestorInfo && (childTag = ancestorInfo.return, null === ancestor || null === childTag || ancestor === childTag && childTag._debugOwner === ancestorInfo._debugOwner || runWithFiberInDEV(ancestor, function() {
        console.error(
          "<%s> cannot contain a nested %s.\nSee this log for the ancestor stack trace.",
          ancestorTag,
          tagDisplayName
        );
      }));
      return false;
    }
    function validateTextNesting(childText, parentTag, implicitRootScope) {
      if (implicitRootScope || isTagValidWithParent("#text", parentTag, false))
        return true;
      implicitRootScope = "#text|" + parentTag;
      if (didWarn[implicitRootScope]) return false;
      didWarn[implicitRootScope] = true;
      var ancestor = (implicitRootScope = current) ? findAncestor(implicitRootScope, parentTag) : null;
      implicitRootScope = null !== implicitRootScope && null !== ancestor ? describeAncestors(
        ancestor,
        implicitRootScope,
        6 !== implicitRootScope.tag ? { children: null } : null
      ) : "";
      /\S/.test(childText) ? console.error(
        "In HTML, text nodes cannot be a child of <%s>.\nThis will cause a hydration error.%s",
        parentTag,
        implicitRootScope
      ) : console.error(
        "In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.%s",
        parentTag,
        implicitRootScope
      );
      return false;
    }
    function setTextContent(node2, text2) {
      if (text2) {
        var firstChild = node2.firstChild;
        if (firstChild && firstChild === node2.lastChild && 3 === firstChild.nodeType) {
          firstChild.nodeValue = text2;
          return;
        }
      }
      node2.textContent = text2;
    }
    function camelize(string2) {
      return string2.replace(hyphenPattern, function(_2, character) {
        return character.toUpperCase();
      });
    }
    function setValueForStyle(style2, styleName, value) {
      var isCustomProperty = 0 === styleName.indexOf("--");
      isCustomProperty || (-1 < styleName.indexOf("-") ? warnedStyleNames.hasOwnProperty(styleName) && warnedStyleNames[styleName] || (warnedStyleNames[styleName] = true, console.error(
        "Unsupported style property %s. Did you mean %s?",
        styleName,
        camelize(styleName.replace(msPattern, "ms-"))
      )) : badVendoredStyleNamePattern.test(styleName) ? warnedStyleNames.hasOwnProperty(styleName) && warnedStyleNames[styleName] || (warnedStyleNames[styleName] = true, console.error(
        "Unsupported vendor-prefixed style property %s. Did you mean %s?",
        styleName,
        styleName.charAt(0).toUpperCase() + styleName.slice(1)
      )) : !badStyleValueWithSemicolonPattern.test(value) || warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value] || (warnedStyleValues[value] = true, console.error(
        `Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`,
        styleName,
        value.replace(badStyleValueWithSemicolonPattern, "")
      )), "number" === typeof value && (isNaN(value) ? warnedForNaNValue || (warnedForNaNValue = true, console.error(
        "`NaN` is an invalid value for the `%s` css style property.",
        styleName
      )) : isFinite(value) || warnedForInfinityValue || (warnedForInfinityValue = true, console.error(
        "`Infinity` is an invalid value for the `%s` css style property.",
        styleName
      ))));
      null == value || "boolean" === typeof value || "" === value ? isCustomProperty ? style2.setProperty(styleName, "") : "float" === styleName ? style2.cssFloat = "" : style2[styleName] = "" : isCustomProperty ? style2.setProperty(styleName, value) : "number" !== typeof value || 0 === value || unitlessNumbers.has(styleName) ? "float" === styleName ? style2.cssFloat = value : (checkCSSPropertyStringCoercion(value, styleName), style2[styleName] = ("" + value).trim()) : style2[styleName] = value + "px";
    }
    function setValueForStyles(node2, styles2, prevStyles) {
      if (null != styles2 && "object" !== typeof styles2)
        throw Error(
          "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
        );
      styles2 && Object.freeze(styles2);
      node2 = node2.style;
      if (null != prevStyles) {
        if (styles2) {
          var expandedUpdates = {};
          if (prevStyles) {
            for (var key in prevStyles)
              if (prevStyles.hasOwnProperty(key) && !styles2.hasOwnProperty(key))
                for (var longhands = shorthandToLonghand[key] || [key], i = 0; i < longhands.length; i++)
                  expandedUpdates[longhands[i]] = key;
          }
          for (var _key in styles2)
            if (styles2.hasOwnProperty(_key) && (!prevStyles || prevStyles[_key] !== styles2[_key]))
              for (key = shorthandToLonghand[_key] || [_key], longhands = 0; longhands < key.length; longhands++)
                expandedUpdates[key[longhands]] = _key;
          _key = {};
          for (var key$jscomp$0 in styles2)
            for (key = shorthandToLonghand[key$jscomp$0] || [key$jscomp$0], longhands = 0; longhands < key.length; longhands++)
              _key[key[longhands]] = key$jscomp$0;
          key$jscomp$0 = {};
          for (var _key2 in expandedUpdates)
            if (key = expandedUpdates[_key2], (longhands = _key[_key2]) && key !== longhands && (i = key + "," + longhands, !key$jscomp$0[i])) {
              key$jscomp$0[i] = true;
              i = console;
              var value = styles2[key];
              i.error.call(
                i,
                "%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.",
                null == value || "boolean" === typeof value || "" === value ? "Removing" : "Updating",
                key,
                longhands
              );
            }
        }
        for (var styleName in prevStyles)
          !prevStyles.hasOwnProperty(styleName) || null != styles2 && styles2.hasOwnProperty(styleName) || (0 === styleName.indexOf("--") ? node2.setProperty(styleName, "") : "float" === styleName ? node2.cssFloat = "" : node2[styleName] = "");
        for (var _styleName in styles2)
          _key2 = styles2[_styleName], styles2.hasOwnProperty(_styleName) && prevStyles[_styleName] !== _key2 && setValueForStyle(node2, _styleName, _key2);
      } else
        for (expandedUpdates in styles2)
          styles2.hasOwnProperty(expandedUpdates) && setValueForStyle(node2, expandedUpdates, styles2[expandedUpdates]);
    }
    function isCustomElement(tagName) {
      if (-1 === tagName.indexOf("-")) return false;
      switch (tagName) {
        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;
      }
    }
    function getAttributeAlias(name2) {
      return aliases.get(name2) || name2;
    }
    function validateProperty$1(tagName, name2) {
      if (hasOwnProperty2.call(warnedProperties$1, name2) && warnedProperties$1[name2])
        return true;
      if (rARIACamel$1.test(name2)) {
        tagName = "aria-" + name2.slice(4).toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.",
            name2
          ), warnedProperties$1[name2] = true;
        if (name2 !== tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. Did you mean `%s`?",
            name2,
            tagName
          ), warnedProperties$1[name2] = true;
      }
      if (rARIA$1.test(name2)) {
        tagName = name2.toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName) return warnedProperties$1[name2] = true, false;
        name2 !== tagName && (console.error(
          "Unknown ARIA attribute `%s`. Did you mean `%s`?",
          name2,
          tagName
        ), warnedProperties$1[name2] = true);
      }
      return true;
    }
    function validateProperties$2(type2, props) {
      var invalidProps = [], key;
      for (key in props)
        validateProperty$1(type2, key) || invalidProps.push(key);
      props = invalidProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === invalidProps.length ? console.error(
        "Invalid aria prop %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type2
      ) : 1 < invalidProps.length && console.error(
        "Invalid aria props %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type2
      );
    }
    function validateProperty(tagName, name2, value, eventRegistry) {
      if (hasOwnProperty2.call(warnedProperties, name2) && warnedProperties[name2])
        return true;
      var lowerCasedName = name2.toLowerCase();
      if ("onfocusin" === lowerCasedName || "onfocusout" === lowerCasedName)
        return console.error(
          "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."
        ), warnedProperties[name2] = true;
      if ("function" === typeof value && ("form" === tagName && "action" === name2 || "input" === tagName && "formAction" === name2 || "button" === tagName && "formAction" === name2))
        return true;
      if (null != eventRegistry) {
        tagName = eventRegistry.possibleRegistrationNames;
        if (eventRegistry.registrationNameDependencies.hasOwnProperty(name2))
          return true;
        eventRegistry = tagName.hasOwnProperty(lowerCasedName) ? tagName[lowerCasedName] : null;
        if (null != eventRegistry)
          return console.error(
            "Invalid event handler property `%s`. Did you mean `%s`?",
            name2,
            eventRegistry
          ), warnedProperties[name2] = true;
        if (EVENT_NAME_REGEX.test(name2))
          return console.error(
            "Unknown event handler property `%s`. It will be ignored.",
            name2
          ), warnedProperties[name2] = true;
      } else if (EVENT_NAME_REGEX.test(name2))
        return INVALID_EVENT_NAME_REGEX.test(name2) && console.error(
          "Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.",
          name2
        ), warnedProperties[name2] = true;
      if (rARIA.test(name2) || rARIACamel.test(name2)) return true;
      if ("innerhtml" === lowerCasedName)
        return console.error(
          "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."
        ), warnedProperties[name2] = true;
      if ("aria" === lowerCasedName)
        return console.error(
          "The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."
        ), warnedProperties[name2] = true;
      if ("is" === lowerCasedName && null !== value && void 0 !== value && "string" !== typeof value)
        return console.error(
          "Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.",
          typeof value
        ), warnedProperties[name2] = true;
      if ("number" === typeof value && isNaN(value))
        return console.error(
          "Received NaN for the `%s` attribute. If this is expected, cast the value to a string.",
          name2
        ), warnedProperties[name2] = true;
      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        if (lowerCasedName = possibleStandardNames[lowerCasedName], lowerCasedName !== name2)
          return console.error(
            "Invalid DOM property `%s`. Did you mean `%s`?",
            name2,
            lowerCasedName
          ), warnedProperties[name2] = true;
      } else if (name2 !== lowerCasedName)
        return console.error(
          "React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.",
          name2,
          lowerCasedName
        ), warnedProperties[name2] = true;
      switch (name2) {
        case "dangerouslySetInnerHTML":
        case "children":
        case "style":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          return true;
        case "innerText":
        case "textContent":
          return true;
      }
      switch (typeof value) {
        case "boolean":
          switch (name2) {
            case "autoFocus":
            case "checked":
            case "multiple":
            case "muted":
            case "selected":
            case "contentEditable":
            case "spellCheck":
            case "draggable":
            case "value":
            case "autoReverse":
            case "externalResourcesRequired":
            case "focusable":
            case "preserveAlpha":
            case "allowFullScreen":
            case "async":
            case "autoPlay":
            case "controls":
            case "default":
            case "defer":
            case "disabled":
            case "disablePictureInPicture":
            case "disableRemotePlayback":
            case "formNoValidate":
            case "hidden":
            case "loop":
            case "noModule":
            case "noValidate":
            case "open":
            case "playsInline":
            case "readOnly":
            case "required":
            case "reversed":
            case "scoped":
            case "seamless":
            case "itemScope":
            case "capture":
            case "download":
            case "inert":
              return true;
            default:
              lowerCasedName = name2.toLowerCase().slice(0, 5);
              if ("data-" === lowerCasedName || "aria-" === lowerCasedName)
                return true;
              value ? console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.',
                value,
                name2,
                name2,
                value,
                name2
              ) : console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.',
                value,
                name2,
                name2,
                value,
                name2,
                name2,
                name2
              );
              return warnedProperties[name2] = true;
          }
        case "function":
        case "symbol":
          return warnedProperties[name2] = true, false;
        case "string":
          if ("false" === value || "true" === value) {
            switch (name2) {
              case "checked":
              case "selected":
              case "multiple":
              case "muted":
              case "allowFullScreen":
              case "async":
              case "autoPlay":
              case "controls":
              case "default":
              case "defer":
              case "disabled":
              case "disablePictureInPicture":
              case "disableRemotePlayback":
              case "formNoValidate":
              case "hidden":
              case "loop":
              case "noModule":
              case "noValidate":
              case "open":
              case "playsInline":
              case "readOnly":
              case "required":
              case "reversed":
              case "scoped":
              case "seamless":
              case "itemScope":
              case "inert":
                break;
              default:
                return true;
            }
            console.error(
              "Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?",
              value,
              name2,
              "false" === value ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".',
              name2,
              value
            );
            warnedProperties[name2] = true;
          }
      }
      return true;
    }
    function warnUnknownProperties(type2, props, eventRegistry) {
      var unknownProps = [], key;
      for (key in props)
        validateProperty(type2, key, props[key], eventRegistry) || unknownProps.push(key);
      props = unknownProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === unknownProps.length ? console.error(
        "Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type2
      ) : 1 < unknownProps.length && console.error(
        "Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type2
      );
    }
    function sanitizeURL(url) {
      return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
    }
    function noop$1() {
    }
    function getEventTarget(nativeEvent) {
      nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;
      nativeEvent.correspondingUseElement && (nativeEvent = nativeEvent.correspondingUseElement);
      return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;
    }
    function restoreStateOfTarget(target) {
      var internalInstance = getInstanceFromNode(target);
      if (internalInstance && (target = internalInstance.stateNode)) {
        var props = target[internalPropsKey] || null;
        a: switch (target = internalInstance.stateNode, internalInstance.type) {
          case "input":
            updateInput(
              target,
              props.value,
              props.defaultValue,
              props.defaultValue,
              props.checked,
              props.defaultChecked,
              props.type,
              props.name
            );
            internalInstance = props.name;
            if ("radio" === props.type && null != internalInstance) {
              for (props = target; props.parentNode; ) props = props.parentNode;
              checkAttributeStringCoercion(internalInstance, "name");
              props = props.querySelectorAll(
                'input[name="' + escapeSelectorAttributeValueInsideDoubleQuotes(
                  "" + internalInstance
                ) + '"][type="radio"]'
              );
              for (internalInstance = 0; internalInstance < props.length; internalInstance++) {
                var otherNode = props[internalInstance];
                if (otherNode !== target && otherNode.form === target.form) {
                  var otherProps = otherNode[internalPropsKey] || null;
                  if (!otherProps)
                    throw Error(
                      "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."
                    );
                  updateInput(
                    otherNode,
                    otherProps.value,
                    otherProps.defaultValue,
                    otherProps.defaultValue,
                    otherProps.checked,
                    otherProps.defaultChecked,
                    otherProps.type,
                    otherProps.name
                  );
                }
              }
              for (internalInstance = 0; internalInstance < props.length; internalInstance++)
                otherNode = props[internalInstance], otherNode.form === target.form && updateValueIfChanged(otherNode);
            }
            break a;
          case "textarea":
            updateTextarea(target, props.value, props.defaultValue);
            break a;
          case "select":
            internalInstance = props.value, null != internalInstance && updateOptions(target, !!props.multiple, internalInstance, false);
        }
      }
    }
    function batchedUpdates$1(fn, a, b2) {
      if (isInsideEventHandler) return fn(a, b2);
      isInsideEventHandler = true;
      try {
        var JSCompiler_inline_result = fn(a);
        return JSCompiler_inline_result;
      } finally {
        if (isInsideEventHandler = false, null !== restoreTarget || null !== restoreQueue) {
          if (flushSyncWork$1(), restoreTarget && (a = restoreTarget, fn = restoreQueue, restoreQueue = restoreTarget = null, restoreStateOfTarget(a), fn))
            for (a = 0; a < fn.length; a++) restoreStateOfTarget(fn[a]);
        }
      }
    }
    function getListener(inst, registrationName) {
      var stateNode = inst.stateNode;
      if (null === stateNode) return null;
      var props = stateNode[internalPropsKey] || null;
      if (null === props) return null;
      stateNode = props[registrationName];
      a: switch (registrationName) {
        case "onClick":
        case "onClickCapture":
        case "onDoubleClick":
        case "onDoubleClickCapture":
        case "onMouseDown":
        case "onMouseDownCapture":
        case "onMouseMove":
        case "onMouseMoveCapture":
        case "onMouseUp":
        case "onMouseUpCapture":
        case "onMouseEnter":
          (props = !props.disabled) || (inst = inst.type, props = !("button" === inst || "input" === inst || "select" === inst || "textarea" === inst));
          inst = !props;
          break a;
        default:
          inst = false;
      }
      if (inst) return null;
      if (stateNode && "function" !== typeof stateNode)
        throw Error(
          "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof stateNode + "` type."
        );
      return stateNode;
    }
    function getData() {
      if (fallbackText) return fallbackText;
      var start, startValue = startText, startLength = startValue.length, end, endValue = "value" in root2 ? root2.value : root2.textContent, endLength = endValue.length;
      for (start = 0; start < startLength && startValue[start] === endValue[start]; start++) ;
      var minEnd = startLength - start;
      for (end = 1; end <= minEnd && startValue[startLength - end] === endValue[endLength - end]; end++) ;
      return fallbackText = endValue.slice(start, 1 < end ? 1 - end : void 0);
    }
    function getEventCharCode(nativeEvent) {
      var keyCode = nativeEvent.keyCode;
      "charCode" in nativeEvent ? (nativeEvent = nativeEvent.charCode, 0 === nativeEvent && 13 === keyCode && (nativeEvent = 13)) : nativeEvent = keyCode;
      10 === nativeEvent && (nativeEvent = 13);
      return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;
    }
    function functionThatReturnsTrue() {
      return true;
    }
    function functionThatReturnsFalse() {
      return false;
    }
    function createSyntheticEvent(Interface) {
      function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
        this._reactName = reactName;
        this._targetInst = targetInst;
        this.type = reactEventType;
        this.nativeEvent = nativeEvent;
        this.target = nativeEventTarget;
        this.currentTarget = null;
        for (var propName in Interface)
          Interface.hasOwnProperty(propName) && (reactName = Interface[propName], this[propName] = reactName ? reactName(nativeEvent) : nativeEvent[propName]);
        this.isDefaultPrevented = (null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : false === nativeEvent.returnValue) ? functionThatReturnsTrue : functionThatReturnsFalse;
        this.isPropagationStopped = functionThatReturnsFalse;
        return this;
      }
      assign(SyntheticBaseEvent.prototype, {
        preventDefault: function() {
          this.defaultPrevented = true;
          var event = this.nativeEvent;
          event && (event.preventDefault ? event.preventDefault() : "unknown" !== typeof event.returnValue && (event.returnValue = false), this.isDefaultPrevented = functionThatReturnsTrue);
        },
        stopPropagation: function() {
          var event = this.nativeEvent;
          event && (event.stopPropagation ? event.stopPropagation() : "unknown" !== typeof event.cancelBubble && (event.cancelBubble = true), this.isPropagationStopped = functionThatReturnsTrue);
        },
        persist: function() {
        },
        isPersistent: functionThatReturnsTrue
      });
      return SyntheticBaseEvent;
    }
    function modifierStateGetter(keyArg) {
      var nativeEvent = this.nativeEvent;
      return nativeEvent.getModifierState ? nativeEvent.getModifierState(keyArg) : (keyArg = modifierKeyToProp[keyArg]) ? !!nativeEvent[keyArg] : false;
    }
    function getEventModifierState() {
      return modifierStateGetter;
    }
    function isFallbackCompositionEnd(domEventName, nativeEvent) {
      switch (domEventName) {
        case "keyup":
          return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
        case "keydown":
          return nativeEvent.keyCode !== START_KEYCODE;
        case "keypress":
        case "mousedown":
        case "focusout":
          return true;
        default:
          return false;
      }
    }
    function getDataFromCustomEvent(nativeEvent) {
      nativeEvent = nativeEvent.detail;
      return "object" === typeof nativeEvent && "data" in nativeEvent ? nativeEvent.data : null;
    }
    function getNativeBeforeInputChars(domEventName, nativeEvent) {
      switch (domEventName) {
        case "compositionend":
          return getDataFromCustomEvent(nativeEvent);
        case "keypress":
          if (nativeEvent.which !== SPACEBAR_CODE) return null;
          hasSpaceKeypress = true;
          return SPACEBAR_CHAR;
        case "textInput":
          return domEventName = nativeEvent.data, domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName;
        default:
          return null;
      }
    }
    function getFallbackBeforeInputChars(domEventName, nativeEvent) {
      if (isComposing)
        return "compositionend" === domEventName || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent) ? (domEventName = getData(), fallbackText = startText = root2 = null, isComposing = false, domEventName) : null;
      switch (domEventName) {
        case "paste":
          return null;
        case "keypress":
          if (!(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) || nativeEvent.ctrlKey && nativeEvent.altKey) {
            if (nativeEvent.char && 1 < nativeEvent.char.length)
              return nativeEvent.char;
            if (nativeEvent.which)
              return String.fromCharCode(nativeEvent.which);
          }
          return null;
        case "compositionend":
          return useFallbackCompositionData && "ko" !== nativeEvent.locale ? null : nativeEvent.data;
        default:
          return null;
      }
    }
    function isTextInputElement(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return "input" === nodeName ? !!supportedInputTypes[elem.type] : "textarea" === nodeName ? true : false;
    }
    function isEventSupported(eventNameSuffix) {
      if (!canUseDOM) return false;
      eventNameSuffix = "on" + eventNameSuffix;
      var isSupported = eventNameSuffix in document;
      isSupported || (isSupported = document.createElement("div"), isSupported.setAttribute(eventNameSuffix, "return;"), isSupported = "function" === typeof isSupported[eventNameSuffix]);
      return isSupported;
    }
    function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target) {
      restoreTarget ? restoreQueue ? restoreQueue.push(target) : restoreQueue = [target] : restoreTarget = target;
      inst = accumulateTwoPhaseListeners(inst, "onChange");
      0 < inst.length && (nativeEvent = new SyntheticEvent(
        "onChange",
        "change",
        null,
        nativeEvent,
        target
      ), dispatchQueue.push({ event: nativeEvent, listeners: inst }));
    }
    function runEventInBatch(dispatchQueue) {
      processDispatchQueue(dispatchQueue, 0);
    }
    function getInstIfValueChanged(targetInst) {
      var targetNode = getNodeFromInstance(targetInst);
      if (updateValueIfChanged(targetNode)) return targetInst;
    }
    function getTargetInstForChangeEvent(domEventName, targetInst) {
      if ("change" === domEventName) return targetInst;
    }
    function stopWatchingForValueChange() {
      activeElement$1 && (activeElement$1.detachEvent("onpropertychange", handlePropertyChange), activeElementInst$1 = activeElement$1 = null);
    }
    function handlePropertyChange(nativeEvent) {
      if ("value" === nativeEvent.propertyName && getInstIfValueChanged(activeElementInst$1)) {
        var dispatchQueue = [];
        createAndAccumulateChangeEvent(
          dispatchQueue,
          activeElementInst$1,
          nativeEvent,
          getEventTarget(nativeEvent)
        );
        batchedUpdates$1(runEventInBatch, dispatchQueue);
      }
    }
    function handleEventsForInputEventPolyfill(domEventName, target, targetInst) {
      "focusin" === domEventName ? (stopWatchingForValueChange(), activeElement$1 = target, activeElementInst$1 = targetInst, activeElement$1.attachEvent("onpropertychange", handlePropertyChange)) : "focusout" === domEventName && stopWatchingForValueChange();
    }
    function getTargetInstForInputEventPolyfill(domEventName) {
      if ("selectionchange" === domEventName || "keyup" === domEventName || "keydown" === domEventName)
        return getInstIfValueChanged(activeElementInst$1);
    }
    function getTargetInstForClickEvent(domEventName, targetInst) {
      if ("click" === domEventName) return getInstIfValueChanged(targetInst);
    }
    function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
      if ("input" === domEventName || "change" === domEventName)
        return getInstIfValueChanged(targetInst);
    }
    function is(x2, y2) {
      return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
    }
    function shallowEqual(objA, objB) {
      if (objectIs(objA, objB)) return true;
      if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
        return false;
      var keysA = Object.keys(objA), keysB = Object.keys(objB);
      if (keysA.length !== keysB.length) return false;
      for (keysB = 0; keysB < keysA.length; keysB++) {
        var currentKey = keysA[keysB];
        if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
          return false;
      }
      return true;
    }
    function getLeafNode(node2) {
      for (; node2 && node2.firstChild; ) node2 = node2.firstChild;
      return node2;
    }
    function getNodeForCharacterOffset(root3, offset) {
      var node2 = getLeafNode(root3);
      root3 = 0;
      for (var nodeEnd; node2; ) {
        if (3 === node2.nodeType) {
          nodeEnd = root3 + node2.textContent.length;
          if (root3 <= offset && nodeEnd >= offset)
            return { node: node2, offset: offset - root3 };
          root3 = nodeEnd;
        }
        a: {
          for (; node2; ) {
            if (node2.nextSibling) {
              node2 = node2.nextSibling;
              break a;
            }
            node2 = node2.parentNode;
          }
          node2 = void 0;
        }
        node2 = getLeafNode(node2);
      }
    }
    function containsNode(outerNode, innerNode) {
      return outerNode && innerNode ? outerNode === innerNode ? true : outerNode && 3 === outerNode.nodeType ? false : innerNode && 3 === innerNode.nodeType ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(outerNode.compareDocumentPosition(innerNode) & 16) : false : false;
    }
    function getActiveElementDeep(containerInfo) {
      containerInfo = null != containerInfo && null != containerInfo.ownerDocument && null != containerInfo.ownerDocument.defaultView ? containerInfo.ownerDocument.defaultView : window;
      for (var element2 = getActiveElement(containerInfo.document); element2 instanceof containerInfo.HTMLIFrameElement; ) {
        try {
          var JSCompiler_inline_result = "string" === typeof element2.contentWindow.location.href;
        } catch (err) {
          JSCompiler_inline_result = false;
        }
        if (JSCompiler_inline_result) containerInfo = element2.contentWindow;
        else break;
        element2 = getActiveElement(containerInfo.document);
      }
      return element2;
    }
    function hasSelectionCapabilities(elem) {
      var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
      return nodeName && ("input" === nodeName && ("text" === elem.type || "search" === elem.type || "tel" === elem.type || "url" === elem.type || "password" === elem.type) || "textarea" === nodeName || "true" === elem.contentEditable);
    }
    function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
      var doc = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : 9 === nativeEventTarget.nodeType ? nativeEventTarget : nativeEventTarget.ownerDocument;
      mouseDown || null == activeElement || activeElement !== getActiveElement(doc) || (doc = activeElement, "selectionStart" in doc && hasSelectionCapabilities(doc) ? doc = { start: doc.selectionStart, end: doc.selectionEnd } : (doc = (doc.ownerDocument && doc.ownerDocument.defaultView || window).getSelection(), doc = {
        anchorNode: doc.anchorNode,
        anchorOffset: doc.anchorOffset,
        focusNode: doc.focusNode,
        focusOffset: doc.focusOffset
      }), lastSelection && shallowEqual(lastSelection, doc) || (lastSelection = doc, doc = accumulateTwoPhaseListeners(activeElementInst, "onSelect"), 0 < doc.length && (nativeEvent = new SyntheticEvent(
        "onSelect",
        "select",
        null,
        nativeEvent,
        nativeEventTarget
      ), dispatchQueue.push({ event: nativeEvent, listeners: doc }), nativeEvent.target = activeElement)));
    }
    function makePrefixMap(styleProp, eventName) {
      var prefixes = {};
      prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
      prefixes["Webkit" + styleProp] = "webkit" + eventName;
      prefixes["Moz" + styleProp] = "moz" + eventName;
      return prefixes;
    }
    function getVendorPrefixedEventName(eventName) {
      if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
      if (!vendorPrefixes[eventName]) return eventName;
      var prefixMap = vendorPrefixes[eventName], styleProp;
      for (styleProp in prefixMap)
        if (prefixMap.hasOwnProperty(styleProp) && styleProp in style)
          return prefixedEventNames[eventName] = prefixMap[styleProp];
      return eventName;
    }
    function registerSimpleEvent(domEventName, reactName) {
      topLevelEventsToReactNames.set(domEventName, reactName);
      registerTwoPhaseEvent(reactName, [domEventName]);
    }
    function getArrayKind(array) {
      for (var kind = EMPTY_ARRAY, i = 0; i < array.length; i++) {
        var value = array[i];
        if ("object" === typeof value && null !== value)
          if (isArrayImpl(value) && 2 === value.length && "string" === typeof value[0]) {
            if (kind !== EMPTY_ARRAY && kind !== ENTRIES_ARRAY)
              return COMPLEX_ARRAY;
            kind = ENTRIES_ARRAY;
          } else return COMPLEX_ARRAY;
        else {
          if ("function" === typeof value || "string" === typeof value && 50 < value.length || kind !== EMPTY_ARRAY && kind !== PRIMITIVE_ARRAY)
            return COMPLEX_ARRAY;
          kind = PRIMITIVE_ARRAY;
        }
      }
      return kind;
    }
    function addObjectToProperties(object, properties, indent, prefix2) {
      for (var key in object)
        hasOwnProperty2.call(object, key) && "_" !== key[0] && addValueToProperties(key, object[key], properties, indent, prefix2);
    }
    function addValueToProperties(propertyName, value, properties, indent, prefix2) {
      switch (typeof value) {
        case "object":
          if (null === value) {
            value = "null";
            break;
          } else {
            if (value.$$typeof === REACT_ELEMENT_TYPE) {
              var typeName2 = getComponentNameFromType(value.type) || "…", key = value.key;
              value = value.props;
              var propsKeys = Object.keys(value), propsLength = propsKeys.length;
              if (null == key && 0 === propsLength) {
                value = "<" + typeName2 + " />";
                break;
              }
              if (3 > indent || 1 === propsLength && "children" === propsKeys[0] && null == key) {
                value = "<" + typeName2 + " … />";
                break;
              }
              properties.push([
                prefix2 + "  ".repeat(indent) + propertyName,
                "<" + typeName2
              ]);
              null !== key && addValueToProperties(
                "key",
                key,
                properties,
                indent + 1,
                prefix2
              );
              propertyName = false;
              for (var propKey in value)
                "children" === propKey ? null != value.children && (!isArrayImpl(value.children) || 0 < value.children.length) && (propertyName = true) : hasOwnProperty2.call(value, propKey) && "_" !== propKey[0] && addValueToProperties(
                  propKey,
                  value[propKey],
                  properties,
                  indent + 1,
                  prefix2
                );
              properties.push([
                "",
                propertyName ? ">…</" + typeName2 + ">" : "/>"
              ]);
              return;
            }
            typeName2 = Object.prototype.toString.call(value);
            typeName2 = typeName2.slice(8, typeName2.length - 1);
            if ("Array" === typeName2) {
              if (propKey = getArrayKind(value), propKey === PRIMITIVE_ARRAY || propKey === EMPTY_ARRAY) {
                value = JSON.stringify(value);
                break;
              } else if (propKey === ENTRIES_ARRAY) {
                properties.push([
                  prefix2 + "  ".repeat(indent) + propertyName,
                  ""
                ]);
                for (propertyName = 0; propertyName < value.length; propertyName++)
                  typeName2 = value[propertyName], addValueToProperties(
                    typeName2[0],
                    typeName2[1],
                    properties,
                    indent + 1,
                    prefix2
                  );
                return;
              }
            }
            if ("Promise" === typeName2) {
              if ("fulfilled" === value.status) {
                if (typeName2 = properties.length, addValueToProperties(
                  propertyName,
                  value.value,
                  properties,
                  indent,
                  prefix2
                ), properties.length > typeName2) {
                  properties = properties[typeName2];
                  properties[1] = "Promise<" + (properties[1] || "Object") + ">";
                  return;
                }
              } else if ("rejected" === value.status && (typeName2 = properties.length, addValueToProperties(
                propertyName,
                value.reason,
                properties,
                indent,
                prefix2
              ), properties.length > typeName2)) {
                properties = properties[typeName2];
                properties[1] = "Rejected Promise<" + properties[1] + ">";
                return;
              }
              properties.push([
                "  ".repeat(indent) + propertyName,
                "Promise"
              ]);
              return;
            }
            "Object" === typeName2 && (propKey = Object.getPrototypeOf(value)) && "function" === typeof propKey.constructor && (typeName2 = propKey.constructor.name);
            properties.push([
              prefix2 + "  ".repeat(indent) + propertyName,
              "Object" === typeName2 ? 3 > indent ? "" : "…" : typeName2
            ]);
            3 > indent && addObjectToProperties(value, properties, indent + 1, prefix2);
            return;
          }
        case "function":
          value = "" === value.name ? "() => {}" : value.name + "() {}";
          break;
        case "string":
          value = value === OMITTED_PROP_ERROR ? "…" : JSON.stringify(value);
          break;
        case "undefined":
          value = "undefined";
          break;
        case "boolean":
          value = value ? "true" : "false";
          break;
        default:
          value = String(value);
      }
      properties.push([
        prefix2 + "  ".repeat(indent) + propertyName,
        value
      ]);
    }
    function addObjectDiffToProperties(prev, next, properties, indent) {
      var isDeeplyEqual = true;
      for (key in prev)
        key in next || (properties.push([
          REMOVED + "  ".repeat(indent) + key,
          "…"
        ]), isDeeplyEqual = false);
      for (var _key in next)
        if (_key in prev) {
          var key = prev[_key];
          var nextValue = next[_key];
          if (key !== nextValue) {
            if (0 === indent && "children" === _key)
              isDeeplyEqual = "  ".repeat(indent) + _key, properties.push(
                [REMOVED + isDeeplyEqual, "…"],
                [ADDED + isDeeplyEqual, "…"]
              );
            else {
              if (!(3 <= indent)) {
                if ("object" === typeof key && "object" === typeof nextValue && null !== key && null !== nextValue && key.$$typeof === nextValue.$$typeof)
                  if (nextValue.$$typeof === REACT_ELEMENT_TYPE) {
                    if (key.type === nextValue.type && key.key === nextValue.key) {
                      key = getComponentNameFromType(nextValue.type) || "…";
                      isDeeplyEqual = "  ".repeat(indent) + _key;
                      key = "<" + key + " … />";
                      properties.push(
                        [REMOVED + isDeeplyEqual, key],
                        [ADDED + isDeeplyEqual, key]
                      );
                      isDeeplyEqual = false;
                      continue;
                    }
                  } else {
                    var prevKind = Object.prototype.toString.call(key), nextKind = Object.prototype.toString.call(nextValue);
                    if (prevKind === nextKind && ("[object Object]" === nextKind || "[object Array]" === nextKind)) {
                      prevKind = [
                        UNCHANGED + "  ".repeat(indent) + _key,
                        "[object Array]" === nextKind ? "Array" : ""
                      ];
                      properties.push(prevKind);
                      nextKind = properties.length;
                      addObjectDiffToProperties(
                        key,
                        nextValue,
                        properties,
                        indent + 1
                      ) ? nextKind === properties.length && (prevKind[1] = "Referentially unequal but deeply equal objects. Consider memoization.") : isDeeplyEqual = false;
                      continue;
                    }
                  }
                else if ("function" === typeof key && "function" === typeof nextValue && key.name === nextValue.name && key.length === nextValue.length && (prevKind = Function.prototype.toString.call(key), nextKind = Function.prototype.toString.call(nextValue), prevKind === nextKind)) {
                  key = "" === nextValue.name ? "() => {}" : nextValue.name + "() {}";
                  properties.push([
                    UNCHANGED + "  ".repeat(indent) + _key,
                    key + " Referentially unequal function closure. Consider memoization."
                  ]);
                  continue;
                }
              }
              addValueToProperties(_key, key, properties, indent, REMOVED);
              addValueToProperties(_key, nextValue, properties, indent, ADDED);
            }
            isDeeplyEqual = false;
          }
        } else
          properties.push([
            ADDED + "  ".repeat(indent) + _key,
            "…"
          ]), isDeeplyEqual = false;
      return isDeeplyEqual;
    }
    function setCurrentTrackFromLanes(lanes) {
      currentTrack = lanes & 63 ? "Blocking" : lanes & 64 ? "Gesture" : lanes & 4194176 ? "Transition" : lanes & 62914560 ? "Suspense" : lanes & 2080374784 ? "Idle" : "Other";
    }
    function logComponentTrigger(fiber, startTime, endTime, trigger) {
      supportsUserTiming && (reusableComponentOptions.start = startTime, reusableComponentOptions.end = endTime, reusableComponentDevToolDetails.color = "warning", reusableComponentDevToolDetails.tooltipText = trigger, reusableComponentDevToolDetails.properties = null, (fiber = fiber._debugTask) ? fiber.run(
        performance.measure.bind(
          performance,
          trigger,
          reusableComponentOptions
        )
      ) : performance.measure(trigger, reusableComponentOptions));
    }
    function logComponentReappeared(fiber, startTime, endTime) {
      logComponentTrigger(fiber, startTime, endTime, "Reconnect");
    }
    function logComponentRender(fiber, startTime, endTime, wasHydrated, committedLanes) {
      var name2 = getComponentNameFromFiber(fiber);
      if (null !== name2 && supportsUserTiming) {
        var alternate = fiber.alternate, selfTime = fiber.actualDuration;
        if (null === alternate || alternate.child !== fiber.child)
          for (var child = fiber.child; null !== child; child = child.sibling)
            selfTime -= child.actualDuration;
        wasHydrated = 0.5 > selfTime ? wasHydrated ? "tertiary-light" : "primary-light" : 10 > selfTime ? wasHydrated ? "tertiary" : "primary" : 100 > selfTime ? wasHydrated ? "tertiary-dark" : "primary-dark" : "error";
        var props = fiber.memoizedProps;
        selfTime = fiber._debugTask;
        null !== props && null !== alternate && alternate.memoizedProps !== props ? (child = [resuableChangedPropsEntry], props = addObjectDiffToProperties(
          alternate.memoizedProps,
          props,
          child,
          0
        ), 1 < child.length && (props && !alreadyWarnedForDeepEquality && 0 === (alternate.lanes & committedLanes) && 100 < fiber.actualDuration ? (alreadyWarnedForDeepEquality = true, child[0] = reusableDeeplyEqualPropsEntry, reusableComponentDevToolDetails.color = "warning", reusableComponentDevToolDetails.tooltipText = DEEP_EQUALITY_WARNING) : (reusableComponentDevToolDetails.color = wasHydrated, reusableComponentDevToolDetails.tooltipText = name2), reusableComponentDevToolDetails.properties = child, reusableComponentOptions.start = startTime, reusableComponentOptions.end = endTime, null != selfTime ? selfTime.run(
          performance.measure.bind(
            performance,
            "​" + name2,
            reusableComponentOptions
          )
        ) : performance.measure(
          "​" + name2,
          reusableComponentOptions
        ))) : null != selfTime ? selfTime.run(
          console.timeStamp.bind(
            console,
            name2,
            startTime,
            endTime,
            COMPONENTS_TRACK,
            void 0,
            wasHydrated
          )
        ) : console.timeStamp(
          name2,
          startTime,
          endTime,
          COMPONENTS_TRACK,
          void 0,
          wasHydrated
        );
      }
    }
    function logComponentErrored(fiber, startTime, endTime, errors) {
      if (supportsUserTiming) {
        var name2 = getComponentNameFromFiber(fiber);
        if (null !== name2) {
          for (var debugTask = null, properties = [], i = 0; i < errors.length; i++) {
            var capturedValue = errors[i];
            null == debugTask && null !== capturedValue.source && (debugTask = capturedValue.source._debugTask);
            capturedValue = capturedValue.value;
            properties.push([
              "Error",
              "object" === typeof capturedValue && null !== capturedValue && "string" === typeof capturedValue.message ? String(capturedValue.message) : String(capturedValue)
            ]);
          }
          null !== fiber.key && addValueToProperties("key", fiber.key, properties, 0, "");
          null !== fiber.memoizedProps && addObjectToProperties(fiber.memoizedProps, properties, 0, "");
          null == debugTask && (debugTask = fiber._debugTask);
          fiber = {
            start: startTime,
            end: endTime,
            detail: {
              devtools: {
                color: "error",
                track: COMPONENTS_TRACK,
                tooltipText: 13 === fiber.tag ? "Hydration failed" : "Error boundary caught an error",
                properties
              }
            }
          };
          debugTask ? debugTask.run(
            performance.measure.bind(performance, "​" + name2, fiber)
          ) : performance.measure("​" + name2, fiber);
        }
      }
    }
    function logComponentEffect(fiber, startTime, endTime, selfTime, errors) {
      if (null !== errors) {
        if (supportsUserTiming) {
          var name2 = getComponentNameFromFiber(fiber);
          if (null !== name2) {
            selfTime = [];
            for (var i = 0; i < errors.length; i++) {
              var error = errors[i].value;
              selfTime.push([
                "Error",
                "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error)
              ]);
            }
            null !== fiber.key && addValueToProperties("key", fiber.key, selfTime, 0, "");
            null !== fiber.memoizedProps && addObjectToProperties(fiber.memoizedProps, selfTime, 0, "");
            startTime = {
              start: startTime,
              end: endTime,
              detail: {
                devtools: {
                  color: "error",
                  track: COMPONENTS_TRACK,
                  tooltipText: "A lifecycle or effect errored",
                  properties: selfTime
                }
              }
            };
            (fiber = fiber._debugTask) ? fiber.run(
              performance.measure.bind(
                performance,
                "​" + name2,
                startTime
              )
            ) : performance.measure("​" + name2, startTime);
          }
        }
      } else
        name2 = getComponentNameFromFiber(fiber), null !== name2 && supportsUserTiming && (errors = 1 > selfTime ? "secondary-light" : 100 > selfTime ? "secondary" : 500 > selfTime ? "secondary-dark" : "error", (fiber = fiber._debugTask) ? fiber.run(
          console.timeStamp.bind(
            console,
            name2,
            startTime,
            endTime,
            COMPONENTS_TRACK,
            void 0,
            errors
          )
        ) : console.timeStamp(
          name2,
          startTime,
          endTime,
          COMPONENTS_TRACK,
          void 0,
          errors
        ));
    }
    function logRenderPhase(startTime, endTime, lanes, debugTask) {
      if (supportsUserTiming && !(endTime <= startTime)) {
        var color2 = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark";
        lanes = (lanes & 536870912) === lanes ? "Prepared" : (lanes & 201326741) === lanes ? "Hydrated" : "Render";
        debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            lanes,
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            color2
          )
        ) : console.timeStamp(
          lanes,
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          color2
        );
      }
    }
    function logSuspendedRenderPhase(startTime, endTime, lanes, debugTask) {
      !supportsUserTiming || endTime <= startTime || (lanes = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          "Prewarm",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          lanes
        )
      ) : console.timeStamp(
        "Prewarm",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        lanes
      ));
    }
    function logSuspendedWithDelayPhase(startTime, endTime, lanes, debugTask) {
      !supportsUserTiming || endTime <= startTime || (lanes = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          "Suspended",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          lanes
        )
      ) : console.timeStamp(
        "Suspended",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        lanes
      ));
    }
    function logRecoveredRenderPhase(startTime, endTime, lanes, recoverableErrors, hydrationFailed, debugTask) {
      if (supportsUserTiming && !(endTime <= startTime)) {
        lanes = [];
        for (var i = 0; i < recoverableErrors.length; i++) {
          var error = recoverableErrors[i].value;
          lanes.push([
            "Recoverable Error",
            "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error)
          ]);
        }
        startTime = {
          start: startTime,
          end: endTime,
          detail: {
            devtools: {
              color: "primary-dark",
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              tooltipText: hydrationFailed ? "Hydration Failed" : "Recovered after Error",
              properties: lanes
            }
          }
        };
        debugTask ? debugTask.run(
          performance.measure.bind(performance, "Recovered", startTime)
        ) : performance.measure("Recovered", startTime);
      }
    }
    function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
      !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          "Errored",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "error"
        )
      ) : console.timeStamp(
        "Errored",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "error"
      ));
    }
    function logSuspendedCommitPhase(startTime, endTime, reason, debugTask) {
      !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
        console.timeStamp.bind(
          console,
          reason,
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "secondary-light"
        )
      ) : console.timeStamp(
        reason,
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "secondary-light"
      ));
    }
    function logCommitErrored(startTime, endTime, errors, passive, debugTask) {
      if (supportsUserTiming && !(endTime <= startTime)) {
        for (var properties = [], i = 0; i < errors.length; i++) {
          var error = errors[i].value;
          properties.push([
            "Error",
            "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error)
          ]);
        }
        startTime = {
          start: startTime,
          end: endTime,
          detail: {
            devtools: {
              color: "error",
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              tooltipText: passive ? "Remaining Effects Errored" : "Commit Errored",
              properties
            }
          }
        };
        debugTask ? debugTask.run(
          performance.measure.bind(performance, "Errored", startTime)
        ) : performance.measure("Errored", startTime);
      }
    }
    function logAnimatingPhase(startTime, endTime, debugTask) {
      !supportsUserTiming || endTime <= startTime || console.timeStamp(
        "Animating",
        startTime,
        endTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "secondary-dark"
      );
    }
    function finishQueueingConcurrentUpdates() {
      for (var endIndex = concurrentQueuesIndex, i = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i < endIndex; ) {
        var fiber = concurrentQueues[i];
        concurrentQueues[i++] = null;
        var queue = concurrentQueues[i];
        concurrentQueues[i++] = null;
        var update = concurrentQueues[i];
        concurrentQueues[i++] = null;
        var lane = concurrentQueues[i];
        concurrentQueues[i++] = null;
        if (null !== queue && null !== update) {
          var pending = queue.pending;
          null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
          queue.pending = update;
        }
        0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);
      }
    }
    function enqueueUpdate$1(fiber, queue, update, lane) {
      concurrentQueues[concurrentQueuesIndex++] = fiber;
      concurrentQueues[concurrentQueuesIndex++] = queue;
      concurrentQueues[concurrentQueuesIndex++] = update;
      concurrentQueues[concurrentQueuesIndex++] = lane;
      concurrentlyUpdatedLanes |= lane;
      fiber.lanes |= lane;
      fiber = fiber.alternate;
      null !== fiber && (fiber.lanes |= lane);
    }
    function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
      enqueueUpdate$1(fiber, queue, update, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function enqueueConcurrentRenderForLane(fiber, lane) {
      enqueueUpdate$1(fiber, null, null, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
      sourceFiber.lanes |= lane;
      var alternate = sourceFiber.alternate;
      null !== alternate && (alternate.lanes |= lane);
      for (var isHidden = false, parent = sourceFiber.return; null !== parent; )
        parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & OffscreenVisible || (isHidden = true)), sourceFiber = parent, parent = parent.return;
      return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden && null !== update && (isHidden = 31 - clz32(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden], null === alternate ? sourceFiber[isHidden] = [update] : alternate.push(update), update.lane = lane | 536870912), parent) : null;
    }
    function getRootForUpdatedFiber(sourceFiber) {
      if (nestedUpdateCount > NESTED_UPDATE_LIMIT)
        throw nestedPassiveUpdateCount = nestedUpdateCount = 0, rootWithPassiveNestedUpdates = rootWithNestedUpdates = null, Error(
          "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."
        );
      nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT && (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, console.error(
        "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
      ));
      null === sourceFiber.alternate && 0 !== (sourceFiber.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
      for (var node2 = sourceFiber, parent = node2.return; null !== parent; )
        null === node2.alternate && 0 !== (node2.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber), node2 = parent, parent = node2.return;
      return 3 === node2.tag ? node2.stateNode : null;
    }
    function resolveFunctionForHotReloading(type2) {
      if (null === resolveFamily2) return type2;
      var family = resolveFamily2(type2);
      return void 0 === family ? type2 : family.current;
    }
    function resolveForwardRefForHotReloading(type2) {
      if (null === resolveFamily2) return type2;
      var family = resolveFamily2(type2);
      return void 0 === family ? null !== type2 && void 0 !== type2 && "function" === typeof type2.render && (family = resolveFunctionForHotReloading(type2.render), type2.render !== family) ? (family = { $$typeof: REACT_FORWARD_REF_TYPE, render: family }, void 0 !== type2.displayName && (family.displayName = type2.displayName), family) : type2 : family.current;
    }
    function isCompatibleFamilyForHotReloading(fiber, element2) {
      if (null === resolveFamily2) return false;
      var prevType = fiber.elementType;
      element2 = element2.type;
      var needsCompareFamilies = false, $$typeofNextType = "object" === typeof element2 && null !== element2 ? element2.$$typeof : null;
      switch (fiber.tag) {
        case 1:
          "function" === typeof element2 && (needsCompareFamilies = true);
          break;
        case 0:
          "function" === typeof element2 ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
          break;
        case 11:
          $$typeofNextType === REACT_FORWARD_REF_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
          break;
        case 14:
        case 15:
          $$typeofNextType === REACT_MEMO_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
          break;
        default:
          return false;
      }
      return needsCompareFamilies && (fiber = resolveFamily2(prevType), void 0 !== fiber && fiber === resolveFamily2(element2)) ? true : false;
    }
    function markFailedErrorBoundaryForHotReloading(fiber) {
      null !== resolveFamily2 && "function" === typeof WeakSet && (null === failedBoundaries && (failedBoundaries = /* @__PURE__ */ new WeakSet()), failedBoundaries.add(fiber));
    }
    function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
      do {
        var _fiber = fiber, alternate = _fiber.alternate, child = _fiber.child, sibling = _fiber.sibling, tag = _fiber.tag;
        _fiber = _fiber.type;
        var candidateType = null;
        switch (tag) {
          case 0:
          case 15:
          case 1:
            candidateType = _fiber;
            break;
          case 11:
            candidateType = _fiber.render;
        }
        if (null === resolveFamily2)
          throw Error("Expected resolveFamily to be set during hot reload.");
        var needsRender = false;
        _fiber = false;
        null !== candidateType && (candidateType = resolveFamily2(candidateType), void 0 !== candidateType && (staleFamilies.has(candidateType) ? _fiber = true : updatedFamilies.has(candidateType) && (1 === tag ? _fiber = true : needsRender = true)));
        null !== failedBoundaries && (failedBoundaries.has(fiber) || null !== alternate && failedBoundaries.has(alternate)) && (_fiber = true);
        _fiber && (fiber._debugNeedsRemount = true);
        if (_fiber || needsRender)
          alternate = enqueueConcurrentRenderForLane(fiber, 2), null !== alternate && scheduleUpdateOnFiber(alternate, fiber, 2);
        null === child || _fiber || scheduleFibersWithFamiliesRecursively(
          child,
          updatedFamilies,
          staleFamilies
        );
        if (null === sibling) break;
        fiber = sibling;
      } while (1);
    }
    function FiberNode(tag, pendingProps, key, mode) {
      this.tag = tag;
      this.key = key;
      this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
      this.index = 0;
      this.refCleanup = this.ref = null;
      this.pendingProps = pendingProps;
      this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
      this.mode = mode;
      this.subtreeFlags = this.flags = 0;
      this.deletions = null;
      this.childLanes = this.lanes = 0;
      this.alternate = null;
      this.actualDuration = -0;
      this.actualStartTime = -1.1;
      this.treeBaseDuration = this.selfBaseDuration = -0;
      this._debugTask = this._debugStack = this._debugOwner = this._debugInfo = null;
      this._debugNeedsRemount = false;
      this._debugHookTypes = null;
      hasBadMapPolyfill || "function" !== typeof Object.preventExtensions || Object.preventExtensions(this);
    }
    function shouldConstruct(Component) {
      Component = Component.prototype;
      return !(!Component || !Component.isReactComponent);
    }
    function createWorkInProgress(current2, pendingProps) {
      var workInProgress2 = current2.alternate;
      null === workInProgress2 ? (workInProgress2 = createFiber(
        current2.tag,
        pendingProps,
        current2.key,
        current2.mode
      ), workInProgress2.elementType = current2.elementType, workInProgress2.type = current2.type, workInProgress2.stateNode = current2.stateNode, workInProgress2._debugOwner = current2._debugOwner, workInProgress2._debugStack = current2._debugStack, workInProgress2._debugTask = current2._debugTask, workInProgress2._debugHookTypes = current2._debugHookTypes, workInProgress2.alternate = current2, current2.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current2.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.actualDuration = -0, workInProgress2.actualStartTime = -1.1);
      workInProgress2.flags = current2.flags & 65011712;
      workInProgress2.childLanes = current2.childLanes;
      workInProgress2.lanes = current2.lanes;
      workInProgress2.child = current2.child;
      workInProgress2.memoizedProps = current2.memoizedProps;
      workInProgress2.memoizedState = current2.memoizedState;
      workInProgress2.updateQueue = current2.updateQueue;
      pendingProps = current2.dependencies;
      workInProgress2.dependencies = null === pendingProps ? null : {
        lanes: pendingProps.lanes,
        firstContext: pendingProps.firstContext,
        _debugThenableState: pendingProps._debugThenableState
      };
      workInProgress2.sibling = current2.sibling;
      workInProgress2.index = current2.index;
      workInProgress2.ref = current2.ref;
      workInProgress2.refCleanup = current2.refCleanup;
      workInProgress2.selfBaseDuration = current2.selfBaseDuration;
      workInProgress2.treeBaseDuration = current2.treeBaseDuration;
      workInProgress2._debugInfo = current2._debugInfo;
      workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
      switch (workInProgress2.tag) {
        case 0:
        case 15:
          workInProgress2.type = resolveFunctionForHotReloading(current2.type);
          break;
        case 1:
          workInProgress2.type = resolveFunctionForHotReloading(current2.type);
          break;
        case 11:
          workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
      }
      return workInProgress2;
    }
    function resetWorkInProgress(workInProgress2, renderLanes2) {
      workInProgress2.flags &= 65011714;
      var current2 = workInProgress2.alternate;
      null === current2 ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null, workInProgress2.selfBaseDuration = 0, workInProgress2.treeBaseDuration = 0) : (workInProgress2.childLanes = current2.childLanes, workInProgress2.lanes = current2.lanes, workInProgress2.child = current2.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current2.memoizedProps, workInProgress2.memoizedState = current2.memoizedState, workInProgress2.updateQueue = current2.updateQueue, workInProgress2.type = current2.type, renderLanes2 = current2.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
        lanes: renderLanes2.lanes,
        firstContext: renderLanes2.firstContext,
        _debugThenableState: renderLanes2._debugThenableState
      }, workInProgress2.selfBaseDuration = current2.selfBaseDuration, workInProgress2.treeBaseDuration = current2.treeBaseDuration);
      return workInProgress2;
    }
    function createFiberFromTypeAndProps(type2, key, pendingProps, owner, mode, lanes) {
      var fiberTag = 0, resolvedType = type2;
      if ("function" === typeof type2)
        shouldConstruct(type2) && (fiberTag = 1), resolvedType = resolveFunctionForHotReloading(resolvedType);
      else if ("string" === typeof type2)
        fiberTag = getHostContext(), fiberTag = isHostHoistableType(type2, pendingProps, fiberTag) ? 26 : "html" === type2 || "head" === type2 || "body" === type2 ? 27 : 5;
      else
        a: switch (type2) {
          case REACT_ACTIVITY_TYPE:
            return key = createFiber(31, pendingProps, key, mode), key.elementType = REACT_ACTIVITY_TYPE, key.lanes = lanes, key;
          case REACT_FRAGMENT_TYPE:
            return createFiberFromFragment(
              pendingProps.children,
              mode,
              lanes,
              key
            );
          case REACT_STRICT_MODE_TYPE:
            fiberTag = 8;
            mode |= StrictLegacyMode;
            mode |= StrictEffectsMode;
            break;
          case REACT_PROFILER_TYPE:
            return type2 = pendingProps, owner = mode, "string" !== typeof type2.id && console.error(
              'Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.',
              typeof type2.id
            ), key = createFiber(12, type2, key, owner | ProfileMode), key.elementType = REACT_PROFILER_TYPE, key.lanes = lanes, key.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }, key;
          case REACT_SUSPENSE_TYPE:
            return key = createFiber(13, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_TYPE, key.lanes = lanes, key;
          case REACT_SUSPENSE_LIST_TYPE:
            return key = createFiber(19, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_LIST_TYPE, key.lanes = lanes, key;
          default:
            if ("object" === typeof type2 && null !== type2)
              switch (type2.$$typeof) {
                case REACT_CONTEXT_TYPE:
                  fiberTag = 10;
                  break a;
                case REACT_CONSUMER_TYPE:
                  fiberTag = 9;
                  break a;
                case REACT_FORWARD_REF_TYPE:
                  fiberTag = 11;
                  resolvedType = resolveForwardRefForHotReloading(resolvedType);
                  break a;
                case REACT_MEMO_TYPE:
                  fiberTag = 14;
                  break a;
                case REACT_LAZY_TYPE:
                  fiberTag = 16;
                  resolvedType = null;
                  break a;
              }
            resolvedType = "";
            if (void 0 === type2 || "object" === typeof type2 && null !== type2 && 0 === Object.keys(type2).length)
              resolvedType += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
            null === type2 ? pendingProps = "null" : isArrayImpl(type2) ? pendingProps = "array" : void 0 !== type2 && type2.$$typeof === REACT_ELEMENT_TYPE ? (pendingProps = "<" + (getComponentNameFromType(type2.type) || "Unknown") + " />", resolvedType = " Did you accidentally export a JSX literal instead of a component?") : pendingProps = typeof type2;
            (fiberTag = owner ? getComponentNameFromOwner(owner) : null) && (resolvedType += "\n\nCheck the render method of `" + fiberTag + "`.");
            fiberTag = 29;
            pendingProps = Error(
              "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (pendingProps + "." + resolvedType)
            );
            resolvedType = null;
        }
      key = createFiber(fiberTag, pendingProps, key, mode);
      key.elementType = type2;
      key.type = resolvedType;
      key.lanes = lanes;
      key._debugOwner = owner;
      return key;
    }
    function createFiberFromElement(element2, mode, lanes) {
      mode = createFiberFromTypeAndProps(
        element2.type,
        element2.key,
        element2.props,
        element2._owner,
        mode,
        lanes
      );
      mode._debugOwner = element2._owner;
      mode._debugStack = element2._debugStack;
      mode._debugTask = element2._debugTask;
      return mode;
    }
    function createFiberFromFragment(elements, mode, lanes, key) {
      elements = createFiber(7, elements, key, mode);
      elements.lanes = lanes;
      return elements;
    }
    function createFiberFromText(content2, mode, lanes) {
      content2 = createFiber(6, content2, null, mode);
      content2.lanes = lanes;
      return content2;
    }
    function createFiberFromDehydratedFragment(dehydratedNode) {
      var fiber = createFiber(18, null, null, NoMode);
      fiber.stateNode = dehydratedNode;
      return fiber;
    }
    function createFiberFromPortal(portal, mode, lanes) {
      mode = createFiber(
        4,
        null !== portal.children ? portal.children : [],
        portal.key,
        mode
      );
      mode.lanes = lanes;
      mode.stateNode = {
        containerInfo: portal.containerInfo,
        pendingChildren: null,
        implementation: portal.implementation
      };
      return mode;
    }
    function createCapturedValueAtFiber(value, source) {
      if ("object" === typeof value && null !== value) {
        var existing = CapturedStacks.get(value);
        if (void 0 !== existing) return existing;
        source = {
          value,
          source,
          stack: getStackByFiberInDevAndProd(source)
        };
        CapturedStacks.set(value, source);
        return source;
      }
      return {
        value,
        source,
        stack: getStackByFiberInDevAndProd(source)
      };
    }
    function pushTreeFork(workInProgress2, totalChildren) {
      warnIfNotHydrating();
      forkStack[forkStackIndex++] = treeForkCount;
      forkStack[forkStackIndex++] = treeForkProvider;
      treeForkProvider = workInProgress2;
      treeForkCount = totalChildren;
    }
    function pushTreeId(workInProgress2, totalChildren, index2) {
      warnIfNotHydrating();
      idStack[idStackIndex++] = treeContextId;
      idStack[idStackIndex++] = treeContextOverflow;
      idStack[idStackIndex++] = treeContextProvider;
      treeContextProvider = workInProgress2;
      var baseIdWithLeadingBit = treeContextId;
      workInProgress2 = treeContextOverflow;
      var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
      baseIdWithLeadingBit &= ~(1 << baseLength);
      index2 += 1;
      var length = 32 - clz32(totalChildren) + baseLength;
      if (30 < length) {
        var numberOfOverflowBits = baseLength - baseLength % 5;
        length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
        baseIdWithLeadingBit >>= numberOfOverflowBits;
        baseLength -= numberOfOverflowBits;
        treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit;
        treeContextOverflow = length + workInProgress2;
      } else
        treeContextId = 1 << length | index2 << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
    }
    function pushMaterializedTreeId(workInProgress2) {
      warnIfNotHydrating();
      null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
    }
    function popTreeContext(workInProgress2) {
      for (; workInProgress2 === treeForkProvider; )
        treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
      for (; workInProgress2 === treeContextProvider; )
        treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
    }
    function getSuspendedTreeContext() {
      warnIfNotHydrating();
      return null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null;
    }
    function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
      warnIfNotHydrating();
      idStack[idStackIndex++] = treeContextId;
      idStack[idStackIndex++] = treeContextOverflow;
      idStack[idStackIndex++] = treeContextProvider;
      treeContextId = suspendedContext.id;
      treeContextOverflow = suspendedContext.overflow;
      treeContextProvider = workInProgress2;
    }
    function warnIfNotHydrating() {
      isHydrating || console.error(
        "Expected to be hydrating. This is a bug in React. Please file an issue."
      );
    }
    function buildHydrationDiffNode(fiber, distanceFromLeaf) {
      if (null === fiber.return) {
        if (null === hydrationDiffRootDEV)
          hydrationDiffRootDEV = {
            fiber,
            children: [],
            serverProps: void 0,
            serverTail: [],
            distanceFromLeaf
          };
        else {
          if (hydrationDiffRootDEV.fiber !== fiber)
            throw Error(
              "Saw multiple hydration diff roots in a pass. This is a bug in React."
            );
          hydrationDiffRootDEV.distanceFromLeaf > distanceFromLeaf && (hydrationDiffRootDEV.distanceFromLeaf = distanceFromLeaf);
        }
        return hydrationDiffRootDEV;
      }
      var siblings = buildHydrationDiffNode(
        fiber.return,
        distanceFromLeaf + 1
      ).children;
      if (0 < siblings.length && siblings[siblings.length - 1].fiber === fiber)
        return siblings = siblings[siblings.length - 1], siblings.distanceFromLeaf > distanceFromLeaf && (siblings.distanceFromLeaf = distanceFromLeaf), siblings;
      distanceFromLeaf = {
        fiber,
        children: [],
        serverProps: void 0,
        serverTail: [],
        distanceFromLeaf
      };
      siblings.push(distanceFromLeaf);
      return distanceFromLeaf;
    }
    function warnIfHydrating() {
      isHydrating && console.error(
        "We should not be hydrating here. This is a bug in React. Please file a bug."
      );
    }
    function warnNonHydratedInstance(fiber, rejectedCandidate) {
      didSuspendOrErrorDEV || (fiber = buildHydrationDiffNode(fiber, 0), fiber.serverProps = null, null !== rejectedCandidate && (rejectedCandidate = describeHydratableInstanceForDevWarnings(rejectedCandidate), fiber.serverTail.push(rejectedCandidate)));
    }
    function throwOnHydrationMismatch(fiber) {
      var fromText = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : false, diff = "", diffRoot = hydrationDiffRootDEV;
      null !== diffRoot && (hydrationDiffRootDEV = null, diff = describeDiff(diffRoot));
      queueHydrationError(
        createCapturedValueAtFiber(
          Error(
            "Hydration failed because the server rendered " + (fromText ? "text" : "HTML") + " didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\nhttps://react.dev/link/hydration-mismatch" + diff
          ),
          fiber
        )
      );
      throw HydrationMismatchException;
    }
    function prepareToHydrateHostInstance(fiber) {
      var didHydrate = fiber.stateNode;
      var type2 = fiber.type, props = fiber.memoizedProps;
      didHydrate[internalInstanceKey] = fiber;
      didHydrate[internalPropsKey] = props;
      validatePropertiesInDevelopment(type2, props);
      switch (type2) {
        case "dialog":
          listenToNonDelegatedEvent("cancel", didHydrate);
          listenToNonDelegatedEvent("close", didHydrate);
          break;
        case "iframe":
        case "object":
        case "embed":
          listenToNonDelegatedEvent("load", didHydrate);
          break;
        case "video":
        case "audio":
          for (type2 = 0; type2 < mediaEventTypes.length; type2++)
            listenToNonDelegatedEvent(mediaEventTypes[type2], didHydrate);
          break;
        case "source":
          listenToNonDelegatedEvent("error", didHydrate);
          break;
        case "img":
        case "image":
        case "link":
          listenToNonDelegatedEvent("error", didHydrate);
          listenToNonDelegatedEvent("load", didHydrate);
          break;
        case "details":
          listenToNonDelegatedEvent("toggle", didHydrate);
          break;
        case "input":
          checkControlledValueProps("input", props);
          listenToNonDelegatedEvent("invalid", didHydrate);
          validateInputProps(didHydrate, props);
          initInput(
            didHydrate,
            props.value,
            props.defaultValue,
            props.checked,
            props.defaultChecked,
            props.type,
            props.name,
            true
          );
          break;
        case "option":
          validateOptionProps(didHydrate, props);
          break;
        case "select":
          checkControlledValueProps("select", props);
          listenToNonDelegatedEvent("invalid", didHydrate);
          validateSelectProps(didHydrate, props);
          break;
        case "textarea":
          checkControlledValueProps("textarea", props), listenToNonDelegatedEvent("invalid", didHydrate), validateTextareaProps(didHydrate, props), initTextarea(
            didHydrate,
            props.value,
            props.defaultValue,
            props.children
          );
      }
      type2 = props.children;
      "string" !== typeof type2 && "number" !== typeof type2 && "bigint" !== typeof type2 || didHydrate.textContent === "" + type2 || true === props.suppressHydrationWarning || checkForUnmatchedText(didHydrate.textContent, type2) ? (null != props.popover && (listenToNonDelegatedEvent("beforetoggle", didHydrate), listenToNonDelegatedEvent("toggle", didHydrate)), null != props.onScroll && listenToNonDelegatedEvent("scroll", didHydrate), null != props.onScrollEnd && listenToNonDelegatedEvent("scrollend", didHydrate), null != props.onClick && (didHydrate.onclick = noop$1), didHydrate = true) : didHydrate = false;
      didHydrate || throwOnHydrationMismatch(fiber, true);
    }
    function popToNextHostParent(fiber) {
      for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
        switch (hydrationParentFiber.tag) {
          case 5:
          case 31:
          case 13:
            rootOrSingletonContext = false;
            return;
          case 27:
          case 3:
            rootOrSingletonContext = true;
            return;
          default:
            hydrationParentFiber = hydrationParentFiber.return;
        }
    }
    function popHydrationState(fiber) {
      if (fiber !== hydrationParentFiber) return false;
      if (!isHydrating)
        return popToNextHostParent(fiber), isHydrating = true, false;
      var tag = fiber.tag, JSCompiler_temp;
      if (JSCompiler_temp = 3 !== tag && 27 !== tag) {
        if (JSCompiler_temp = 5 === tag)
          JSCompiler_temp = fiber.type, JSCompiler_temp = !("form" !== JSCompiler_temp && "button" !== JSCompiler_temp) || shouldSetTextContent(fiber.type, fiber.memoizedProps);
        JSCompiler_temp = !JSCompiler_temp;
      }
      if (JSCompiler_temp && nextHydratableInstance) {
        for (JSCompiler_temp = nextHydratableInstance; JSCompiler_temp; ) {
          var diffNode = buildHydrationDiffNode(fiber, 0), description = describeHydratableInstanceForDevWarnings(JSCompiler_temp);
          diffNode.serverTail.push(description);
          JSCompiler_temp = "Suspense" === description.type ? getNextHydratableInstanceAfterHydrationBoundary(JSCompiler_temp) : getNextHydratable(JSCompiler_temp.nextSibling);
        }
        throwOnHydrationMismatch(fiber);
      }
      popToNextHostParent(fiber);
      if (13 === tag) {
        fiber = fiber.memoizedState;
        fiber = null !== fiber ? fiber.dehydrated : null;
        if (!fiber)
          throw Error(
            "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
          );
        nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
      } else if (31 === tag) {
        fiber = fiber.memoizedState;
        fiber = null !== fiber ? fiber.dehydrated : null;
        if (!fiber)
          throw Error(
            "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
          );
        nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
      } else
        27 === tag ? (tag = nextHydratableInstance, isSingletonScope(fiber.type) ? (fiber = previousHydratableOnEnteringScopedSingleton, previousHydratableOnEnteringScopedSingleton = null, nextHydratableInstance = fiber) : nextHydratableInstance = tag) : nextHydratableInstance = hydrationParentFiber ? getNextHydratable(fiber.stateNode.nextSibling) : null;
      return true;
    }
    function resetHydrationState() {
      nextHydratableInstance = hydrationParentFiber = null;
      didSuspendOrErrorDEV = isHydrating = false;
    }
    function upgradeHydrationErrorsToRecoverable() {
      var queuedErrors = hydrationErrors;
      null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
        workInProgressRootRecoverableErrors,
        queuedErrors
      ), hydrationErrors = null);
      return queuedErrors;
    }
    function queueHydrationError(error) {
      null === hydrationErrors ? hydrationErrors = [error] : hydrationErrors.push(error);
    }
    function emitPendingHydrationWarnings() {
      var diffRoot = hydrationDiffRootDEV;
      if (null !== diffRoot) {
        hydrationDiffRootDEV = null;
        for (var diff = describeDiff(diffRoot); 0 < diffRoot.children.length; )
          diffRoot = diffRoot.children[0];
        runWithFiberInDEV(diffRoot.fiber, function() {
          console.error(
            "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\n%s%s",
            "https://react.dev/link/hydration-mismatch",
            diff
          );
        });
      }
    }
    function resetContextDependencies() {
      lastContextDependency = currentlyRenderingFiber$1 = null;
      isDisallowedContextReadInDEV = false;
    }
    function pushProvider(providerFiber, context, nextValue) {
      push2(valueCursor, context._currentValue, providerFiber);
      context._currentValue = nextValue;
      push2(rendererCursorDEV, context._currentRenderer, providerFiber);
      void 0 !== context._currentRenderer && null !== context._currentRenderer && context._currentRenderer !== rendererSigil && console.error(
        "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
      );
      context._currentRenderer = rendererSigil;
    }
    function popProvider(context, providerFiber) {
      context._currentValue = valueCursor.current;
      var currentRenderer = rendererCursorDEV.current;
      pop(rendererCursorDEV, providerFiber);
      context._currentRenderer = currentRenderer;
      pop(valueCursor, providerFiber);
    }
    function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
      for (; null !== parent; ) {
        var alternate = parent.alternate;
        (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
        if (parent === propagationRoot) break;
        parent = parent.return;
      }
      parent !== propagationRoot && console.error(
        "Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue."
      );
    }
    function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
      var fiber = workInProgress2.child;
      null !== fiber && (fiber.return = workInProgress2);
      for (; null !== fiber; ) {
        var list2 = fiber.dependencies;
        if (null !== list2) {
          var nextFiber = fiber.child;
          list2 = list2.firstContext;
          a: for (; null !== list2; ) {
            var dependency = list2;
            list2 = fiber;
            for (var i = 0; i < contexts.length; i++)
              if (dependency.context === contexts[i]) {
                list2.lanes |= renderLanes2;
                dependency = list2.alternate;
                null !== dependency && (dependency.lanes |= renderLanes2);
                scheduleContextWorkOnParentPath(
                  list2.return,
                  renderLanes2,
                  workInProgress2
                );
                forcePropagateEntireTree || (nextFiber = null);
                break a;
              }
            list2 = dependency.next;
          }
        } else if (18 === fiber.tag) {
          nextFiber = fiber.return;
          if (null === nextFiber)
            throw Error(
              "We just came from a parent so we must have had a parent. This is a bug in React."
            );
          nextFiber.lanes |= renderLanes2;
          list2 = nextFiber.alternate;
          null !== list2 && (list2.lanes |= renderLanes2);
          scheduleContextWorkOnParentPath(
            nextFiber,
            renderLanes2,
            workInProgress2
          );
          nextFiber = null;
        } else nextFiber = fiber.child;
        if (null !== nextFiber) nextFiber.return = fiber;
        else
          for (nextFiber = fiber; null !== nextFiber; ) {
            if (nextFiber === workInProgress2) {
              nextFiber = null;
              break;
            }
            fiber = nextFiber.sibling;
            if (null !== fiber) {
              fiber.return = nextFiber.return;
              nextFiber = fiber;
              break;
            }
            nextFiber = nextFiber.return;
          }
        fiber = nextFiber;
      }
    }
    function propagateParentContextChanges(current2, workInProgress2, renderLanes2, forcePropagateEntireTree) {
      current2 = null;
      for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
        if (!isInsidePropagationBailout) {
          if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
          else if (0 !== (parent.flags & 262144)) break;
        }
        if (10 === parent.tag) {
          var currentParent = parent.alternate;
          if (null === currentParent)
            throw Error("Should have a current fiber. This is a bug in React.");
          currentParent = currentParent.memoizedProps;
          if (null !== currentParent) {
            var context = parent.type;
            objectIs(parent.pendingProps.value, currentParent.value) || (null !== current2 ? current2.push(context) : current2 = [context]);
          }
        } else if (parent === hostTransitionProviderCursor.current) {
          currentParent = parent.alternate;
          if (null === currentParent)
            throw Error("Should have a current fiber. This is a bug in React.");
          currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current2 ? current2.push(HostTransitionContext) : current2 = [HostTransitionContext]);
        }
        parent = parent.return;
      }
      null !== current2 && propagateContextChanges(
        workInProgress2,
        current2,
        renderLanes2,
        forcePropagateEntireTree
      );
      workInProgress2.flags |= 262144;
    }
    function checkIfContextChanged(currentDependencies) {
      for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
        if (!objectIs(
          currentDependencies.context._currentValue,
          currentDependencies.memoizedValue
        ))
          return true;
        currentDependencies = currentDependencies.next;
      }
      return false;
    }
    function prepareToReadContext(workInProgress2) {
      currentlyRenderingFiber$1 = workInProgress2;
      lastContextDependency = null;
      workInProgress2 = workInProgress2.dependencies;
      null !== workInProgress2 && (workInProgress2.firstContext = null);
    }
    function readContext(context) {
      isDisallowedContextReadInDEV && console.error(
        "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
      );
      return readContextForConsumer(currentlyRenderingFiber$1, context);
    }
    function readContextDuringReconciliation(consumer, context) {
      null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
      return readContextForConsumer(consumer, context);
    }
    function readContextForConsumer(consumer, context) {
      var value = context._currentValue;
      context = { context, memoizedValue: value, next: null };
      if (null === lastContextDependency) {
        if (null === consumer)
          throw Error(
            "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
          );
        lastContextDependency = context;
        consumer.dependencies = {
          lanes: 0,
          firstContext: context,
          _debugThenableState: null
        };
        consumer.flags |= 524288;
      } else lastContextDependency = lastContextDependency.next = context;
      return value;
    }
    function createCache() {
      return {
        controller: new AbortControllerLocal(),
        data: /* @__PURE__ */ new Map(),
        refCount: 0
      };
    }
    function retainCache(cache) {
      cache.controller.signal.aborted && console.warn(
        "A cache instance was retained after it was already freed. This likely indicates a bug in React."
      );
      cache.refCount++;
    }
    function releaseCache(cache) {
      cache.refCount--;
      0 > cache.refCount && console.warn(
        "A cache instance was released after it was already freed. This likely indicates a bug in React."
      );
      0 === cache.refCount && scheduleCallback$2(NormalPriority, function() {
        cache.controller.abort();
      });
    }
    function startUpdateTimerByLane(lane, method, fiber) {
      if (0 !== (lane & 127))
        0 > blockingUpdateTime && (blockingUpdateTime = now(), blockingUpdateTask = createTask(method), blockingUpdateMethodName = method, null != fiber && (blockingUpdateComponentName = getComponentNameFromFiber(fiber)), (executionContext & (RenderContext | CommitContext)) !== NoContext && (componentEffectSpawnedUpdate = true, blockingUpdateType = SPAWNED_UPDATE), lane = resolveEventTimeStamp(), method = resolveEventType(), lane !== blockingEventRepeatTime || method !== blockingEventType ? blockingEventRepeatTime = -1.1 : null !== method && (blockingUpdateType = SPAWNED_UPDATE), blockingEventTime = lane, blockingEventType = method);
      else if (0 !== (lane & 4194048) && 0 > transitionUpdateTime && (transitionUpdateTime = now(), transitionUpdateTask = createTask(method), transitionUpdateMethodName = method, null != fiber && (transitionUpdateComponentName = getComponentNameFromFiber(fiber)), 0 > transitionStartTime)) {
        lane = resolveEventTimeStamp();
        method = resolveEventType();
        if (lane !== transitionEventRepeatTime || method !== transitionEventType)
          transitionEventRepeatTime = -1.1;
        transitionEventTime = lane;
        transitionEventType = method;
      }
    }
    function startHostActionTimer(fiber) {
      if (0 > blockingUpdateTime) {
        blockingUpdateTime = now();
        blockingUpdateTask = null != fiber._debugTask ? fiber._debugTask : null;
        (executionContext & (RenderContext | CommitContext)) !== NoContext && (blockingUpdateType = SPAWNED_UPDATE);
        var newEventTime = resolveEventTimeStamp(), newEventType = resolveEventType();
        newEventTime !== blockingEventRepeatTime || newEventType !== blockingEventType ? blockingEventRepeatTime = -1.1 : null !== newEventType && (blockingUpdateType = SPAWNED_UPDATE);
        blockingEventTime = newEventTime;
        blockingEventType = newEventType;
      }
      if (0 > transitionUpdateTime && (transitionUpdateTime = now(), transitionUpdateTask = null != fiber._debugTask ? fiber._debugTask : null, 0 > transitionStartTime)) {
        fiber = resolveEventTimeStamp();
        newEventTime = resolveEventType();
        if (fiber !== transitionEventRepeatTime || newEventTime !== transitionEventType)
          transitionEventRepeatTime = -1.1;
        transitionEventTime = fiber;
        transitionEventType = newEventTime;
      }
    }
    function pushNestedEffectDurations() {
      var prevEffectDuration = profilerEffectDuration;
      profilerEffectDuration = 0;
      return prevEffectDuration;
    }
    function popNestedEffectDurations(prevEffectDuration) {
      var elapsedTime = profilerEffectDuration;
      profilerEffectDuration = prevEffectDuration;
      return elapsedTime;
    }
    function bubbleNestedEffectDurations(prevEffectDuration) {
      var elapsedTime = profilerEffectDuration;
      profilerEffectDuration += prevEffectDuration;
      return elapsedTime;
    }
    function resetComponentEffectTimers() {
      componentEffectEndTime = componentEffectStartTime = -1.1;
    }
    function pushComponentEffectStart() {
      var prevEffectStart = componentEffectStartTime;
      componentEffectStartTime = -1.1;
      return prevEffectStart;
    }
    function popComponentEffectStart(prevEffectStart) {
      0 <= prevEffectStart && (componentEffectStartTime = prevEffectStart);
    }
    function pushComponentEffectDuration() {
      var prevEffectDuration = componentEffectDuration;
      componentEffectDuration = -0;
      return prevEffectDuration;
    }
    function popComponentEffectDuration(prevEffectDuration) {
      0 <= prevEffectDuration && (componentEffectDuration = prevEffectDuration);
    }
    function pushComponentEffectErrors() {
      var prevErrors = componentEffectErrors;
      componentEffectErrors = null;
      return prevErrors;
    }
    function pushComponentEffectDidSpawnUpdate() {
      var prev = componentEffectSpawnedUpdate;
      componentEffectSpawnedUpdate = false;
      return prev;
    }
    function startProfilerTimer(fiber) {
      profilerStartTime = now();
      0 > fiber.actualStartTime && (fiber.actualStartTime = profilerStartTime);
    }
    function stopProfilerTimerIfRunningAndRecordDuration(fiber) {
      if (0 <= profilerStartTime) {
        var elapsedTime = now() - profilerStartTime;
        fiber.actualDuration += elapsedTime;
        fiber.selfBaseDuration = elapsedTime;
        profilerStartTime = -1;
      }
    }
    function stopProfilerTimerIfRunningAndRecordIncompleteDuration(fiber) {
      if (0 <= profilerStartTime) {
        var elapsedTime = now() - profilerStartTime;
        fiber.actualDuration += elapsedTime;
        profilerStartTime = -1;
      }
    }
    function recordEffectDuration() {
      if (0 <= profilerStartTime) {
        var endTime = now(), elapsedTime = endTime - profilerStartTime;
        profilerStartTime = -1;
        profilerEffectDuration += elapsedTime;
        componentEffectDuration += elapsedTime;
        componentEffectEndTime = endTime;
      }
    }
    function recordEffectError(errorInfo) {
      null === componentEffectErrors && (componentEffectErrors = []);
      componentEffectErrors.push(errorInfo);
      null === commitErrors && (commitErrors = []);
      commitErrors.push(errorInfo);
    }
    function startEffectTimer() {
      profilerStartTime = now();
      0 > componentEffectStartTime && (componentEffectStartTime = profilerStartTime);
    }
    function transferActualDuration(fiber) {
      for (var child = fiber.child; child; )
        fiber.actualDuration += child.actualDuration, child = child.sibling;
    }
    function entangleAsyncAction(transition, thenable) {
      if (null === currentEntangledListeners) {
        var entangledListeners = currentEntangledListeners = [];
        currentEntangledPendingCount = 0;
        currentEntangledLane = requestTransitionLane();
        currentEntangledActionThenable = {
          status: "pending",
          value: void 0,
          then: function(resolve) {
            entangledListeners.push(resolve);
          }
        };
      }
      currentEntangledPendingCount++;
      thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
      return thenable;
    }
    function pingEngtangledActionScope() {
      if (0 === --currentEntangledPendingCount && (-1 < transitionUpdateTime || (transitionStartTime = -1.1), null !== currentEntangledListeners)) {
        null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
        var listeners = currentEntangledListeners;
        currentEntangledListeners = null;
        currentEntangledLane = 0;
        currentEntangledActionThenable = null;
        for (var i = 0; i < listeners.length; i++) (0, listeners[i])();
      }
    }
    function chainThenableValue(thenable, result) {
      var listeners = [], thenableWithOverride = {
        status: "pending",
        value: null,
        reason: null,
        then: function(resolve) {
          listeners.push(resolve);
        }
      };
      thenable.then(
        function() {
          thenableWithOverride.status = "fulfilled";
          thenableWithOverride.value = result;
          for (var i = 0; i < listeners.length; i++) (0, listeners[i])(result);
        },
        function(error) {
          thenableWithOverride.status = "rejected";
          thenableWithOverride.reason = error;
          for (error = 0; error < listeners.length; error++)
            (0, listeners[error])(void 0);
        }
      );
      return thenableWithOverride;
    }
    function peekCacheFromPool() {
      var cacheResumedFromPreviousRender = resumedCache.current;
      return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
    }
    function pushTransition(offscreenWorkInProgress, prevCachePool) {
      null === prevCachePool ? push2(resumedCache, resumedCache.current, offscreenWorkInProgress) : push2(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
    }
    function getSuspendedCache() {
      var cacheFromPool = peekCacheFromPool();
      return null === cacheFromPool ? null : { parent: CacheContext._currentValue, pool: cacheFromPool };
    }
    function createThenableState() {
      return { didWarnAboutUncachedPromise: false, thenables: [] };
    }
    function isThenableResolved(thenable) {
      thenable = thenable.status;
      return "fulfilled" === thenable || "rejected" === thenable;
    }
    function trackUsedThenable(thenableState2, thenable, index2) {
      null !== ReactSharedInternals.actQueue && (ReactSharedInternals.didUsePromise = true);
      var trackedThenables = thenableState2.thenables;
      index2 = trackedThenables[index2];
      void 0 === index2 ? trackedThenables.push(thenable) : index2 !== thenable && (thenableState2.didWarnAboutUncachedPromise || (thenableState2.didWarnAboutUncachedPromise = true, console.error(
        "A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework."
      )), thenable.then(noop$1, noop$1), thenable = index2);
      if (void 0 === thenable._debugInfo) {
        thenableState2 = performance.now();
        trackedThenables = thenable.displayName;
        var ioInfo = {
          name: "string" === typeof trackedThenables ? trackedThenables : "Promise",
          start: thenableState2,
          end: thenableState2,
          value: thenable
        };
        thenable._debugInfo = [{ awaited: ioInfo }];
        "fulfilled" !== thenable.status && "rejected" !== thenable.status && (thenableState2 = function() {
          ioInfo.end = performance.now();
        }, thenable.then(thenableState2, thenableState2));
      }
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
        default:
          if ("string" === typeof thenable.status)
            thenable.then(noop$1, noop$1);
          else {
            thenableState2 = workInProgressRoot;
            if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
              throw Error(
                "An unknown Component is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
              );
            thenableState2 = thenable;
            thenableState2.status = "pending";
            thenableState2.then(
              function(fulfilledValue) {
                if ("pending" === thenable.status) {
                  var fulfilledThenable = thenable;
                  fulfilledThenable.status = "fulfilled";
                  fulfilledThenable.value = fulfilledValue;
                }
              },
              function(error) {
                if ("pending" === thenable.status) {
                  var rejectedThenable = thenable;
                  rejectedThenable.status = "rejected";
                  rejectedThenable.reason = error;
                }
              }
            );
          }
          switch (thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
          }
          suspendedThenable = thenable;
          needsToResetSuspendedThenableDEV = true;
          throw SuspenseException;
      }
    }
    function resolveLazy(lazyType) {
      try {
        return callLazyInitInDEV(lazyType);
      } catch (x2) {
        if (null !== x2 && "object" === typeof x2 && "function" === typeof x2.then)
          throw suspendedThenable = x2, needsToResetSuspendedThenableDEV = true, SuspenseException;
        throw x2;
      }
    }
    function getSuspendedThenable() {
      if (null === suspendedThenable)
        throw Error(
          "Expected a suspended thenable. This is a bug in React. Please file an issue."
        );
      var thenable = suspendedThenable;
      suspendedThenable = null;
      needsToResetSuspendedThenableDEV = false;
      return thenable;
    }
    function checkIfUseWrappedInAsyncCatch(rejectedReason) {
      if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
        throw Error(
          "Hooks are not supported inside an async component. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
        );
    }
    function pushDebugInfo(debugInfo) {
      var previousDebugInfo = currentDebugInfo;
      null != debugInfo && (currentDebugInfo = null === previousDebugInfo ? debugInfo : previousDebugInfo.concat(debugInfo));
      return previousDebugInfo;
    }
    function getCurrentDebugTask() {
      var debugInfo = currentDebugInfo;
      if (null != debugInfo) {
        for (var i = debugInfo.length - 1; 0 <= i; i--)
          if (null != debugInfo[i].name) {
            var debugTask = debugInfo[i].debugTask;
            if (null != debugTask) return debugTask;
          }
      }
      return null;
    }
    function validateFragmentProps(element2, fiber, returnFiber) {
      for (var keys2 = Object.keys(element2.props), i = 0; i < keys2.length; i++) {
        var key = keys2[i];
        if ("children" !== key && "key" !== key) {
          null === fiber && (fiber = createFiberFromElement(element2, returnFiber.mode, 0), fiber._debugInfo = currentDebugInfo, fiber.return = returnFiber);
          runWithFiberInDEV(
            fiber,
            function(erroredKey) {
              console.error(
                "Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",
                erroredKey
              );
            },
            key
          );
          break;
        }
      }
    }
    function unwrapThenable(thenable) {
      var index2 = thenableIndexCounter$1;
      thenableIndexCounter$1 += 1;
      null === thenableState$1 && (thenableState$1 = createThenableState());
      return trackUsedThenable(thenableState$1, thenable, index2);
    }
    function coerceRef(workInProgress2, element2) {
      element2 = element2.props.ref;
      workInProgress2.ref = void 0 !== element2 ? element2 : null;
    }
    function throwOnInvalidObjectTypeImpl(returnFiber, newChild) {
      if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
        throw Error(
          'A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.'
        );
      returnFiber = Object.prototype.toString.call(newChild);
      throw Error(
        "Objects are not valid as a React child (found: " + ("[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber) + "). If you meant to render a collection of children, use an array instead."
      );
    }
    function throwOnInvalidObjectType(returnFiber, newChild) {
      var debugTask = getCurrentDebugTask();
      null !== debugTask ? debugTask.run(
        throwOnInvalidObjectTypeImpl.bind(null, returnFiber, newChild)
      ) : throwOnInvalidObjectTypeImpl(returnFiber, newChild);
    }
    function warnOnFunctionTypeImpl(returnFiber, invalidChild) {
      var parentName = getComponentNameFromFiber(returnFiber) || "Component";
      ownerHasFunctionTypeWarning[parentName] || (ownerHasFunctionTypeWarning[parentName] = true, invalidChild = invalidChild.displayName || invalidChild.name || "Component", 3 === returnFiber.tag ? console.error(
        "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  root.render(%s)",
        invalidChild,
        invalidChild,
        invalidChild
      ) : console.error(
        "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  <%s>{%s}</%s>",
        invalidChild,
        invalidChild,
        parentName,
        invalidChild,
        parentName
      ));
    }
    function warnOnFunctionType(returnFiber, invalidChild) {
      var debugTask = getCurrentDebugTask();
      null !== debugTask ? debugTask.run(
        warnOnFunctionTypeImpl.bind(null, returnFiber, invalidChild)
      ) : warnOnFunctionTypeImpl(returnFiber, invalidChild);
    }
    function warnOnSymbolTypeImpl(returnFiber, invalidChild) {
      var parentName = getComponentNameFromFiber(returnFiber) || "Component";
      ownerHasSymbolTypeWarning[parentName] || (ownerHasSymbolTypeWarning[parentName] = true, invalidChild = String(invalidChild), 3 === returnFiber.tag ? console.error(
        "Symbols are not valid as a React child.\n  root.render(%s)",
        invalidChild
      ) : console.error(
        "Symbols are not valid as a React child.\n  <%s>%s</%s>",
        parentName,
        invalidChild,
        parentName
      ));
    }
    function warnOnSymbolType(returnFiber, invalidChild) {
      var debugTask = getCurrentDebugTask();
      null !== debugTask ? debugTask.run(
        warnOnSymbolTypeImpl.bind(null, returnFiber, invalidChild)
      ) : warnOnSymbolTypeImpl(returnFiber, invalidChild);
    }
    function createChildReconciler(shouldTrackSideEffects) {
      function deleteChild(returnFiber, childToDelete) {
        if (shouldTrackSideEffects) {
          var deletions = returnFiber.deletions;
          null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
        }
      }
      function deleteRemainingChildren(returnFiber, currentFirstChild) {
        if (!shouldTrackSideEffects) return null;
        for (; null !== currentFirstChild; )
          deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
        return null;
      }
      function mapRemainingChildren(currentFirstChild) {
        for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
          null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
        return existingChildren;
      }
      function useFiber(fiber, pendingProps) {
        fiber = createWorkInProgress(fiber, pendingProps);
        fiber.index = 0;
        fiber.sibling = null;
        return fiber;
      }
      function placeChild(newFiber, lastPlacedIndex, newIndex) {
        newFiber.index = newIndex;
        if (!shouldTrackSideEffects)
          return newFiber.flags |= 1048576, lastPlacedIndex;
        newIndex = newFiber.alternate;
        if (null !== newIndex)
          return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
        newFiber.flags |= 67108866;
        return lastPlacedIndex;
      }
      function placeSingleChild(newFiber) {
        shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
        return newFiber;
      }
      function updateTextNode(returnFiber, current2, textContent, lanes) {
        if (null === current2 || 6 !== current2.tag)
          return current2 = createFiberFromText(
            textContent,
            returnFiber.mode,
            lanes
          ), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugTask = returnFiber._debugTask, current2._debugInfo = currentDebugInfo, current2;
        current2 = useFiber(current2, textContent);
        current2.return = returnFiber;
        current2._debugInfo = currentDebugInfo;
        return current2;
      }
      function updateElement(returnFiber, current2, element2, lanes) {
        var elementType = element2.type;
        if (elementType === REACT_FRAGMENT_TYPE)
          return current2 = updateFragment(
            returnFiber,
            current2,
            element2.props.children,
            lanes,
            element2.key
          ), validateFragmentProps(element2, current2, returnFiber), current2;
        if (null !== current2 && (current2.elementType === elementType || isCompatibleFamilyForHotReloading(current2, element2) || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type))
          return current2 = useFiber(current2, element2.props), coerceRef(current2, element2), current2.return = returnFiber, current2._debugOwner = element2._owner, current2._debugInfo = currentDebugInfo, current2;
        current2 = createFiberFromElement(element2, returnFiber.mode, lanes);
        coerceRef(current2, element2);
        current2.return = returnFiber;
        current2._debugInfo = currentDebugInfo;
        return current2;
      }
      function updatePortal(returnFiber, current2, portal, lanes) {
        if (null === current2 || 4 !== current2.tag || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation)
          return current2 = createFiberFromPortal(portal, returnFiber.mode, lanes), current2.return = returnFiber, current2._debugInfo = currentDebugInfo, current2;
        current2 = useFiber(current2, portal.children || []);
        current2.return = returnFiber;
        current2._debugInfo = currentDebugInfo;
        return current2;
      }
      function updateFragment(returnFiber, current2, fragment, lanes, key) {
        if (null === current2 || 7 !== current2.tag)
          return current2 = createFiberFromFragment(
            fragment,
            returnFiber.mode,
            lanes,
            key
          ), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugTask = returnFiber._debugTask, current2._debugInfo = currentDebugInfo, current2;
        current2 = useFiber(current2, fragment);
        current2.return = returnFiber;
        current2._debugInfo = currentDebugInfo;
        return current2;
      }
      function createChild(returnFiber, newChild, lanes) {
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return newChild = createFiberFromText(
            "" + newChild,
            returnFiber.mode,
            lanes
          ), newChild.return = returnFiber, newChild._debugOwner = returnFiber, newChild._debugTask = returnFiber._debugTask, newChild._debugInfo = currentDebugInfo, newChild;
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return lanes = createFiberFromElement(
                newChild,
                returnFiber.mode,
                lanes
              ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
            case REACT_PORTAL_TYPE:
              return newChild = createFiberFromPortal(
                newChild,
                returnFiber.mode,
                lanes
              ), newChild.return = returnFiber, newChild._debugInfo = currentDebugInfo, newChild;
            case REACT_LAZY_TYPE:
              var _prevDebugInfo = pushDebugInfo(newChild._debugInfo);
              newChild = resolveLazy(newChild);
              returnFiber = createChild(returnFiber, newChild, lanes);
              currentDebugInfo = _prevDebugInfo;
              return returnFiber;
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return lanes = createFiberFromFragment(
              newChild,
              returnFiber.mode,
              lanes,
              null
            ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
          if ("function" === typeof newChild.then)
            return _prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = createChild(
              returnFiber,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = _prevDebugInfo, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return createChild(
              returnFiber,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return null;
      }
      function updateSlot(returnFiber, oldFiber, newChild, lanes) {
        var key = null !== oldFiber ? oldFiber.key : null;
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return newChild.key === key ? (key = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                returnFiber,
                oldFiber,
                newChild,
                lanes
              ), currentDebugInfo = key, returnFiber) : null;
            case REACT_PORTAL_TYPE:
              return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
            case REACT_LAZY_TYPE:
              return key = pushDebugInfo(newChild._debugInfo), newChild = resolveLazy(newChild), returnFiber = updateSlot(
                returnFiber,
                oldFiber,
                newChild,
                lanes
              ), currentDebugInfo = key, returnFiber;
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild)) {
            if (null !== key) return null;
            key = pushDebugInfo(newChild._debugInfo);
            returnFiber = updateFragment(
              returnFiber,
              oldFiber,
              newChild,
              lanes,
              null
            );
            currentDebugInfo = key;
            return returnFiber;
          }
          if ("function" === typeof newChild.then)
            return key = pushDebugInfo(newChild._debugInfo), returnFiber = updateSlot(
              returnFiber,
              oldFiber,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = key, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return updateSlot(
              returnFiber,
              oldFiber,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return null;
      }
      function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              return newIdx = existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                returnFiber,
                newIdx,
                newChild,
                lanes
              ), currentDebugInfo = existingChildren, returnFiber;
            case REACT_PORTAL_TYPE:
              return existingChildren = existingChildren.get(
                null === newChild.key ? newIdx : newChild.key
              ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
            case REACT_LAZY_TYPE:
              var _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo);
              newChild = resolveLazy(newChild);
              returnFiber = updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                newChild,
                lanes
              );
              currentDebugInfo = _prevDebugInfo7;
              return returnFiber;
          }
          if (isArrayImpl(newChild) || getIteratorFn(newChild))
            return newIdx = existingChildren.get(newIdx) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateFragment(
              returnFiber,
              newIdx,
              newChild,
              lanes,
              null
            ), currentDebugInfo = existingChildren, returnFiber;
          if ("function" === typeof newChild.then)
            return _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo), returnFiber = updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = _prevDebugInfo7, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return updateFromMap(
              existingChildren,
              returnFiber,
              newIdx,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return null;
      }
      function warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys) {
        if ("object" !== typeof child || null === child) return knownKeys;
        switch (child.$$typeof) {
          case REACT_ELEMENT_TYPE:
          case REACT_PORTAL_TYPE:
            warnForMissingKey(returnFiber, workInProgress2, child);
            var key = child.key;
            if ("string" !== typeof key) break;
            if (null === knownKeys) {
              knownKeys = /* @__PURE__ */ new Set();
              knownKeys.add(key);
              break;
            }
            if (!knownKeys.has(key)) {
              knownKeys.add(key);
              break;
            }
            runWithFiberInDEV(workInProgress2, function() {
              console.error(
                "Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.",
                key
              );
            });
            break;
          case REACT_LAZY_TYPE:
            child = resolveLazy(child), warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys);
        }
        return knownKeys;
      }
      function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
        for (var knownKeys = null, resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
          oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
          var newFiber = updateSlot(
            returnFiber,
            oldFiber,
            newChildren[newIdx],
            lanes
          );
          if (null === newFiber) {
            null === oldFiber && (oldFiber = nextOldFiber);
            break;
          }
          knownKeys = warnOnInvalidKey(
            returnFiber,
            newFiber,
            newChildren[newIdx],
            knownKeys
          );
          shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
          currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
          null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }
        if (newIdx === newChildren.length)
          return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
        if (null === oldFiber) {
          for (; newIdx < newChildren.length; newIdx++)
            oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              oldFiber,
              newChildren[newIdx],
              knownKeys
            ), currentFirstChild = placeChild(
              oldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
          nextOldFiber = updateFromMap(
            oldFiber,
            returnFiber,
            newIdx,
            newChildren[newIdx],
            lanes
          ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
            returnFiber,
            nextOldFiber,
            newChildren[newIdx],
            knownKeys
          ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
            null === nextOldFiber.key ? newIdx : nextOldFiber.key
          ), currentFirstChild = placeChild(
            nextOldFiber,
            currentFirstChild,
            newIdx
          ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
        shouldTrackSideEffects && oldFiber.forEach(function(child) {
          return deleteChild(returnFiber, child);
        });
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
        if (null == newChildren)
          throw Error("An iterable object provided no iterator.");
        for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, knownKeys = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
          oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
          var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
          if (null === newFiber) {
            null === oldFiber && (oldFiber = nextOldFiber);
            break;
          }
          knownKeys = warnOnInvalidKey(
            returnFiber,
            newFiber,
            step.value,
            knownKeys
          );
          shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
          currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
          null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
          previousNewFiber = newFiber;
          oldFiber = nextOldFiber;
        }
        if (step.done)
          return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
        if (null === oldFiber) {
          for (; !step.done; newIdx++, step = newChildren.next())
            oldFiber = createChild(returnFiber, step.value, lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              oldFiber,
              step.value,
              knownKeys
            ), currentFirstChild = placeChild(
              oldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
          nextOldFiber = updateFromMap(
            oldFiber,
            returnFiber,
            newIdx,
            step.value,
            lanes
          ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
            returnFiber,
            nextOldFiber,
            step.value,
            knownKeys
          ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
            null === nextOldFiber.key ? newIdx : nextOldFiber.key
          ), currentFirstChild = placeChild(
            nextOldFiber,
            currentFirstChild,
            newIdx
          ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
        shouldTrackSideEffects && oldFiber.forEach(function(child) {
          return deleteChild(returnFiber, child);
        });
        isHydrating && pushTreeFork(returnFiber, newIdx);
        return resultingFirstChild;
      }
      function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
        "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (validateFragmentProps(newChild, null, returnFiber), newChild = newChild.props.children);
        if ("object" === typeof newChild && null !== newChild) {
          switch (newChild.$$typeof) {
            case REACT_ELEMENT_TYPE:
              var prevDebugInfo = pushDebugInfo(newChild._debugInfo);
              a: {
                for (var key = newChild.key; null !== currentFirstChild; ) {
                  if (currentFirstChild.key === key) {
                    key = newChild.type;
                    if (key === REACT_FRAGMENT_TYPE) {
                      if (7 === currentFirstChild.tag) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(
                          currentFirstChild,
                          newChild.props.children
                        );
                        lanes.return = returnFiber;
                        lanes._debugOwner = newChild._owner;
                        lanes._debugInfo = currentDebugInfo;
                        validateFragmentProps(newChild, lanes, returnFiber);
                        returnFiber = lanes;
                        break a;
                      }
                    } else if (currentFirstChild.elementType === key || isCompatibleFamilyForHotReloading(
                      currentFirstChild,
                      newChild
                    ) || "object" === typeof key && null !== key && key.$$typeof === REACT_LAZY_TYPE && resolveLazy(key) === currentFirstChild.type) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(currentFirstChild, newChild.props);
                      coerceRef(lanes, newChild);
                      lanes.return = returnFiber;
                      lanes._debugOwner = newChild._owner;
                      lanes._debugInfo = currentDebugInfo;
                      returnFiber = lanes;
                      break a;
                    }
                    deleteRemainingChildren(returnFiber, currentFirstChild);
                    break;
                  } else deleteChild(returnFiber, currentFirstChild);
                  currentFirstChild = currentFirstChild.sibling;
                }
                newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                  newChild.props.children,
                  returnFiber.mode,
                  lanes,
                  newChild.key
                ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, validateFragmentProps(newChild, lanes, returnFiber), returnFiber = lanes) : (lanes = createFiberFromElement(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes._debugInfo = currentDebugInfo, returnFiber = lanes);
              }
              returnFiber = placeSingleChild(returnFiber);
              currentDebugInfo = prevDebugInfo;
              return returnFiber;
            case REACT_PORTAL_TYPE:
              a: {
                prevDebugInfo = newChild;
                for (newChild = prevDebugInfo.key; null !== currentFirstChild; ) {
                  if (currentFirstChild.key === newChild)
                    if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === prevDebugInfo.containerInfo && currentFirstChild.stateNode.implementation === prevDebugInfo.implementation) {
                      deleteRemainingChildren(
                        returnFiber,
                        currentFirstChild.sibling
                      );
                      lanes = useFiber(
                        currentFirstChild,
                        prevDebugInfo.children || []
                      );
                      lanes.return = returnFiber;
                      returnFiber = lanes;
                      break a;
                    } else {
                      deleteRemainingChildren(returnFiber, currentFirstChild);
                      break;
                    }
                  else deleteChild(returnFiber, currentFirstChild);
                  currentFirstChild = currentFirstChild.sibling;
                }
                lanes = createFiberFromPortal(
                  prevDebugInfo,
                  returnFiber.mode,
                  lanes
                );
                lanes.return = returnFiber;
                returnFiber = lanes;
              }
              return placeSingleChild(returnFiber);
            case REACT_LAZY_TYPE:
              return prevDebugInfo = pushDebugInfo(newChild._debugInfo), newChild = resolveLazy(newChild), returnFiber = reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              ), currentDebugInfo = prevDebugInfo, returnFiber;
          }
          if (isArrayImpl(newChild))
            return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildrenArray(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            ), currentDebugInfo = prevDebugInfo, returnFiber;
          if (getIteratorFn(newChild)) {
            prevDebugInfo = pushDebugInfo(newChild._debugInfo);
            key = getIteratorFn(newChild);
            if ("function" !== typeof key)
              throw Error(
                "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."
              );
            var newChildren = key.call(newChild);
            if (newChildren === newChild) {
              if (0 !== returnFiber.tag || "[object GeneratorFunction]" !== Object.prototype.toString.call(returnFiber.type) || "[object Generator]" !== Object.prototype.toString.call(newChildren))
                didWarnAboutGenerators || console.error(
                  "Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."
                ), didWarnAboutGenerators = true;
            } else
              newChild.entries !== key || didWarnAboutMaps || (console.error(
                "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
              ), didWarnAboutMaps = true);
            returnFiber = reconcileChildrenIterator(
              returnFiber,
              currentFirstChild,
              newChildren,
              lanes
            );
            currentDebugInfo = prevDebugInfo;
            return returnFiber;
          }
          if ("function" === typeof newChild.then)
            return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              unwrapThenable(newChild),
              lanes
            ), currentDebugInfo = prevDebugInfo, returnFiber;
          if (newChild.$$typeof === REACT_CONTEXT_TYPE)
            return reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              readContextDuringReconciliation(returnFiber, newChild),
              lanes
            );
          throwOnInvalidObjectType(returnFiber, newChild);
        }
        if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
          return prevDebugInfo = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(
            returnFiber,
            currentFirstChild.sibling
          ), lanes = useFiber(currentFirstChild, prevDebugInfo), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(
            prevDebugInfo,
            returnFiber.mode,
            lanes
          ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, returnFiber = lanes), placeSingleChild(returnFiber);
        "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
        "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
        return deleteRemainingChildren(returnFiber, currentFirstChild);
      }
      return function(returnFiber, currentFirstChild, newChild, lanes) {
        var prevDebugInfo = currentDebugInfo;
        currentDebugInfo = null;
        try {
          thenableIndexCounter$1 = 0;
          var firstChildFiber = reconcileChildFibersImpl(
            returnFiber,
            currentFirstChild,
            newChild,
            lanes
          );
          thenableState$1 = null;
          return firstChildFiber;
        } catch (x2) {
          if (x2 === SuspenseException || x2 === SuspenseActionException) throw x2;
          var fiber = createFiber(29, x2, null, returnFiber.mode);
          fiber.lanes = lanes;
          fiber.return = returnFiber;
          var debugInfo = fiber._debugInfo = currentDebugInfo;
          fiber._debugOwner = returnFiber._debugOwner;
          fiber._debugTask = returnFiber._debugTask;
          if (null != debugInfo) {
            for (var i = debugInfo.length - 1; 0 <= i; i--)
              if ("string" === typeof debugInfo[i].stack) {
                fiber._debugOwner = debugInfo[i];
                fiber._debugTask = debugInfo[i].debugTask;
                break;
              }
          }
          return fiber;
        } finally {
          currentDebugInfo = prevDebugInfo;
        }
      };
    }
    function validateSuspenseListNestedChild(childSlot, index2) {
      var isAnArray = isArrayImpl(childSlot);
      childSlot = !isAnArray && "function" === typeof getIteratorFn(childSlot);
      return isAnArray || childSlot ? (isAnArray = isAnArray ? "array" : "iterable", console.error(
        "A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>",
        isAnArray,
        index2,
        isAnArray
      ), false) : true;
    }
    function initializeUpdateQueue(fiber) {
      fiber.updateQueue = {
        baseState: fiber.memoizedState,
        firstBaseUpdate: null,
        lastBaseUpdate: null,
        shared: { pending: null, lanes: 0, hiddenCallbacks: null },
        callbacks: null
      };
    }
    function cloneUpdateQueue(current2, workInProgress2) {
      current2 = current2.updateQueue;
      workInProgress2.updateQueue === current2 && (workInProgress2.updateQueue = {
        baseState: current2.baseState,
        firstBaseUpdate: current2.firstBaseUpdate,
        lastBaseUpdate: current2.lastBaseUpdate,
        shared: current2.shared,
        callbacks: null
      });
    }
    function createUpdate(lane) {
      return {
        lane,
        tag: UpdateState,
        payload: null,
        callback: null,
        next: null
      };
    }
    function enqueueUpdate(fiber, update, lane) {
      var updateQueue = fiber.updateQueue;
      if (null === updateQueue) return null;
      updateQueue = updateQueue.shared;
      if (currentlyProcessingQueue === updateQueue && !didWarnUpdateInsideUpdate) {
        var componentName2 = getComponentNameFromFiber(fiber);
        console.error(
          "An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.\n\nPlease update the following component: %s",
          componentName2
        );
        didWarnUpdateInsideUpdate = true;
      }
      if ((executionContext & RenderContext) !== NoContext)
        return componentName2 = updateQueue.pending, null === componentName2 ? update.next = update : (update.next = componentName2.next, componentName2.next = update), updateQueue.pending = update, update = getRootForUpdatedFiber(fiber), markUpdateLaneFromFiberToRoot(fiber, null, lane), update;
      enqueueUpdate$1(fiber, updateQueue, update, lane);
      return getRootForUpdatedFiber(fiber);
    }
    function entangleTransitions(root3, fiber, lane) {
      fiber = fiber.updateQueue;
      if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
        var queueLanes = fiber.lanes;
        queueLanes &= root3.pendingLanes;
        lane |= queueLanes;
        fiber.lanes = lane;
        markRootEntangled(root3, lane);
      }
    }
    function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
      var queue = workInProgress2.updateQueue, current2 = workInProgress2.alternate;
      if (null !== current2 && (current2 = current2.updateQueue, queue === current2)) {
        var newFirst = null, newLast = null;
        queue = queue.firstBaseUpdate;
        if (null !== queue) {
          do {
            var clone = {
              lane: queue.lane,
              tag: queue.tag,
              payload: queue.payload,
              callback: null,
              next: null
            };
            null === newLast ? newFirst = newLast = clone : newLast = newLast.next = clone;
            queue = queue.next;
          } while (null !== queue);
          null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
        } else newFirst = newLast = capturedUpdate;
        queue = {
          baseState: current2.baseState,
          firstBaseUpdate: newFirst,
          lastBaseUpdate: newLast,
          shared: current2.shared,
          callbacks: current2.callbacks
        };
        workInProgress2.updateQueue = queue;
        return;
      }
      workInProgress2 = queue.lastBaseUpdate;
      null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
      queue.lastBaseUpdate = capturedUpdate;
    }
    function suspendIfUpdateReadFromEntangledAsyncAction() {
      if (didReadFromEntangledAsyncAction) {
        var entangledActionThenable = currentEntangledActionThenable;
        if (null !== entangledActionThenable) throw entangledActionThenable;
      }
    }
    function processUpdateQueue(workInProgress2, props, instance$jscomp$0, renderLanes2) {
      didReadFromEntangledAsyncAction = false;
      var queue = workInProgress2.updateQueue;
      hasForceUpdate = false;
      currentlyProcessingQueue = queue.shared;
      var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
      if (null !== pendingQueue) {
        queue.shared.pending = null;
        var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
        lastPendingUpdate.next = null;
        null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
        lastBaseUpdate = lastPendingUpdate;
        var current2 = workInProgress2.alternate;
        null !== current2 && (current2 = current2.updateQueue, pendingQueue = current2.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current2.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current2.lastBaseUpdate = lastPendingUpdate));
      }
      if (null !== firstBaseUpdate) {
        var newState = queue.baseState;
        lastBaseUpdate = 0;
        current2 = firstPendingUpdate = lastPendingUpdate = null;
        pendingQueue = firstBaseUpdate;
        do {
          var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
          if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
            0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
            null !== current2 && (current2 = current2.next = {
              lane: 0,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: null,
              next: null
            });
            a: {
              updateLane = workInProgress2;
              var partialState = pendingQueue;
              var nextProps = props, instance = instance$jscomp$0;
              switch (partialState.tag) {
                case ReplaceState:
                  partialState = partialState.payload;
                  if ("function" === typeof partialState) {
                    isDisallowedContextReadInDEV = true;
                    var nextState = partialState.call(
                      instance,
                      newState,
                      nextProps
                    );
                    if (updateLane.mode & StrictLegacyMode) {
                      setIsStrictModeForDevtools(true);
                      try {
                        partialState.call(instance, newState, nextProps);
                      } finally {
                        setIsStrictModeForDevtools(false);
                      }
                    }
                    isDisallowedContextReadInDEV = false;
                    newState = nextState;
                    break a;
                  }
                  newState = partialState;
                  break a;
                case CaptureUpdate:
                  updateLane.flags = updateLane.flags & -65537 | 128;
                case UpdateState:
                  nextState = partialState.payload;
                  if ("function" === typeof nextState) {
                    isDisallowedContextReadInDEV = true;
                    partialState = nextState.call(
                      instance,
                      newState,
                      nextProps
                    );
                    if (updateLane.mode & StrictLegacyMode) {
                      setIsStrictModeForDevtools(true);
                      try {
                        nextState.call(instance, newState, nextProps);
                      } finally {
                        setIsStrictModeForDevtools(false);
                      }
                    }
                    isDisallowedContextReadInDEV = false;
                  } else partialState = nextState;
                  if (null === partialState || void 0 === partialState) break a;
                  newState = assign({}, newState, partialState);
                  break a;
                case ForceUpdate:
                  hasForceUpdate = true;
              }
            }
            updateLane = pendingQueue.callback;
            null !== updateLane && (workInProgress2.flags |= 64, isHiddenUpdate && (workInProgress2.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
          } else
            isHiddenUpdate = {
              lane: updateLane,
              tag: pendingQueue.tag,
              payload: pendingQueue.payload,
              callback: pendingQueue.callback,
              next: null
            }, null === current2 ? (firstPendingUpdate = current2 = isHiddenUpdate, lastPendingUpdate = newState) : current2 = current2.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
          pendingQueue = pendingQueue.next;
          if (null === pendingQueue)
            if (pendingQueue = queue.shared.pending, null === pendingQueue)
              break;
            else
              isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
        } while (1);
        null === current2 && (lastPendingUpdate = newState);
        queue.baseState = lastPendingUpdate;
        queue.firstBaseUpdate = firstPendingUpdate;
        queue.lastBaseUpdate = current2;
        null === firstBaseUpdate && (queue.shared.lanes = 0);
        workInProgressRootSkippedLanes |= lastBaseUpdate;
        workInProgress2.lanes = lastBaseUpdate;
        workInProgress2.memoizedState = newState;
      }
      currentlyProcessingQueue = null;
    }
    function callCallback(callback, context) {
      if ("function" !== typeof callback)
        throw Error(
          "Invalid argument passed as callback. Expected a function. Instead received: " + callback
        );
      callback.call(context);
    }
    function commitHiddenCallbacks(updateQueue, context) {
      var hiddenCallbacks = updateQueue.shared.hiddenCallbacks;
      if (null !== hiddenCallbacks)
        for (updateQueue.shared.hiddenCallbacks = null, updateQueue = 0; updateQueue < hiddenCallbacks.length; updateQueue++)
          callCallback(hiddenCallbacks[updateQueue], context);
    }
    function commitCallbacks(updateQueue, context) {
      var callbacks = updateQueue.callbacks;
      if (null !== callbacks)
        for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
          callCallback(callbacks[updateQueue], context);
    }
    function pushHiddenContext(fiber, context) {
      var prevEntangledRenderLanes = entangledRenderLanes;
      push2(prevEntangledRenderLanesCursor, prevEntangledRenderLanes, fiber);
      push2(currentTreeHiddenStackCursor, context, fiber);
      entangledRenderLanes = prevEntangledRenderLanes | context.baseLanes;
    }
    function reuseHiddenContextOnStack(fiber) {
      push2(prevEntangledRenderLanesCursor, entangledRenderLanes, fiber);
      push2(
        currentTreeHiddenStackCursor,
        currentTreeHiddenStackCursor.current,
        fiber
      );
    }
    function popHiddenContext(fiber) {
      entangledRenderLanes = prevEntangledRenderLanesCursor.current;
      pop(currentTreeHiddenStackCursor, fiber);
      pop(prevEntangledRenderLanesCursor, fiber);
    }
    function pushPrimaryTreeSuspenseHandler(handler) {
      var current2 = handler.alternate;
      push2(
        suspenseStackCursor,
        suspenseStackCursor.current & SubtreeSuspenseContextMask,
        handler
      );
      push2(suspenseHandlerStackCursor, handler, handler);
      null === shellBoundary && (null === current2 || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current2.memoizedState && (shellBoundary = handler));
    }
    function pushDehydratedActivitySuspenseHandler(fiber) {
      push2(suspenseStackCursor, suspenseStackCursor.current, fiber);
      push2(suspenseHandlerStackCursor, fiber, fiber);
      null === shellBoundary && (shellBoundary = fiber);
    }
    function pushOffscreenSuspenseHandler(fiber) {
      22 === fiber.tag ? (push2(suspenseStackCursor, suspenseStackCursor.current, fiber), push2(suspenseHandlerStackCursor, fiber, fiber), null === shellBoundary && (shellBoundary = fiber)) : reuseSuspenseHandlerOnStack(fiber);
    }
    function reuseSuspenseHandlerOnStack(fiber) {
      push2(suspenseStackCursor, suspenseStackCursor.current, fiber);
      push2(
        suspenseHandlerStackCursor,
        suspenseHandlerStackCursor.current,
        fiber
      );
    }
    function popSuspenseHandler(fiber) {
      pop(suspenseHandlerStackCursor, fiber);
      shellBoundary === fiber && (shellBoundary = null);
      pop(suspenseStackCursor, fiber);
    }
    function findFirstSuspended(row) {
      for (var node2 = row; null !== node2; ) {
        if (13 === node2.tag) {
          var state = node2.memoizedState;
          if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
            return node2;
        } else if (19 === node2.tag && ("forwards" === node2.memoizedProps.revealOrder || "backwards" === node2.memoizedProps.revealOrder || "unstable_legacy-backwards" === node2.memoizedProps.revealOrder || "together" === node2.memoizedProps.revealOrder)) {
          if (0 !== (node2.flags & 128)) return node2;
        } else if (null !== node2.child) {
          node2.child.return = node2;
          node2 = node2.child;
          continue;
        }
        if (node2 === row) break;
        for (; null === node2.sibling; ) {
          if (null === node2.return || node2.return === row) return null;
          node2 = node2.return;
        }
        node2.sibling.return = node2.return;
        node2 = node2.sibling;
      }
      return null;
    }
    function mountHookTypesDev() {
      var hookName = currentHookNameInDev;
      null === hookTypesDev ? hookTypesDev = [hookName] : hookTypesDev.push(hookName);
    }
    function updateHookTypesDev() {
      var hookName = currentHookNameInDev;
      if (null !== hookTypesDev && (hookTypesUpdateIndexDev++, hookTypesDev[hookTypesUpdateIndexDev] !== hookName)) {
        var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
        if (!didWarnAboutMismatchedHooksForComponent.has(componentName2) && (didWarnAboutMismatchedHooksForComponent.add(componentName2), null !== hookTypesDev)) {
          for (var table2 = "", i = 0; i <= hookTypesUpdateIndexDev; i++) {
            var oldHookName = hookTypesDev[i], newHookName = i === hookTypesUpdateIndexDev ? hookName : oldHookName;
            for (oldHookName = i + 1 + ". " + oldHookName; 30 > oldHookName.length; )
              oldHookName += " ";
            oldHookName += newHookName + "\n";
            table2 += oldHookName;
          }
          console.error(
            "React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks\n\n   Previous render            Next render\n   ------------------------------------------------------\n%s   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
            componentName2,
            table2
          );
        }
      }
    }
    function checkDepsAreArrayDev(deps) {
      void 0 === deps || null === deps || isArrayImpl(deps) || console.error(
        "%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.",
        currentHookNameInDev,
        typeof deps
      );
    }
    function warnOnUseFormStateInDev() {
      var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
      didWarnAboutUseFormState.has(componentName2) || (didWarnAboutUseFormState.add(componentName2), console.error(
        "ReactDOM.useFormState has been renamed to React.useActionState. Please update %s to use React.useActionState.",
        componentName2
      ));
    }
    function throwInvalidHookError() {
      throw Error(
        "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
      );
    }
    function areHookInputsEqual(nextDeps, prevDeps) {
      if (ignorePreviousDependencies) return false;
      if (null === prevDeps)
        return console.error(
          "%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",
          currentHookNameInDev
        ), false;
      nextDeps.length !== prevDeps.length && console.error(
        "The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",
        currentHookNameInDev,
        "[" + prevDeps.join(", ") + "]",
        "[" + nextDeps.join(", ") + "]"
      );
      for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
        if (!objectIs(nextDeps[i], prevDeps[i])) return false;
      return true;
    }
    function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) {
      renderLanes = nextRenderLanes;
      currentlyRenderingFiber = workInProgress2;
      hookTypesDev = null !== current2 ? current2._debugHookTypes : null;
      hookTypesUpdateIndexDev = -1;
      ignorePreviousDependencies = null !== current2 && current2.type !== workInProgress2.type;
      if ("[object AsyncFunction]" === Object.prototype.toString.call(Component) || "[object AsyncGeneratorFunction]" === Object.prototype.toString.call(Component))
        nextRenderLanes = getComponentNameFromFiber(currentlyRenderingFiber), didWarnAboutAsyncClientComponent.has(nextRenderLanes) || (didWarnAboutAsyncClientComponent.add(nextRenderLanes), console.error(
          "%s is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.",
          null === nextRenderLanes ? "An unknown Component" : "<" + nextRenderLanes + ">"
        ));
      workInProgress2.memoizedState = null;
      workInProgress2.updateQueue = null;
      workInProgress2.lanes = 0;
      ReactSharedInternals.H = null !== current2 && null !== current2.memoizedState ? HooksDispatcherOnUpdateInDEV : null !== hookTypesDev ? HooksDispatcherOnMountWithHookTypesInDEV : HooksDispatcherOnMountInDEV;
      shouldDoubleInvokeUserFnsInHooksDEV = nextRenderLanes = (workInProgress2.mode & StrictLegacyMode) !== NoMode;
      var children = callComponentInDEV(Component, props, secondArg);
      shouldDoubleInvokeUserFnsInHooksDEV = false;
      didScheduleRenderPhaseUpdateDuringThisPass && (children = renderWithHooksAgain(
        workInProgress2,
        Component,
        props,
        secondArg
      ));
      if (nextRenderLanes) {
        setIsStrictModeForDevtools(true);
        try {
          children = renderWithHooksAgain(
            workInProgress2,
            Component,
            props,
            secondArg
          );
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      finishRenderingHooks(current2, workInProgress2);
      return children;
    }
    function finishRenderingHooks(current2, workInProgress2) {
      workInProgress2._debugHookTypes = hookTypesDev;
      null === workInProgress2.dependencies ? null !== thenableState && (workInProgress2.dependencies = {
        lanes: 0,
        firstContext: null,
        _debugThenableState: thenableState
      }) : workInProgress2.dependencies._debugThenableState = thenableState;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
      renderLanes = 0;
      hookTypesDev = currentHookNameInDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
      hookTypesUpdateIndexDev = -1;
      null !== current2 && (current2.flags & 65011712) !== (workInProgress2.flags & 65011712) && console.error(
        "Internal React error: Expected static flag was missing. Please notify the React team."
      );
      didScheduleRenderPhaseUpdate = false;
      thenableIndexCounter = 0;
      thenableState = null;
      if (didRenderTooFewHooks)
        throw Error(
          "Rendered fewer hooks than expected. This may be caused by an accidental early return statement."
        );
      null === current2 || didReceiveUpdate || (current2 = current2.dependencies, null !== current2 && checkIfContextChanged(current2) && (didReceiveUpdate = true));
      needsToResetSuspendedThenableDEV ? (needsToResetSuspendedThenableDEV = false, current2 = true) : current2 = false;
      current2 && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Unknown", didWarnAboutUseWrappedInTryCatch.has(workInProgress2) || didWarnAboutAsyncClientComponent.has(workInProgress2) || (didWarnAboutUseWrappedInTryCatch.add(workInProgress2), console.error(
        "`use` was called from inside a try/catch block. This is not allowed and can lead to unexpected behavior. To handle errors triggered by `use`, wrap your component in a error boundary."
      )));
    }
    function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
      currentlyRenderingFiber = workInProgress2;
      var numberOfReRenders = 0;
      do {
        didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
        thenableIndexCounter = 0;
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        if (numberOfReRenders >= RE_RENDER_LIMIT)
          throw Error(
            "Too many re-renders. React limits the number of renders to prevent an infinite loop."
          );
        numberOfReRenders += 1;
        ignorePreviousDependencies = false;
        workInProgressHook = currentHook = null;
        if (null != workInProgress2.updateQueue) {
          var children = workInProgress2.updateQueue;
          children.lastEffect = null;
          children.events = null;
          children.stores = null;
          null != children.memoCache && (children.memoCache.index = 0);
        }
        hookTypesUpdateIndexDev = -1;
        ReactSharedInternals.H = HooksDispatcherOnRerenderInDEV;
        children = callComponentInDEV(Component, props, secondArg);
      } while (didScheduleRenderPhaseUpdateDuringThisPass);
      return children;
    }
    function TransitionAwareHostComponent() {
      var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
      maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
      dispatcher = dispatcher.useState()[0];
      (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
      return maybeThenable;
    }
    function checkDidRenderIdHook() {
      var didRenderIdHook = 0 !== localIdCounter;
      localIdCounter = 0;
      return didRenderIdHook;
    }
    function bailoutHooks(current2, workInProgress2, lanes) {
      workInProgress2.updateQueue = current2.updateQueue;
      workInProgress2.flags = (workInProgress2.mode & StrictEffectsMode) !== NoMode ? workInProgress2.flags & -402655237 : workInProgress2.flags & -2053;
      current2.lanes &= ~lanes;
    }
    function resetHooksOnUnwind(workInProgress2) {
      if (didScheduleRenderPhaseUpdate) {
        for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
          var queue = workInProgress2.queue;
          null !== queue && (queue.pending = null);
          workInProgress2 = workInProgress2.next;
        }
        didScheduleRenderPhaseUpdate = false;
      }
      renderLanes = 0;
      hookTypesDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
      hookTypesUpdateIndexDev = -1;
      currentHookNameInDev = null;
      didScheduleRenderPhaseUpdateDuringThisPass = false;
      thenableIndexCounter = localIdCounter = 0;
      thenableState = null;
    }
    function mountWorkInProgressHook() {
      var hook = {
        memoizedState: null,
        baseState: null,
        baseQueue: null,
        queue: null,
        next: null
      };
      null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
      return workInProgressHook;
    }
    function updateWorkInProgressHook() {
      if (null === currentHook) {
        var nextCurrentHook = currentlyRenderingFiber.alternate;
        nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
      } else nextCurrentHook = currentHook.next;
      var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
      if (null !== nextWorkInProgressHook)
        workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
      else {
        if (null === nextCurrentHook) {
          if (null === currentlyRenderingFiber.alternate)
            throw Error(
              "Update hook called on initial render. This is likely a bug in React. Please file an issue."
            );
          throw Error("Rendered more hooks than during the previous render.");
        }
        currentHook = nextCurrentHook;
        nextCurrentHook = {
          memoizedState: currentHook.memoizedState,
          baseState: currentHook.baseState,
          baseQueue: currentHook.baseQueue,
          queue: currentHook.queue,
          next: null
        };
        null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
      }
      return workInProgressHook;
    }
    function createFunctionComponentUpdateQueue() {
      return { lastEffect: null, events: null, stores: null, memoCache: null };
    }
    function useThenable(thenable) {
      var index2 = thenableIndexCounter;
      thenableIndexCounter += 1;
      null === thenableState && (thenableState = createThenableState());
      thenable = trackUsedThenable(thenableState, thenable, index2);
      index2 = currentlyRenderingFiber;
      null === (null === workInProgressHook ? index2.memoizedState : workInProgressHook.next) && (index2 = index2.alternate, ReactSharedInternals.H = null !== index2 && null !== index2.memoizedState ? HooksDispatcherOnUpdateInDEV : HooksDispatcherOnMountInDEV);
      return thenable;
    }
    function use(usable) {
      if (null !== usable && "object" === typeof usable) {
        if ("function" === typeof usable.then) return useThenable(usable);
        if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
      }
      throw Error("An unsupported type was passed to use(): " + String(usable));
    }
    function useMemoCache(size) {
      var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
      null !== updateQueue && (memoCache = updateQueue.memoCache);
      if (null == memoCache) {
        var current2 = currentlyRenderingFiber.alternate;
        null !== current2 && (current2 = current2.updateQueue, null !== current2 && (current2 = current2.memoCache, null != current2 && (memoCache = {
          data: current2.data.map(function(array) {
            return array.slice();
          }),
          index: 0
        })));
      }
      null == memoCache && (memoCache = { data: [], index: 0 });
      null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
      updateQueue.memoCache = memoCache;
      updateQueue = memoCache.data[memoCache.index];
      if (void 0 === updateQueue || ignorePreviousDependencies)
        for (updateQueue = memoCache.data[memoCache.index] = Array(size), current2 = 0; current2 < size; current2++)
          updateQueue[current2] = REACT_MEMO_CACHE_SENTINEL;
      else
        updateQueue.length !== size && console.error(
          "Expected a constant size argument for each invocation of useMemoCache. The previous cache was allocated with size %s but size %s was requested.",
          updateQueue.length,
          size
        );
      memoCache.index++;
      return updateQueue;
    }
    function basicStateReducer(state, action) {
      return "function" === typeof action ? action(state) : action;
    }
    function mountReducer(reducer2, initialArg, init2) {
      var hook = mountWorkInProgressHook();
      if (void 0 !== init2) {
        var initialState2 = init2(initialArg);
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            init2(initialArg);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      } else initialState2 = initialArg;
      hook.memoizedState = hook.baseState = initialState2;
      reducer2 = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: reducer2,
        lastRenderedState: initialState2
      };
      hook.queue = reducer2;
      reducer2 = reducer2.dispatch = dispatchReducerAction.bind(
        null,
        currentlyRenderingFiber,
        reducer2
      );
      return [hook.memoizedState, reducer2];
    }
    function updateReducer(reducer2) {
      var hook = updateWorkInProgressHook();
      return updateReducerImpl(hook, currentHook, reducer2);
    }
    function updateReducerImpl(hook, current2, reducer2) {
      var queue = hook.queue;
      if (null === queue)
        throw Error(
          "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
        );
      queue.lastRenderedReducer = reducer2;
      var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
      if (null !== pendingQueue) {
        if (null !== baseQueue) {
          var baseFirst = baseQueue.next;
          baseQueue.next = pendingQueue.next;
          pendingQueue.next = baseFirst;
        }
        current2.baseQueue !== baseQueue && console.error(
          "Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."
        );
        current2.baseQueue = baseQueue = pendingQueue;
        queue.pending = null;
      }
      pendingQueue = hook.baseState;
      if (null === baseQueue) hook.memoizedState = pendingQueue;
      else {
        current2 = baseQueue.next;
        var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update = current2, didReadFromEntangledAsyncAction2 = false;
        do {
          var updateLane = update.lane & -536870913;
          if (updateLane !== update.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
            var revertLane = update.revertLane;
            if (0 === revertLane)
              null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
                lane: 0,
                revertLane: 0,
                gesture: null,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
            else if ((renderLanes & revertLane) === revertLane) {
              update = update.next;
              revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
              continue;
            } else
              updateLane = {
                lane: 0,
                revertLane: update.revertLane,
                gesture: null,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
            updateLane = update.action;
            shouldDoubleInvokeUserFnsInHooksDEV && reducer2(pendingQueue, updateLane);
            pendingQueue = update.hasEagerState ? update.eagerState : reducer2(pendingQueue, updateLane);
          } else
            revertLane = {
              lane: updateLane,
              revertLane: update.revertLane,
              gesture: update.gesture,
              action: update.action,
              hasEagerState: update.hasEagerState,
              eagerState: update.eagerState,
              next: null
            }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
          update = update.next;
        } while (null !== update && update !== current2);
        null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
        if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction2 && (reducer2 = currentEntangledActionThenable, null !== reducer2)))
          throw reducer2;
        hook.memoizedState = pendingQueue;
        hook.baseState = baseFirst;
        hook.baseQueue = newBaseQueueLast;
        queue.lastRenderedState = pendingQueue;
      }
      null === baseQueue && (queue.lanes = 0);
      return [hook.memoizedState, queue.dispatch];
    }
    function rerenderReducer(reducer2) {
      var hook = updateWorkInProgressHook(), queue = hook.queue;
      if (null === queue)
        throw Error(
          "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
        );
      queue.lastRenderedReducer = reducer2;
      var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
      if (null !== lastRenderPhaseUpdate) {
        queue.pending = null;
        var update = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
        do
          newState = reducer2(newState, update.action), update = update.next;
        while (update !== lastRenderPhaseUpdate);
        objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
        hook.memoizedState = newState;
        null === hook.baseQueue && (hook.baseState = newState);
        queue.lastRenderedState = newState;
      }
      return [newState, dispatch];
    }
    function mountSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
      if (isHydrating) {
        if (void 0 === getServerSnapshot)
          throw Error(
            "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
          );
        var nextSnapshot = getServerSnapshot();
        didWarnUncachedGetSnapshot || nextSnapshot === getServerSnapshot() || (console.error(
          "The result of getServerSnapshot should be cached to avoid an infinite loop"
        ), didWarnUncachedGetSnapshot = true);
      } else {
        nextSnapshot = getSnapshot();
        didWarnUncachedGetSnapshot || (getServerSnapshot = getSnapshot(), objectIs(nextSnapshot, getServerSnapshot) || (console.error(
          "The result of getSnapshot should be cached to avoid an infinite loop"
        ), didWarnUncachedGetSnapshot = true));
        if (null === workInProgressRoot)
          throw Error(
            "Expected a work-in-progress root. This is a bug in React. Please file an issue."
          );
        0 !== (workInProgressRootRenderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
      }
      hook.memoizedState = nextSnapshot;
      getServerSnapshot = { value: nextSnapshot, getSnapshot };
      hook.queue = getServerSnapshot;
      mountEffect(
        subscribeToStore.bind(null, fiber, getServerSnapshot, subscribe),
        [subscribe]
      );
      fiber.flags |= 2048;
      pushSimpleEffect(
        HasEffect | Passive,
        { destroy: void 0 },
        updateStoreInstance.bind(
          null,
          fiber,
          getServerSnapshot,
          nextSnapshot,
          getSnapshot
        ),
        null
      );
      return nextSnapshot;
    }
    function updateSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) {
      var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
      if (isHydrating$jscomp$0) {
        if (void 0 === getServerSnapshot)
          throw Error(
            "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
          );
        getServerSnapshot = getServerSnapshot();
      } else if (getServerSnapshot = getSnapshot(), !didWarnUncachedGetSnapshot) {
        var cachedSnapshot = getSnapshot();
        objectIs(getServerSnapshot, cachedSnapshot) || (console.error(
          "The result of getSnapshot should be cached to avoid an infinite loop"
        ), didWarnUncachedGetSnapshot = true);
      }
      if (cachedSnapshot = !objectIs(
        (currentHook || hook).memoizedState,
        getServerSnapshot
      ))
        hook.memoizedState = getServerSnapshot, didReceiveUpdate = true;
      hook = hook.queue;
      var create2 = subscribeToStore.bind(null, fiber, hook, subscribe);
      updateEffectImpl(2048, Passive, create2, [subscribe]);
      if (hook.getSnapshot !== getSnapshot || cachedSnapshot || null !== workInProgressHook && workInProgressHook.memoizedState.tag & HasEffect) {
        fiber.flags |= 2048;
        pushSimpleEffect(
          HasEffect | Passive,
          { destroy: void 0 },
          updateStoreInstance.bind(
            null,
            fiber,
            hook,
            getServerSnapshot,
            getSnapshot
          ),
          null
        );
        if (null === workInProgressRoot)
          throw Error(
            "Expected a work-in-progress root. This is a bug in React. Please file an issue."
          );
        isHydrating$jscomp$0 || 0 !== (renderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
      }
      return getServerSnapshot;
    }
    function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
      fiber.flags |= 16384;
      fiber = { getSnapshot, value: renderedSnapshot };
      getSnapshot = currentlyRenderingFiber.updateQueue;
      null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
    }
    function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
      inst.value = nextSnapshot;
      inst.getSnapshot = getSnapshot;
      checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
    }
    function subscribeToStore(fiber, inst, subscribe) {
      return subscribe(function() {
        checkIfSnapshotChanged(inst) && (startUpdateTimerByLane(2, "updateSyncExternalStore()", fiber), forceStoreRerender(fiber));
      });
    }
    function checkIfSnapshotChanged(inst) {
      var latestGetSnapshot = inst.getSnapshot;
      inst = inst.value;
      try {
        var nextValue = latestGetSnapshot();
        return !objectIs(inst, nextValue);
      } catch (error) {
        return true;
      }
    }
    function forceStoreRerender(fiber) {
      var root3 = enqueueConcurrentRenderForLane(fiber, 2);
      null !== root3 && scheduleUpdateOnFiber(root3, fiber, 2);
    }
    function mountStateImpl(initialState2) {
      var hook = mountWorkInProgressHook();
      if ("function" === typeof initialState2) {
        var initialStateInitializer = initialState2;
        initialState2 = initialStateInitializer();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            initialStateInitializer();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
      }
      hook.memoizedState = hook.baseState = initialState2;
      hook.queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: basicStateReducer,
        lastRenderedState: initialState2
      };
      return hook;
    }
    function mountState(initialState2) {
      initialState2 = mountStateImpl(initialState2);
      var queue = initialState2.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber, queue);
      queue.dispatch = dispatch;
      return [initialState2.memoizedState, dispatch];
    }
    function mountOptimistic(passthrough) {
      var hook = mountWorkInProgressHook();
      hook.memoizedState = hook.baseState = passthrough;
      var queue = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: null,
        lastRenderedState: null
      };
      hook.queue = queue;
      hook = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber,
        true,
        queue
      );
      queue.dispatch = hook;
      return [passthrough, hook];
    }
    function updateOptimistic(passthrough, reducer2) {
      var hook = updateWorkInProgressHook();
      return updateOptimisticImpl(hook, currentHook, passthrough, reducer2);
    }
    function updateOptimisticImpl(hook, current2, passthrough, reducer2) {
      hook.baseState = passthrough;
      return updateReducerImpl(
        hook,
        currentHook,
        "function" === typeof reducer2 ? reducer2 : basicStateReducer
      );
    }
    function rerenderOptimistic(passthrough, reducer2) {
      var hook = updateWorkInProgressHook();
      if (null !== currentHook)
        return updateOptimisticImpl(hook, currentHook, passthrough, reducer2);
      hook.baseState = passthrough;
      return [passthrough, hook.queue.dispatch];
    }
    function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
      if (isRenderPhaseUpdate(fiber))
        throw Error("Cannot update form state while rendering.");
      fiber = actionQueue.action;
      if (null !== fiber) {
        var actionNode = {
          payload,
          action: fiber,
          next: null,
          isTransition: true,
          status: "pending",
          value: null,
          reason: null,
          listeners: [],
          then: function(listener) {
            actionNode.listeners.push(listener);
          }
        };
        null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
        setState(actionNode);
        setPendingState = actionQueue.pending;
        null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
      }
    }
    function runActionStateAction(actionQueue, node2) {
      var action = node2.action, payload = node2.payload, prevState = actionQueue.state;
      if (node2.isTransition) {
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        ReactSharedInternals.T = currentTransition;
        try {
          var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          handleActionReturnValue(actionQueue, node2, returnValue);
        } catch (error) {
          onActionError(actionQueue, node2, error);
        } finally {
          null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
          ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (actionQueue = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < actionQueue && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          ));
        }
      } else
        try {
          currentTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node2, currentTransition);
        } catch (error$4) {
          onActionError(actionQueue, node2, error$4);
        }
    }
    function handleActionReturnValue(actionQueue, node2, returnValue) {
      null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(
        function(nextState) {
          onActionSuccess(actionQueue, node2, nextState);
        },
        function(error) {
          return onActionError(actionQueue, node2, error);
        }
      ), node2.isTransition || console.error(
        "An async function with useActionState was called outside of a transition. This is likely not what you intended (for example, isPending will not update correctly). Either call the returned function inside startTransition, or pass it to an `action` or `formAction` prop."
      )) : onActionSuccess(actionQueue, node2, returnValue);
    }
    function onActionSuccess(actionQueue, actionNode, nextState) {
      actionNode.status = "fulfilled";
      actionNode.value = nextState;
      notifyActionListeners(actionNode);
      actionQueue.state = nextState;
      actionNode = actionQueue.pending;
      null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
    }
    function onActionError(actionQueue, actionNode, error) {
      var last = actionQueue.pending;
      actionQueue.pending = null;
      if (null !== last) {
        last = last.next;
        do
          actionNode.status = "rejected", actionNode.reason = error, notifyActionListeners(actionNode), actionNode = actionNode.next;
        while (actionNode !== last);
      }
      actionQueue.action = null;
    }
    function notifyActionListeners(actionNode) {
      actionNode = actionNode.listeners;
      for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
    }
    function actionStateReducer(oldState, newState) {
      return newState;
    }
    function mountActionState(action, initialStateProp) {
      if (isHydrating) {
        var ssrFormState = workInProgressRoot.formState;
        if (null !== ssrFormState) {
          a: {
            var isMatching = currentlyRenderingFiber;
            if (isHydrating) {
              if (nextHydratableInstance) {
                b: {
                  var markerInstance = nextHydratableInstance;
                  for (var inRootOrSingleton = rootOrSingletonContext; 8 !== markerInstance.nodeType; ) {
                    if (!inRootOrSingleton) {
                      markerInstance = null;
                      break b;
                    }
                    markerInstance = getNextHydratable(
                      markerInstance.nextSibling
                    );
                    if (null === markerInstance) {
                      markerInstance = null;
                      break b;
                    }
                  }
                  inRootOrSingleton = markerInstance.data;
                  markerInstance = inRootOrSingleton === FORM_STATE_IS_MATCHING || inRootOrSingleton === FORM_STATE_IS_NOT_MATCHING ? markerInstance : null;
                }
                if (markerInstance) {
                  nextHydratableInstance = getNextHydratable(
                    markerInstance.nextSibling
                  );
                  isMatching = markerInstance.data === FORM_STATE_IS_MATCHING;
                  break a;
                }
              }
              throwOnHydrationMismatch(isMatching);
            }
            isMatching = false;
          }
          isMatching && (initialStateProp = ssrFormState[0]);
        }
      }
      ssrFormState = mountWorkInProgressHook();
      ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
      isMatching = {
        pending: null,
        lanes: 0,
        dispatch: null,
        lastRenderedReducer: actionStateReducer,
        lastRenderedState: initialStateProp
      };
      ssrFormState.queue = isMatching;
      ssrFormState = dispatchSetState.bind(
        null,
        currentlyRenderingFiber,
        isMatching
      );
      isMatching.dispatch = ssrFormState;
      isMatching = mountStateImpl(false);
      inRootOrSingleton = dispatchOptimisticSetState.bind(
        null,
        currentlyRenderingFiber,
        false,
        isMatching.queue
      );
      isMatching = mountWorkInProgressHook();
      markerInstance = {
        state: initialStateProp,
        dispatch: null,
        action,
        pending: null
      };
      isMatching.queue = markerInstance;
      ssrFormState = dispatchActionState.bind(
        null,
        currentlyRenderingFiber,
        markerInstance,
        inRootOrSingleton,
        ssrFormState
      );
      markerInstance.dispatch = ssrFormState;
      isMatching.memoizedState = action;
      return [initialStateProp, ssrFormState, false];
    }
    function updateActionState(action) {
      var stateHook = updateWorkInProgressHook();
      return updateActionStateImpl(stateHook, currentHook, action);
    }
    function updateActionStateImpl(stateHook, currentStateHook, action) {
      currentStateHook = updateReducerImpl(
        stateHook,
        currentStateHook,
        actionStateReducer
      )[0];
      stateHook = updateReducer(basicStateReducer)[0];
      if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
        try {
          var state = useThenable(currentStateHook);
        } catch (x2) {
          if (x2 === SuspenseException) throw SuspenseActionException;
          throw x2;
        }
      else state = currentStateHook;
      currentStateHook = updateWorkInProgressHook();
      var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
      action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
        HasEffect | Passive,
        { destroy: void 0 },
        actionStateActionEffect.bind(null, actionQueue, action),
        null
      ));
      return [state, dispatch, stateHook];
    }
    function actionStateActionEffect(actionQueue, action) {
      actionQueue.action = action;
    }
    function rerenderActionState(action) {
      var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
      if (null !== currentStateHook)
        return updateActionStateImpl(stateHook, currentStateHook, action);
      updateWorkInProgressHook();
      stateHook = stateHook.memoizedState;
      currentStateHook = updateWorkInProgressHook();
      var dispatch = currentStateHook.queue.dispatch;
      currentStateHook.memoizedState = action;
      return [stateHook, dispatch, false];
    }
    function pushSimpleEffect(tag, inst, create2, deps) {
      tag = { tag, create: create2, deps, inst, next: null };
      inst = currentlyRenderingFiber.updateQueue;
      null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
      create2 = inst.lastEffect;
      null === create2 ? inst.lastEffect = tag.next = tag : (deps = create2.next, create2.next = tag, tag.next = deps, inst.lastEffect = tag);
      return tag;
    }
    function mountRef(initialValue) {
      var hook = mountWorkInProgressHook();
      initialValue = { current: initialValue };
      return hook.memoizedState = initialValue;
    }
    function mountEffectImpl(fiberFlags, hookFlags, create2, deps) {
      var hook = mountWorkInProgressHook();
      currentlyRenderingFiber.flags |= fiberFlags;
      hook.memoizedState = pushSimpleEffect(
        HasEffect | hookFlags,
        { destroy: void 0 },
        create2,
        void 0 === deps ? null : deps
      );
    }
    function updateEffectImpl(fiberFlags, hookFlags, create2, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var inst = hook.memoizedState.inst;
      null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create2, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
        HasEffect | hookFlags,
        inst,
        create2,
        deps
      ));
    }
    function mountEffect(create2, deps) {
      (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode ? mountEffectImpl(276826112, Passive, create2, deps) : mountEffectImpl(8390656, Passive, create2, deps);
    }
    function useEffectEventImpl(payload) {
      currentlyRenderingFiber.flags |= 4;
      var componentUpdateQueue = currentlyRenderingFiber.updateQueue;
      if (null === componentUpdateQueue)
        componentUpdateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = componentUpdateQueue, componentUpdateQueue.events = [payload];
      else {
        var events = componentUpdateQueue.events;
        null === events ? componentUpdateQueue.events = [payload] : events.push(payload);
      }
    }
    function mountEvent(callback) {
      var hook = mountWorkInProgressHook(), ref2 = { impl: callback };
      hook.memoizedState = ref2;
      return function() {
        if ((executionContext & RenderContext) !== NoContext)
          throw Error(
            "A function wrapped in useEffectEvent can't be called during rendering."
          );
        return ref2.impl.apply(void 0, arguments);
      };
    }
    function updateEvent(callback) {
      var ref2 = updateWorkInProgressHook().memoizedState;
      useEffectEventImpl({ ref: ref2, nextImpl: callback });
      return function() {
        if ((executionContext & RenderContext) !== NoContext)
          throw Error(
            "A function wrapped in useEffectEvent can't be called during rendering."
          );
        return ref2.impl.apply(void 0, arguments);
      };
    }
    function mountLayoutEffect(create2, deps) {
      var fiberFlags = 4194308;
      (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (fiberFlags |= 134217728);
      return mountEffectImpl(fiberFlags, Layout, create2, deps);
    }
    function imperativeHandleEffect(create2, ref2) {
      if ("function" === typeof ref2) {
        create2 = create2();
        var refCleanup = ref2(create2);
        return function() {
          "function" === typeof refCleanup ? refCleanup() : ref2(null);
        };
      }
      if (null !== ref2 && void 0 !== ref2)
        return ref2.hasOwnProperty("current") || console.error(
          "Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.",
          "an object with keys {" + Object.keys(ref2).join(", ") + "}"
        ), create2 = create2(), ref2.current = create2, function() {
          ref2.current = null;
        };
    }
    function mountImperativeHandle(ref2, create2, deps) {
      "function" !== typeof create2 && console.error(
        "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
        null !== create2 ? typeof create2 : "null"
      );
      deps = null !== deps && void 0 !== deps ? deps.concat([ref2]) : null;
      var fiberFlags = 4194308;
      (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (fiberFlags |= 134217728);
      mountEffectImpl(
        fiberFlags,
        Layout,
        imperativeHandleEffect.bind(null, create2, ref2),
        deps
      );
    }
    function updateImperativeHandle(ref2, create2, deps) {
      "function" !== typeof create2 && console.error(
        "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
        null !== create2 ? typeof create2 : "null"
      );
      deps = null !== deps && void 0 !== deps ? deps.concat([ref2]) : null;
      updateEffectImpl(
        4,
        Layout,
        imperativeHandleEffect.bind(null, create2, ref2),
        deps
      );
    }
    function mountCallback(callback, deps) {
      mountWorkInProgressHook().memoizedState = [
        callback,
        void 0 === deps ? null : deps
      ];
      return callback;
    }
    function updateCallback(callback, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var prevState = hook.memoizedState;
      if (null !== deps && areHookInputsEqual(deps, prevState[1]))
        return prevState[0];
      hook.memoizedState = [callback, deps];
      return callback;
    }
    function mountMemo(nextCreate, deps) {
      var hook = mountWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var nextValue = nextCreate();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          nextCreate();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      hook.memoizedState = [nextValue, deps];
      return nextValue;
    }
    function updateMemo(nextCreate, deps) {
      var hook = updateWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      var prevState = hook.memoizedState;
      if (null !== deps && areHookInputsEqual(deps, prevState[1]))
        return prevState[0];
      prevState = nextCreate();
      if (shouldDoubleInvokeUserFnsInHooksDEV) {
        setIsStrictModeForDevtools(true);
        try {
          nextCreate();
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      hook.memoizedState = [prevState, deps];
      return prevState;
    }
    function mountDeferredValue(value, initialValue) {
      var hook = mountWorkInProgressHook();
      return mountDeferredValueImpl(hook, value, initialValue);
    }
    function updateDeferredValue(value, initialValue) {
      var hook = updateWorkInProgressHook();
      return updateDeferredValueImpl(
        hook,
        currentHook.memoizedState,
        value,
        initialValue
      );
    }
    function rerenderDeferredValue(value, initialValue) {
      var hook = updateWorkInProgressHook();
      return null === currentHook ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(
        hook,
        currentHook.memoizedState,
        value,
        initialValue
      );
    }
    function mountDeferredValueImpl(hook, value, initialValue) {
      if (void 0 === initialValue || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
        return hook.memoizedState = value;
      hook.memoizedState = initialValue;
      hook = requestDeferredLane();
      currentlyRenderingFiber.lanes |= hook;
      workInProgressRootSkippedLanes |= hook;
      return initialValue;
    }
    function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
      if (objectIs(value, prevValue)) return value;
      if (null !== currentTreeHiddenStackCursor.current)
        return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
      if (0 === (renderLanes & 42) || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
        return didReceiveUpdate = true, hook.memoizedState = value;
      hook = requestDeferredLane();
      currentlyRenderingFiber.lanes |= hook;
      workInProgressRootSkippedLanes |= hook;
      return prevValue;
    }
    function releaseAsyncTransition() {
      ReactSharedInternals.asyncTransitions--;
    }
    function startTransition(fiber, queue, pendingState, finishedState, callback) {
      var previousPriority = ReactDOMSharedInternals.p;
      ReactDOMSharedInternals.p = 0 !== previousPriority && previousPriority < ContinuousEventPriority ? previousPriority : ContinuousEventPriority;
      var prevTransition = ReactSharedInternals.T, currentTransition = {};
      currentTransition._updatedFibers = /* @__PURE__ */ new Set();
      ReactSharedInternals.T = currentTransition;
      dispatchOptimisticSetState(fiber, false, queue, pendingState);
      try {
        var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
          ReactSharedInternals.asyncTransitions++;
          returnValue.then(releaseAsyncTransition, releaseAsyncTransition);
          var thenableForFinishedState = chainThenableValue(
            returnValue,
            finishedState
          );
          dispatchSetStateInternal(
            fiber,
            queue,
            thenableForFinishedState,
            requestUpdateLane(fiber)
          );
        } else
          dispatchSetStateInternal(
            fiber,
            queue,
            finishedState,
            requestUpdateLane(fiber)
          );
      } catch (error) {
        dispatchSetStateInternal(
          fiber,
          queue,
          { then: function() {
          }, status: "rejected", reason: error },
          requestUpdateLane(fiber)
        );
      } finally {
        ReactDOMSharedInternals.p = previousPriority, null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
          "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
        ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (fiber = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < fiber && console.warn(
          "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
        ));
      }
    }
    function startHostTransition(formFiber, pendingState, action, formData) {
      if (5 !== formFiber.tag)
        throw Error(
          "Expected the form instance to be a HostComponent. This is a bug in React."
        );
      var queue = ensureFormComponentIsStateful(formFiber).queue;
      startHostActionTimer(formFiber);
      startTransition(
        formFiber,
        queue,
        pendingState,
        NotPendingTransition,
        null === action ? noop2 : function() {
          requestFormReset$1(formFiber);
          return action(formData);
        }
      );
    }
    function ensureFormComponentIsStateful(formFiber) {
      var existingStateHook = formFiber.memoizedState;
      if (null !== existingStateHook) return existingStateHook;
      existingStateHook = {
        memoizedState: NotPendingTransition,
        baseState: NotPendingTransition,
        baseQueue: null,
        queue: {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: NotPendingTransition
        },
        next: null
      };
      var initialResetState = {};
      existingStateHook.next = {
        memoizedState: initialResetState,
        baseState: initialResetState,
        baseQueue: null,
        queue: {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialResetState
        },
        next: null
      };
      formFiber.memoizedState = existingStateHook;
      formFiber = formFiber.alternate;
      null !== formFiber && (formFiber.memoizedState = existingStateHook);
      return existingStateHook;
    }
    function requestFormReset$1(formFiber) {
      null === ReactSharedInternals.T && console.error(
        "requestFormReset was called outside a transition or action. To fix, move to an action, or wrap with startTransition."
      );
      var stateHook = ensureFormComponentIsStateful(formFiber);
      null === stateHook.next && (stateHook = formFiber.alternate.memoizedState);
      dispatchSetStateInternal(
        formFiber,
        stateHook.next.queue,
        {},
        requestUpdateLane(formFiber)
      );
    }
    function mountTransition() {
      var stateHook = mountStateImpl(false);
      stateHook = startTransition.bind(
        null,
        currentlyRenderingFiber,
        stateHook.queue,
        true,
        false
      );
      mountWorkInProgressHook().memoizedState = stateHook;
      return [false, stateHook];
    }
    function updateTransition() {
      var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
      return [
        "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
        start
      ];
    }
    function rerenderTransition() {
      var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
      return [
        "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
        start
      ];
    }
    function useHostTransitionStatus() {
      return readContext(HostTransitionContext);
    }
    function mountId() {
      var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
      if (isHydrating) {
        var treeId = treeContextOverflow;
        var idWithLeadingBit = treeContextId;
        treeId = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + treeId;
        identifierPrefix = "_" + identifierPrefix + "R_" + treeId;
        treeId = localIdCounter++;
        0 < treeId && (identifierPrefix += "H" + treeId.toString(32));
        identifierPrefix += "_";
      } else
        treeId = globalClientIdCounter++, identifierPrefix = "_" + identifierPrefix + "r_" + treeId.toString(32) + "_";
      return hook.memoizedState = identifierPrefix;
    }
    function mountRefresh() {
      return mountWorkInProgressHook().memoizedState = refreshCache.bind(
        null,
        currentlyRenderingFiber
      );
    }
    function refreshCache(fiber, seedKey) {
      for (var provider = fiber.return; null !== provider; ) {
        switch (provider.tag) {
          case 24:
          case 3:
            var lane = requestUpdateLane(provider), refreshUpdate = createUpdate(lane), root3 = enqueueUpdate(provider, refreshUpdate, lane);
            null !== root3 && (startUpdateTimerByLane(lane, "refresh()", fiber), scheduleUpdateOnFiber(root3, provider, lane), entangleTransitions(root3, provider, lane));
            fiber = createCache();
            null !== seedKey && void 0 !== seedKey && null !== root3 && console.error(
              "The seed argument is not enabled outside experimental channels."
            );
            refreshUpdate.payload = { cache: fiber };
            return;
        }
        provider = provider.return;
      }
    }
    function dispatchReducerAction(fiber, queue, action) {
      var args = arguments;
      "function" === typeof args[3] && console.error(
        "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
      );
      args = requestUpdateLane(fiber);
      var update = {
        lane: args,
        revertLane: 0,
        gesture: null,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, update) : (update = enqueueConcurrentHookUpdate(fiber, queue, update, args), null !== update && (startUpdateTimerByLane(args, "dispatch()", fiber), scheduleUpdateOnFiber(update, fiber, args), entangleTransitionUpdate(update, queue, args)));
    }
    function dispatchSetState(fiber, queue, action) {
      var args = arguments;
      "function" === typeof args[3] && console.error(
        "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
      );
      args = requestUpdateLane(fiber);
      dispatchSetStateInternal(fiber, queue, action, args) && startUpdateTimerByLane(args, "setState()", fiber);
    }
    function dispatchSetStateInternal(fiber, queue, action, lane) {
      var update = {
        lane,
        revertLane: 0,
        gesture: null,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);
      else {
        var alternate = fiber.alternate;
        if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate)) {
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
            update.hasEagerState = true;
            update.eagerState = eagerState;
            if (objectIs(eagerState, currentState))
              return enqueueUpdate$1(fiber, queue, update, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
          } catch (error) {
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        }
        action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
        if (null !== action)
          return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
      }
      return false;
    }
    function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
      null === ReactSharedInternals.T && 0 === currentEntangledLane && console.error(
        "An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition."
      );
      action = {
        lane: 2,
        revertLane: requestTransitionLane(),
        gesture: null,
        action,
        hasEagerState: false,
        eagerState: null,
        next: null
      };
      if (isRenderPhaseUpdate(fiber)) {
        if (throwIfDuringRender)
          throw Error("Cannot update optimistic state while rendering.");
        console.error("Cannot call startTransition while rendering.");
      } else
        throwIfDuringRender = enqueueConcurrentHookUpdate(
          fiber,
          queue,
          action,
          2
        ), null !== throwIfDuringRender && (startUpdateTimerByLane(2, "setOptimistic()", fiber), scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2));
    }
    function isRenderPhaseUpdate(fiber) {
      var alternate = fiber.alternate;
      return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
    }
    function enqueueRenderPhaseUpdate(queue, update) {
      didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
      var pending = queue.pending;
      null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
      queue.pending = update;
    }
    function entangleTransitionUpdate(root3, queue, lane) {
      if (0 !== (lane & 4194048)) {
        var queueLanes = queue.lanes;
        queueLanes &= root3.pendingLanes;
        lane |= queueLanes;
        queue.lanes = lane;
        markRootEntangled(root3, lane);
      }
    }
    function warnOnInvalidCallback(callback) {
      if (null !== callback && "function" !== typeof callback) {
        var key = String(callback);
        didWarnOnInvalidCallback.has(key) || (didWarnOnInvalidCallback.add(key), console.error(
          "Expected the last optional `callback` argument to be a function. Instead received: %s.",
          callback
        ));
      }
    }
    function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
      var prevState = workInProgress2.memoizedState, partialState = getDerivedStateFromProps(nextProps, prevState);
      if (workInProgress2.mode & StrictLegacyMode) {
        setIsStrictModeForDevtools(true);
        try {
          partialState = getDerivedStateFromProps(nextProps, prevState);
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      void 0 === partialState && (ctor = getComponentNameFromType(ctor) || "Component", didWarnAboutUndefinedDerivedState.has(ctor) || (didWarnAboutUndefinedDerivedState.add(ctor), console.error(
        "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",
        ctor
      )));
      prevState = null === partialState || void 0 === partialState ? prevState : assign({}, prevState, partialState);
      workInProgress2.memoizedState = prevState;
      0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = prevState);
    }
    function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
      var instance = workInProgress2.stateNode;
      if ("function" === typeof instance.shouldComponentUpdate) {
        oldProps = instance.shouldComponentUpdate(
          newProps,
          newState,
          nextContext
        );
        if (workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            oldProps = instance.shouldComponentUpdate(
              newProps,
              newState,
              nextContext
            );
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        void 0 === oldProps && console.error(
          "%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",
          getComponentNameFromType(ctor) || "Component"
        );
        return oldProps;
      }
      return ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState) : true;
    }
    function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
      var oldState = instance.state;
      "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
      "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
      instance.state !== oldState && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Component", didWarnAboutStateAssignmentForComponent.has(workInProgress2) || (didWarnAboutStateAssignmentForComponent.add(workInProgress2), console.error(
        "%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
        workInProgress2
      )), classComponentUpdater.enqueueReplaceState(
        instance,
        instance.state,
        null
      ));
    }
    function resolveClassComponentProps(Component, baseProps) {
      var newProps = baseProps;
      if ("ref" in baseProps) {
        newProps = {};
        for (var propName in baseProps)
          "ref" !== propName && (newProps[propName] = baseProps[propName]);
      }
      if (Component = Component.defaultProps) {
        newProps === baseProps && (newProps = assign({}, newProps));
        for (var _propName in Component)
          void 0 === newProps[_propName] && (newProps[_propName] = Component[_propName]);
      }
      return newProps;
    }
    function defaultOnUncaughtError(error) {
      reportGlobalError(error);
      console.warn(
        "%s\n\n%s\n",
        componentName ? "An error occurred in the <" + componentName + "> component." : "An error occurred in one of your React components.",
        "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://react.dev/link/error-boundaries to learn more about error boundaries."
      );
    }
    function defaultOnCaughtError(error) {
      var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component." : "The above error occurred in one of your React components.", recreateMessage = "React will try to recreate this component tree from scratch using the error boundary you provided, " + ((errorBoundaryName || "Anonymous") + ".");
      if ("object" === typeof error && null !== error && "string" === typeof error.environmentName) {
        var JSCompiler_inline_result = error.environmentName;
        error = [
          "%o\n\n%s\n\n%s\n",
          error,
          componentNameMessage,
          recreateMessage
        ].slice(0);
        "string" === typeof error[0] ? error.splice(
          0,
          1,
          badgeFormat + " " + error[0],
          badgeStyle,
          pad2 + JSCompiler_inline_result + pad2,
          resetStyle
        ) : error.splice(
          0,
          0,
          badgeFormat,
          badgeStyle,
          pad2 + JSCompiler_inline_result + pad2,
          resetStyle
        );
        error.unshift(console);
        JSCompiler_inline_result = bind2.apply(console.error, error);
        JSCompiler_inline_result();
      } else
        console.error(
          "%o\n\n%s\n\n%s\n",
          error,
          componentNameMessage,
          recreateMessage
        );
    }
    function defaultOnRecoverableError(error) {
      reportGlobalError(error);
    }
    function logUncaughtError(root3, errorInfo) {
      try {
        componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
        errorBoundaryName = null;
        var error = errorInfo.value;
        if (null !== ReactSharedInternals.actQueue)
          ReactSharedInternals.thrownErrors.push(error);
        else {
          var onUncaughtError = root3.onUncaughtError;
          onUncaughtError(error, { componentStack: errorInfo.stack });
        }
      } catch (e$5) {
        setTimeout(function() {
          throw e$5;
        });
      }
    }
    function logCaughtError(root3, boundary, errorInfo) {
      try {
        componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
        errorBoundaryName = getComponentNameFromFiber(boundary);
        var onCaughtError = root3.onCaughtError;
        onCaughtError(errorInfo.value, {
          componentStack: errorInfo.stack,
          errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
        });
      } catch (e$6) {
        setTimeout(function() {
          throw e$6;
        });
      }
    }
    function createRootErrorUpdate(root3, errorInfo, lane) {
      lane = createUpdate(lane);
      lane.tag = CaptureUpdate;
      lane.payload = { element: null };
      lane.callback = function() {
        runWithFiberInDEV(errorInfo.source, logUncaughtError, root3, errorInfo);
      };
      return lane;
    }
    function createClassErrorUpdate(lane) {
      lane = createUpdate(lane);
      lane.tag = CaptureUpdate;
      return lane;
    }
    function initializeClassErrorUpdate(update, root3, fiber, errorInfo) {
      var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
      if ("function" === typeof getDerivedStateFromError) {
        var error = errorInfo.value;
        update.payload = function() {
          return getDerivedStateFromError(error);
        };
        update.callback = function() {
          markFailedErrorBoundaryForHotReloading(fiber);
          runWithFiberInDEV(
            errorInfo.source,
            logCaughtError,
            root3,
            fiber,
            errorInfo
          );
        };
      }
      var inst = fiber.stateNode;
      null !== inst && "function" === typeof inst.componentDidCatch && (update.callback = function() {
        markFailedErrorBoundaryForHotReloading(fiber);
        runWithFiberInDEV(
          errorInfo.source,
          logCaughtError,
          root3,
          fiber,
          errorInfo
        );
        "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
        callComponentDidCatchInDEV(this, errorInfo);
        "function" === typeof getDerivedStateFromError || 0 === (fiber.lanes & 2) && console.error(
          "%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.",
          getComponentNameFromFiber(fiber) || "Unknown"
        );
      });
    }
    function throwException(root3, returnFiber, sourceFiber, value, rootRenderLanes) {
      sourceFiber.flags |= 32768;
      isDevToolsPresent && restorePendingUpdaters(root3, rootRenderLanes);
      if (null !== value && "object" === typeof value && "function" === typeof value.then) {
        returnFiber = sourceFiber.alternate;
        null !== returnFiber && propagateParentContextChanges(
          returnFiber,
          sourceFiber,
          rootRenderLanes,
          true
        );
        isHydrating && (didSuspendOrErrorDEV = true);
        sourceFiber = suspenseHandlerStackCursor.current;
        if (null !== sourceFiber) {
          switch (sourceFiber.tag) {
            case 31:
            case 13:
              return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootSuspended), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value]) : returnFiber.add(value), attachPingListener(root3, value, rootRenderLanes)), false;
            case 22:
              return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
                transitions: null,
                markerInstances: null,
                retryQueue: /* @__PURE__ */ new Set([value])
              }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value]) : sourceFiber.add(value)), attachPingListener(root3, value, rootRenderLanes)), false;
          }
          throw Error(
            "Unexpected Suspense handler tag (" + sourceFiber.tag + "). This is a bug in React."
          );
        }
        attachPingListener(root3, value, rootRenderLanes);
        renderDidSuspendDelayIfPossible();
        return false;
      }
      if (isHydrating)
        return didSuspendOrErrorDEV = true, returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && queueHydrationError(
          createCapturedValueAtFiber(
            Error(
              "There was an error while hydrating but React was able to recover by instead client rendering from the nearest Suspense boundary.",
              { cause: value }
            ),
            sourceFiber
          )
        )) : (value !== HydrationMismatchException && queueHydrationError(
          createCapturedValueAtFiber(
            Error(
              "There was an error while hydrating but React was able to recover by instead client rendering the entire root.",
              { cause: value }
            ),
            sourceFiber
          )
        ), root3 = root3.current.alternate, root3.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root3.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(
          root3.stateNode,
          value,
          rootRenderLanes
        ), enqueueCapturedUpdate(root3, rootRenderLanes), workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored)), false;
      var error = createCapturedValueAtFiber(
        Error(
          "There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root.",
          { cause: value }
        ),
        sourceFiber
      );
      null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [error] : workInProgressRootConcurrentErrors.push(error);
      workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored);
      if (null === returnFiber) return true;
      value = createCapturedValueAtFiber(value, sourceFiber);
      sourceFiber = returnFiber;
      do {
        switch (sourceFiber.tag) {
          case 3:
            return sourceFiber.flags |= 65536, root3 = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root3, root3 = createRootErrorUpdate(
              sourceFiber.stateNode,
              value,
              root3
            ), enqueueCapturedUpdate(sourceFiber, root3), false;
          case 1:
            if (returnFiber = sourceFiber.type, error = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== error && "function" === typeof error.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(error))))
              return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
                rootRenderLanes,
                root3,
                sourceFiber,
                value
              ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
        }
        sourceFiber = sourceFiber.return;
      } while (null !== sourceFiber);
      return false;
    }
    function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
      workInProgress2.child = null === current2 ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
        workInProgress2,
        current2.child,
        nextChildren,
        renderLanes2
      );
    }
    function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) {
      Component = Component.render;
      var ref2 = workInProgress2.ref;
      if ("ref" in nextProps) {
        var propsWithoutRef = {};
        for (var key in nextProps)
          "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
      } else propsWithoutRef = nextProps;
      prepareToReadContext(workInProgress2);
      nextProps = renderWithHooks(
        current2,
        workInProgress2,
        Component,
        propsWithoutRef,
        ref2,
        renderLanes2
      );
      key = checkDidRenderIdHook();
      if (null !== current2 && !didReceiveUpdate)
        return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      isHydrating && key && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
      return workInProgress2.child;
    }
    function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
      if (null === current2) {
        var type2 = Component.type;
        if ("function" === typeof type2 && !shouldConstruct(type2) && void 0 === type2.defaultProps && null === Component.compare)
          return Component = resolveFunctionForHotReloading(type2), workInProgress2.tag = 15, workInProgress2.type = Component, validateFunctionComponentInDev(workInProgress2, type2), updateSimpleMemoComponent(
            current2,
            workInProgress2,
            Component,
            nextProps,
            renderLanes2
          );
        current2 = createFiberFromTypeAndProps(
          Component.type,
          null,
          nextProps,
          workInProgress2,
          workInProgress2.mode,
          renderLanes2
        );
        current2.ref = workInProgress2.ref;
        current2.return = workInProgress2;
        return workInProgress2.child = current2;
      }
      type2 = current2.child;
      if (!checkScheduledUpdateOrContext(current2, renderLanes2)) {
        var prevProps = type2.memoizedProps;
        Component = Component.compare;
        Component = null !== Component ? Component : shallowEqual;
        if (Component(prevProps, nextProps) && current2.ref === workInProgress2.ref)
          return bailoutOnAlreadyFinishedWork(
            current2,
            workInProgress2,
            renderLanes2
          );
      }
      workInProgress2.flags |= 1;
      current2 = createWorkInProgress(type2, nextProps);
      current2.ref = workInProgress2.ref;
      current2.return = workInProgress2;
      return workInProgress2.child = current2;
    }
    function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
      if (null !== current2) {
        var prevProps = current2.memoizedProps;
        if (shallowEqual(prevProps, nextProps) && current2.ref === workInProgress2.ref && workInProgress2.type === current2.type)
          if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current2, renderLanes2))
            0 !== (current2.flags & 131072) && (didReceiveUpdate = true);
          else
            return workInProgress2.lanes = current2.lanes, bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      }
      return updateFunctionComponent(
        current2,
        workInProgress2,
        Component,
        nextProps,
        renderLanes2
      );
    }
    function updateOffscreenComponent(current2, workInProgress2, renderLanes2, nextProps) {
      var nextChildren = nextProps.children, prevState = null !== current2 ? current2.memoizedState : null;
      null === current2 && null === workInProgress2.stateNode && (workInProgress2.stateNode = {
        _visibility: OffscreenVisible,
        _pendingMarkers: null,
        _retryCache: null,
        _transitions: null
      });
      if ("hidden" === nextProps.mode) {
        if (0 !== (workInProgress2.flags & 128)) {
          prevState = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
          if (null !== current2) {
            nextProps = workInProgress2.child = current2.child;
            for (nextChildren = 0; null !== nextProps; )
              nextChildren = nextChildren | nextProps.lanes | nextProps.childLanes, nextProps = nextProps.sibling;
            nextProps = nextChildren & ~prevState;
          } else nextProps = 0, workInProgress2.child = null;
          return deferHiddenOffscreenComponent(
            current2,
            workInProgress2,
            prevState,
            renderLanes2,
            nextProps
          );
        }
        if (0 !== (renderLanes2 & 536870912))
          workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current2 && pushTransition(
            workInProgress2,
            null !== prevState ? prevState.cachePool : null
          ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(workInProgress2), pushOffscreenSuspenseHandler(workInProgress2);
        else
          return nextProps = workInProgress2.lanes = 536870912, deferHiddenOffscreenComponent(
            current2,
            workInProgress2,
            null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
            renderLanes2,
            nextProps
          );
      } else
        null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (null !== current2 && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(workInProgress2), reuseSuspenseHandlerOnStack(workInProgress2));
      reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
      return workInProgress2.child;
    }
    function bailoutOffscreenComponent(current2, workInProgress2) {
      null !== current2 && 22 === current2.tag || null !== workInProgress2.stateNode || (workInProgress2.stateNode = {
        _visibility: OffscreenVisible,
        _pendingMarkers: null,
        _retryCache: null,
        _transitions: null
      });
      return workInProgress2.sibling;
    }
    function deferHiddenOffscreenComponent(current2, workInProgress2, nextBaseLanes, renderLanes2, remainingChildLanes) {
      var JSCompiler_inline_result = peekCacheFromPool();
      JSCompiler_inline_result = null === JSCompiler_inline_result ? null : {
        parent: CacheContext._currentValue,
        pool: JSCompiler_inline_result
      };
      workInProgress2.memoizedState = {
        baseLanes: nextBaseLanes,
        cachePool: JSCompiler_inline_result
      };
      null !== current2 && pushTransition(workInProgress2, null);
      reuseHiddenContextOnStack(workInProgress2);
      pushOffscreenSuspenseHandler(workInProgress2);
      null !== current2 && propagateParentContextChanges(current2, workInProgress2, renderLanes2, true);
      workInProgress2.childLanes = remainingChildLanes;
      return null;
    }
    function mountActivityChildren(workInProgress2, nextProps) {
      var hiddenProp = nextProps.hidden;
      void 0 !== hiddenProp && console.error(
        `<Activity> doesn't accept a hidden prop. Use mode="hidden" instead.
- <Activity %s>
+ <Activity %s>`,
        true === hiddenProp ? "hidden" : false === hiddenProp ? "hidden={false}" : "hidden={...}",
        hiddenProp ? 'mode="hidden"' : 'mode="visible"'
      );
      nextProps = mountWorkInProgressOffscreenFiber(
        { mode: nextProps.mode, children: nextProps.children },
        workInProgress2.mode
      );
      nextProps.ref = workInProgress2.ref;
      workInProgress2.child = nextProps;
      nextProps.return = workInProgress2;
      return nextProps;
    }
    function retryActivityComponentWithoutHydrating(current2, workInProgress2, renderLanes2) {
      reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
      current2 = mountActivityChildren(
        workInProgress2,
        workInProgress2.pendingProps
      );
      current2.flags |= 2;
      popSuspenseHandler(workInProgress2);
      workInProgress2.memoizedState = null;
      return current2;
    }
    function updateActivityComponent(current2, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, didSuspend = 0 !== (workInProgress2.flags & 128);
      workInProgress2.flags &= -129;
      if (null === current2) {
        if (isHydrating) {
          if ("hidden" === nextProps.mode)
            return current2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.lanes = 536870912, bailoutOffscreenComponent(null, current2);
          pushDehydratedActivitySuspenseHandler(workInProgress2);
          (current2 = nextHydratableInstance) ? (renderLanes2 = canHydrateHydrationBoundary(
            current2,
            rootOrSingletonContext
          ), renderLanes2 = null !== renderLanes2 && renderLanes2.data === ACTIVITY_START_DATA ? renderLanes2 : null, null !== renderLanes2 && (nextProps = {
            dehydrated: renderLanes2,
            treeContext: getSuspendedTreeContext(),
            retryLane: 536870912,
            hydrationErrors: null
          }, workInProgress2.memoizedState = nextProps, nextProps = createFiberFromDehydratedFragment(renderLanes2), nextProps.return = workInProgress2, workInProgress2.child = nextProps, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : renderLanes2 = null;
          if (null === renderLanes2)
            throw warnNonHydratedInstance(workInProgress2, current2), throwOnHydrationMismatch(workInProgress2);
          workInProgress2.lanes = 536870912;
          return null;
        }
        return mountActivityChildren(workInProgress2, nextProps);
      }
      var prevState = current2.memoizedState;
      if (null !== prevState) {
        var activityInstance = prevState.dehydrated;
        pushDehydratedActivitySuspenseHandler(workInProgress2);
        if (didSuspend)
          if (workInProgress2.flags & 256)
            workInProgress2.flags &= -257, workInProgress2 = retryActivityComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            );
          else if (null !== workInProgress2.memoizedState)
            workInProgress2.child = current2.child, workInProgress2.flags |= 128, workInProgress2 = null;
          else
            throw Error(
              "Client rendering an Activity suspended it again. This is a bug in React."
            );
        else if (warnIfHydrating(), 0 !== (renderLanes2 & 536870912) && markRenderDerivedCause(workInProgress2), didReceiveUpdate || propagateParentContextChanges(
          current2,
          workInProgress2,
          renderLanes2,
          false
        ), didSuspend = 0 !== (renderLanes2 & current2.childLanes), didReceiveUpdate || didSuspend) {
          nextProps = workInProgressRoot;
          if (null !== nextProps && (activityInstance = getBumpedLaneForHydration(
            nextProps,
            renderLanes2
          ), 0 !== activityInstance && activityInstance !== prevState.retryLane))
            throw prevState.retryLane = activityInstance, enqueueConcurrentRenderForLane(current2, activityInstance), scheduleUpdateOnFiber(nextProps, current2, activityInstance), SelectiveHydrationException;
          renderDidSuspendDelayIfPossible();
          workInProgress2 = retryActivityComponentWithoutHydrating(
            current2,
            workInProgress2,
            renderLanes2
          );
        } else
          current2 = prevState.treeContext, nextHydratableInstance = getNextHydratable(
            activityInstance.nextSibling
          ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current2 && restoreSuspendedTreeContext(workInProgress2, current2), workInProgress2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.flags |= 4096;
        return workInProgress2;
      }
      prevState = current2.child;
      nextProps = { mode: nextProps.mode, children: nextProps.children };
      0 !== (renderLanes2 & 536870912) && 0 !== (renderLanes2 & current2.lanes) && markRenderDerivedCause(workInProgress2);
      current2 = createWorkInProgress(prevState, nextProps);
      current2.ref = workInProgress2.ref;
      workInProgress2.child = current2;
      current2.return = workInProgress2;
      return current2;
    }
    function markRef(current2, workInProgress2) {
      var ref2 = workInProgress2.ref;
      if (null === ref2)
        null !== current2 && null !== current2.ref && (workInProgress2.flags |= 4194816);
      else {
        if ("function" !== typeof ref2 && "object" !== typeof ref2)
          throw Error(
            "Expected ref to be a function, an object returned by React.createRef(), or undefined/null."
          );
        if (null === current2 || current2.ref !== ref2)
          workInProgress2.flags |= 4194816;
      }
    }
    function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
      if (Component.prototype && "function" === typeof Component.prototype.render) {
        var componentName2 = getComponentNameFromType(Component) || "Unknown";
        didWarnAboutBadClass[componentName2] || (console.error(
          "The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",
          componentName2,
          componentName2
        ), didWarnAboutBadClass[componentName2] = true);
      }
      workInProgress2.mode & StrictLegacyMode && ReactStrictModeWarnings.recordLegacyContextWarning(
        workInProgress2,
        null
      );
      null === current2 && (validateFunctionComponentInDev(workInProgress2, workInProgress2.type), Component.contextTypes && (componentName2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypes[componentName2] || (didWarnAboutContextTypes[componentName2] = true, console.error(
        "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)",
        componentName2
      ))));
      prepareToReadContext(workInProgress2);
      Component = renderWithHooks(
        current2,
        workInProgress2,
        Component,
        nextProps,
        void 0,
        renderLanes2
      );
      nextProps = checkDidRenderIdHook();
      if (null !== current2 && !didReceiveUpdate)
        return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current2, workInProgress2, Component, renderLanes2);
      return workInProgress2.child;
    }
    function replayFunctionComponent(current2, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
      prepareToReadContext(workInProgress2);
      hookTypesUpdateIndexDev = -1;
      ignorePreviousDependencies = null !== current2 && current2.type !== workInProgress2.type;
      workInProgress2.updateQueue = null;
      nextProps = renderWithHooksAgain(
        workInProgress2,
        Component,
        nextProps,
        secondArg
      );
      finishRenderingHooks(current2, workInProgress2);
      Component = checkDidRenderIdHook();
      if (null !== current2 && !didReceiveUpdate)
        return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      isHydrating && Component && pushMaterializedTreeId(workInProgress2);
      workInProgress2.flags |= 1;
      reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
      return workInProgress2.child;
    }
    function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
      switch (shouldErrorImpl(workInProgress2)) {
        case false:
          var _instance = workInProgress2.stateNode, state = new workInProgress2.type(
            workInProgress2.memoizedProps,
            _instance.context
          ).state;
          _instance.updater.enqueueSetState(_instance, state, null);
          break;
        case true:
          workInProgress2.flags |= 128;
          workInProgress2.flags |= 65536;
          _instance = Error("Simulated error coming from DevTools");
          var lane = renderLanes2 & -renderLanes2;
          workInProgress2.lanes |= lane;
          state = workInProgressRoot;
          if (null === state)
            throw Error(
              "Expected a work-in-progress root. This is a bug in React. Please file an issue."
            );
          lane = createClassErrorUpdate(lane);
          initializeClassErrorUpdate(
            lane,
            state,
            workInProgress2,
            createCapturedValueAtFiber(_instance, workInProgress2)
          );
          enqueueCapturedUpdate(workInProgress2, lane);
      }
      prepareToReadContext(workInProgress2);
      if (null === workInProgress2.stateNode) {
        state = emptyContextObject;
        _instance = Component.contextType;
        "contextType" in Component && null !== _instance && (void 0 === _instance || _instance.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(Component) && (didWarnAboutInvalidateContextType.add(Component), lane = void 0 === _instance ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : "object" !== typeof _instance ? " However, it is set to a " + typeof _instance + "." : _instance.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(_instance).join(", ") + "}.", console.error(
          "%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",
          getComponentNameFromType(Component) || "Component",
          lane
        ));
        "object" === typeof _instance && null !== _instance && (state = readContext(_instance));
        _instance = new Component(nextProps, state);
        if (workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            _instance = new Component(nextProps, state);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        state = workInProgress2.memoizedState = null !== _instance.state && void 0 !== _instance.state ? _instance.state : null;
        _instance.updater = classComponentUpdater;
        workInProgress2.stateNode = _instance;
        _instance._reactInternals = workInProgress2;
        _instance._reactInternalInstance = fakeInternalInstance;
        "function" === typeof Component.getDerivedStateFromProps && null === state && (state = getComponentNameFromType(Component) || "Component", didWarnAboutUninitializedState.has(state) || (didWarnAboutUninitializedState.add(state), console.error(
          "`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",
          state,
          null === _instance.state ? "null" : "undefined",
          state
        )));
        if ("function" === typeof Component.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate) {
          var foundWillUpdateName = lane = state = null;
          "function" === typeof _instance.componentWillMount && true !== _instance.componentWillMount.__suppressDeprecationWarning ? state = "componentWillMount" : "function" === typeof _instance.UNSAFE_componentWillMount && (state = "UNSAFE_componentWillMount");
          "function" === typeof _instance.componentWillReceiveProps && true !== _instance.componentWillReceiveProps.__suppressDeprecationWarning ? lane = "componentWillReceiveProps" : "function" === typeof _instance.UNSAFE_componentWillReceiveProps && (lane = "UNSAFE_componentWillReceiveProps");
          "function" === typeof _instance.componentWillUpdate && true !== _instance.componentWillUpdate.__suppressDeprecationWarning ? foundWillUpdateName = "componentWillUpdate" : "function" === typeof _instance.UNSAFE_componentWillUpdate && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
          if (null !== state || null !== lane || null !== foundWillUpdateName) {
            _instance = getComponentNameFromType(Component) || "Component";
            var newApiName = "function" === typeof Component.getDerivedStateFromProps ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
            didWarnAboutLegacyLifecyclesAndDerivedState.has(_instance) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(_instance), console.error(
              "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://react.dev/link/unsafe-component-lifecycles",
              _instance,
              newApiName,
              null !== state ? "\n  " + state : "",
              null !== lane ? "\n  " + lane : "",
              null !== foundWillUpdateName ? "\n  " + foundWillUpdateName : ""
            ));
          }
        }
        _instance = workInProgress2.stateNode;
        state = getComponentNameFromType(Component) || "Component";
        _instance.render || (Component.prototype && "function" === typeof Component.prototype.render ? console.error(
          "No `render` method found on the %s instance: did you accidentally return an object from the constructor?",
          state
        ) : console.error(
          "No `render` method found on the %s instance: you may have forgotten to define `render`.",
          state
        ));
        !_instance.getInitialState || _instance.getInitialState.isReactClassApproved || _instance.state || console.error(
          "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",
          state
        );
        _instance.getDefaultProps && !_instance.getDefaultProps.isReactClassApproved && console.error(
          "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",
          state
        );
        _instance.contextType && console.error(
          "contextType was defined as an instance property on %s. Use a static property to define contextType instead.",
          state
        );
        Component.childContextTypes && !didWarnAboutChildContextTypes.has(Component) && (didWarnAboutChildContextTypes.add(Component), console.error(
          "%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)",
          state
        ));
        Component.contextTypes && !didWarnAboutContextTypes$1.has(Component) && (didWarnAboutContextTypes$1.add(Component), console.error(
          "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)",
          state
        ));
        "function" === typeof _instance.componentShouldUpdate && console.error(
          "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",
          state
        );
        Component.prototype && Component.prototype.isPureReactComponent && "undefined" !== typeof _instance.shouldComponentUpdate && console.error(
          "%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",
          getComponentNameFromType(Component) || "A pure component"
        );
        "function" === typeof _instance.componentDidUnmount && console.error(
          "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",
          state
        );
        "function" === typeof _instance.componentDidReceiveProps && console.error(
          "%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",
          state
        );
        "function" === typeof _instance.componentWillRecieveProps && console.error(
          "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",
          state
        );
        "function" === typeof _instance.UNSAFE_componentWillRecieveProps && console.error(
          "%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",
          state
        );
        lane = _instance.props !== nextProps;
        void 0 !== _instance.props && lane && console.error(
          "When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",
          state
        );
        _instance.defaultProps && console.error(
          "Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",
          state,
          state
        );
        "function" !== typeof _instance.getSnapshotBeforeUpdate || "function" === typeof _instance.componentDidUpdate || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(Component) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(Component), console.error(
          "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",
          getComponentNameFromType(Component)
        ));
        "function" === typeof _instance.getDerivedStateFromProps && console.error(
          "%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
          state
        );
        "function" === typeof _instance.getDerivedStateFromError && console.error(
          "%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
          state
        );
        "function" === typeof Component.getSnapshotBeforeUpdate && console.error(
          "%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",
          state
        );
        (lane = _instance.state) && ("object" !== typeof lane || isArrayImpl(lane)) && console.error("%s.state: must be set to an object or null", state);
        "function" === typeof _instance.getChildContext && "object" !== typeof Component.childContextTypes && console.error(
          "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",
          state
        );
        _instance = workInProgress2.stateNode;
        _instance.props = nextProps;
        _instance.state = workInProgress2.memoizedState;
        _instance.refs = {};
        initializeUpdateQueue(workInProgress2);
        state = Component.contextType;
        _instance.context = "object" === typeof state && null !== state ? readContext(state) : emptyContextObject;
        _instance.state === nextProps && (state = getComponentNameFromType(Component) || "Component", didWarnAboutDirectlyAssigningPropsToState.has(state) || (didWarnAboutDirectlyAssigningPropsToState.add(state), console.error(
          "%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",
          state
        )));
        workInProgress2.mode & StrictLegacyMode && ReactStrictModeWarnings.recordLegacyContextWarning(
          workInProgress2,
          _instance
        );
        ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
          workInProgress2,
          _instance
        );
        _instance.state = workInProgress2.memoizedState;
        state = Component.getDerivedStateFromProps;
        "function" === typeof state && (applyDerivedStateFromProps(
          workInProgress2,
          Component,
          state,
          nextProps
        ), _instance.state = workInProgress2.memoizedState);
        "function" === typeof Component.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || (state = _instance.state, "function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount(), state !== _instance.state && (console.error(
          "%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
          getComponentNameFromFiber(workInProgress2) || "Component"
        ), classComponentUpdater.enqueueReplaceState(
          _instance,
          _instance.state,
          null
        )), processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), _instance.state = workInProgress2.memoizedState);
        "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308);
        (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728);
        _instance = true;
      } else if (null === current2) {
        _instance = workInProgress2.stateNode;
        var unresolvedOldProps = workInProgress2.memoizedProps;
        lane = resolveClassComponentProps(Component, unresolvedOldProps);
        _instance.props = lane;
        var oldContext = _instance.context;
        foundWillUpdateName = Component.contextType;
        state = emptyContextObject;
        "object" === typeof foundWillUpdateName && null !== foundWillUpdateName && (state = readContext(foundWillUpdateName));
        newApiName = Component.getDerivedStateFromProps;
        foundWillUpdateName = "function" === typeof newApiName || "function" === typeof _instance.getSnapshotBeforeUpdate;
        unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
        foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (unresolvedOldProps || oldContext !== state) && callComponentWillReceiveProps(
          workInProgress2,
          _instance,
          nextProps,
          state
        );
        hasForceUpdate = false;
        var oldState = workInProgress2.memoizedState;
        _instance.state = oldState;
        processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
        suspendIfUpdateReadFromEntangledAsyncAction();
        oldContext = workInProgress2.memoizedState;
        unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof newApiName && (applyDerivedStateFromProps(
          workInProgress2,
          Component,
          newApiName,
          nextProps
        ), oldContext = workInProgress2.memoizedState), (lane = hasForceUpdate || checkShouldComponentUpdate(
          workInProgress2,
          Component,
          lane,
          nextProps,
          oldState,
          oldContext,
          state
        )) ? (foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || ("function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount()), "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728)) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), _instance.props = nextProps, _instance.state = oldContext, _instance.context = state, _instance = lane) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728), _instance = false);
      } else {
        _instance = workInProgress2.stateNode;
        cloneUpdateQueue(current2, workInProgress2);
        state = workInProgress2.memoizedProps;
        foundWillUpdateName = resolveClassComponentProps(Component, state);
        _instance.props = foundWillUpdateName;
        newApiName = workInProgress2.pendingProps;
        oldState = _instance.context;
        oldContext = Component.contextType;
        lane = emptyContextObject;
        "object" === typeof oldContext && null !== oldContext && (lane = readContext(oldContext));
        unresolvedOldProps = Component.getDerivedStateFromProps;
        (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof _instance.getSnapshotBeforeUpdate) || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (state !== newApiName || oldState !== lane) && callComponentWillReceiveProps(
          workInProgress2,
          _instance,
          nextProps,
          lane
        );
        hasForceUpdate = false;
        oldState = workInProgress2.memoizedState;
        _instance.state = oldState;
        processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
        suspendIfUpdateReadFromEntangledAsyncAction();
        var newState = workInProgress2.memoizedState;
        state !== newApiName || oldState !== newState || hasForceUpdate || null !== current2 && null !== current2.dependencies && checkIfContextChanged(current2.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
          workInProgress2,
          Component,
          unresolvedOldProps,
          nextProps
        ), newState = workInProgress2.memoizedState), (foundWillUpdateName = hasForceUpdate || checkShouldComponentUpdate(
          workInProgress2,
          Component,
          foundWillUpdateName,
          nextProps,
          oldState,
          newState,
          lane
        ) || null !== current2 && null !== current2.dependencies && checkIfContextChanged(current2.dependencies)) ? (oldContext || "function" !== typeof _instance.UNSAFE_componentWillUpdate && "function" !== typeof _instance.componentWillUpdate || ("function" === typeof _instance.componentWillUpdate && _instance.componentWillUpdate(nextProps, newState, lane), "function" === typeof _instance.UNSAFE_componentWillUpdate && _instance.UNSAFE_componentWillUpdate(
          nextProps,
          newState,
          lane
        )), "function" === typeof _instance.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof _instance.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof _instance.componentDidUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), _instance.props = nextProps, _instance.state = newState, _instance.context = lane, _instance = foundWillUpdateName) : ("function" !== typeof _instance.componentDidUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 1024), _instance = false);
      }
      lane = _instance;
      markRef(current2, workInProgress2);
      state = 0 !== (workInProgress2.flags & 128);
      if (lane || state) {
        lane = workInProgress2.stateNode;
        setCurrentFiber(workInProgress2);
        if (state && "function" !== typeof Component.getDerivedStateFromError)
          Component = null, profilerStartTime = -1;
        else if (Component = callRenderInDEV(lane), workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            callRenderInDEV(lane);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        workInProgress2.flags |= 1;
        null !== current2 && state ? (workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          current2.child,
          null,
          renderLanes2
        ), workInProgress2.child = reconcileChildFibers(
          workInProgress2,
          null,
          Component,
          renderLanes2
        )) : reconcileChildren(current2, workInProgress2, Component, renderLanes2);
        workInProgress2.memoizedState = lane.state;
        current2 = workInProgress2.child;
      } else
        current2 = bailoutOnAlreadyFinishedWork(
          current2,
          workInProgress2,
          renderLanes2
        );
      renderLanes2 = workInProgress2.stateNode;
      _instance && renderLanes2.props !== nextProps && (didWarnAboutReassigningProps || console.error(
        "It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",
        getComponentNameFromFiber(workInProgress2) || "a component"
      ), didWarnAboutReassigningProps = true);
      return current2;
    }
    function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2) {
      resetHydrationState();
      workInProgress2.flags |= 256;
      reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
      return workInProgress2.child;
    }
    function validateFunctionComponentInDev(workInProgress2, Component) {
      Component && Component.childContextTypes && console.error(
        "childContextTypes cannot be defined on a function component.\n  %s.childContextTypes = ...",
        Component.displayName || Component.name || "Component"
      );
      "function" === typeof Component.getDerivedStateFromProps && (workInProgress2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] || (console.error(
        "%s: Function components do not support getDerivedStateFromProps.",
        workInProgress2
      ), didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] = true));
      "object" === typeof Component.contextType && null !== Component.contextType && (Component = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypeOnFunctionComponent[Component] || (console.error(
        "%s: Function components do not support contextType.",
        Component
      ), didWarnAboutContextTypeOnFunctionComponent[Component] = true));
    }
    function mountSuspenseOffscreenState(renderLanes2) {
      return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
    }
    function getRemainingWorkInPrimaryTree(current2, primaryTreeDidDefer, renderLanes2) {
      current2 = null !== current2 ? current2.childLanes & ~renderLanes2 : 0;
      primaryTreeDidDefer && (current2 |= workInProgressDeferredLane);
      return current2;
    }
    function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
      var JSCompiler_object_inline_digest_2724;
      var JSCompiler_object_inline_stack_2725 = workInProgress2.pendingProps;
      shouldSuspendImpl(workInProgress2) && (workInProgress2.flags |= 128);
      var JSCompiler_object_inline_message_2723 = false;
      var didSuspend = 0 !== (workInProgress2.flags & 128);
      (JSCompiler_object_inline_digest_2724 = didSuspend) || (JSCompiler_object_inline_digest_2724 = null !== current2 && null === current2.memoizedState ? false : 0 !== (suspenseStackCursor.current & ForceSuspenseFallback));
      JSCompiler_object_inline_digest_2724 && (JSCompiler_object_inline_message_2723 = true, workInProgress2.flags &= -129);
      JSCompiler_object_inline_digest_2724 = 0 !== (workInProgress2.flags & 32);
      workInProgress2.flags &= -33;
      if (null === current2) {
        if (isHydrating) {
          JSCompiler_object_inline_message_2723 ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
          (current2 = nextHydratableInstance) ? (renderLanes2 = canHydrateHydrationBoundary(
            current2,
            rootOrSingletonContext
          ), renderLanes2 = null !== renderLanes2 && renderLanes2.data !== ACTIVITY_START_DATA ? renderLanes2 : null, null !== renderLanes2 && (JSCompiler_object_inline_digest_2724 = {
            dehydrated: renderLanes2,
            treeContext: getSuspendedTreeContext(),
            retryLane: 536870912,
            hydrationErrors: null
          }, workInProgress2.memoizedState = JSCompiler_object_inline_digest_2724, JSCompiler_object_inline_digest_2724 = createFiberFromDehydratedFragment(renderLanes2), JSCompiler_object_inline_digest_2724.return = workInProgress2, workInProgress2.child = JSCompiler_object_inline_digest_2724, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : renderLanes2 = null;
          if (null === renderLanes2)
            throw warnNonHydratedInstance(workInProgress2, current2), throwOnHydrationMismatch(workInProgress2);
          isSuspenseInstanceFallback(renderLanes2) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912;
          return null;
        }
        var nextPrimaryChildren = JSCompiler_object_inline_stack_2725.children;
        JSCompiler_object_inline_stack_2725 = JSCompiler_object_inline_stack_2725.fallback;
        if (JSCompiler_object_inline_message_2723) {
          reuseSuspenseHandlerOnStack(workInProgress2);
          var mode = workInProgress2.mode;
          nextPrimaryChildren = mountWorkInProgressOffscreenFiber(
            { mode: "hidden", children: nextPrimaryChildren },
            mode
          );
          JSCompiler_object_inline_stack_2725 = createFiberFromFragment(
            JSCompiler_object_inline_stack_2725,
            mode,
            renderLanes2,
            null
          );
          nextPrimaryChildren.return = workInProgress2;
          JSCompiler_object_inline_stack_2725.return = workInProgress2;
          nextPrimaryChildren.sibling = JSCompiler_object_inline_stack_2725;
          workInProgress2.child = nextPrimaryChildren;
          JSCompiler_object_inline_stack_2725 = workInProgress2.child;
          JSCompiler_object_inline_stack_2725.memoizedState = mountSuspenseOffscreenState(renderLanes2);
          JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
            current2,
            JSCompiler_object_inline_digest_2724,
            renderLanes2
          );
          workInProgress2.memoizedState = SUSPENDED_MARKER;
          return bailoutOffscreenComponent(
            null,
            JSCompiler_object_inline_stack_2725
          );
        }
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        return mountSuspensePrimaryChildren(
          workInProgress2,
          nextPrimaryChildren
        );
      }
      var prevState = current2.memoizedState;
      if (null !== prevState) {
        var JSCompiler_object_inline_componentStack_2726 = prevState.dehydrated;
        if (null !== JSCompiler_object_inline_componentStack_2726) {
          if (didSuspend)
            workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current2.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = JSCompiler_object_inline_stack_2725.fallback, mode = workInProgress2.mode, JSCompiler_object_inline_stack_2725 = mountWorkInProgressOffscreenFiber(
              {
                mode: "visible",
                children: JSCompiler_object_inline_stack_2725.children
              },
              mode
            ), nextPrimaryChildren = createFiberFromFragment(
              nextPrimaryChildren,
              mode,
              renderLanes2,
              null
            ), nextPrimaryChildren.flags |= 2, JSCompiler_object_inline_stack_2725.return = workInProgress2, nextPrimaryChildren.return = workInProgress2, JSCompiler_object_inline_stack_2725.sibling = nextPrimaryChildren, workInProgress2.child = JSCompiler_object_inline_stack_2725, reconcileChildFibers(
              workInProgress2,
              current2.child,
              null,
              renderLanes2
            ), JSCompiler_object_inline_stack_2725 = workInProgress2.child, JSCompiler_object_inline_stack_2725.memoizedState = mountSuspenseOffscreenState(renderLanes2), JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
              current2,
              JSCompiler_object_inline_digest_2724,
              renderLanes2
            ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = bailoutOffscreenComponent(
              null,
              JSCompiler_object_inline_stack_2725
            ));
          else if (pushPrimaryTreeSuspenseHandler(workInProgress2), warnIfHydrating(), 0 !== (renderLanes2 & 536870912) && markRenderDerivedCause(workInProgress2), isSuspenseInstanceFallback(
            JSCompiler_object_inline_componentStack_2726
          )) {
            JSCompiler_object_inline_digest_2724 = JSCompiler_object_inline_componentStack_2726.nextSibling && JSCompiler_object_inline_componentStack_2726.nextSibling.dataset;
            if (JSCompiler_object_inline_digest_2724) {
              nextPrimaryChildren = JSCompiler_object_inline_digest_2724.dgst;
              var message = JSCompiler_object_inline_digest_2724.msg;
              mode = JSCompiler_object_inline_digest_2724.stck;
              var componentStack = JSCompiler_object_inline_digest_2724.cstck;
            }
            JSCompiler_object_inline_message_2723 = message;
            JSCompiler_object_inline_digest_2724 = nextPrimaryChildren;
            JSCompiler_object_inline_stack_2725 = mode;
            JSCompiler_object_inline_componentStack_2726 = componentStack;
            nextPrimaryChildren = JSCompiler_object_inline_message_2723;
            mode = JSCompiler_object_inline_componentStack_2726;
            nextPrimaryChildren = nextPrimaryChildren ? Error(nextPrimaryChildren) : Error(
              "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."
            );
            nextPrimaryChildren.stack = JSCompiler_object_inline_stack_2725 || "";
            nextPrimaryChildren.digest = JSCompiler_object_inline_digest_2724;
            JSCompiler_object_inline_digest_2724 = void 0 === mode ? null : mode;
            JSCompiler_object_inline_stack_2725 = {
              value: nextPrimaryChildren,
              source: null,
              stack: JSCompiler_object_inline_digest_2724
            };
            "string" === typeof JSCompiler_object_inline_digest_2724 && CapturedStacks.set(
              nextPrimaryChildren,
              JSCompiler_object_inline_stack_2725
            );
            queueHydrationError(JSCompiler_object_inline_stack_2725);
            workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            );
          } else if (didReceiveUpdate || propagateParentContextChanges(
            current2,
            workInProgress2,
            renderLanes2,
            false
          ), JSCompiler_object_inline_digest_2724 = 0 !== (renderLanes2 & current2.childLanes), didReceiveUpdate || JSCompiler_object_inline_digest_2724) {
            JSCompiler_object_inline_digest_2724 = workInProgressRoot;
            if (null !== JSCompiler_object_inline_digest_2724 && (JSCompiler_object_inline_stack_2725 = getBumpedLaneForHydration(
              JSCompiler_object_inline_digest_2724,
              renderLanes2
            ), 0 !== JSCompiler_object_inline_stack_2725 && JSCompiler_object_inline_stack_2725 !== prevState.retryLane))
              throw prevState.retryLane = JSCompiler_object_inline_stack_2725, enqueueConcurrentRenderForLane(
                current2,
                JSCompiler_object_inline_stack_2725
              ), scheduleUpdateOnFiber(
                JSCompiler_object_inline_digest_2724,
                current2,
                JSCompiler_object_inline_stack_2725
              ), SelectiveHydrationException;
            isSuspenseInstancePending(
              JSCompiler_object_inline_componentStack_2726
            ) || renderDidSuspendDelayIfPossible();
            workInProgress2 = retrySuspenseComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            );
          } else
            isSuspenseInstancePending(
              JSCompiler_object_inline_componentStack_2726
            ) ? (workInProgress2.flags |= 192, workInProgress2.child = current2.child, workInProgress2 = null) : (current2 = prevState.treeContext, nextHydratableInstance = getNextHydratable(
              JSCompiler_object_inline_componentStack_2726.nextSibling
            ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current2 && restoreSuspendedTreeContext(workInProgress2, current2), workInProgress2 = mountSuspensePrimaryChildren(
              workInProgress2,
              JSCompiler_object_inline_stack_2725.children
            ), workInProgress2.flags |= 4096);
          return workInProgress2;
        }
      }
      if (JSCompiler_object_inline_message_2723)
        return reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = JSCompiler_object_inline_stack_2725.fallback, mode = workInProgress2.mode, componentStack = current2.child, JSCompiler_object_inline_componentStack_2726 = componentStack.sibling, JSCompiler_object_inline_stack_2725 = createWorkInProgress(
          componentStack,
          {
            mode: "hidden",
            children: JSCompiler_object_inline_stack_2725.children
          }
        ), JSCompiler_object_inline_stack_2725.subtreeFlags = componentStack.subtreeFlags & 65011712, null !== JSCompiler_object_inline_componentStack_2726 ? nextPrimaryChildren = createWorkInProgress(
          JSCompiler_object_inline_componentStack_2726,
          nextPrimaryChildren
        ) : (nextPrimaryChildren = createFiberFromFragment(
          nextPrimaryChildren,
          mode,
          renderLanes2,
          null
        ), nextPrimaryChildren.flags |= 2), nextPrimaryChildren.return = workInProgress2, JSCompiler_object_inline_stack_2725.return = workInProgress2, JSCompiler_object_inline_stack_2725.sibling = nextPrimaryChildren, workInProgress2.child = JSCompiler_object_inline_stack_2725, bailoutOffscreenComponent(null, JSCompiler_object_inline_stack_2725), JSCompiler_object_inline_stack_2725 = workInProgress2.child, nextPrimaryChildren = current2.child.memoizedState, null === nextPrimaryChildren ? nextPrimaryChildren = mountSuspenseOffscreenState(renderLanes2) : (mode = nextPrimaryChildren.cachePool, null !== mode ? (componentStack = CacheContext._currentValue, mode = mode.parent !== componentStack ? { parent: componentStack, pool: componentStack } : mode) : mode = getSuspendedCache(), nextPrimaryChildren = {
          baseLanes: nextPrimaryChildren.baseLanes | renderLanes2,
          cachePool: mode
        }), JSCompiler_object_inline_stack_2725.memoizedState = nextPrimaryChildren, JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
          current2,
          JSCompiler_object_inline_digest_2724,
          renderLanes2
        ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(
          current2.child,
          JSCompiler_object_inline_stack_2725
        );
      null !== prevState && (renderLanes2 & 62914560) === renderLanes2 && 0 !== (renderLanes2 & current2.lanes) && markRenderDerivedCause(workInProgress2);
      pushPrimaryTreeSuspenseHandler(workInProgress2);
      renderLanes2 = current2.child;
      current2 = renderLanes2.sibling;
      renderLanes2 = createWorkInProgress(renderLanes2, {
        mode: "visible",
        children: JSCompiler_object_inline_stack_2725.children
      });
      renderLanes2.return = workInProgress2;
      renderLanes2.sibling = null;
      null !== current2 && (JSCompiler_object_inline_digest_2724 = workInProgress2.deletions, null === JSCompiler_object_inline_digest_2724 ? (workInProgress2.deletions = [current2], workInProgress2.flags |= 16) : JSCompiler_object_inline_digest_2724.push(current2));
      workInProgress2.child = renderLanes2;
      workInProgress2.memoizedState = null;
      return renderLanes2;
    }
    function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
      primaryChildren = mountWorkInProgressOffscreenFiber(
        { mode: "visible", children: primaryChildren },
        workInProgress2.mode
      );
      primaryChildren.return = workInProgress2;
      return workInProgress2.child = primaryChildren;
    }
    function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
      offscreenProps = createFiber(22, offscreenProps, null, mode);
      offscreenProps.lanes = 0;
      return offscreenProps;
    }
    function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2) {
      reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
      current2 = mountSuspensePrimaryChildren(
        workInProgress2,
        workInProgress2.pendingProps.children
      );
      current2.flags |= 2;
      workInProgress2.memoizedState = null;
      return current2;
    }
    function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
      fiber.lanes |= renderLanes2;
      var alternate = fiber.alternate;
      null !== alternate && (alternate.lanes |= renderLanes2);
      scheduleContextWorkOnParentPath(
        fiber.return,
        renderLanes2,
        propagationRoot
      );
    }
    function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode, treeForkCount2) {
      var renderState = workInProgress2.memoizedState;
      null === renderState ? workInProgress2.memoizedState = {
        isBackwards,
        rendering: null,
        renderingStartTime: 0,
        last: lastContentRow,
        tail,
        tailMode,
        treeForkCount: treeForkCount2
      } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode, renderState.treeForkCount = treeForkCount2);
    }
    function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
      var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail, newChildren = nextProps.children, suspenseContext = suspenseStackCursor.current;
      (nextProps = 0 !== (suspenseContext & ForceSuspenseFallback)) ? (suspenseContext = suspenseContext & SubtreeSuspenseContextMask | ForceSuspenseFallback, workInProgress2.flags |= 128) : suspenseContext &= SubtreeSuspenseContextMask;
      push2(suspenseStackCursor, suspenseContext, workInProgress2);
      suspenseContext = null == revealOrder ? "null" : revealOrder;
      if ("forwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder && "together" !== revealOrder && "independent" !== revealOrder && !didWarnAboutRevealOrder[suspenseContext])
        if (didWarnAboutRevealOrder[suspenseContext] = true, null == revealOrder)
          console.error(
            'The default for the <SuspenseList revealOrder="..."> prop is changing. To be future compatible you must explictly specify either "independent" (the current default), "together", "forwards" or "legacy_unstable-backwards".'
          );
        else if ("backwards" === revealOrder)
          console.error(
            'The rendering order of <SuspenseList revealOrder="backwards"> is changing. To be future compatible you must specify revealOrder="legacy_unstable-backwards" instead.'
          );
        else if ("string" === typeof revealOrder)
          switch (revealOrder.toLowerCase()) {
            case "together":
            case "forwards":
            case "backwards":
            case "independent":
              console.error(
                '"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.',
                revealOrder,
                revealOrder.toLowerCase()
              );
              break;
            case "forward":
            case "backward":
              console.error(
                '"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.',
                revealOrder,
                revealOrder.toLowerCase()
              );
              break;
            default:
              console.error(
                '"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "independent", "together", "forwards" or "backwards"?',
                revealOrder
              );
          }
        else
          console.error(
            '%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "independent", "together", "forwards" or "backwards"?',
            revealOrder
          );
      suspenseContext = null == tailMode ? "null" : tailMode;
      if (!didWarnAboutTailOptions[suspenseContext])
        if (null == tailMode) {
          if ("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder)
            didWarnAboutTailOptions[suspenseContext] = true, console.error(
              'The default for the <SuspenseList tail="..."> prop is changing. To be future compatible you must explictly specify either "visible" (the current default), "collapsed" or "hidden".'
            );
        } else
          "visible" !== tailMode && "collapsed" !== tailMode && "hidden" !== tailMode ? (didWarnAboutTailOptions[suspenseContext] = true, console.error(
            '"%s" is not a supported value for tail on <SuspenseList />. Did you mean "visible", "collapsed" or "hidden"?',
            tailMode
          )) : "forwards" !== revealOrder && "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder && (didWarnAboutTailOptions[suspenseContext] = true, console.error(
            '<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?',
            tailMode
          ));
      a: if (("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder) && void 0 !== newChildren && null !== newChildren && false !== newChildren)
        if (isArrayImpl(newChildren))
          for (suspenseContext = 0; suspenseContext < newChildren.length; suspenseContext++) {
            if (!validateSuspenseListNestedChild(
              newChildren[suspenseContext],
              suspenseContext
            ))
              break a;
          }
        else if (suspenseContext = getIteratorFn(newChildren), "function" === typeof suspenseContext) {
          if (suspenseContext = suspenseContext.call(newChildren))
            for (var step = suspenseContext.next(), _i = 0; !step.done; step = suspenseContext.next()) {
              if (!validateSuspenseListNestedChild(step.value, _i)) break a;
              _i++;
            }
        } else
          console.error(
            'A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?',
            revealOrder
          );
      reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
      isHydrating ? (warnIfNotHydrating(), newChildren = treeForkCount) : newChildren = 0;
      if (!nextProps && null !== current2 && 0 !== (current2.flags & 128))
        a: for (current2 = workInProgress2.child; null !== current2; ) {
          if (13 === current2.tag)
            null !== current2.memoizedState && scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
          else if (19 === current2.tag)
            scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
          else if (null !== current2.child) {
            current2.child.return = current2;
            current2 = current2.child;
            continue;
          }
          if (current2 === workInProgress2) break a;
          for (; null === current2.sibling; ) {
            if (null === current2.return || current2.return === workInProgress2)
              break a;
            current2 = current2.return;
          }
          current2.sibling.return = current2.return;
          current2 = current2.sibling;
        }
      switch (revealOrder) {
        case "forwards":
          renderLanes2 = workInProgress2.child;
          for (revealOrder = null; null !== renderLanes2; )
            current2 = renderLanes2.alternate, null !== current2 && null === findFirstSuspended(current2) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
          renderLanes2 = revealOrder;
          null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
          initSuspenseListRenderState(
            workInProgress2,
            false,
            revealOrder,
            renderLanes2,
            tailMode,
            newChildren
          );
          break;
        case "backwards":
        case "unstable_legacy-backwards":
          renderLanes2 = null;
          revealOrder = workInProgress2.child;
          for (workInProgress2.child = null; null !== revealOrder; ) {
            current2 = revealOrder.alternate;
            if (null !== current2 && null === findFirstSuspended(current2)) {
              workInProgress2.child = revealOrder;
              break;
            }
            current2 = revealOrder.sibling;
            revealOrder.sibling = renderLanes2;
            renderLanes2 = revealOrder;
            revealOrder = current2;
          }
          initSuspenseListRenderState(
            workInProgress2,
            true,
            renderLanes2,
            null,
            tailMode,
            newChildren
          );
          break;
        case "together":
          initSuspenseListRenderState(
            workInProgress2,
            false,
            null,
            null,
            void 0,
            newChildren
          );
          break;
        default:
          workInProgress2.memoizedState = null;
      }
      return workInProgress2.child;
    }
    function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
      null !== current2 && (workInProgress2.dependencies = current2.dependencies);
      profilerStartTime = -1;
      workInProgressRootSkippedLanes |= workInProgress2.lanes;
      if (0 === (renderLanes2 & workInProgress2.childLanes))
        if (null !== current2) {
          if (propagateParentContextChanges(
            current2,
            workInProgress2,
            renderLanes2,
            false
          ), 0 === (renderLanes2 & workInProgress2.childLanes))
            return null;
        } else return null;
      if (null !== current2 && workInProgress2.child !== current2.child)
        throw Error("Resuming work not yet implemented.");
      if (null !== workInProgress2.child) {
        current2 = workInProgress2.child;
        renderLanes2 = createWorkInProgress(current2, current2.pendingProps);
        workInProgress2.child = renderLanes2;
        for (renderLanes2.return = workInProgress2; null !== current2.sibling; )
          current2 = current2.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current2, current2.pendingProps), renderLanes2.return = workInProgress2;
        renderLanes2.sibling = null;
      }
      return workInProgress2.child;
    }
    function checkScheduledUpdateOrContext(current2, renderLanes2) {
      if (0 !== (current2.lanes & renderLanes2)) return true;
      current2 = current2.dependencies;
      return null !== current2 && checkIfContextChanged(current2) ? true : false;
    }
    function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) {
      switch (workInProgress2.tag) {
        case 3:
          pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          );
          pushProvider(
            workInProgress2,
            CacheContext,
            current2.memoizedState.cache
          );
          resetHydrationState();
          break;
        case 27:
        case 5:
          pushHostContext(workInProgress2);
          break;
        case 4:
          pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          );
          break;
        case 10:
          pushProvider(
            workInProgress2,
            workInProgress2.type,
            workInProgress2.memoizedProps.value
          );
          break;
        case 12:
          0 !== (renderLanes2 & workInProgress2.childLanes) && (workInProgress2.flags |= 4);
          workInProgress2.flags |= 2048;
          var stateNode = workInProgress2.stateNode;
          stateNode.effectDuration = -0;
          stateNode.passiveEffectDuration = -0;
          break;
        case 31:
          if (null !== workInProgress2.memoizedState)
            return workInProgress2.flags |= 128, pushDehydratedActivitySuspenseHandler(workInProgress2), null;
          break;
        case 13:
          stateNode = workInProgress2.memoizedState;
          if (null !== stateNode) {
            if (null !== stateNode.dehydrated)
              return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
            if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
              return updateSuspenseComponent(
                current2,
                workInProgress2,
                renderLanes2
              );
            pushPrimaryTreeSuspenseHandler(workInProgress2);
            current2 = bailoutOnAlreadyFinishedWork(
              current2,
              workInProgress2,
              renderLanes2
            );
            return null !== current2 ? current2.sibling : null;
          }
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          break;
        case 19:
          var didSuspendBefore = 0 !== (current2.flags & 128);
          stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes);
          stateNode || (propagateParentContextChanges(
            current2,
            workInProgress2,
            renderLanes2,
            false
          ), stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes));
          if (didSuspendBefore) {
            if (stateNode)
              return updateSuspenseListComponent(
                current2,
                workInProgress2,
                renderLanes2
              );
            workInProgress2.flags |= 128;
          }
          didSuspendBefore = workInProgress2.memoizedState;
          null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
          push2(
            suspenseStackCursor,
            suspenseStackCursor.current,
            workInProgress2
          );
          if (stateNode) break;
          else return null;
        case 22:
          return workInProgress2.lanes = 0, updateOffscreenComponent(
            current2,
            workInProgress2,
            renderLanes2,
            workInProgress2.pendingProps
          );
        case 24:
          pushProvider(
            workInProgress2,
            CacheContext,
            current2.memoizedState.cache
          );
      }
      return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
    }
    function beginWork(current2, workInProgress2, renderLanes2) {
      if (workInProgress2._debugNeedsRemount && null !== current2) {
        renderLanes2 = createFiberFromTypeAndProps(
          workInProgress2.type,
          workInProgress2.key,
          workInProgress2.pendingProps,
          workInProgress2._debugOwner || null,
          workInProgress2.mode,
          workInProgress2.lanes
        );
        renderLanes2._debugStack = workInProgress2._debugStack;
        renderLanes2._debugTask = workInProgress2._debugTask;
        var returnFiber = workInProgress2.return;
        if (null === returnFiber) throw Error("Cannot swap the root fiber.");
        current2.alternate = null;
        workInProgress2.alternate = null;
        renderLanes2.index = workInProgress2.index;
        renderLanes2.sibling = workInProgress2.sibling;
        renderLanes2.return = workInProgress2.return;
        renderLanes2.ref = workInProgress2.ref;
        renderLanes2._debugInfo = workInProgress2._debugInfo;
        if (workInProgress2 === returnFiber.child)
          returnFiber.child = renderLanes2;
        else {
          var prevSibling = returnFiber.child;
          if (null === prevSibling)
            throw Error("Expected parent to have a child.");
          for (; prevSibling.sibling !== workInProgress2; )
            if (prevSibling = prevSibling.sibling, null === prevSibling)
              throw Error("Expected to find the previous sibling.");
          prevSibling.sibling = renderLanes2;
        }
        workInProgress2 = returnFiber.deletions;
        null === workInProgress2 ? (returnFiber.deletions = [current2], returnFiber.flags |= 16) : workInProgress2.push(current2);
        renderLanes2.flags |= 2;
        return renderLanes2;
      }
      if (null !== current2)
        if (current2.memoizedProps !== workInProgress2.pendingProps || workInProgress2.type !== current2.type)
          didReceiveUpdate = true;
        else {
          if (!checkScheduledUpdateOrContext(current2, renderLanes2) && 0 === (workInProgress2.flags & 128))
            return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
              current2,
              workInProgress2,
              renderLanes2
            );
          didReceiveUpdate = 0 !== (current2.flags & 131072) ? true : false;
        }
      else {
        didReceiveUpdate = false;
        if (returnFiber = isHydrating)
          warnIfNotHydrating(), returnFiber = 0 !== (workInProgress2.flags & 1048576);
        returnFiber && (returnFiber = workInProgress2.index, warnIfNotHydrating(), pushTreeId(workInProgress2, treeForkCount, returnFiber));
      }
      workInProgress2.lanes = 0;
      switch (workInProgress2.tag) {
        case 16:
          a: if (returnFiber = workInProgress2.pendingProps, current2 = resolveLazy(workInProgress2.elementType), workInProgress2.type = current2, "function" === typeof current2)
            shouldConstruct(current2) ? (returnFiber = resolveClassComponentProps(
              current2,
              returnFiber
            ), workInProgress2.tag = 1, workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateClassComponent(
              null,
              workInProgress2,
              current2,
              returnFiber,
              renderLanes2
            )) : (workInProgress2.tag = 0, validateFunctionComponentInDev(workInProgress2, current2), workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateFunctionComponent(
              null,
              workInProgress2,
              current2,
              returnFiber,
              renderLanes2
            ));
          else {
            if (void 0 !== current2 && null !== current2) {
              if (prevSibling = current2.$$typeof, prevSibling === REACT_FORWARD_REF_TYPE) {
                workInProgress2.tag = 11;
                workInProgress2.type = current2 = resolveForwardRefForHotReloading(current2);
                workInProgress2 = updateForwardRef(
                  null,
                  workInProgress2,
                  current2,
                  returnFiber,
                  renderLanes2
                );
                break a;
              } else if (prevSibling === REACT_MEMO_TYPE) {
                workInProgress2.tag = 14;
                workInProgress2 = updateMemoComponent(
                  null,
                  workInProgress2,
                  current2,
                  returnFiber,
                  renderLanes2
                );
                break a;
              }
            }
            workInProgress2 = "";
            null !== current2 && "object" === typeof current2 && current2.$$typeof === REACT_LAZY_TYPE && (workInProgress2 = " Did you wrap a component in React.lazy() more than once?");
            renderLanes2 = getComponentNameFromType(current2) || current2;
            throw Error(
              "Element type is invalid. Received a promise that resolves to: " + renderLanes2 + ". Lazy element type must resolve to a class or function." + workInProgress2
            );
          }
          return workInProgress2;
        case 0:
          return updateFunctionComponent(
            current2,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 1:
          return returnFiber = workInProgress2.type, prevSibling = resolveClassComponentProps(
            returnFiber,
            workInProgress2.pendingProps
          ), updateClassComponent(
            current2,
            workInProgress2,
            returnFiber,
            prevSibling,
            renderLanes2
          );
        case 3:
          a: {
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            if (null === current2)
              throw Error(
                "Should have a current fiber. This is a bug in React."
              );
            returnFiber = workInProgress2.pendingProps;
            var prevState = workInProgress2.memoizedState;
            prevSibling = prevState.element;
            cloneUpdateQueue(current2, workInProgress2);
            processUpdateQueue(workInProgress2, returnFiber, null, renderLanes2);
            var nextState = workInProgress2.memoizedState;
            returnFiber = nextState.cache;
            pushProvider(workInProgress2, CacheContext, returnFiber);
            returnFiber !== prevState.cache && propagateContextChanges(
              workInProgress2,
              [CacheContext],
              renderLanes2,
              true
            );
            suspendIfUpdateReadFromEntangledAsyncAction();
            returnFiber = nextState.element;
            if (prevState.isDehydrated)
              if (prevState = {
                element: returnFiber,
                isDehydrated: false,
                cache: nextState.cache
              }, workInProgress2.updateQueue.baseState = prevState, workInProgress2.memoizedState = prevState, workInProgress2.flags & 256) {
                workInProgress2 = mountHostRootWithoutHydrating(
                  current2,
                  workInProgress2,
                  returnFiber,
                  renderLanes2
                );
                break a;
              } else if (returnFiber !== prevSibling) {
                prevSibling = createCapturedValueAtFiber(
                  Error(
                    "This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."
                  ),
                  workInProgress2
                );
                queueHydrationError(prevSibling);
                workInProgress2 = mountHostRootWithoutHydrating(
                  current2,
                  workInProgress2,
                  returnFiber,
                  renderLanes2
                );
                break a;
              } else {
                current2 = workInProgress2.stateNode.containerInfo;
                switch (current2.nodeType) {
                  case 9:
                    current2 = current2.body;
                    break;
                  default:
                    current2 = "HTML" === current2.nodeName ? current2.ownerDocument.body : current2;
                }
                nextHydratableInstance = getNextHydratable(current2.firstChild);
                hydrationParentFiber = workInProgress2;
                isHydrating = true;
                hydrationErrors = null;
                didSuspendOrErrorDEV = false;
                hydrationDiffRootDEV = null;
                rootOrSingletonContext = true;
                renderLanes2 = mountChildFibers(
                  workInProgress2,
                  null,
                  returnFiber,
                  renderLanes2
                );
                for (workInProgress2.child = renderLanes2; renderLanes2; )
                  renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
              }
            else {
              resetHydrationState();
              if (returnFiber === prevSibling) {
                workInProgress2 = bailoutOnAlreadyFinishedWork(
                  current2,
                  workInProgress2,
                  renderLanes2
                );
                break a;
              }
              reconcileChildren(
                current2,
                workInProgress2,
                returnFiber,
                renderLanes2
              );
            }
            workInProgress2 = workInProgress2.child;
          }
          return workInProgress2;
        case 26:
          return markRef(current2, workInProgress2), null === current2 ? (renderLanes2 = getResource(
            workInProgress2.type,
            null,
            workInProgress2.pendingProps,
            null
          )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (renderLanes2 = workInProgress2.type, current2 = workInProgress2.pendingProps, returnFiber = requiredContext(
            rootInstanceStackCursor.current
          ), returnFiber = getOwnerDocumentFromRootContainer(
            returnFiber
          ).createElement(renderLanes2), returnFiber[internalInstanceKey] = workInProgress2, returnFiber[internalPropsKey] = current2, setInitialProperties(returnFiber, renderLanes2, current2), markNodeAsHoistable(returnFiber), workInProgress2.stateNode = returnFiber) : workInProgress2.memoizedState = getResource(
            workInProgress2.type,
            current2.memoizedProps,
            workInProgress2.pendingProps,
            current2.memoizedState
          ), null;
        case 27:
          return pushHostContext(workInProgress2), null === current2 && isHydrating && (returnFiber = requiredContext(rootInstanceStackCursor.current), prevSibling = getHostContext(), returnFiber = workInProgress2.stateNode = resolveSingletonInstance(
            workInProgress2.type,
            workInProgress2.pendingProps,
            returnFiber,
            prevSibling,
            false
          ), didSuspendOrErrorDEV || (prevSibling = diffHydratedProperties(
            returnFiber,
            workInProgress2.type,
            workInProgress2.pendingProps,
            prevSibling
          ), null !== prevSibling && (buildHydrationDiffNode(workInProgress2, 0).serverProps = prevSibling)), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, prevSibling = nextHydratableInstance, isSingletonScope(workInProgress2.type) ? (previousHydratableOnEnteringScopedSingleton = prevSibling, nextHydratableInstance = getNextHydratable(
            returnFiber.firstChild
          )) : nextHydratableInstance = prevSibling), reconcileChildren(
            current2,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), markRef(current2, workInProgress2), null === current2 && (workInProgress2.flags |= 4194304), workInProgress2.child;
        case 5:
          return null === current2 && isHydrating && (prevState = getHostContext(), returnFiber = validateDOMNesting(
            workInProgress2.type,
            prevState.ancestorInfo
          ), prevSibling = nextHydratableInstance, (nextState = !prevSibling) || (nextState = canHydrateInstance(
            prevSibling,
            workInProgress2.type,
            workInProgress2.pendingProps,
            rootOrSingletonContext
          ), null !== nextState ? (workInProgress2.stateNode = nextState, didSuspendOrErrorDEV || (prevState = diffHydratedProperties(
            nextState,
            workInProgress2.type,
            workInProgress2.pendingProps,
            prevState
          ), null !== prevState && (buildHydrationDiffNode(workInProgress2, 0).serverProps = prevState)), hydrationParentFiber = workInProgress2, nextHydratableInstance = getNextHydratable(
            nextState.firstChild
          ), rootOrSingletonContext = false, prevState = true) : prevState = false, nextState = !prevState), nextState && (returnFiber && warnNonHydratedInstance(workInProgress2, prevSibling), throwOnHydrationMismatch(workInProgress2))), pushHostContext(workInProgress2), prevSibling = workInProgress2.type, prevState = workInProgress2.pendingProps, nextState = null !== current2 ? current2.memoizedProps : null, returnFiber = prevState.children, shouldSetTextContent(prevSibling, prevState) ? returnFiber = null : null !== nextState && shouldSetTextContent(prevSibling, nextState) && (workInProgress2.flags |= 32), null !== workInProgress2.memoizedState && (prevSibling = renderWithHooks(
            current2,
            workInProgress2,
            TransitionAwareHostComponent,
            null,
            null,
            renderLanes2
          ), HostTransitionContext._currentValue = prevSibling), markRef(current2, workInProgress2), reconcileChildren(
            current2,
            workInProgress2,
            returnFiber,
            renderLanes2
          ), workInProgress2.child;
        case 6:
          return null === current2 && isHydrating && (renderLanes2 = workInProgress2.pendingProps, current2 = getHostContext(), returnFiber = current2.ancestorInfo.current, renderLanes2 = null != returnFiber ? validateTextNesting(
            renderLanes2,
            returnFiber.tag,
            current2.ancestorInfo.implicitRootScope
          ) : true, current2 = nextHydratableInstance, (returnFiber = !current2) || (returnFiber = canHydrateTextInstance(
            current2,
            workInProgress2.pendingProps,
            rootOrSingletonContext
          ), null !== returnFiber ? (workInProgress2.stateNode = returnFiber, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, returnFiber = true) : returnFiber = false, returnFiber = !returnFiber), returnFiber && (renderLanes2 && warnNonHydratedInstance(workInProgress2, current2), throwOnHydrationMismatch(workInProgress2))), null;
        case 13:
          return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
        case 4:
          return pushHostContainer(
            workInProgress2,
            workInProgress2.stateNode.containerInfo
          ), returnFiber = workInProgress2.pendingProps, null === current2 ? workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            null,
            returnFiber,
            renderLanes2
          ) : reconcileChildren(
            current2,
            workInProgress2,
            returnFiber,
            renderLanes2
          ), workInProgress2.child;
        case 11:
          return updateForwardRef(
            current2,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 7:
          return reconcileChildren(
            current2,
            workInProgress2,
            workInProgress2.pendingProps,
            renderLanes2
          ), workInProgress2.child;
        case 8:
          return reconcileChildren(
            current2,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 12:
          return workInProgress2.flags |= 4, workInProgress2.flags |= 2048, returnFiber = workInProgress2.stateNode, returnFiber.effectDuration = -0, returnFiber.passiveEffectDuration = -0, reconcileChildren(
            current2,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 10:
          return returnFiber = workInProgress2.type, prevSibling = workInProgress2.pendingProps, prevState = prevSibling.value, "value" in prevSibling || hasWarnedAboutUsingNoValuePropOnContextProvider || (hasWarnedAboutUsingNoValuePropOnContextProvider = true, console.error(
            "The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?"
          )), pushProvider(workInProgress2, returnFiber, prevState), reconcileChildren(
            current2,
            workInProgress2,
            prevSibling.children,
            renderLanes2
          ), workInProgress2.child;
        case 9:
          return prevSibling = workInProgress2.type._context, returnFiber = workInProgress2.pendingProps.children, "function" !== typeof returnFiber && console.error(
            "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."
          ), prepareToReadContext(workInProgress2), prevSibling = readContext(prevSibling), returnFiber = callComponentInDEV(
            returnFiber,
            prevSibling,
            void 0
          ), workInProgress2.flags |= 1, reconcileChildren(
            current2,
            workInProgress2,
            returnFiber,
            renderLanes2
          ), workInProgress2.child;
        case 14:
          return updateMemoComponent(
            current2,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 15:
          return updateSimpleMemoComponent(
            current2,
            workInProgress2,
            workInProgress2.type,
            workInProgress2.pendingProps,
            renderLanes2
          );
        case 19:
          return updateSuspenseListComponent(
            current2,
            workInProgress2,
            renderLanes2
          );
        case 31:
          return updateActivityComponent(current2, workInProgress2, renderLanes2);
        case 22:
          return updateOffscreenComponent(
            current2,
            workInProgress2,
            renderLanes2,
            workInProgress2.pendingProps
          );
        case 24:
          return prepareToReadContext(workInProgress2), returnFiber = readContext(CacheContext), null === current2 ? (prevSibling = peekCacheFromPool(), null === prevSibling && (prevSibling = workInProgressRoot, prevState = createCache(), prevSibling.pooledCache = prevState, retainCache(prevState), null !== prevState && (prevSibling.pooledCacheLanes |= renderLanes2), prevSibling = prevState), workInProgress2.memoizedState = {
            parent: returnFiber,
            cache: prevSibling
          }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, prevSibling)) : (0 !== (current2.lanes & renderLanes2) && (cloneUpdateQueue(current2, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), prevSibling = current2.memoizedState, prevState = workInProgress2.memoizedState, prevSibling.parent !== returnFiber ? (prevSibling = {
            parent: returnFiber,
            cache: returnFiber
          }, workInProgress2.memoizedState = prevSibling, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = prevSibling), pushProvider(workInProgress2, CacheContext, returnFiber)) : (returnFiber = prevState.cache, pushProvider(workInProgress2, CacheContext, returnFiber), returnFiber !== prevSibling.cache && propagateContextChanges(
            workInProgress2,
            [CacheContext],
            renderLanes2,
            true
          ))), reconcileChildren(
            current2,
            workInProgress2,
            workInProgress2.pendingProps.children,
            renderLanes2
          ), workInProgress2.child;
        case 29:
          throw workInProgress2.pendingProps;
      }
      throw Error(
        "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
      );
    }
    function markUpdate(workInProgress2) {
      workInProgress2.flags |= 4;
    }
    function preloadInstanceAndSuspendIfNeeded(workInProgress2, type2, oldProps, newProps, renderLanes2) {
      if (type2 = (workInProgress2.mode & SuspenseyImagesMode) !== NoMode)
        type2 = false;
      if (type2) {
        if (workInProgress2.flags |= 16777216, (renderLanes2 & 335544128) === renderLanes2)
          if (workInProgress2.stateNode.complete) workInProgress2.flags |= 8192;
          else if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
          else
            throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
      } else workInProgress2.flags &= -16777217;
    }
    function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
      if ("stylesheet" !== resource.type || (resource.state.loading & Inserted) !== NotLoaded)
        workInProgress2.flags &= -16777217;
      else if (workInProgress2.flags |= 16777216, !preloadResource(resource))
        if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
        else
          throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
    }
    function scheduleRetryEffect(workInProgress2, retryQueue) {
      null !== retryQueue && (workInProgress2.flags |= 4);
      workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
    }
    function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
      if (!isHydrating)
        switch (renderState.tailMode) {
          case "hidden":
            hasRenderedATailFallback = renderState.tail;
            for (var lastTailNode = null; null !== hasRenderedATailFallback; )
              null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
            null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
            break;
          case "collapsed":
            lastTailNode = renderState.tail;
            for (var _lastTailNode = null; null !== lastTailNode; )
              null !== lastTailNode.alternate && (_lastTailNode = lastTailNode), lastTailNode = lastTailNode.sibling;
            null === _lastTailNode ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : _lastTailNode.sibling = null;
        }
    }
    function bubbleProperties(completedWork) {
      var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
      if (didBailout)
        if ((completedWork.mode & ProfileMode) !== NoMode) {
          for (var _treeBaseDuration = completedWork.selfBaseDuration, _child2 = completedWork.child; null !== _child2; )
            newChildLanes |= _child2.lanes | _child2.childLanes, subtreeFlags |= _child2.subtreeFlags & 65011712, subtreeFlags |= _child2.flags & 65011712, _treeBaseDuration += _child2.treeBaseDuration, _child2 = _child2.sibling;
          completedWork.treeBaseDuration = _treeBaseDuration;
        } else
          for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
            newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags & 65011712, subtreeFlags |= _treeBaseDuration.flags & 65011712, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
      else if ((completedWork.mode & ProfileMode) !== NoMode) {
        _treeBaseDuration = completedWork.actualDuration;
        _child2 = completedWork.selfBaseDuration;
        for (var child = completedWork.child; null !== child; )
          newChildLanes |= child.lanes | child.childLanes, subtreeFlags |= child.subtreeFlags, subtreeFlags |= child.flags, _treeBaseDuration += child.actualDuration, _child2 += child.treeBaseDuration, child = child.sibling;
        completedWork.actualDuration = _treeBaseDuration;
        completedWork.treeBaseDuration = _child2;
      } else
        for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
          newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags, subtreeFlags |= _treeBaseDuration.flags, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
      completedWork.subtreeFlags |= subtreeFlags;
      completedWork.childLanes = newChildLanes;
      return didBailout;
    }
    function completeWork(current2, workInProgress2, renderLanes2) {
      var newProps = workInProgress2.pendingProps;
      popTreeContext(workInProgress2);
      switch (workInProgress2.tag) {
        case 16:
        case 15:
        case 0:
        case 11:
        case 7:
        case 8:
        case 12:
        case 9:
        case 14:
          return bubbleProperties(workInProgress2), null;
        case 1:
          return bubbleProperties(workInProgress2), null;
        case 3:
          renderLanes2 = workInProgress2.stateNode;
          newProps = null;
          null !== current2 && (newProps = current2.memoizedState.cache);
          workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
          popProvider(CacheContext, workInProgress2);
          popHostContainer(workInProgress2);
          renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
          if (null === current2 || null === current2.child)
            popHydrationState(workInProgress2) ? (emitPendingHydrationWarnings(), markUpdate(workInProgress2)) : null === current2 || current2.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
          bubbleProperties(workInProgress2);
          return null;
        case 26:
          var type2 = workInProgress2.type, nextResource = workInProgress2.memoizedState;
          null === current2 ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
            workInProgress2,
            nextResource
          )) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
            workInProgress2,
            type2,
            null,
            newProps,
            renderLanes2
          ))) : nextResource ? nextResource !== current2.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
            workInProgress2,
            nextResource
          )) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (current2 = current2.memoizedProps, current2 !== newProps && markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
            workInProgress2,
            type2,
            current2,
            newProps,
            renderLanes2
          ));
          return null;
        case 27:
          popHostContext(workInProgress2);
          renderLanes2 = requiredContext(rootInstanceStackCursor.current);
          type2 = workInProgress2.type;
          if (null !== current2 && null != workInProgress2.stateNode)
            current2.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if (!newProps) {
              if (null === workInProgress2.stateNode)
                throw Error(
                  "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                );
              bubbleProperties(workInProgress2);
              return null;
            }
            current2 = getHostContext();
            popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2) : (current2 = resolveSingletonInstance(
              type2,
              newProps,
              renderLanes2,
              current2,
              true
            ), workInProgress2.stateNode = current2, markUpdate(workInProgress2));
          }
          bubbleProperties(workInProgress2);
          return null;
        case 5:
          popHostContext(workInProgress2);
          type2 = workInProgress2.type;
          if (null !== current2 && null != workInProgress2.stateNode)
            current2.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if (!newProps) {
              if (null === workInProgress2.stateNode)
                throw Error(
                  "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                );
              bubbleProperties(workInProgress2);
              return null;
            }
            var _currentHostContext = getHostContext();
            if (popHydrationState(workInProgress2))
              prepareToHydrateHostInstance(workInProgress2);
            else {
              nextResource = requiredContext(rootInstanceStackCursor.current);
              validateDOMNesting(type2, _currentHostContext.ancestorInfo);
              _currentHostContext = _currentHostContext.context;
              nextResource = getOwnerDocumentFromRootContainer(nextResource);
              switch (_currentHostContext) {
                case HostContextNamespaceSvg:
                  nextResource = nextResource.createElementNS(
                    SVG_NAMESPACE,
                    type2
                  );
                  break;
                case HostContextNamespaceMath:
                  nextResource = nextResource.createElementNS(
                    MATH_NAMESPACE,
                    type2
                  );
                  break;
                default:
                  switch (type2) {
                    case "svg":
                      nextResource = nextResource.createElementNS(
                        SVG_NAMESPACE,
                        type2
                      );
                      break;
                    case "math":
                      nextResource = nextResource.createElementNS(
                        MATH_NAMESPACE,
                        type2
                      );
                      break;
                    case "script":
                      nextResource = nextResource.createElement("div");
                      nextResource.innerHTML = "<script><\/script>";
                      nextResource = nextResource.removeChild(
                        nextResource.firstChild
                      );
                      break;
                    case "select":
                      nextResource = "string" === typeof newProps.is ? nextResource.createElement("select", {
                        is: newProps.is
                      }) : nextResource.createElement("select");
                      newProps.multiple ? nextResource.multiple = true : newProps.size && (nextResource.size = newProps.size);
                      break;
                    default:
                      nextResource = "string" === typeof newProps.is ? nextResource.createElement(type2, {
                        is: newProps.is
                      }) : nextResource.createElement(type2), -1 === type2.indexOf("-") && (type2 !== type2.toLowerCase() && console.error(
                        "<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",
                        type2
                      ), "[object HTMLUnknownElement]" !== Object.prototype.toString.call(nextResource) || hasOwnProperty2.call(warnedUnknownTags, type2) || (warnedUnknownTags[type2] = true, console.error(
                        "The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.",
                        type2
                      )));
                  }
              }
              nextResource[internalInstanceKey] = workInProgress2;
              nextResource[internalPropsKey] = newProps;
              a: for (_currentHostContext = workInProgress2.child; null !== _currentHostContext; ) {
                if (5 === _currentHostContext.tag || 6 === _currentHostContext.tag)
                  nextResource.appendChild(_currentHostContext.stateNode);
                else if (4 !== _currentHostContext.tag && 27 !== _currentHostContext.tag && null !== _currentHostContext.child) {
                  _currentHostContext.child.return = _currentHostContext;
                  _currentHostContext = _currentHostContext.child;
                  continue;
                }
                if (_currentHostContext === workInProgress2) break a;
                for (; null === _currentHostContext.sibling; ) {
                  if (null === _currentHostContext.return || _currentHostContext.return === workInProgress2)
                    break a;
                  _currentHostContext = _currentHostContext.return;
                }
                _currentHostContext.sibling.return = _currentHostContext.return;
                _currentHostContext = _currentHostContext.sibling;
              }
              workInProgress2.stateNode = nextResource;
              a: switch (setInitialProperties(nextResource, type2, newProps), type2) {
                case "button":
                case "input":
                case "select":
                case "textarea":
                  newProps = !!newProps.autoFocus;
                  break a;
                case "img":
                  newProps = true;
                  break a;
                default:
                  newProps = false;
              }
              newProps && markUpdate(workInProgress2);
            }
          }
          bubbleProperties(workInProgress2);
          preloadInstanceAndSuspendIfNeeded(
            workInProgress2,
            workInProgress2.type,
            null === current2 ? null : current2.memoizedProps,
            workInProgress2.pendingProps,
            renderLanes2
          );
          return null;
        case 6:
          if (current2 && null != workInProgress2.stateNode)
            current2.memoizedProps !== newProps && markUpdate(workInProgress2);
          else {
            if ("string" !== typeof newProps && null === workInProgress2.stateNode)
              throw Error(
                "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
              );
            current2 = requiredContext(rootInstanceStackCursor.current);
            renderLanes2 = getHostContext();
            if (popHydrationState(workInProgress2)) {
              current2 = workInProgress2.stateNode;
              renderLanes2 = workInProgress2.memoizedProps;
              type2 = !didSuspendOrErrorDEV;
              newProps = null;
              nextResource = hydrationParentFiber;
              if (null !== nextResource)
                switch (nextResource.tag) {
                  case 3:
                    type2 && (type2 = diffHydratedTextForDevWarnings(
                      current2,
                      renderLanes2,
                      newProps
                    ), null !== type2 && (buildHydrationDiffNode(workInProgress2, 0).serverProps = type2));
                    break;
                  case 27:
                  case 5:
                    newProps = nextResource.memoizedProps, type2 && (type2 = diffHydratedTextForDevWarnings(
                      current2,
                      renderLanes2,
                      newProps
                    ), null !== type2 && (buildHydrationDiffNode(
                      workInProgress2,
                      0
                    ).serverProps = type2));
                }
              current2[internalInstanceKey] = workInProgress2;
              current2 = current2.nodeValue === renderLanes2 || null !== newProps && true === newProps.suppressHydrationWarning || checkForUnmatchedText(current2.nodeValue, renderLanes2) ? true : false;
              current2 || throwOnHydrationMismatch(workInProgress2, true);
            } else
              type2 = renderLanes2.ancestorInfo.current, null != type2 && validateTextNesting(
                newProps,
                type2.tag,
                renderLanes2.ancestorInfo.implicitRootScope
              ), current2 = getOwnerDocumentFromRootContainer(current2).createTextNode(
                newProps
              ), current2[internalInstanceKey] = workInProgress2, workInProgress2.stateNode = current2;
          }
          bubbleProperties(workInProgress2);
          return null;
        case 31:
          renderLanes2 = workInProgress2.memoizedState;
          if (null === current2 || null !== current2.memoizedState) {
            newProps = popHydrationState(workInProgress2);
            if (null !== renderLanes2) {
              if (null === current2) {
                if (!newProps)
                  throw Error(
                    "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                  );
                current2 = workInProgress2.memoizedState;
                current2 = null !== current2 ? current2.dehydrated : null;
                if (!current2)
                  throw Error(
                    "Expected to have a hydrated activity instance. This error is likely caused by a bug in React. Please file an issue."
                  );
                current2[internalInstanceKey] = workInProgress2;
                bubbleProperties(workInProgress2);
                (workInProgress2.mode & ProfileMode) !== NoMode && null !== renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
              } else
                emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (renderLanes2 = workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & ProfileMode) !== NoMode && null !== renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
              current2 = false;
            } else
              renderLanes2 = upgradeHydrationErrorsToRecoverable(), null !== current2 && null !== current2.memoizedState && (current2.memoizedState.hydrationErrors = renderLanes2), current2 = true;
            if (!current2) {
              if (workInProgress2.flags & 256)
                return popSuspenseHandler(workInProgress2), workInProgress2;
              popSuspenseHandler(workInProgress2);
              return null;
            }
            if (0 !== (workInProgress2.flags & 128))
              throw Error(
                "Client rendering an Activity suspended it again. This is a bug in React."
              );
          }
          bubbleProperties(workInProgress2);
          return null;
        case 13:
          newProps = workInProgress2.memoizedState;
          if (null === current2 || null !== current2.memoizedState && null !== current2.memoizedState.dehydrated) {
            type2 = newProps;
            nextResource = popHydrationState(workInProgress2);
            if (null !== type2 && null !== type2.dehydrated) {
              if (null === current2) {
                if (!nextResource)
                  throw Error(
                    "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                  );
                nextResource = workInProgress2.memoizedState;
                nextResource = null !== nextResource ? nextResource.dehydrated : null;
                if (!nextResource)
                  throw Error(
                    "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
                  );
                nextResource[internalInstanceKey] = workInProgress2;
                bubbleProperties(workInProgress2);
                (workInProgress2.mode & ProfileMode) !== NoMode && null !== type2 && (type2 = workInProgress2.child, null !== type2 && (workInProgress2.treeBaseDuration -= type2.treeBaseDuration));
              } else
                emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (type2 = workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & ProfileMode) !== NoMode && null !== type2 && (type2 = workInProgress2.child, null !== type2 && (workInProgress2.treeBaseDuration -= type2.treeBaseDuration));
              type2 = false;
            } else
              type2 = upgradeHydrationErrorsToRecoverable(), null !== current2 && null !== current2.memoizedState && (current2.memoizedState.hydrationErrors = type2), type2 = true;
            if (!type2) {
              if (workInProgress2.flags & 256)
                return popSuspenseHandler(workInProgress2), workInProgress2;
              popSuspenseHandler(workInProgress2);
              return null;
            }
          }
          popSuspenseHandler(workInProgress2);
          if (0 !== (workInProgress2.flags & 128))
            return workInProgress2.lanes = renderLanes2, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2;
          renderLanes2 = null !== newProps;
          current2 = null !== current2 && null !== current2.memoizedState;
          renderLanes2 && (newProps = workInProgress2.child, type2 = null, null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (type2 = newProps.alternate.memoizedState.cachePool.pool), nextResource = null, null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (nextResource = newProps.memoizedState.cachePool.pool), nextResource !== type2 && (newProps.flags |= 2048));
          renderLanes2 !== current2 && renderLanes2 && (workInProgress2.child.flags |= 8192);
          scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
          bubbleProperties(workInProgress2);
          (workInProgress2.mode & ProfileMode) !== NoMode && renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
          return null;
        case 4:
          return popHostContainer(workInProgress2), null === current2 && listenToAllSupportedEvents(
            workInProgress2.stateNode.containerInfo
          ), bubbleProperties(workInProgress2), null;
        case 10:
          return popProvider(workInProgress2.type, workInProgress2), bubbleProperties(workInProgress2), null;
        case 19:
          pop(suspenseStackCursor, workInProgress2);
          newProps = workInProgress2.memoizedState;
          if (null === newProps) return bubbleProperties(workInProgress2), null;
          type2 = 0 !== (workInProgress2.flags & 128);
          nextResource = newProps.rendering;
          if (null === nextResource)
            if (type2) cutOffTailIfNeeded(newProps, false);
            else {
              if (workInProgressRootExitStatus !== RootInProgress || null !== current2 && 0 !== (current2.flags & 128))
                for (current2 = workInProgress2.child; null !== current2; ) {
                  nextResource = findFirstSuspended(current2);
                  if (null !== nextResource) {
                    workInProgress2.flags |= 128;
                    cutOffTailIfNeeded(newProps, false);
                    current2 = nextResource.updateQueue;
                    workInProgress2.updateQueue = current2;
                    scheduleRetryEffect(workInProgress2, current2);
                    workInProgress2.subtreeFlags = 0;
                    current2 = renderLanes2;
                    for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                      resetWorkInProgress(renderLanes2, current2), renderLanes2 = renderLanes2.sibling;
                    push2(
                      suspenseStackCursor,
                      suspenseStackCursor.current & SubtreeSuspenseContextMask | ForceSuspenseFallback,
                      workInProgress2
                    );
                    isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount);
                    return workInProgress2.child;
                  }
                  current2 = current2.sibling;
                }
              null !== newProps.tail && now$1() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, type2 = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
            }
          else {
            if (!type2)
              if (current2 = findFirstSuspended(nextResource), null !== current2) {
                if (workInProgress2.flags |= 128, type2 = true, current2 = current2.updateQueue, workInProgress2.updateQueue = current2, scheduleRetryEffect(workInProgress2, current2), cutOffTailIfNeeded(newProps, true), null === newProps.tail && "hidden" === newProps.tailMode && !nextResource.alternate && !isHydrating)
                  return bubbleProperties(workInProgress2), null;
              } else
                2 * now$1() - newProps.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, type2 = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
            newProps.isBackwards ? (nextResource.sibling = workInProgress2.child, workInProgress2.child = nextResource) : (current2 = newProps.last, null !== current2 ? current2.sibling = nextResource : workInProgress2.child = nextResource, newProps.last = nextResource);
          }
          if (null !== newProps.tail)
            return current2 = newProps.tail, newProps.rendering = current2, newProps.tail = current2.sibling, newProps.renderingStartTime = now$1(), current2.sibling = null, renderLanes2 = suspenseStackCursor.current, renderLanes2 = type2 ? renderLanes2 & SubtreeSuspenseContextMask | ForceSuspenseFallback : renderLanes2 & SubtreeSuspenseContextMask, push2(suspenseStackCursor, renderLanes2, workInProgress2), isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount), current2;
          bubbleProperties(workInProgress2);
          return null;
        case 22:
        case 23:
          return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), newProps = null !== workInProgress2.memoizedState, null !== current2 ? null !== current2.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current2 && null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (renderLanes2 = current2.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current2 && pop(resumedCache, workInProgress2), null;
        case 24:
          return renderLanes2 = null, null !== current2 && (renderLanes2 = current2.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext, workInProgress2), bubbleProperties(workInProgress2), null;
        case 25:
          return null;
        case 30:
          return null;
      }
      throw Error(
        "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
      );
    }
    function unwindWork(current2, workInProgress2) {
      popTreeContext(workInProgress2);
      switch (workInProgress2.tag) {
        case 1:
          return current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 3:
          return popProvider(CacheContext, workInProgress2), popHostContainer(workInProgress2), current2 = workInProgress2.flags, 0 !== (current2 & 65536) && 0 === (current2 & 128) ? (workInProgress2.flags = current2 & -65537 | 128, workInProgress2) : null;
        case 26:
        case 27:
        case 5:
          return popHostContext(workInProgress2), null;
        case 31:
          if (null !== workInProgress2.memoizedState) {
            popSuspenseHandler(workInProgress2);
            if (null === workInProgress2.alternate)
              throw Error(
                "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
              );
            resetHydrationState();
          }
          current2 = workInProgress2.flags;
          return current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 13:
          popSuspenseHandler(workInProgress2);
          current2 = workInProgress2.memoizedState;
          if (null !== current2 && null !== current2.dehydrated) {
            if (null === workInProgress2.alternate)
              throw Error(
                "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
              );
            resetHydrationState();
          }
          current2 = workInProgress2.flags;
          return current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 19:
          return pop(suspenseStackCursor, workInProgress2), null;
        case 4:
          return popHostContainer(workInProgress2), null;
        case 10:
          return popProvider(workInProgress2.type, workInProgress2), null;
        case 22:
        case 23:
          return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), null !== current2 && pop(resumedCache, workInProgress2), current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
        case 24:
          return popProvider(CacheContext, workInProgress2), null;
        case 25:
          return null;
        default:
          return null;
      }
    }
    function unwindInterruptedWork(current2, interruptedWork) {
      popTreeContext(interruptedWork);
      switch (interruptedWork.tag) {
        case 3:
          popProvider(CacheContext, interruptedWork);
          popHostContainer(interruptedWork);
          break;
        case 26:
        case 27:
        case 5:
          popHostContext(interruptedWork);
          break;
        case 4:
          popHostContainer(interruptedWork);
          break;
        case 31:
          null !== interruptedWork.memoizedState && popSuspenseHandler(interruptedWork);
          break;
        case 13:
          popSuspenseHandler(interruptedWork);
          break;
        case 19:
          pop(suspenseStackCursor, interruptedWork);
          break;
        case 10:
          popProvider(interruptedWork.type, interruptedWork);
          break;
        case 22:
        case 23:
          popSuspenseHandler(interruptedWork);
          popHiddenContext(interruptedWork);
          null !== current2 && pop(resumedCache, interruptedWork);
          break;
        case 24:
          popProvider(CacheContext, interruptedWork);
      }
    }
    function shouldProfile(current2) {
      return (current2.mode & ProfileMode) !== NoMode;
    }
    function commitHookLayoutEffects(finishedWork, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
    }
    function commitHookLayoutUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      ), recordEffectDuration()) : commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      );
    }
    function commitHookEffectListMount(flags, finishedWork) {
      try {
        var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
        if (null !== lastEffect) {
          var firstEffect = lastEffect.next;
          updateQueue = firstEffect;
          do {
            if ((updateQueue.tag & flags) === flags && (lastEffect = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = runWithFiberInDEV(
              finishedWork,
              callCreateInDEV,
              updateQueue
            ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), void 0 !== lastEffect && "function" !== typeof lastEffect)) {
              var hookName = void 0;
              hookName = 0 !== (updateQueue.tag & Layout) ? "useLayoutEffect" : 0 !== (updateQueue.tag & Insertion) ? "useInsertionEffect" : "useEffect";
              var addendum = void 0;
              addendum = null === lastEffect ? " You returned null. If your effect does not require clean up, return undefined (or nothing)." : "function" === typeof lastEffect.then ? "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n  async function fetchData() {\n    // You can await here\n    const response = await MyAPI.getData(someId);\n    // ...\n  }\n  fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching" : " You returned: " + lastEffect;
              runWithFiberInDEV(
                finishedWork,
                function(n, a) {
                  console.error(
                    "%s must not return anything besides a function, which is used for clean-up.%s",
                    n,
                    a
                  );
                },
                hookName,
                addendum
              );
            }
            updateQueue = updateQueue.next;
          } while (updateQueue !== firstEffect);
        }
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
    function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
      try {
        var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
        if (null !== lastEffect) {
          var firstEffect = lastEffect.next;
          updateQueue = firstEffect;
          do {
            if ((updateQueue.tag & flags) === flags) {
              var inst = updateQueue.inst, destroy = inst.destroy;
              void 0 !== destroy && (inst.destroy = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = finishedWork, runWithFiberInDEV(
                lastEffect,
                callDestroyInDEV,
                lastEffect,
                nearestMountedAncestor,
                destroy
              ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false));
            }
            updateQueue = updateQueue.next;
          } while (updateQueue !== firstEffect);
        }
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
    function commitHookPassiveMountEffects(finishedWork, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
    }
    function commitHookPassiveUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
      shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      ), recordEffectDuration()) : commitHookEffectListUnmount(
        hookFlags,
        finishedWork,
        nearestMountedAncestor
      );
    }
    function commitClassCallbacks(finishedWork) {
      var updateQueue = finishedWork.updateQueue;
      if (null !== updateQueue) {
        var instance = finishedWork.stateNode;
        finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (instance.props !== finishedWork.memoizedProps && console.error(
          "Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ), instance.state !== finishedWork.memoizedState && console.error(
          "Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ));
        try {
          runWithFiberInDEV(
            finishedWork,
            commitCallbacks,
            updateQueue,
            instance
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
    }
    function callGetSnapshotBeforeUpdates(instance, prevProps, prevState) {
      return instance.getSnapshotBeforeUpdate(prevProps, prevState);
    }
    function commitClassSnapshot(finishedWork, current2) {
      var prevProps = current2.memoizedProps, prevState = current2.memoizedState;
      current2 = finishedWork.stateNode;
      finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (current2.props !== finishedWork.memoizedProps && console.error(
        "Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
        getComponentNameFromFiber(finishedWork) || "instance"
      ), current2.state !== finishedWork.memoizedState && console.error(
        "Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
        getComponentNameFromFiber(finishedWork) || "instance"
      ));
      try {
        var resolvedPrevProps = resolveClassComponentProps(
          finishedWork.type,
          prevProps
        );
        var snapshot = runWithFiberInDEV(
          finishedWork,
          callGetSnapshotBeforeUpdates,
          current2,
          resolvedPrevProps,
          prevState
        );
        prevProps = didWarnAboutUndefinedSnapshotBeforeUpdate;
        void 0 !== snapshot || prevProps.has(finishedWork.type) || (prevProps.add(finishedWork.type), runWithFiberInDEV(finishedWork, function() {
          console.error(
            "%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.",
            getComponentNameFromFiber(finishedWork)
          );
        }));
        current2.__reactInternalSnapshotBeforeUpdate = snapshot;
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
    function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) {
      instance.props = resolveClassComponentProps(
        current2.type,
        current2.memoizedProps
      );
      instance.state = current2.memoizedState;
      shouldProfile(current2) ? (startEffectTimer(), runWithFiberInDEV(
        current2,
        callComponentWillUnmountInDEV,
        current2,
        nearestMountedAncestor,
        instance
      ), recordEffectDuration()) : runWithFiberInDEV(
        current2,
        callComponentWillUnmountInDEV,
        current2,
        nearestMountedAncestor,
        instance
      );
    }
    function commitAttachRef(finishedWork) {
      var ref2 = finishedWork.ref;
      if (null !== ref2) {
        switch (finishedWork.tag) {
          case 26:
          case 27:
          case 5:
            var instanceToUse = finishedWork.stateNode;
            break;
          case 30:
            instanceToUse = finishedWork.stateNode;
            break;
          default:
            instanceToUse = finishedWork.stateNode;
        }
        if ("function" === typeof ref2)
          if (shouldProfile(finishedWork))
            try {
              startEffectTimer(), finishedWork.refCleanup = ref2(instanceToUse);
            } finally {
              recordEffectDuration();
            }
          else finishedWork.refCleanup = ref2(instanceToUse);
        else
          "string" === typeof ref2 ? console.error("String refs are no longer supported.") : ref2.hasOwnProperty("current") || console.error(
            "Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().",
            getComponentNameFromFiber(finishedWork)
          ), ref2.current = instanceToUse;
      }
    }
    function safelyAttachRef(current2, nearestMountedAncestor) {
      try {
        runWithFiberInDEV(current2, commitAttachRef, current2);
      } catch (error) {
        captureCommitPhaseError(current2, nearestMountedAncestor, error);
      }
    }
    function safelyDetachRef(current2, nearestMountedAncestor) {
      var ref2 = current2.ref, refCleanup = current2.refCleanup;
      if (null !== ref2)
        if ("function" === typeof refCleanup)
          try {
            if (shouldProfile(current2))
              try {
                startEffectTimer(), runWithFiberInDEV(current2, refCleanup);
              } finally {
                recordEffectDuration(current2);
              }
            else runWithFiberInDEV(current2, refCleanup);
          } catch (error) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error);
          } finally {
            current2.refCleanup = null, current2 = current2.alternate, null != current2 && (current2.refCleanup = null);
          }
        else if ("function" === typeof ref2)
          try {
            if (shouldProfile(current2))
              try {
                startEffectTimer(), runWithFiberInDEV(current2, ref2, null);
              } finally {
                recordEffectDuration(current2);
              }
            else runWithFiberInDEV(current2, ref2, null);
          } catch (error$7) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error$7);
          }
        else ref2.current = null;
    }
    function commitProfiler(finishedWork, current2, commitStartTime2, effectDuration) {
      var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onCommit = _finishedWork$memoize.onCommit;
      _finishedWork$memoize = _finishedWork$memoize.onRender;
      current2 = null === current2 ? "mount" : "update";
      currentUpdateIsNested && (current2 = "nested-update");
      "function" === typeof _finishedWork$memoize && _finishedWork$memoize(
        id,
        current2,
        finishedWork.actualDuration,
        finishedWork.treeBaseDuration,
        finishedWork.actualStartTime,
        commitStartTime2
      );
      "function" === typeof onCommit && onCommit(id, current2, effectDuration, commitStartTime2);
    }
    function commitProfilerPostCommitImpl(finishedWork, current2, commitStartTime2, passiveEffectDuration) {
      var _finishedWork$memoize2 = finishedWork.memoizedProps;
      finishedWork = _finishedWork$memoize2.id;
      _finishedWork$memoize2 = _finishedWork$memoize2.onPostCommit;
      current2 = null === current2 ? "mount" : "update";
      currentUpdateIsNested && (current2 = "nested-update");
      "function" === typeof _finishedWork$memoize2 && _finishedWork$memoize2(
        finishedWork,
        current2,
        passiveEffectDuration,
        commitStartTime2
      );
    }
    function commitHostMount(finishedWork) {
      var type2 = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
      try {
        runWithFiberInDEV(
          finishedWork,
          commitMount,
          instance,
          type2,
          props,
          finishedWork
        );
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
    function commitHostUpdate(finishedWork, newProps, oldProps) {
      try {
        runWithFiberInDEV(
          finishedWork,
          commitUpdate,
          finishedWork.stateNode,
          finishedWork.type,
          oldProps,
          newProps,
          finishedWork
        );
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
    function isHostParent(fiber) {
      return 5 === fiber.tag || 3 === fiber.tag || 26 === fiber.tag || 27 === fiber.tag && isSingletonScope(fiber.type) || 4 === fiber.tag;
    }
    function getHostSibling(fiber) {
      a: for (; ; ) {
        for (; null === fiber.sibling; ) {
          if (null === fiber.return || isHostParent(fiber.return)) return null;
          fiber = fiber.return;
        }
        fiber.sibling.return = fiber.return;
        for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
          if (27 === fiber.tag && isSingletonScope(fiber.type)) continue a;
          if (fiber.flags & 2) continue a;
          if (null === fiber.child || 4 === fiber.tag) continue a;
          else fiber.child.return = fiber, fiber = fiber.child;
        }
        if (!(fiber.flags & 2)) return fiber.stateNode;
      }
    }
    function insertOrAppendPlacementNodeIntoContainer(node2, before, parent) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag)
        node2 = node2.stateNode, before ? (warnForReactChildrenConflict(parent), (9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent).insertBefore(node2, before)) : (warnForReactChildrenConflict(parent), before = 9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent, before.appendChild(node2), parent = parent._reactRootContainer, null !== parent && void 0 !== parent || null !== before.onclick || (before.onclick = noop$1));
      else if (4 !== tag && (27 === tag && isSingletonScope(node2.type) && (parent = node2.stateNode, before = null), node2 = node2.child, null !== node2))
        for (insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling; null !== node2; )
          insertOrAppendPlacementNodeIntoContainer(node2, before, parent), node2 = node2.sibling;
    }
    function insertOrAppendPlacementNode(node2, before, parent) {
      var tag = node2.tag;
      if (5 === tag || 6 === tag)
        node2 = node2.stateNode, before ? parent.insertBefore(node2, before) : parent.appendChild(node2);
      else if (4 !== tag && (27 === tag && isSingletonScope(node2.type) && (parent = node2.stateNode), node2 = node2.child, null !== node2))
        for (insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling; null !== node2; )
          insertOrAppendPlacementNode(node2, before, parent), node2 = node2.sibling;
    }
    function commitPlacement(finishedWork) {
      for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
        if (isHostParent(parentFiber)) {
          hostParentFiber = parentFiber;
          break;
        }
        parentFiber = parentFiber.return;
      }
      if (null == hostParentFiber)
        throw Error(
          "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
        );
      switch (hostParentFiber.tag) {
        case 27:
          hostParentFiber = hostParentFiber.stateNode;
          parentFiber = getHostSibling(finishedWork);
          insertOrAppendPlacementNode(
            finishedWork,
            parentFiber,
            hostParentFiber
          );
          break;
        case 5:
          parentFiber = hostParentFiber.stateNode;
          hostParentFiber.flags & 32 && (resetTextContent(parentFiber), hostParentFiber.flags &= -33);
          hostParentFiber = getHostSibling(finishedWork);
          insertOrAppendPlacementNode(
            finishedWork,
            hostParentFiber,
            parentFiber
          );
          break;
        case 3:
        case 4:
          hostParentFiber = hostParentFiber.stateNode.containerInfo;
          parentFiber = getHostSibling(finishedWork);
          insertOrAppendPlacementNodeIntoContainer(
            finishedWork,
            parentFiber,
            hostParentFiber
          );
          break;
        default:
          throw Error(
            "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."
          );
      }
    }
    function commitHostSingletonAcquisition(finishedWork) {
      var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
      try {
        runWithFiberInDEV(
          finishedWork,
          acquireSingletonInstance,
          finishedWork.type,
          props,
          singleton,
          finishedWork
        );
      } catch (error) {
        captureCommitPhaseError(finishedWork, finishedWork.return, error);
      }
    }
    function isHydratingParent(current2, finishedWork) {
      return 31 === finishedWork.tag ? (finishedWork = finishedWork.memoizedState, null !== current2.memoizedState && null === finishedWork) : 13 === finishedWork.tag ? (current2 = current2.memoizedState, finishedWork = finishedWork.memoizedState, null !== current2 && null !== current2.dehydrated && (null === finishedWork || null === finishedWork.dehydrated)) : 3 === finishedWork.tag ? current2.memoizedState.isDehydrated && 0 === (finishedWork.flags & 256) : false;
    }
    function commitBeforeMutationEffects(root3, firstChild) {
      root3 = root3.containerInfo;
      eventsEnabled = _enabled;
      root3 = getActiveElementDeep(root3);
      if (hasSelectionCapabilities(root3)) {
        if ("selectionStart" in root3)
          var JSCompiler_temp = {
            start: root3.selectionStart,
            end: root3.selectionEnd
          };
        else
          a: {
            JSCompiler_temp = (JSCompiler_temp = root3.ownerDocument) && JSCompiler_temp.defaultView || window;
            var selection = JSCompiler_temp.getSelection && JSCompiler_temp.getSelection();
            if (selection && 0 !== selection.rangeCount) {
              JSCompiler_temp = selection.anchorNode;
              var anchorOffset = selection.anchorOffset, focusNode = selection.focusNode;
              selection = selection.focusOffset;
              try {
                JSCompiler_temp.nodeType, focusNode.nodeType;
              } catch (e$2) {
                JSCompiler_temp = null;
                break a;
              }
              var length = 0, start = -1, end = -1, indexWithinAnchor = 0, indexWithinFocus = 0, node2 = root3, parentNode = null;
              b: for (; ; ) {
                for (var next; ; ) {
                  node2 !== JSCompiler_temp || 0 !== anchorOffset && 3 !== node2.nodeType || (start = length + anchorOffset);
                  node2 !== focusNode || 0 !== selection && 3 !== node2.nodeType || (end = length + selection);
                  3 === node2.nodeType && (length += node2.nodeValue.length);
                  if (null === (next = node2.firstChild)) break;
                  parentNode = node2;
                  node2 = next;
                }
                for (; ; ) {
                  if (node2 === root3) break b;
                  parentNode === JSCompiler_temp && ++indexWithinAnchor === anchorOffset && (start = length);
                  parentNode === focusNode && ++indexWithinFocus === selection && (end = length);
                  if (null !== (next = node2.nextSibling)) break;
                  node2 = parentNode;
                  parentNode = node2.parentNode;
                }
                node2 = next;
              }
              JSCompiler_temp = -1 === start || -1 === end ? null : { start, end };
            } else JSCompiler_temp = null;
          }
        JSCompiler_temp = JSCompiler_temp || { start: 0, end: 0 };
      } else JSCompiler_temp = null;
      selectionInformation = {
        focusedElem: root3,
        selectionRange: JSCompiler_temp
      };
      _enabled = false;
      for (nextEffect = firstChild; null !== nextEffect; )
        if (firstChild = nextEffect, root3 = firstChild.child, 0 !== (firstChild.subtreeFlags & 1028) && null !== root3)
          root3.return = firstChild, nextEffect = root3;
        else
          for (; null !== nextEffect; ) {
            root3 = firstChild = nextEffect;
            JSCompiler_temp = root3.alternate;
            anchorOffset = root3.flags;
            switch (root3.tag) {
              case 0:
                if (0 !== (anchorOffset & 4) && (root3 = root3.updateQueue, root3 = null !== root3 ? root3.events : null, null !== root3))
                  for (JSCompiler_temp = 0; JSCompiler_temp < root3.length; JSCompiler_temp++)
                    anchorOffset = root3[JSCompiler_temp], anchorOffset.ref.impl = anchorOffset.nextImpl;
                break;
              case 11:
              case 15:
                break;
              case 1:
                0 !== (anchorOffset & 1024) && null !== JSCompiler_temp && commitClassSnapshot(root3, JSCompiler_temp);
                break;
              case 3:
                if (0 !== (anchorOffset & 1024)) {
                  if (root3 = root3.stateNode.containerInfo, JSCompiler_temp = root3.nodeType, 9 === JSCompiler_temp)
                    clearContainerSparingly(root3);
                  else if (1 === JSCompiler_temp)
                    switch (root3.nodeName) {
                      case "HEAD":
                      case "HTML":
                      case "BODY":
                        clearContainerSparingly(root3);
                        break;
                      default:
                        root3.textContent = "";
                    }
                }
                break;
              case 5:
              case 26:
              case 27:
              case 6:
              case 4:
              case 17:
                break;
              default:
                if (0 !== (anchorOffset & 1024))
                  throw Error(
                    "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."
                  );
            }
            root3 = firstChild.sibling;
            if (null !== root3) {
              root3.return = firstChild.return;
              nextEffect = root3;
              break;
            }
            nextEffect = firstChild.return;
          }
    }
    function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitHookLayoutEffects(finishedWork, Layout | HasEffect);
          break;
        case 1:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (flags & 4)
            if (finishedRoot = finishedWork.stateNode, null === current2)
              finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                "Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                "Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              )), shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                finishedWork,
                callComponentDidMountInDEV,
                finishedWork,
                finishedRoot
              ), recordEffectDuration()) : runWithFiberInDEV(
                finishedWork,
                callComponentDidMountInDEV,
                finishedWork,
                finishedRoot
              );
            else {
              var prevProps = resolveClassComponentProps(
                finishedWork.type,
                current2.memoizedProps
              );
              current2 = current2.memoizedState;
              finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                "Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                "Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                getComponentNameFromFiber(finishedWork) || "instance"
              ));
              shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                finishedWork,
                callComponentDidUpdateInDEV,
                finishedWork,
                finishedRoot,
                prevProps,
                current2,
                finishedRoot.__reactInternalSnapshotBeforeUpdate
              ), recordEffectDuration()) : runWithFiberInDEV(
                finishedWork,
                callComponentDidUpdateInDEV,
                finishedWork,
                finishedRoot,
                prevProps,
                current2,
                finishedRoot.__reactInternalSnapshotBeforeUpdate
              );
            }
          flags & 64 && commitClassCallbacks(finishedWork);
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 3:
          current2 = pushNestedEffectDurations();
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (flags & 64 && (flags = finishedWork.updateQueue, null !== flags)) {
            prevProps = null;
            if (null !== finishedWork.child)
              switch (finishedWork.child.tag) {
                case 27:
                case 5:
                  prevProps = finishedWork.child.stateNode;
                  break;
                case 1:
                  prevProps = finishedWork.child.stateNode;
              }
            try {
              runWithFiberInDEV(
                finishedWork,
                commitCallbacks,
                flags,
                prevProps
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
          finishedRoot.effectDuration += popNestedEffectDurations(current2);
          break;
        case 27:
          null === current2 && flags & 4 && commitHostSingletonAcquisition(finishedWork);
        case 26:
        case 5:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          if (null === current2) {
            if (flags & 4) commitHostMount(finishedWork);
            else if (flags & 64) {
              finishedRoot = finishedWork.type;
              current2 = finishedWork.memoizedProps;
              prevProps = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitHydratedInstance,
                  prevProps,
                  finishedRoot,
                  current2,
                  finishedWork
                );
              } catch (error) {
                captureCommitPhaseError(
                  finishedWork,
                  finishedWork.return,
                  error
                );
              }
            }
          }
          flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 12:
          if (flags & 4) {
            flags = pushNestedEffectDurations();
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            finishedRoot = finishedWork.stateNode;
            finishedRoot.effectDuration += bubbleNestedEffectDurations(flags);
            try {
              runWithFiberInDEV(
                finishedWork,
                commitProfiler,
                finishedWork,
                current2,
                commitStartTime,
                finishedRoot.effectDuration
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          break;
        case 31:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 13:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
          flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          flags & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (flags = retryDehydratedSuspenseBoundary.bind(
            null,
            finishedWork
          ), registerSuspenseInstanceRetry(finishedRoot, flags))));
          break;
        case 22:
          flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
          if (!flags) {
            current2 = null !== current2 && null !== current2.memoizedState || offscreenSubtreeWasHidden;
            prevProps = offscreenSubtreeIsHidden;
            var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = flags;
            (offscreenSubtreeWasHidden = current2) && !prevOffscreenSubtreeWasHidden ? (recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              0 !== (finishedWork.subtreeFlags & 8772)
            ), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime
            )) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            offscreenSubtreeIsHidden = prevProps;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          }
          break;
        case 30:
          break;
        default:
          recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      ), null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate && 0.05 < componentEffectEndTime - componentEffectStartTime && (isHydratingParent(
        finishedWork.return.alternate,
        finishedWork.return
      ) || logComponentTrigger(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        "Mount"
      )));
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function detachFiberAfterEffects(fiber) {
      var alternate = fiber.alternate;
      null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
      fiber.child = null;
      fiber.deletions = null;
      fiber.sibling = null;
      5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
      fiber.stateNode = null;
      fiber._debugOwner = null;
      fiber.return = null;
      fiber.dependencies = null;
      fiber.memoizedProps = null;
      fiber.memoizedState = null;
      fiber.pendingProps = null;
      fiber.stateNode = null;
      fiber.updateQueue = null;
    }
    function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
      for (parent = parent.child; null !== parent; )
        commitDeletionEffectsOnFiber(
          finishedRoot,
          nearestMountedAncestor,
          parent
        ), parent = parent.sibling;
    }
    function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
      if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
        try {
          injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
        } catch (err) {
          hasLoggedError || (hasLoggedError = true, console.error(
            "React instrumentation encountered an error: %o",
            err
          ));
        }
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (deletedFiber.tag) {
        case 26:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          deletedFiber.memoizedState ? deletedFiber.memoizedState.count-- : deletedFiber.stateNode && (finishedRoot = deletedFiber.stateNode, finishedRoot.parentNode.removeChild(finishedRoot));
          break;
        case 27:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
          isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          runWithFiberInDEV(
            deletedFiber,
            releaseSingletonInstance,
            deletedFiber.stateNode
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          break;
        case 5:
          offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
        case 6:
          prevHostParent = hostParent;
          prevHostParentIsContainer = hostParentIsContainer;
          hostParent = null;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          if (null !== hostParent)
            if (hostParentIsContainer)
              try {
                runWithFiberInDEV(
                  deletedFiber,
                  removeChildFromContainer,
                  hostParent,
                  deletedFiber.stateNode
                );
              } catch (error) {
                captureCommitPhaseError(
                  deletedFiber,
                  nearestMountedAncestor,
                  error
                );
              }
            else
              try {
                runWithFiberInDEV(
                  deletedFiber,
                  removeChild,
                  hostParent,
                  deletedFiber.stateNode
                );
              } catch (error) {
                captureCommitPhaseError(
                  deletedFiber,
                  nearestMountedAncestor,
                  error
                );
              }
          break;
        case 18:
          null !== hostParent && (hostParentIsContainer ? (finishedRoot = hostParent, clearHydrationBoundary(
            9 === finishedRoot.nodeType ? finishedRoot.body : "HTML" === finishedRoot.nodeName ? finishedRoot.ownerDocument.body : finishedRoot,
            deletedFiber.stateNode
          ), retryIfBlockedOn(finishedRoot)) : clearHydrationBoundary(hostParent, deletedFiber.stateNode));
          break;
        case 4:
          prevHostParent = hostParent;
          prevHostParentIsContainer = hostParentIsContainer;
          hostParent = deletedFiber.stateNode.containerInfo;
          hostParentIsContainer = true;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          hostParent = prevHostParent;
          hostParentIsContainer = prevHostParentIsContainer;
          break;
        case 0:
        case 11:
        case 14:
        case 15:
          commitHookEffectListUnmount(
            Insertion,
            deletedFiber,
            nearestMountedAncestor
          );
          offscreenSubtreeWasHidden || commitHookLayoutUnmountEffects(
            deletedFiber,
            nearestMountedAncestor,
            Layout
          );
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 1:
          offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
            deletedFiber,
            nearestMountedAncestor,
            prevHostParent
          ));
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 21:
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          break;
        case 22:
          offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
          offscreenSubtreeWasHidden = prevHostParent;
          break;
        default:
          recursivelyTraverseDeletionEffects(
            finishedRoot,
            nearestMountedAncestor,
            deletedFiber
          );
      }
      (deletedFiber.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        deletedFiber,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function commitActivityHydrationCallbacks(finishedRoot, finishedWork) {
      if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot))) {
        finishedRoot = finishedRoot.dehydrated;
        try {
          runWithFiberInDEV(
            finishedWork,
            commitHydratedActivityInstance,
            finishedRoot
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
    }
    function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
      if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
        try {
          runWithFiberInDEV(
            finishedWork,
            commitHydratedSuspenseInstance,
            finishedRoot
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
    }
    function getRetryCache(finishedWork) {
      switch (finishedWork.tag) {
        case 31:
        case 13:
        case 19:
          var retryCache = finishedWork.stateNode;
          null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
          return retryCache;
        case 22:
          return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
        default:
          throw Error(
            "Unexpected Suspense handler tag (" + finishedWork.tag + "). This is a bug in React."
          );
      }
    }
    function attachSuspenseRetryListeners(finishedWork, wakeables) {
      var retryCache = getRetryCache(finishedWork);
      wakeables.forEach(function(wakeable) {
        if (!retryCache.has(wakeable)) {
          retryCache.add(wakeable);
          if (isDevToolsPresent)
            if (null !== inProgressLanes && null !== inProgressRoot)
              restorePendingUpdaters(inProgressRoot, inProgressLanes);
            else
              throw Error(
                "Expected finished root and lanes to be set. This is a bug in React."
              );
          var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
          wakeable.then(retry, retry);
        }
      });
    }
    function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
      var deletions = parentFiber.deletions;
      if (null !== deletions)
        for (var i = 0; i < deletions.length; i++) {
          var root3 = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i], prevEffectStart = pushComponentEffectStart(), parent = returnFiber;
          a: for (; null !== parent; ) {
            switch (parent.tag) {
              case 27:
                if (isSingletonScope(parent.type)) {
                  hostParent = parent.stateNode;
                  hostParentIsContainer = false;
                  break a;
                }
                break;
              case 5:
                hostParent = parent.stateNode;
                hostParentIsContainer = false;
                break a;
              case 3:
              case 4:
                hostParent = parent.stateNode.containerInfo;
                hostParentIsContainer = true;
                break a;
            }
            parent = parent.return;
          }
          if (null === hostParent)
            throw Error(
              "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
            );
          commitDeletionEffectsOnFiber(root3, returnFiber, deletedFiber);
          hostParent = null;
          hostParentIsContainer = false;
          (deletedFiber.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
            deletedFiber,
            componentEffectStartTime,
            componentEffectEndTime,
            "Unmount"
          );
          popComponentEffectStart(prevEffectStart);
          root3 = deletedFiber;
          returnFiber = root3.alternate;
          null !== returnFiber && (returnFiber.return = null);
          root3.return = null;
        }
      if (parentFiber.subtreeFlags & 13886)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
    }
    function commitMutationEffectsOnFiber(finishedWork, root3) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), current2 = finishedWork.alternate, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (commitHookEffectListUnmount(
            Insertion | HasEffect,
            finishedWork,
            finishedWork.return
          ), commitHookEffectListMount(Insertion | HasEffect, finishedWork), commitHookLayoutUnmountEffects(
            finishedWork,
            finishedWork.return,
            Layout | HasEffect
          ));
          break;
        case 1:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
          if (flags & 64 && offscreenSubtreeIsHidden && (flags = finishedWork.updateQueue, null !== flags && (current2 = flags.callbacks, null !== current2))) {
            var existingHiddenCallbacks = flags.shared.hiddenCallbacks;
            flags.shared.hiddenCallbacks = null === existingHiddenCallbacks ? current2 : existingHiddenCallbacks.concat(current2);
          }
          break;
        case 26:
          existingHiddenCallbacks = currentHoistableRoot;
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
          if (flags & 4) {
            var currentResource = null !== current2 ? current2.memoizedState : null;
            flags = finishedWork.memoizedState;
            if (null === current2)
              if (null === flags)
                if (null === finishedWork.stateNode) {
                  a: {
                    flags = finishedWork.type;
                    current2 = finishedWork.memoizedProps;
                    existingHiddenCallbacks = existingHiddenCallbacks.ownerDocument || existingHiddenCallbacks;
                    b: switch (flags) {
                      case "title":
                        currentResource = existingHiddenCallbacks.getElementsByTagName(
                          "title"
                        )[0];
                        if (!currentResource || currentResource[internalHoistableMarker] || currentResource[internalInstanceKey] || currentResource.namespaceURI === SVG_NAMESPACE || currentResource.hasAttribute("itemprop"))
                          currentResource = existingHiddenCallbacks.createElement(flags), existingHiddenCallbacks.head.insertBefore(
                            currentResource,
                            existingHiddenCallbacks.querySelector(
                              "head > title"
                            )
                          );
                        setInitialProperties(currentResource, flags, current2);
                        currentResource[internalInstanceKey] = finishedWork;
                        markNodeAsHoistable(currentResource);
                        flags = currentResource;
                        break a;
                      case "link":
                        var maybeNodes = getHydratableHoistableCache(
                          "link",
                          "href",
                          existingHiddenCallbacks
                        ).get(flags + (current2.href || ""));
                        if (maybeNodes) {
                          for (var i = 0; i < maybeNodes.length; i++)
                            if (currentResource = maybeNodes[i], currentResource.getAttribute("href") === (null == current2.href || "" === current2.href ? null : current2.href) && currentResource.getAttribute("rel") === (null == current2.rel ? null : current2.rel) && currentResource.getAttribute("title") === (null == current2.title ? null : current2.title) && currentResource.getAttribute("crossorigin") === (null == current2.crossOrigin ? null : current2.crossOrigin)) {
                              maybeNodes.splice(i, 1);
                              break b;
                            }
                        }
                        currentResource = existingHiddenCallbacks.createElement(flags);
                        setInitialProperties(currentResource, flags, current2);
                        existingHiddenCallbacks.head.appendChild(
                          currentResource
                        );
                        break;
                      case "meta":
                        if (maybeNodes = getHydratableHoistableCache(
                          "meta",
                          "content",
                          existingHiddenCallbacks
                        ).get(flags + (current2.content || ""))) {
                          for (i = 0; i < maybeNodes.length; i++)
                            if (currentResource = maybeNodes[i], checkAttributeStringCoercion(
                              current2.content,
                              "content"
                            ), currentResource.getAttribute("content") === (null == current2.content ? null : "" + current2.content) && currentResource.getAttribute("name") === (null == current2.name ? null : current2.name) && currentResource.getAttribute("property") === (null == current2.property ? null : current2.property) && currentResource.getAttribute("http-equiv") === (null == current2.httpEquiv ? null : current2.httpEquiv) && currentResource.getAttribute("charset") === (null == current2.charSet ? null : current2.charSet)) {
                              maybeNodes.splice(i, 1);
                              break b;
                            }
                        }
                        currentResource = existingHiddenCallbacks.createElement(flags);
                        setInitialProperties(currentResource, flags, current2);
                        existingHiddenCallbacks.head.appendChild(
                          currentResource
                        );
                        break;
                      default:
                        throw Error(
                          'getNodesForType encountered a type it did not expect: "' + flags + '". This is a bug in React.'
                        );
                    }
                    currentResource[internalInstanceKey] = finishedWork;
                    markNodeAsHoistable(currentResource);
                    flags = currentResource;
                  }
                  finishedWork.stateNode = flags;
                } else
                  mountHoistable(
                    existingHiddenCallbacks,
                    finishedWork.type,
                    finishedWork.stateNode
                  );
              else
                finishedWork.stateNode = acquireResource(
                  existingHiddenCallbacks,
                  flags,
                  finishedWork.memoizedProps
                );
            else
              currentResource !== flags ? (null === currentResource ? null !== current2.stateNode && (current2 = current2.stateNode, current2.parentNode.removeChild(current2)) : currentResource.count--, null === flags ? mountHoistable(
                existingHiddenCallbacks,
                finishedWork.type,
                finishedWork.stateNode
              ) : acquireResource(
                existingHiddenCallbacks,
                flags,
                finishedWork.memoizedProps
              )) : null === flags && null !== finishedWork.stateNode && commitHostUpdate(
                finishedWork,
                finishedWork.memoizedProps,
                current2.memoizedProps
              );
          }
          break;
        case 27:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
          null !== current2 && flags & 4 && commitHostUpdate(
            finishedWork,
            finishedWork.memoizedProps,
            current2.memoizedProps
          );
          break;
        case 5:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
          if (finishedWork.flags & 32) {
            existingHiddenCallbacks = finishedWork.stateNode;
            try {
              runWithFiberInDEV(
                finishedWork,
                resetTextContent,
                existingHiddenCallbacks
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
          flags & 4 && null != finishedWork.stateNode && (existingHiddenCallbacks = finishedWork.memoizedProps, commitHostUpdate(
            finishedWork,
            existingHiddenCallbacks,
            null !== current2 ? current2.memoizedProps : existingHiddenCallbacks
          ));
          flags & 1024 && (needsFormReset = true, "form" !== finishedWork.type && console.error(
            "Unexpected host component type. Expected a form. This is a bug in React."
          ));
          break;
        case 6:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          if (flags & 4) {
            if (null === finishedWork.stateNode)
              throw Error(
                "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."
              );
            flags = finishedWork.memoizedProps;
            current2 = null !== current2 ? current2.memoizedProps : flags;
            existingHiddenCallbacks = finishedWork.stateNode;
            try {
              runWithFiberInDEV(
                finishedWork,
                commitTextUpdate,
                existingHiddenCallbacks,
                current2,
                flags
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
          break;
        case 3:
          existingHiddenCallbacks = pushNestedEffectDurations();
          tagCaches = null;
          currentResource = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(root3.containerInfo);
          recursivelyTraverseMutationEffects(root3, finishedWork);
          currentHoistableRoot = currentResource;
          commitReconciliationEffects(finishedWork);
          if (flags & 4 && null !== current2 && current2.memoizedState.isDehydrated)
            try {
              runWithFiberInDEV(
                finishedWork,
                commitHydratedContainer,
                root3.containerInfo
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
          root3.effectDuration += popNestedEffectDurations(
            existingHiddenCallbacks
          );
          break;
        case 4:
          flags = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(
            finishedWork.stateNode.containerInfo
          );
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          currentHoistableRoot = flags;
          break;
        case 12:
          flags = pushNestedEffectDurations();
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          finishedWork.stateNode.effectDuration += bubbleNestedEffectDurations(flags);
          break;
        case 31:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 13:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current2 && null !== current2.memoizedState) && (globalMostRecentFallbackTime = now$1());
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 22:
          existingHiddenCallbacks = null !== finishedWork.memoizedState;
          var wasHidden = null !== current2 && null !== current2.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
          offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || existingHiddenCallbacks;
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
          recursivelyTraverseMutationEffects(root3, finishedWork);
          offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
          offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
          wasHidden && !existingHiddenCallbacks && !prevOffscreenSubtreeIsHidden && !prevOffscreenSubtreeWasHidden && (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime
          );
          commitReconciliationEffects(finishedWork);
          if (flags & 8192)
            a: for (root3 = finishedWork.stateNode, root3._visibility = existingHiddenCallbacks ? root3._visibility & ~OffscreenVisible : root3._visibility | OffscreenVisible, !existingHiddenCallbacks || null === current2 || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || (recursivelyTraverseDisappearLayoutEffects(finishedWork), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime,
              "Disconnect"
            )), current2 = null, root3 = finishedWork; ; ) {
              if (5 === root3.tag || 26 === root3.tag) {
                if (null === current2) {
                  wasHidden = current2 = root3;
                  try {
                    currentResource = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                      wasHidden,
                      hideInstance,
                      currentResource
                    ) : runWithFiberInDEV(
                      wasHidden,
                      unhideInstance,
                      wasHidden.stateNode,
                      wasHidden.memoizedProps
                    );
                  } catch (error) {
                    captureCommitPhaseError(wasHidden, wasHidden.return, error);
                  }
                }
              } else if (6 === root3.tag) {
                if (null === current2) {
                  wasHidden = root3;
                  try {
                    maybeNodes = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                      wasHidden,
                      hideTextInstance,
                      maybeNodes
                    ) : runWithFiberInDEV(
                      wasHidden,
                      unhideTextInstance,
                      maybeNodes,
                      wasHidden.memoizedProps
                    );
                  } catch (error) {
                    captureCommitPhaseError(wasHidden, wasHidden.return, error);
                  }
                }
              } else if (18 === root3.tag) {
                if (null === current2) {
                  wasHidden = root3;
                  try {
                    i = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                      wasHidden,
                      hideDehydratedBoundary,
                      i
                    ) : runWithFiberInDEV(
                      wasHidden,
                      unhideDehydratedBoundary,
                      wasHidden.stateNode
                    );
                  } catch (error) {
                    captureCommitPhaseError(wasHidden, wasHidden.return, error);
                  }
                }
              } else if ((22 !== root3.tag && 23 !== root3.tag || null === root3.memoizedState || root3 === finishedWork) && null !== root3.child) {
                root3.child.return = root3;
                root3 = root3.child;
                continue;
              }
              if (root3 === finishedWork) break a;
              for (; null === root3.sibling; ) {
                if (null === root3.return || root3.return === finishedWork)
                  break a;
                current2 === root3 && (current2 = null);
                root3 = root3.return;
              }
              current2 === root3 && (current2 = null);
              root3.sibling.return = root3.return;
              root3 = root3.sibling;
            }
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current2 = flags.retryQueue, null !== current2 && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current2))));
          break;
        case 19:
          recursivelyTraverseMutationEffects(root3, finishedWork);
          commitReconciliationEffects(finishedWork);
          flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
          break;
        case 30:
          break;
        case 21:
          break;
        default:
          recursivelyTraverseMutationEffects(root3, finishedWork), commitReconciliationEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      ), null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate && 0.05 < componentEffectEndTime - componentEffectStartTime && (isHydratingParent(
        finishedWork.return.alternate,
        finishedWork.return
      ) || logComponentTrigger(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        "Mount"
      )));
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function commitReconciliationEffects(finishedWork) {
      var flags = finishedWork.flags;
      if (flags & 2) {
        try {
          runWithFiberInDEV(finishedWork, commitPlacement, finishedWork);
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
        finishedWork.flags &= -3;
      }
      flags & 4096 && (finishedWork.flags &= -4097);
    }
    function recursivelyResetForms(parentFiber) {
      if (parentFiber.subtreeFlags & 1024)
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var fiber = parentFiber;
          recursivelyResetForms(fiber);
          5 === fiber.tag && fiber.flags & 1024 && fiber.stateNode.reset();
          parentFiber = parentFiber.sibling;
        }
    }
    function recursivelyTraverseLayoutEffects(root3, parentFiber) {
      if (parentFiber.subtreeFlags & 8772)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitLayoutEffectOnFiber(root3, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
    }
    function disappearLayoutEffects(finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          commitHookLayoutUnmountEffects(
            finishedWork,
            finishedWork.return,
            Layout
          );
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 1:
          safelyDetachRef(finishedWork, finishedWork.return);
          var instance = finishedWork.stateNode;
          "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
            finishedWork,
            finishedWork.return,
            instance
          );
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 27:
          runWithFiberInDEV(
            finishedWork,
            releaseSingletonInstance,
            finishedWork.stateNode
          );
        case 26:
        case 5:
          safelyDetachRef(finishedWork, finishedWork.return);
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 22:
          null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        case 30:
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
          break;
        default:
          recursivelyTraverseDisappearLayoutEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        disappearLayoutEffects(parentFiber), parentFiber = parentFiber.sibling;
    }
    function reappearLayoutEffects(finishedRoot, current2, finishedWork, includeWorkInProgressEffects) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          commitHookLayoutEffects(finishedWork, Layout);
          break;
        case 1:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          current2 = finishedWork.stateNode;
          "function" === typeof current2.componentDidMount && runWithFiberInDEV(
            finishedWork,
            callComponentDidMountInDEV,
            finishedWork,
            current2
          );
          current2 = finishedWork.updateQueue;
          if (null !== current2) {
            finishedRoot = finishedWork.stateNode;
            try {
              runWithFiberInDEV(
                finishedWork,
                commitHiddenCallbacks,
                current2,
                finishedRoot
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          }
          includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 27:
          commitHostSingletonAcquisition(finishedWork);
        case 26:
        case 5:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && null === current2 && flags & 4 && commitHostMount(finishedWork);
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 12:
          if (includeWorkInProgressEffects && flags & 4) {
            flags = pushNestedEffectDurations();
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects = finishedWork.stateNode;
            includeWorkInProgressEffects.effectDuration += bubbleNestedEffectDurations(flags);
            try {
              runWithFiberInDEV(
                finishedWork,
                commitProfiler,
                finishedWork,
                current2,
                commitStartTime,
                includeWorkInProgressEffects.effectDuration
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          } else
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
          break;
        case 31:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 13:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
          break;
        case 22:
          null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
          safelyAttachRef(finishedWork, finishedWork.return);
          break;
        case 30:
          break;
        default:
          recursivelyTraverseReappearLayoutEffects(
            finishedRoot,
            finishedWork,
            includeWorkInProgressEffects
          );
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
    }
    function recursivelyTraverseReappearLayoutEffects(finishedRoot, parentFiber, includeWorkInProgressEffects) {
      includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        reappearLayoutEffects(
          finishedRoot,
          parentFiber.alternate,
          parentFiber,
          includeWorkInProgressEffects
        ), parentFiber = parentFiber.sibling;
    }
    function commitOffscreenPassiveMountEffects(current2, finishedWork) {
      var previousCache = null;
      null !== current2 && null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (previousCache = current2.memoizedState.cachePool.pool);
      current2 = null;
      null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current2 = finishedWork.memoizedState.cachePool.pool);
      current2 !== previousCache && (null != current2 && retainCache(current2), null != previousCache && releaseCache(previousCache));
    }
    function commitCachePassiveMountEffect(current2, finishedWork) {
      current2 = null;
      null !== finishedWork.alternate && (current2 = finishedWork.alternate.memoizedState.cache);
      finishedWork = finishedWork.memoizedState.cache;
      finishedWork !== current2 && (retainCache(finishedWork), null != current2 && releaseCache(current2));
    }
    function recursivelyTraversePassiveMountEffects(root3, parentFiber, committedLanes, committedTransitions, endTime) {
      if (parentFiber.subtreeFlags & 10256 || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child))
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var nextSibling = parentFiber.sibling;
          commitPassiveMountOnFiber(
            root3,
            parentFiber,
            committedLanes,
            committedTransitions,
            null !== nextSibling ? nextSibling.actualStartTime : endTime
          );
          parentFiber = nextSibling;
        }
    }
    function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions, endTime) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), prevDeepEquality = alreadyWarnedForDeepEquality, flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && 0 !== (finishedWork.flags & 1) && logComponentRender(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            inHydratedSubtree,
            committedLanes
          );
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          flags & 2048 && commitHookPassiveMountEffects(finishedWork, Passive | HasEffect);
          break;
        case 1:
          (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && (0 !== (finishedWork.flags & 128) ? logComponentErrored(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            []
          ) : 0 !== (finishedWork.flags & 1) && logComponentRender(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            inHydratedSubtree,
            committedLanes
          ));
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          break;
        case 3:
          var prevProfilerEffectDuration = pushNestedEffectDurations(), wasInHydratedSubtree = inHydratedSubtree;
          inHydratedSubtree = null !== finishedWork.alternate && finishedWork.alternate.memoizedState.isDehydrated && 0 === (finishedWork.flags & 256);
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          inHydratedSubtree = wasInHydratedSubtree;
          flags & 2048 && (committedLanes = null, null !== finishedWork.alternate && (committedLanes = finishedWork.alternate.memoizedState.cache), committedTransitions = finishedWork.memoizedState.cache, committedTransitions !== committedLanes && (retainCache(committedTransitions), null != committedLanes && releaseCache(committedLanes)));
          finishedRoot.passiveEffectDuration += popNestedEffectDurations(
            prevProfilerEffectDuration
          );
          break;
        case 12:
          if (flags & 2048) {
            flags = pushNestedEffectDurations();
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            finishedRoot = finishedWork.stateNode;
            finishedRoot.passiveEffectDuration += bubbleNestedEffectDurations(flags);
            try {
              runWithFiberInDEV(
                finishedWork,
                commitProfilerPostCommitImpl,
                finishedWork,
                finishedWork.alternate,
                commitStartTime,
                finishedRoot.passiveEffectDuration
              );
            } catch (error) {
              captureCommitPhaseError(finishedWork, finishedWork.return, error);
            }
          } else
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
          break;
        case 31:
          flags = inHydratedSubtree;
          prevProfilerEffectDuration = null !== finishedWork.alternate ? finishedWork.alternate.memoizedState : null;
          wasInHydratedSubtree = finishedWork.memoizedState;
          null !== prevProfilerEffectDuration && null === wasInHydratedSubtree ? (wasInHydratedSubtree = finishedWork.deletions, null !== wasInHydratedSubtree && 0 < wasInHydratedSubtree.length && 18 === wasInHydratedSubtree[0].tag ? (inHydratedSubtree = false, prevProfilerEffectDuration = prevProfilerEffectDuration.hydrationErrors, null !== prevProfilerEffectDuration && logComponentErrored(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            prevProfilerEffectDuration
          )) : inHydratedSubtree = true) : inHydratedSubtree = false;
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          inHydratedSubtree = flags;
          break;
        case 13:
          flags = inHydratedSubtree;
          prevProfilerEffectDuration = null !== finishedWork.alternate ? finishedWork.alternate.memoizedState : null;
          wasInHydratedSubtree = finishedWork.memoizedState;
          null === prevProfilerEffectDuration || null === prevProfilerEffectDuration.dehydrated || null !== wasInHydratedSubtree && null !== wasInHydratedSubtree.dehydrated ? inHydratedSubtree = false : (wasInHydratedSubtree = finishedWork.deletions, null !== wasInHydratedSubtree && 0 < wasInHydratedSubtree.length && 18 === wasInHydratedSubtree[0].tag ? (inHydratedSubtree = false, prevProfilerEffectDuration = prevProfilerEffectDuration.hydrationErrors, null !== prevProfilerEffectDuration && logComponentErrored(
            finishedWork,
            finishedWork.actualStartTime,
            endTime,
            prevProfilerEffectDuration
          )) : inHydratedSubtree = true);
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          inHydratedSubtree = flags;
          break;
        case 23:
          break;
        case 22:
          wasInHydratedSubtree = finishedWork.stateNode;
          prevProfilerEffectDuration = finishedWork.alternate;
          null !== finishedWork.memoizedState ? wasInHydratedSubtree._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : recursivelyTraverseAtomicPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : wasInHydratedSubtree._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : (wasInHydratedSubtree._visibility |= OffscreenPassiveEffectsConnected, recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            0 !== (finishedWork.subtreeFlags & 10256) || 0 !== finishedWork.actualDuration && (null === finishedWork.alternate || finishedWork.alternate.child !== finishedWork.child),
            endTime
          ), (finishedWork.mode & ProfileMode) === NoMode || inHydratedSubtree || (finishedRoot = finishedWork.actualStartTime, 0 <= finishedRoot && 0.05 < endTime - finishedRoot && logComponentReappeared(finishedWork, finishedRoot, endTime), 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime
          )));
          flags & 2048 && commitOffscreenPassiveMountEffects(
            prevProfilerEffectDuration,
            finishedWork
          );
          break;
        case 24:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
          flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraversePassiveMountEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          );
      }
      if ((finishedWork.mode & ProfileMode) !== NoMode) {
        if (finishedRoot = !inHydratedSubtree && null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate)
          committedLanes = finishedWork.actualStartTime, 0 <= committedLanes && 0.05 < endTime - committedLanes && logComponentTrigger(
            finishedWork,
            committedLanes,
            endTime,
            "Mount"
          );
        0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        ), finishedRoot && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          "Mount"
        ));
      }
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      alreadyWarnedForDeepEquality = prevDeepEquality;
    }
    function recursivelyTraverseReconnectPassiveEffects(finishedRoot, parentFiber, committedLanes, committedTransitions, includeWorkInProgressEffects, endTime) {
      includeWorkInProgressEffects = includeWorkInProgressEffects && (0 !== (parentFiber.subtreeFlags & 10256) || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child));
      for (parentFiber = parentFiber.child; null !== parentFiber; ) {
        var nextSibling = parentFiber.sibling;
        reconnectPassiveEffects(
          finishedRoot,
          parentFiber,
          committedLanes,
          committedTransitions,
          includeWorkInProgressEffects,
          null !== nextSibling ? nextSibling.actualStartTime : endTime
        );
        parentFiber = nextSibling;
      }
    }
    function reconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, endTime) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), prevDeepEquality = alreadyWarnedForDeepEquality;
      includeWorkInProgressEffects && (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && 0 !== (finishedWork.flags & 1) && logComponentRender(
        finishedWork,
        finishedWork.actualStartTime,
        endTime,
        inHydratedSubtree,
        committedLanes
      );
      var flags = finishedWork.flags;
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          );
          commitHookPassiveMountEffects(finishedWork, Passive);
          break;
        case 23:
          break;
        case 22:
          var _instance2 = finishedWork.stateNode;
          null !== finishedWork.memoizedState ? _instance2._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          ) : recursivelyTraverseAtomicPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            endTime
          ) : (_instance2._visibility |= OffscreenPassiveEffectsConnected, recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          ));
          includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
            finishedWork.alternate,
            finishedWork
          );
          break;
        case 24:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          );
          includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
          break;
        default:
          recursivelyTraverseReconnectPassiveEffects(
            finishedRoot,
            finishedWork,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            endTime
          );
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectErrors = prevEffectErrors;
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      alreadyWarnedForDeepEquality = prevDeepEquality;
    }
    function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, endTime$jscomp$0) {
      if (parentFiber.subtreeFlags & 10256 || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child))
        for (var child = parentFiber.child; null !== child; ) {
          parentFiber = child.sibling;
          var finishedRoot = finishedRoot$jscomp$0, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, endTime = null !== parentFiber ? parentFiber.actualStartTime : endTime$jscomp$0, prevDeepEquality = alreadyWarnedForDeepEquality;
          (child.mode & ProfileMode) !== NoMode && 0 < child.actualStartTime && 0 !== (child.flags & 1) && logComponentRender(
            child,
            child.actualStartTime,
            endTime,
            inHydratedSubtree,
            committedLanes
          );
          var flags = child.flags;
          switch (child.tag) {
            case 22:
              recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                child,
                committedLanes,
                committedTransitions,
                endTime
              );
              flags & 2048 && commitOffscreenPassiveMountEffects(child.alternate, child);
              break;
            case 24:
              recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                child,
                committedLanes,
                committedTransitions,
                endTime
              );
              flags & 2048 && commitCachePassiveMountEffect(child.alternate, child);
              break;
            default:
              recursivelyTraverseAtomicPassiveEffects(
                finishedRoot,
                child,
                committedLanes,
                committedTransitions,
                endTime
              );
          }
          alreadyWarnedForDeepEquality = prevDeepEquality;
          child = parentFiber;
        }
    }
    function recursivelyAccumulateSuspenseyCommit(parentFiber, committedLanes, suspendedState) {
      if (parentFiber.subtreeFlags & suspenseyCommitFlag)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          accumulateSuspenseyCommitOnFiber(
            parentFiber,
            committedLanes,
            suspendedState
          ), parentFiber = parentFiber.sibling;
    }
    function accumulateSuspenseyCommitOnFiber(fiber, committedLanes, suspendedState) {
      switch (fiber.tag) {
        case 26:
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
          fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState && suspendResource(
            suspendedState,
            currentHoistableRoot,
            fiber.memoizedState,
            fiber.memoizedProps
          );
          break;
        case 5:
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
          break;
        case 3:
        case 4:
          var previousHoistableRoot = currentHoistableRoot;
          currentHoistableRoot = getHoistableRoot(
            fiber.stateNode.containerInfo
          );
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
          currentHoistableRoot = previousHoistableRoot;
          break;
        case 22:
          null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          ), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          ));
          break;
        default:
          recursivelyAccumulateSuspenseyCommit(
            fiber,
            committedLanes,
            suspendedState
          );
      }
    }
    function detachAlternateSiblings(parentFiber) {
      var previousFiber = parentFiber.alternate;
      if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
        previousFiber.child = null;
        do
          previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
        while (null !== parentFiber);
      }
    }
    function recursivelyTraversePassiveUnmountEffects(parentFiber) {
      var deletions = parentFiber.deletions;
      if (0 !== (parentFiber.flags & 16)) {
        if (null !== deletions)
          for (var i = 0; i < deletions.length; i++) {
            var childToDelete = deletions[i], prevEffectStart = pushComponentEffectStart();
            nextEffect = childToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
              childToDelete,
              parentFiber
            );
            (childToDelete.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              childToDelete,
              componentEffectStartTime,
              componentEffectEndTime,
              "Unmount"
            );
            popComponentEffectStart(prevEffectStart);
          }
        detachAlternateSiblings(parentFiber);
      }
      if (parentFiber.subtreeFlags & 10256)
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
    }
    function commitPassiveUnmountOnFiber(finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.flags & 2048 && commitHookPassiveUnmountEffects(
            finishedWork,
            finishedWork.return,
            Passive | HasEffect
          );
          break;
        case 3:
          var prevProfilerEffectDuration = pushNestedEffectDurations();
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.stateNode.passiveEffectDuration += popNestedEffectDurations(prevProfilerEffectDuration);
          break;
        case 12:
          prevProfilerEffectDuration = pushNestedEffectDurations();
          recursivelyTraversePassiveUnmountEffects(finishedWork);
          finishedWork.stateNode.passiveEffectDuration += bubbleNestedEffectDurations(prevProfilerEffectDuration);
          break;
        case 22:
          prevProfilerEffectDuration = finishedWork.stateNode;
          null !== finishedWork.memoizedState && prevProfilerEffectDuration._visibility & OffscreenPassiveEffectsConnected && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (prevProfilerEffectDuration._visibility &= ~OffscreenPassiveEffectsConnected, recursivelyTraverseDisconnectPassiveEffects(finishedWork), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime,
            "Disconnect"
          )) : recursivelyTraversePassiveUnmountEffects(finishedWork);
          break;
        default:
          recursivelyTraversePassiveUnmountEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      componentEffectErrors = prevEffectErrors;
    }
    function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
      var deletions = parentFiber.deletions;
      if (0 !== (parentFiber.flags & 16)) {
        if (null !== deletions)
          for (var i = 0; i < deletions.length; i++) {
            var childToDelete = deletions[i], prevEffectStart = pushComponentEffectStart();
            nextEffect = childToDelete;
            commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
              childToDelete,
              parentFiber
            );
            (childToDelete.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              childToDelete,
              componentEffectStartTime,
              componentEffectEndTime,
              "Unmount"
            );
            popComponentEffectStart(prevEffectStart);
          }
        detachAlternateSiblings(parentFiber);
      }
      for (parentFiber = parentFiber.child; null !== parentFiber; )
        disconnectPassiveEffect(parentFiber), parentFiber = parentFiber.sibling;
    }
    function disconnectPassiveEffect(finishedWork) {
      var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
      switch (finishedWork.tag) {
        case 0:
        case 11:
        case 15:
          commitHookPassiveUnmountEffects(
            finishedWork,
            finishedWork.return,
            Passive
          );
          recursivelyTraverseDisconnectPassiveEffects(finishedWork);
          break;
        case 22:
          var instance = finishedWork.stateNode;
          instance._visibility & OffscreenPassiveEffectsConnected && (instance._visibility &= ~OffscreenPassiveEffectsConnected, recursivelyTraverseDisconnectPassiveEffects(finishedWork));
          break;
        default:
          recursivelyTraverseDisconnectPassiveEffects(finishedWork);
      }
      (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
        finishedWork,
        componentEffectStartTime,
        componentEffectEndTime,
        componentEffectDuration,
        componentEffectErrors
      );
      popComponentEffectStart(prevEffectStart);
      popComponentEffectDuration(prevEffectDuration);
      componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      componentEffectErrors = prevEffectErrors;
    }
    function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor$jscomp$0) {
      for (; null !== nextEffect; ) {
        var fiber = nextEffect, current2 = fiber, nearestMountedAncestor = nearestMountedAncestor$jscomp$0, prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
        switch (current2.tag) {
          case 0:
          case 11:
          case 15:
            commitHookPassiveUnmountEffects(
              current2,
              nearestMountedAncestor,
              Passive
            );
            break;
          case 23:
          case 22:
            null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (nearestMountedAncestor = current2.memoizedState.cachePool.pool, null != nearestMountedAncestor && retainCache(nearestMountedAncestor));
            break;
          case 24:
            releaseCache(current2.memoizedState.cache);
        }
        (current2.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          current2,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
        componentEffectErrors = prevEffectErrors;
        current2 = fiber.child;
        if (null !== current2) current2.return = fiber, nextEffect = current2;
        else
          a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
            current2 = nextEffect;
            prevEffectStart = current2.sibling;
            prevEffectDuration = current2.return;
            detachFiberAfterEffects(current2);
            if (current2 === fiber) {
              nextEffect = null;
              break a;
            }
            if (null !== prevEffectStart) {
              prevEffectStart.return = prevEffectDuration;
              nextEffect = prevEffectStart;
              break a;
            }
            nextEffect = prevEffectDuration;
          }
      }
    }
    function onCommitRoot() {
      commitHooks.forEach(function(commitHook) {
        return commitHook();
      });
    }
    function isConcurrentActEnvironment() {
      var isReactActEnvironmentGlobal = "undefined" !== typeof IS_REACT_ACT_ENVIRONMENT ? IS_REACT_ACT_ENVIRONMENT : void 0;
      isReactActEnvironmentGlobal || null === ReactSharedInternals.actQueue || console.error(
        "The current testing environment is not configured to support act(...)"
      );
      return isReactActEnvironmentGlobal;
    }
    function requestUpdateLane(fiber) {
      if ((executionContext & RenderContext) !== NoContext && 0 !== workInProgressRootRenderLanes)
        return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
      var transition = ReactSharedInternals.T;
      return null !== transition ? (transition._updatedFibers || (transition._updatedFibers = /* @__PURE__ */ new Set()), transition._updatedFibers.add(fiber), requestTransitionLane()) : resolveUpdatePriority();
    }
    function requestDeferredLane() {
      if (0 === workInProgressDeferredLane)
        if (0 === (workInProgressRootRenderLanes & 536870912) || isHydrating) {
          var lane = nextTransitionDeferredLane;
          nextTransitionDeferredLane <<= 1;
          0 === (nextTransitionDeferredLane & 3932160) && (nextTransitionDeferredLane = 262144);
          workInProgressDeferredLane = lane;
        } else workInProgressDeferredLane = 536870912;
      lane = suspenseHandlerStackCursor.current;
      null !== lane && (lane.flags |= 32);
      return workInProgressDeferredLane;
    }
    function scheduleUpdateOnFiber(root3, fiber, lane) {
      isRunningInsertionEffect && console.error("useInsertionEffect must not schedule updates.");
      isFlushingPassiveEffects && (didScheduleUpdateDuringPassiveEffects = true);
      if (root3 === workInProgressRoot && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root3.cancelPendingCommit)
        prepareFreshStack(root3, 0), markRootSuspended(
          root3,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        );
      markRootUpdated$1(root3, lane);
      if ((executionContext & RenderContext) !== NoContext && root3 === workInProgressRoot) {
        if (isRendering)
          switch (fiber.tag) {
            case 0:
            case 11:
            case 15:
              root3 = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
              didWarnAboutUpdateInRenderForAnotherComponent.has(root3) || (didWarnAboutUpdateInRenderForAnotherComponent.add(root3), fiber = getComponentNameFromFiber(fiber) || "Unknown", console.error(
                "Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://react.dev/link/setstate-in-render",
                fiber,
                root3,
                root3
              ));
              break;
            case 1:
              didWarnAboutUpdateInRender || (console.error(
                "Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."
              ), didWarnAboutUpdateInRender = true);
          }
      } else
        isDevToolsPresent && addFiberToLanesMap(root3, fiber, lane), warnIfUpdatesNotWrappedWithActDEV(fiber), root3 === workInProgressRoot && ((executionContext & RenderContext) === NoContext && (workInProgressRootInterleavedUpdatedLanes |= lane), workInProgressRootExitStatus === RootSuspendedWithDelay && markRootSuspended(
          root3,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        )), ensureRootIsScheduled(root3);
    }
    function performWorkOnRoot(root3, lanes, forceSync) {
      if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
        throw Error("Should not already be working.");
      if (0 !== workInProgressRootRenderLanes && null !== workInProgress) {
        var yieldedFiber = workInProgress, yieldEndTime = now$1();
        switch (yieldReason) {
          case SuspendedOnImmediate:
          case SuspendedOnData:
            var startTime = yieldStartTime;
            supportsUserTiming && ((yieldedFiber = yieldedFiber._debugTask) ? yieldedFiber.run(
              console.timeStamp.bind(
                console,
                "Suspended",
                startTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                "primary-light"
              )
            ) : console.timeStamp(
              "Suspended",
              startTime,
              yieldEndTime,
              COMPONENTS_TRACK,
              void 0,
              "primary-light"
            ));
            break;
          case SuspendedOnAction:
            startTime = yieldStartTime;
            supportsUserTiming && ((yieldedFiber = yieldedFiber._debugTask) ? yieldedFiber.run(
              console.timeStamp.bind(
                console,
                "Action",
                startTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                "primary-light"
              )
            ) : console.timeStamp(
              "Action",
              startTime,
              yieldEndTime,
              COMPONENTS_TRACK,
              void 0,
              "primary-light"
            ));
            break;
          default:
            supportsUserTiming && (yieldedFiber = yieldEndTime - yieldStartTime, 3 > yieldedFiber || console.timeStamp(
              "Blocked",
              yieldStartTime,
              yieldEndTime,
              COMPONENTS_TRACK,
              void 0,
              5 > yieldedFiber ? "primary-light" : 10 > yieldedFiber ? "primary" : 100 > yieldedFiber ? "primary-dark" : "error"
            ));
        }
      }
      startTime = (forceSync = !forceSync && 0 === (lanes & 127) && 0 === (lanes & root3.expiredLanes) || checkIfRootIsPrerendering(root3, lanes)) ? renderRootConcurrent(root3, lanes) : renderRootSync(root3, lanes, true);
      var renderWasConcurrent = forceSync;
      do {
        if (startTime === RootInProgress) {
          workInProgressRootIsPrerendering && !forceSync && markRootSuspended(root3, lanes, 0, false);
          lanes = workInProgressSuspendedReason;
          yieldStartTime = now();
          yieldReason = lanes;
          break;
        } else {
          yieldedFiber = now$1();
          yieldEndTime = root3.current.alternate;
          if (renderWasConcurrent && !isRenderConsistentWithExternalStores(yieldEndTime)) {
            setCurrentTrackFromLanes(lanes);
            yieldEndTime = renderStartTime;
            startTime = yieldedFiber;
            !supportsUserTiming || startTime <= yieldEndTime || (workInProgressUpdateTask ? workInProgressUpdateTask.run(
              console.timeStamp.bind(
                console,
                "Teared Render",
                yieldEndTime,
                startTime,
                currentTrack,
                LANES_TRACK_GROUP,
                "error"
              )
            ) : console.timeStamp(
              "Teared Render",
              yieldEndTime,
              startTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "error"
            ));
            finalizeRender(lanes, yieldedFiber);
            startTime = renderRootSync(root3, lanes, false);
            renderWasConcurrent = false;
            continue;
          }
          if (startTime === RootErrored) {
            renderWasConcurrent = lanes;
            if (root3.errorRecoveryDisabledLanes & renderWasConcurrent)
              var errorRetryLanes = 0;
            else
              errorRetryLanes = root3.pendingLanes & -536870913, errorRetryLanes = 0 !== errorRetryLanes ? errorRetryLanes : errorRetryLanes & 536870912 ? 536870912 : 0;
            if (0 !== errorRetryLanes) {
              setCurrentTrackFromLanes(lanes);
              logErroredRenderPhase(
                renderStartTime,
                yieldedFiber,
                lanes,
                workInProgressUpdateTask
              );
              finalizeRender(lanes, yieldedFiber);
              lanes = errorRetryLanes;
              a: {
                yieldedFiber = root3;
                startTime = renderWasConcurrent;
                renderWasConcurrent = workInProgressRootConcurrentErrors;
                var wasRootDehydrated = yieldedFiber.current.memoizedState.isDehydrated;
                wasRootDehydrated && (prepareFreshStack(yieldedFiber, errorRetryLanes).flags |= 256);
                errorRetryLanes = renderRootSync(
                  yieldedFiber,
                  errorRetryLanes,
                  false
                );
                if (errorRetryLanes !== RootErrored) {
                  if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                    yieldedFiber.errorRecoveryDisabledLanes |= startTime;
                    workInProgressRootInterleavedUpdatedLanes |= startTime;
                    startTime = RootSuspendedWithDelay;
                    break a;
                  }
                  yieldedFiber = workInProgressRootRecoverableErrors;
                  workInProgressRootRecoverableErrors = renderWasConcurrent;
                  null !== yieldedFiber && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = yieldedFiber : workInProgressRootRecoverableErrors.push.apply(
                    workInProgressRootRecoverableErrors,
                    yieldedFiber
                  ));
                }
                startTime = errorRetryLanes;
              }
              renderWasConcurrent = false;
              if (startTime !== RootErrored) continue;
              else yieldedFiber = now$1();
            }
          }
          if (startTime === RootFatalErrored) {
            setCurrentTrackFromLanes(lanes);
            logErroredRenderPhase(
              renderStartTime,
              yieldedFiber,
              lanes,
              workInProgressUpdateTask
            );
            finalizeRender(lanes, yieldedFiber);
            prepareFreshStack(root3, 0);
            markRootSuspended(root3, lanes, 0, true);
            break;
          }
          a: {
            forceSync = root3;
            switch (startTime) {
              case RootInProgress:
              case RootFatalErrored:
                throw Error("Root did not complete. This is a bug in React.");
              case RootSuspendedWithDelay:
                if ((lanes & 4194048) !== lanes) break;
              case RootSuspendedAtTheShell:
                setCurrentTrackFromLanes(lanes);
                logSuspendedRenderPhase(
                  renderStartTime,
                  yieldedFiber,
                  lanes,
                  workInProgressUpdateTask
                );
                finalizeRender(lanes, yieldedFiber);
                yieldEndTime = lanes;
                0 !== (yieldEndTime & 127) ? blockingSuspendedTime = yieldedFiber : 0 !== (yieldEndTime & 4194048) && (transitionSuspendedTime = yieldedFiber);
                markRootSuspended(
                  forceSync,
                  lanes,
                  workInProgressDeferredLane,
                  !workInProgressRootDidSkipSuspendedSiblings
                );
                break a;
              case RootErrored:
                workInProgressRootRecoverableErrors = null;
                break;
              case RootSuspended:
              case RootCompleted:
                break;
              default:
                throw Error("Unknown root exit status.");
            }
            if (null !== ReactSharedInternals.actQueue)
              commitRoot(
                forceSync,
                yieldEndTime,
                lanes,
                workInProgressRootRecoverableErrors,
                workInProgressTransitions,
                workInProgressRootDidIncludeRecursiveRenderUpdate,
                workInProgressDeferredLane,
                workInProgressRootInterleavedUpdatedLanes,
                workInProgressSuspendedRetryLanes,
                startTime,
                null,
                null,
                renderStartTime,
                yieldedFiber
              );
            else {
              if ((lanes & 62914560) === lanes && (renderWasConcurrent = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(), 10 < renderWasConcurrent)) {
                markRootSuspended(
                  forceSync,
                  lanes,
                  workInProgressDeferredLane,
                  !workInProgressRootDidSkipSuspendedSiblings
                );
                if (0 !== getNextLanes(forceSync, 0, true)) break a;
                pendingEffectsLanes = lanes;
                forceSync.timeoutHandle = scheduleTimeout(
                  commitRootWhenReady.bind(
                    null,
                    forceSync,
                    yieldEndTime,
                    workInProgressRootRecoverableErrors,
                    workInProgressTransitions,
                    workInProgressRootDidIncludeRecursiveRenderUpdate,
                    lanes,
                    workInProgressDeferredLane,
                    workInProgressRootInterleavedUpdatedLanes,
                    workInProgressSuspendedRetryLanes,
                    workInProgressRootDidSkipSuspendedSiblings,
                    startTime,
                    "Throttled",
                    renderStartTime,
                    yieldedFiber
                  ),
                  renderWasConcurrent
                );
                break a;
              }
              commitRootWhenReady(
                forceSync,
                yieldEndTime,
                workInProgressRootRecoverableErrors,
                workInProgressTransitions,
                workInProgressRootDidIncludeRecursiveRenderUpdate,
                lanes,
                workInProgressDeferredLane,
                workInProgressRootInterleavedUpdatedLanes,
                workInProgressSuspendedRetryLanes,
                workInProgressRootDidSkipSuspendedSiblings,
                startTime,
                null,
                renderStartTime,
                yieldedFiber
              );
            }
          }
        }
        break;
      } while (1);
      ensureRootIsScheduled(root3);
    }
    function commitRootWhenReady(root3, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
      root3.timeoutHandle = noTimeout;
      var subtreeFlags = finishedWork.subtreeFlags, suspendedState = null;
      if (subtreeFlags & 8192 || 16785408 === (subtreeFlags & 16785408)) {
        if (suspendedState = {
          stylesheets: null,
          count: 0,
          imgCount: 0,
          imgBytes: 0,
          suspenseyImages: [],
          waitingForImages: true,
          waitingForViewTransition: false,
          unsuspend: noop$1
        }, accumulateSuspenseyCommitOnFiber(finishedWork, lanes, suspendedState), subtreeFlags = (lanes & 62914560) === lanes ? globalMostRecentFallbackTime - now$1() : (lanes & 4194048) === lanes ? globalMostRecentTransitionTime - now$1() : 0, subtreeFlags = waitForCommitToBeReady(suspendedState, subtreeFlags), null !== subtreeFlags) {
          pendingEffectsLanes = lanes;
          root3.cancelPendingCommit = subtreeFlags(
            commitRoot.bind(
              null,
              root3,
              finishedWork,
              lanes,
              recoverableErrors,
              transitions,
              didIncludeRenderPhaseUpdate,
              spawnedLane,
              updatedLanes,
              suspendedRetryLanes,
              exitStatus,
              suspendedState,
              suspendedState.waitingForViewTransition ? "Waiting for the previous Animation" : 0 < suspendedState.count ? 0 < suspendedState.imgCount ? "Suspended on CSS and Images" : "Suspended on CSS" : 1 === suspendedState.imgCount ? "Suspended on an Image" : 0 < suspendedState.imgCount ? "Suspended on Images" : null,
              completedRenderStartTime,
              completedRenderEndTime
            )
          );
          markRootSuspended(
            root3,
            lanes,
            spawnedLane,
            !didSkipSuspendedSiblings
          );
          return;
        }
      }
      commitRoot(
        root3,
        finishedWork,
        lanes,
        recoverableErrors,
        transitions,
        didIncludeRenderPhaseUpdate,
        spawnedLane,
        updatedLanes,
        suspendedRetryLanes,
        exitStatus,
        suspendedState,
        suspendedCommitReason,
        completedRenderStartTime,
        completedRenderEndTime
      );
    }
    function isRenderConsistentWithExternalStores(finishedWork) {
      for (var node2 = finishedWork; ; ) {
        var tag = node2.tag;
        if ((0 === tag || 11 === tag || 15 === tag) && node2.flags & 16384 && (tag = node2.updateQueue, null !== tag && (tag = tag.stores, null !== tag)))
          for (var i = 0; i < tag.length; i++) {
            var check = tag[i], getSnapshot = check.getSnapshot;
            check = check.value;
            try {
              if (!objectIs(getSnapshot(), check)) return false;
            } catch (error) {
              return false;
            }
          }
        tag = node2.child;
        if (node2.subtreeFlags & 16384 && null !== tag)
          tag.return = node2, node2 = tag;
        else {
          if (node2 === finishedWork) break;
          for (; null === node2.sibling; ) {
            if (null === node2.return || node2.return === finishedWork) return true;
            node2 = node2.return;
          }
          node2.sibling.return = node2.return;
          node2 = node2.sibling;
        }
      }
      return true;
    }
    function markRootSuspended(root3, suspendedLanes, spawnedLane, didAttemptEntireTree) {
      suspendedLanes &= ~workInProgressRootPingedLanes;
      suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
      root3.suspendedLanes |= suspendedLanes;
      root3.pingedLanes &= ~suspendedLanes;
      didAttemptEntireTree && (root3.warmLanes |= suspendedLanes);
      didAttemptEntireTree = root3.expirationTimes;
      for (var lanes = suspendedLanes; 0 < lanes; ) {
        var index2 = 31 - clz32(lanes), lane = 1 << index2;
        didAttemptEntireTree[index2] = -1;
        lanes &= ~lane;
      }
      0 !== spawnedLane && markSpawnedDeferredLane(root3, spawnedLane, suspendedLanes);
    }
    function flushSyncWork$1() {
      return (executionContext & (RenderContext | CommitContext)) === NoContext ? (flushSyncWorkAcrossRoots_impl(0), false) : true;
    }
    function resetWorkInProgressStack() {
      if (null !== workInProgress) {
        if (workInProgressSuspendedReason === NotSuspended)
          var interruptedWork = workInProgress.return;
        else
          interruptedWork = workInProgress, resetContextDependencies(), resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
        for (; null !== interruptedWork; )
          unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
        workInProgress = null;
      }
    }
    function finalizeRender(lanes, finalizationTime) {
      0 !== (lanes & 127) && (blockingClampTime = finalizationTime);
      0 !== (lanes & 4194048) && (transitionClampTime = finalizationTime);
      0 !== (lanes & 62914560) && (retryClampTime = finalizationTime);
      0 !== (lanes & 2080374784) && (idleClampTime = finalizationTime);
    }
    function prepareFreshStack(root3, lanes) {
      supportsUserTiming && (console.timeStamp(
        "Blocking Track",
        3e-3,
        3e-3,
        "Blocking",
        LANES_TRACK_GROUP,
        "primary-light"
      ), console.timeStamp(
        "Transition Track",
        3e-3,
        3e-3,
        "Transition",
        LANES_TRACK_GROUP,
        "primary-light"
      ), console.timeStamp(
        "Suspense Track",
        3e-3,
        3e-3,
        "Suspense",
        LANES_TRACK_GROUP,
        "primary-light"
      ), console.timeStamp(
        "Idle Track",
        3e-3,
        3e-3,
        "Idle",
        LANES_TRACK_GROUP,
        "primary-light"
      ));
      var previousRenderStartTime = renderStartTime;
      renderStartTime = now();
      if (0 !== workInProgressRootRenderLanes && 0 < previousRenderStartTime) {
        setCurrentTrackFromLanes(workInProgressRootRenderLanes);
        if (workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootSuspendedWithDelay)
          logSuspendedRenderPhase(
            previousRenderStartTime,
            renderStartTime,
            lanes,
            workInProgressUpdateTask
          );
        else {
          var endTime = renderStartTime, debugTask = workInProgressUpdateTask;
          if (supportsUserTiming && !(endTime <= previousRenderStartTime)) {
            var color2 = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", label = (lanes & 536870912) === lanes ? "Prewarm" : (lanes & 201326741) === lanes ? "Interrupted Hydration" : "Interrupted Render";
            debugTask ? debugTask.run(
              console.timeStamp.bind(
                console,
                label,
                previousRenderStartTime,
                endTime,
                currentTrack,
                LANES_TRACK_GROUP,
                color2
              )
            ) : console.timeStamp(
              label,
              previousRenderStartTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              color2
            );
          }
        }
        finalizeRender(workInProgressRootRenderLanes, renderStartTime);
      }
      previousRenderStartTime = workInProgressUpdateTask;
      workInProgressUpdateTask = null;
      if (0 !== (lanes & 127)) {
        workInProgressUpdateTask = blockingUpdateTask;
        debugTask = 0 <= blockingUpdateTime && blockingUpdateTime < blockingClampTime ? blockingClampTime : blockingUpdateTime;
        endTime = 0 <= blockingEventTime && blockingEventTime < blockingClampTime ? blockingClampTime : blockingEventTime;
        color2 = 0 <= endTime ? endTime : 0 <= debugTask ? debugTask : renderStartTime;
        0 <= blockingSuspendedTime ? (setCurrentTrackFromLanes(2), logSuspendedWithDelayPhase(
          blockingSuspendedTime,
          color2,
          lanes,
          previousRenderStartTime
        )) : 0 !== (animatingLanes & 127);
        previousRenderStartTime = debugTask;
        var eventTime = endTime, eventType = blockingEventType, eventIsRepeat = 0 < blockingEventRepeatTime, isSpawnedUpdate = blockingUpdateType === SPAWNED_UPDATE, isPingedUpdate = blockingUpdateType === PINGED_UPDATE;
        debugTask = renderStartTime;
        endTime = blockingUpdateTask;
        color2 = blockingUpdateMethodName;
        label = blockingUpdateComponentName;
        if (supportsUserTiming) {
          currentTrack = "Blocking";
          0 < previousRenderStartTime ? previousRenderStartTime > debugTask && (previousRenderStartTime = debugTask) : previousRenderStartTime = debugTask;
          0 < eventTime ? eventTime > previousRenderStartTime && (eventTime = previousRenderStartTime) : eventTime = previousRenderStartTime;
          if (null !== eventType && previousRenderStartTime > eventTime) {
            var color$jscomp$0 = eventIsRepeat ? "secondary-light" : "warning";
            endTime ? endTime.run(
              console.timeStamp.bind(
                console,
                eventIsRepeat ? "Consecutive" : "Event: " + eventType,
                eventTime,
                previousRenderStartTime,
                currentTrack,
                LANES_TRACK_GROUP,
                color$jscomp$0
              )
            ) : console.timeStamp(
              eventIsRepeat ? "Consecutive" : "Event: " + eventType,
              eventTime,
              previousRenderStartTime,
              currentTrack,
              LANES_TRACK_GROUP,
              color$jscomp$0
            );
          }
          debugTask > previousRenderStartTime && (eventTime = isSpawnedUpdate ? "error" : (lanes & 738197653) === lanes ? "tertiary-light" : "primary-light", isSpawnedUpdate = isPingedUpdate ? "Promise Resolved" : isSpawnedUpdate ? "Cascading Update" : 5 < debugTask - previousRenderStartTime ? "Update Blocked" : "Update", isPingedUpdate = [], null != label && isPingedUpdate.push(["Component name", label]), null != color2 && isPingedUpdate.push(["Method name", color2]), previousRenderStartTime = {
            start: previousRenderStartTime,
            end: debugTask,
            detail: {
              devtools: {
                properties: isPingedUpdate,
                track: currentTrack,
                trackGroup: LANES_TRACK_GROUP,
                color: eventTime
              }
            }
          }, endTime ? endTime.run(
            performance.measure.bind(
              performance,
              isSpawnedUpdate,
              previousRenderStartTime
            )
          ) : performance.measure(isSpawnedUpdate, previousRenderStartTime));
        }
        blockingUpdateTime = -1.1;
        blockingUpdateType = 0;
        blockingUpdateComponentName = blockingUpdateMethodName = null;
        blockingSuspendedTime = -1.1;
        blockingEventRepeatTime = blockingEventTime;
        blockingEventTime = -1.1;
        blockingClampTime = now();
      }
      0 !== (lanes & 4194048) && (workInProgressUpdateTask = transitionUpdateTask, debugTask = 0 <= transitionStartTime && transitionStartTime < transitionClampTime ? transitionClampTime : transitionStartTime, previousRenderStartTime = 0 <= transitionUpdateTime && transitionUpdateTime < transitionClampTime ? transitionClampTime : transitionUpdateTime, endTime = 0 <= transitionEventTime && transitionEventTime < transitionClampTime ? transitionClampTime : transitionEventTime, color2 = 0 <= endTime ? endTime : 0 <= previousRenderStartTime ? previousRenderStartTime : renderStartTime, 0 <= transitionSuspendedTime ? (setCurrentTrackFromLanes(256), logSuspendedWithDelayPhase(
        transitionSuspendedTime,
        color2,
        lanes,
        workInProgressUpdateTask
      )) : 0 !== (animatingLanes & 4194048), isPingedUpdate = endTime, eventTime = transitionEventType, eventType = 0 < transitionEventRepeatTime, eventIsRepeat = transitionUpdateType === PINGED_UPDATE, color2 = renderStartTime, endTime = transitionUpdateTask, label = transitionUpdateMethodName, isSpawnedUpdate = transitionUpdateComponentName, supportsUserTiming && (currentTrack = "Transition", 0 < previousRenderStartTime ? previousRenderStartTime > color2 && (previousRenderStartTime = color2) : previousRenderStartTime = color2, 0 < debugTask ? debugTask > previousRenderStartTime && (debugTask = previousRenderStartTime) : debugTask = previousRenderStartTime, 0 < isPingedUpdate ? isPingedUpdate > debugTask && (isPingedUpdate = debugTask) : isPingedUpdate = debugTask, debugTask > isPingedUpdate && null !== eventTime && (color$jscomp$0 = eventType ? "secondary-light" : "warning", endTime ? endTime.run(
        console.timeStamp.bind(
          console,
          eventType ? "Consecutive" : "Event: " + eventTime,
          isPingedUpdate,
          debugTask,
          currentTrack,
          LANES_TRACK_GROUP,
          color$jscomp$0
        )
      ) : console.timeStamp(
        eventType ? "Consecutive" : "Event: " + eventTime,
        isPingedUpdate,
        debugTask,
        currentTrack,
        LANES_TRACK_GROUP,
        color$jscomp$0
      )), previousRenderStartTime > debugTask && (endTime ? endTime.run(
        console.timeStamp.bind(
          console,
          "Action",
          debugTask,
          previousRenderStartTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "primary-dark"
        )
      ) : console.timeStamp(
        "Action",
        debugTask,
        previousRenderStartTime,
        currentTrack,
        LANES_TRACK_GROUP,
        "primary-dark"
      )), color2 > previousRenderStartTime && (debugTask = eventIsRepeat ? "Promise Resolved" : 5 < color2 - previousRenderStartTime ? "Update Blocked" : "Update", isPingedUpdate = [], null != isSpawnedUpdate && isPingedUpdate.push(["Component name", isSpawnedUpdate]), null != label && isPingedUpdate.push(["Method name", label]), previousRenderStartTime = {
        start: previousRenderStartTime,
        end: color2,
        detail: {
          devtools: {
            properties: isPingedUpdate,
            track: currentTrack,
            trackGroup: LANES_TRACK_GROUP,
            color: "primary-light"
          }
        }
      }, endTime ? endTime.run(
        performance.measure.bind(
          performance,
          debugTask,
          previousRenderStartTime
        )
      ) : performance.measure(debugTask, previousRenderStartTime))), transitionUpdateTime = transitionStartTime = -1.1, transitionUpdateType = 0, transitionSuspendedTime = -1.1, transitionEventRepeatTime = transitionEventTime, transitionEventTime = -1.1, transitionClampTime = now());
      0 !== (lanes & 62914560) && 0 !== (animatingLanes & 62914560) && (setCurrentTrackFromLanes(4194304), logAnimatingPhase(retryClampTime, renderStartTime));
      0 !== (lanes & 2080374784) && 0 !== (animatingLanes & 2080374784) && (setCurrentTrackFromLanes(268435456), logAnimatingPhase(idleClampTime, renderStartTime));
      previousRenderStartTime = root3.timeoutHandle;
      previousRenderStartTime !== noTimeout && (root3.timeoutHandle = noTimeout, cancelTimeout(previousRenderStartTime));
      previousRenderStartTime = root3.cancelPendingCommit;
      null !== previousRenderStartTime && (root3.cancelPendingCommit = null, previousRenderStartTime());
      pendingEffectsLanes = 0;
      resetWorkInProgressStack();
      workInProgressRoot = root3;
      workInProgress = previousRenderStartTime = createWorkInProgress(
        root3.current,
        null
      );
      workInProgressRootRenderLanes = lanes;
      workInProgressSuspendedReason = NotSuspended;
      workInProgressThrownValue = null;
      workInProgressRootDidSkipSuspendedSiblings = false;
      workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root3, lanes);
      workInProgressRootDidAttachPingListener = false;
      workInProgressRootExitStatus = RootInProgress;
      workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = 0;
      workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
      workInProgressRootDidIncludeRecursiveRenderUpdate = false;
      0 !== (lanes & 8) && (lanes |= lanes & 32);
      endTime = root3.entangledLanes;
      if (0 !== endTime)
        for (root3 = root3.entanglements, endTime &= lanes; 0 < endTime; )
          debugTask = 31 - clz32(endTime), color2 = 1 << debugTask, lanes |= root3[debugTask], endTime &= ~color2;
      entangledRenderLanes = lanes;
      finishQueueingConcurrentUpdates();
      root3 = getCurrentTime();
      1e3 < root3 - lastResetTime && (ReactSharedInternals.recentlyCreatedOwnerStacks = 0, lastResetTime = root3);
      ReactStrictModeWarnings.discardPendingWarnings();
      return previousRenderStartTime;
    }
    function handleThrow(root3, thrownValue) {
      currentlyRenderingFiber = null;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      ReactSharedInternals.getCurrentStack = null;
      isRendering = false;
      current = null;
      thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnImmediate) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnInstance) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? SuspendedOnHydration : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? SuspendedOnDeprecatedThrowPromise : SuspendedOnError;
      workInProgressThrownValue = thrownValue;
      var erroredWork = workInProgress;
      null === erroredWork ? (workInProgressRootExitStatus = RootFatalErrored, logUncaughtError(
        root3,
        createCapturedValueAtFiber(thrownValue, root3.current)
      )) : erroredWork.mode & ProfileMode && stopProfilerTimerIfRunningAndRecordDuration(erroredWork);
    }
    function shouldRemainOnPreviousScreen() {
      var handler = suspenseHandlerStackCursor.current;
      return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
    }
    function pushDispatcher() {
      var prevDispatcher = ReactSharedInternals.H;
      ReactSharedInternals.H = ContextOnlyDispatcher;
      return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
    }
    function pushAsyncDispatcher() {
      var prevAsyncDispatcher = ReactSharedInternals.A;
      ReactSharedInternals.A = DefaultAsyncDispatcher;
      return prevAsyncDispatcher;
    }
    function markRenderDerivedCause(fiber) {
      null === workInProgressUpdateTask && (workInProgressUpdateTask = null == fiber._debugTask ? null : fiber._debugTask);
    }
    function renderDidSuspendDelayIfPossible() {
      workInProgressRootExitStatus = RootSuspendedWithDelay;
      workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
      0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
        workInProgressRoot,
        workInProgressRootRenderLanes,
        workInProgressDeferredLane,
        false
      );
    }
    function renderRootSync(root3, lanes, shouldYieldForPrerendering) {
      var prevExecutionContext = executionContext;
      executionContext |= RenderContext;
      var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
      if (workInProgressRoot !== root3 || workInProgressRootRenderLanes !== lanes) {
        if (isDevToolsPresent) {
          var memoizedUpdaters = root3.memoizedUpdaters;
          0 < memoizedUpdaters.size && (restorePendingUpdaters(root3, workInProgressRootRenderLanes), memoizedUpdaters.clear());
          movePendingFibersToMemoized(root3, lanes);
        }
        workInProgressTransitions = null;
        prepareFreshStack(root3, lanes);
      }
      lanes = false;
      memoizedUpdaters = workInProgressRootExitStatus;
      a: do
        try {
          if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress) {
            var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
            switch (workInProgressSuspendedReason) {
              case SuspendedOnHydration:
                resetWorkInProgressStack();
                memoizedUpdaters = RootSuspendedAtTheShell;
                break a;
              case SuspendedOnImmediate:
              case SuspendedOnData:
              case SuspendedOnAction:
              case SuspendedOnDeprecatedThrowPromise:
                null === suspenseHandlerStackCursor.current && (lanes = true);
                var reason = workInProgressSuspendedReason;
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(root3, unitOfWork, thrownValue, reason);
                if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                  memoizedUpdaters = RootInProgress;
                  break a;
                }
                break;
              default:
                reason = workInProgressSuspendedReason, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root3, unitOfWork, thrownValue, reason);
            }
          }
          workLoopSync();
          memoizedUpdaters = workInProgressRootExitStatus;
          break;
        } catch (thrownValue$8) {
          handleThrow(root3, thrownValue$8);
        }
      while (1);
      lanes && root3.shellSuspendCounter++;
      resetContextDependencies();
      executionContext = prevExecutionContext;
      ReactSharedInternals.H = prevDispatcher;
      ReactSharedInternals.A = prevAsyncDispatcher;
      null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
      return memoizedUpdaters;
    }
    function workLoopSync() {
      for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
    }
    function renderRootConcurrent(root3, lanes) {
      var prevExecutionContext = executionContext;
      executionContext |= RenderContext;
      var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
      if (workInProgressRoot !== root3 || workInProgressRootRenderLanes !== lanes) {
        if (isDevToolsPresent) {
          var memoizedUpdaters = root3.memoizedUpdaters;
          0 < memoizedUpdaters.size && (restorePendingUpdaters(root3, workInProgressRootRenderLanes), memoizedUpdaters.clear());
          movePendingFibersToMemoized(root3, lanes);
        }
        workInProgressTransitions = null;
        workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS;
        prepareFreshStack(root3, lanes);
      } else
        workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
          root3,
          lanes
        );
      a: do
        try {
          if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress)
            b: switch (lanes = workInProgress, memoizedUpdaters = workInProgressThrownValue, workInProgressSuspendedReason) {
              case SuspendedOnError:
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(
                  root3,
                  lanes,
                  memoizedUpdaters,
                  SuspendedOnError
                );
                break;
              case SuspendedOnData:
              case SuspendedOnAction:
                if (isThenableResolved(memoizedUpdaters)) {
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  replaySuspendedUnitOfWork(lanes);
                  break;
                }
                lanes = function() {
                  workInProgressSuspendedReason !== SuspendedOnData && workInProgressSuspendedReason !== SuspendedOnAction || workInProgressRoot !== root3 || (workInProgressSuspendedReason = SuspendedAndReadyToContinue);
                  ensureRootIsScheduled(root3);
                };
                memoizedUpdaters.then(lanes, lanes);
                break a;
              case SuspendedOnImmediate:
                workInProgressSuspendedReason = SuspendedAndReadyToContinue;
                break a;
              case SuspendedOnInstance:
                workInProgressSuspendedReason = SuspendedOnInstanceAndReadyToContinue;
                break a;
              case SuspendedAndReadyToContinue:
                isThenableResolved(memoizedUpdaters) ? (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(
                  root3,
                  lanes,
                  memoizedUpdaters,
                  SuspendedAndReadyToContinue
                ));
                break;
              case SuspendedOnInstanceAndReadyToContinue:
                var resource = null;
                switch (workInProgress.tag) {
                  case 26:
                    resource = workInProgress.memoizedState;
                  case 5:
                  case 27:
                    var hostFiber = workInProgress;
                    if (resource ? preloadResource(resource) : hostFiber.stateNode.complete) {
                      workInProgressSuspendedReason = NotSuspended;
                      workInProgressThrownValue = null;
                      var sibling = hostFiber.sibling;
                      if (null !== sibling) workInProgress = sibling;
                      else {
                        var returnFiber = hostFiber.return;
                        null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                      }
                      break b;
                    }
                    break;
                  default:
                    console.error(
                      "Unexpected type of fiber triggered a suspensey commit. This is a bug in React."
                    );
                }
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(
                  root3,
                  lanes,
                  memoizedUpdaters,
                  SuspendedOnInstanceAndReadyToContinue
                );
                break;
              case SuspendedOnDeprecatedThrowPromise:
                workInProgressSuspendedReason = NotSuspended;
                workInProgressThrownValue = null;
                throwAndUnwindWorkLoop(
                  root3,
                  lanes,
                  memoizedUpdaters,
                  SuspendedOnDeprecatedThrowPromise
                );
                break;
              case SuspendedOnHydration:
                resetWorkInProgressStack();
                workInProgressRootExitStatus = RootSuspendedAtTheShell;
                break a;
              default:
                throw Error(
                  "Unexpected SuspendedReason. This is a bug in React."
                );
            }
          null !== ReactSharedInternals.actQueue ? workLoopSync() : workLoopConcurrentByScheduler();
          break;
        } catch (thrownValue$9) {
          handleThrow(root3, thrownValue$9);
        }
      while (1);
      resetContextDependencies();
      ReactSharedInternals.H = prevDispatcher;
      ReactSharedInternals.A = prevAsyncDispatcher;
      executionContext = prevExecutionContext;
      if (null !== workInProgress) return RootInProgress;
      workInProgressRoot = null;
      workInProgressRootRenderLanes = 0;
      finishQueueingConcurrentUpdates();
      return workInProgressRootExitStatus;
    }
    function workLoopConcurrentByScheduler() {
      for (; null !== workInProgress && !shouldYield(); )
        performUnitOfWork(workInProgress);
    }
    function performUnitOfWork(unitOfWork) {
      var current2 = unitOfWork.alternate;
      (unitOfWork.mode & ProfileMode) !== NoMode ? (startProfilerTimer(unitOfWork), current2 = runWithFiberInDEV(
        unitOfWork,
        beginWork,
        current2,
        unitOfWork,
        entangledRenderLanes
      ), stopProfilerTimerIfRunningAndRecordDuration(unitOfWork)) : current2 = runWithFiberInDEV(
        unitOfWork,
        beginWork,
        current2,
        unitOfWork,
        entangledRenderLanes
      );
      unitOfWork.memoizedProps = unitOfWork.pendingProps;
      null === current2 ? completeUnitOfWork(unitOfWork) : workInProgress = current2;
    }
    function replaySuspendedUnitOfWork(unitOfWork) {
      var next = runWithFiberInDEV(unitOfWork, replayBeginWork, unitOfWork);
      unitOfWork.memoizedProps = unitOfWork.pendingProps;
      null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
    }
    function replayBeginWork(unitOfWork) {
      var current2 = unitOfWork.alternate, isProfilingMode = (unitOfWork.mode & ProfileMode) !== NoMode;
      isProfilingMode && startProfilerTimer(unitOfWork);
      switch (unitOfWork.tag) {
        case 15:
        case 0:
          current2 = replayFunctionComponent(
            current2,
            unitOfWork,
            unitOfWork.pendingProps,
            unitOfWork.type,
            void 0,
            workInProgressRootRenderLanes
          );
          break;
        case 11:
          current2 = replayFunctionComponent(
            current2,
            unitOfWork,
            unitOfWork.pendingProps,
            unitOfWork.type.render,
            unitOfWork.ref,
            workInProgressRootRenderLanes
          );
          break;
        case 5:
          resetHooksOnUnwind(unitOfWork);
        default:
          unwindInterruptedWork(current2, unitOfWork), unitOfWork = workInProgress = resetWorkInProgress(unitOfWork, entangledRenderLanes), current2 = beginWork(current2, unitOfWork, entangledRenderLanes);
      }
      isProfilingMode && stopProfilerTimerIfRunningAndRecordDuration(unitOfWork);
      return current2;
    }
    function throwAndUnwindWorkLoop(root3, unitOfWork, thrownValue, suspendedReason) {
      resetContextDependencies();
      resetHooksOnUnwind(unitOfWork);
      thenableState$1 = null;
      thenableIndexCounter$1 = 0;
      var returnFiber = unitOfWork.return;
      try {
        if (throwException(
          root3,
          returnFiber,
          unitOfWork,
          thrownValue,
          workInProgressRootRenderLanes
        )) {
          workInProgressRootExitStatus = RootFatalErrored;
          logUncaughtError(
            root3,
            createCapturedValueAtFiber(thrownValue, root3.current)
          );
          workInProgress = null;
          return;
        }
      } catch (error) {
        if (null !== returnFiber) throw workInProgress = returnFiber, error;
        workInProgressRootExitStatus = RootFatalErrored;
        logUncaughtError(
          root3,
          createCapturedValueAtFiber(thrownValue, root3.current)
        );
        workInProgress = null;
        return;
      }
      if (unitOfWork.flags & 32768) {
        if (isHydrating || suspendedReason === SuspendedOnError) root3 = true;
        else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
          root3 = false;
        else if (workInProgressRootDidSkipSuspendedSiblings = root3 = true, suspendedReason === SuspendedOnData || suspendedReason === SuspendedOnAction || suspendedReason === SuspendedOnImmediate || suspendedReason === SuspendedOnDeprecatedThrowPromise)
          suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
        unwindUnitOfWork(unitOfWork, root3);
      } else completeUnitOfWork(unitOfWork);
    }
    function completeUnitOfWork(unitOfWork) {
      var completedWork = unitOfWork;
      do {
        if (0 !== (completedWork.flags & 32768)) {
          unwindUnitOfWork(
            completedWork,
            workInProgressRootDidSkipSuspendedSiblings
          );
          return;
        }
        var current2 = completedWork.alternate;
        unitOfWork = completedWork.return;
        startProfilerTimer(completedWork);
        current2 = runWithFiberInDEV(
          completedWork,
          completeWork,
          current2,
          completedWork,
          entangledRenderLanes
        );
        (completedWork.mode & ProfileMode) !== NoMode && stopProfilerTimerIfRunningAndRecordIncompleteDuration(completedWork);
        if (null !== current2) {
          workInProgress = current2;
          return;
        }
        completedWork = completedWork.sibling;
        if (null !== completedWork) {
          workInProgress = completedWork;
          return;
        }
        workInProgress = completedWork = unitOfWork;
      } while (null !== completedWork);
      workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootCompleted);
    }
    function unwindUnitOfWork(unitOfWork, skipSiblings) {
      do {
        var next = unwindWork(unitOfWork.alternate, unitOfWork);
        if (null !== next) {
          next.flags &= 32767;
          workInProgress = next;
          return;
        }
        if ((unitOfWork.mode & ProfileMode) !== NoMode) {
          stopProfilerTimerIfRunningAndRecordIncompleteDuration(unitOfWork);
          next = unitOfWork.actualDuration;
          for (var child = unitOfWork.child; null !== child; )
            next += child.actualDuration, child = child.sibling;
          unitOfWork.actualDuration = next;
        }
        next = unitOfWork.return;
        null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
        if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
          workInProgress = unitOfWork;
          return;
        }
        workInProgress = unitOfWork = next;
      } while (null !== unitOfWork);
      workInProgressRootExitStatus = RootSuspendedAtTheShell;
      workInProgress = null;
    }
    function commitRoot(root3, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, exitStatus, suspendedState, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
      root3.cancelPendingCommit = null;
      do
        flushPendingEffects();
      while (pendingEffectsStatus !== NO_PENDING_EFFECTS);
      ReactStrictModeWarnings.flushLegacyContextWarning();
      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
      if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
        throw Error("Should not already be working.");
      setCurrentTrackFromLanes(lanes);
      exitStatus === RootErrored ? logErroredRenderPhase(
        completedRenderStartTime,
        completedRenderEndTime,
        lanes,
        workInProgressUpdateTask
      ) : null !== recoverableErrors ? logRecoveredRenderPhase(
        completedRenderStartTime,
        completedRenderEndTime,
        lanes,
        recoverableErrors,
        null !== finishedWork && null !== finishedWork.alternate && finishedWork.alternate.memoizedState.isDehydrated && 0 !== (finishedWork.flags & 256),
        workInProgressUpdateTask
      ) : logRenderPhase(
        completedRenderStartTime,
        completedRenderEndTime,
        lanes,
        workInProgressUpdateTask
      );
      if (null !== finishedWork) {
        0 === lanes && console.error(
          "finishedLanes should not be empty during a commit. This is a bug in React."
        );
        if (finishedWork === root3.current)
          throw Error(
            "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."
          );
        didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
        didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
        markRootFinished(
          root3,
          lanes,
          didIncludeRenderPhaseUpdate,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes
        );
        root3 === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
        pendingFinishedWork = finishedWork;
        pendingEffectsRoot = root3;
        pendingEffectsLanes = lanes;
        pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
        pendingPassiveTransitions = transitions;
        pendingRecoverableErrors = recoverableErrors;
        pendingEffectsRenderEndTime = completedRenderEndTime;
        pendingSuspendedCommitReason = suspendedCommitReason;
        pendingDelayedCommitReason = IMMEDIATE_COMMIT;
        pendingSuspendedViewTransitionReason = null;
        0 !== finishedWork.actualDuration || 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root3.callbackNode = null, root3.callbackPriority = 0, scheduleCallback$1(NormalPriority$1, function() {
          schedulerEvent = window.event;
          pendingDelayedCommitReason === IMMEDIATE_COMMIT && (pendingDelayedCommitReason = DELAYED_PASSIVE_COMMIT);
          flushPassiveEffects();
          return null;
        })) : (root3.callbackNode = null, root3.callbackPriority = 0);
        commitErrors = null;
        commitStartTime = now();
        null !== suspendedCommitReason && logSuspendedCommitPhase(
          completedRenderEndTime,
          commitStartTime,
          suspendedCommitReason,
          workInProgressUpdateTask
        );
        recoverableErrors = 0 !== (finishedWork.flags & 13878);
        if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
          recoverableErrors = ReactSharedInternals.T;
          ReactSharedInternals.T = null;
          transitions = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          spawnedLane = executionContext;
          executionContext |= CommitContext;
          try {
            commitBeforeMutationEffects(root3, finishedWork, lanes);
          } finally {
            executionContext = spawnedLane, ReactDOMSharedInternals.p = transitions, ReactSharedInternals.T = recoverableErrors;
          }
        }
        pendingEffectsStatus = PENDING_MUTATION_PHASE;
        flushMutationEffects();
        flushLayoutEffects();
        flushSpawnedWork();
      }
    }
    function flushMutationEffects() {
      if (pendingEffectsStatus === PENDING_MUTATION_PHASE) {
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        var root3 = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
        if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
          rootMutationHasEffect = ReactSharedInternals.T;
          ReactSharedInternals.T = null;
          var previousPriority = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          var prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          try {
            inProgressLanes = lanes;
            inProgressRoot = root3;
            resetComponentEffectTimers();
            commitMutationEffectsOnFiber(finishedWork, root3);
            inProgressRoot = inProgressLanes = null;
            lanes = selectionInformation;
            var curFocusedElem = getActiveElementDeep(root3.containerInfo), priorFocusedElem = lanes.focusedElem, priorSelectionRange = lanes.selectionRange;
            if (curFocusedElem !== priorFocusedElem && priorFocusedElem && priorFocusedElem.ownerDocument && containsNode(
              priorFocusedElem.ownerDocument.documentElement,
              priorFocusedElem
            )) {
              if (null !== priorSelectionRange && hasSelectionCapabilities(priorFocusedElem)) {
                var start = priorSelectionRange.start, end = priorSelectionRange.end;
                void 0 === end && (end = start);
                if ("selectionStart" in priorFocusedElem)
                  priorFocusedElem.selectionStart = start, priorFocusedElem.selectionEnd = Math.min(
                    end,
                    priorFocusedElem.value.length
                  );
                else {
                  var doc = priorFocusedElem.ownerDocument || document, win = doc && doc.defaultView || window;
                  if (win.getSelection) {
                    var selection = win.getSelection(), length = priorFocusedElem.textContent.length, start$jscomp$0 = Math.min(
                      priorSelectionRange.start,
                      length
                    ), end$jscomp$0 = void 0 === priorSelectionRange.end ? start$jscomp$0 : Math.min(priorSelectionRange.end, length);
                    !selection.extend && start$jscomp$0 > end$jscomp$0 && (curFocusedElem = end$jscomp$0, end$jscomp$0 = start$jscomp$0, start$jscomp$0 = curFocusedElem);
                    var startMarker = getNodeForCharacterOffset(
                      priorFocusedElem,
                      start$jscomp$0
                    ), endMarker = getNodeForCharacterOffset(
                      priorFocusedElem,
                      end$jscomp$0
                    );
                    if (startMarker && endMarker && (1 !== selection.rangeCount || selection.anchorNode !== startMarker.node || selection.anchorOffset !== startMarker.offset || selection.focusNode !== endMarker.node || selection.focusOffset !== endMarker.offset)) {
                      var range2 = doc.createRange();
                      range2.setStart(startMarker.node, startMarker.offset);
                      selection.removeAllRanges();
                      start$jscomp$0 > end$jscomp$0 ? (selection.addRange(range2), selection.extend(endMarker.node, endMarker.offset)) : (range2.setEnd(endMarker.node, endMarker.offset), selection.addRange(range2));
                    }
                  }
                }
              }
              doc = [];
              for (selection = priorFocusedElem; selection = selection.parentNode; )
                1 === selection.nodeType && doc.push({
                  element: selection,
                  left: selection.scrollLeft,
                  top: selection.scrollTop
                });
              "function" === typeof priorFocusedElem.focus && priorFocusedElem.focus();
              for (priorFocusedElem = 0; priorFocusedElem < doc.length; priorFocusedElem++) {
                var info = doc[priorFocusedElem];
                info.element.scrollLeft = info.left;
                info.element.scrollTop = info.top;
              }
            }
            _enabled = !!eventsEnabled;
            selectionInformation = eventsEnabled = null;
          } finally {
            executionContext = prevExecutionContext, ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = rootMutationHasEffect;
          }
        }
        root3.current = finishedWork;
        pendingEffectsStatus = PENDING_LAYOUT_PHASE;
      }
    }
    function flushLayoutEffects() {
      if (pendingEffectsStatus === PENDING_LAYOUT_PHASE) {
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        var suspendedViewTransitionReason = pendingSuspendedViewTransitionReason;
        if (null !== suspendedViewTransitionReason) {
          commitStartTime = now();
          var startTime = commitEndTime, endTime = commitStartTime;
          !supportsUserTiming || endTime <= startTime || console.timeStamp(
            suspendedViewTransitionReason,
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-light"
          );
        }
        suspendedViewTransitionReason = pendingEffectsRoot;
        startTime = pendingFinishedWork;
        endTime = pendingEffectsLanes;
        var rootHasLayoutEffect = 0 !== (startTime.flags & 8772);
        if (0 !== (startTime.subtreeFlags & 8772) || rootHasLayoutEffect) {
          rootHasLayoutEffect = ReactSharedInternals.T;
          ReactSharedInternals.T = null;
          var _previousPriority = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          var _prevExecutionContext = executionContext;
          executionContext |= CommitContext;
          try {
            inProgressLanes = endTime, inProgressRoot = suspendedViewTransitionReason, resetComponentEffectTimers(), commitLayoutEffectOnFiber(
              suspendedViewTransitionReason,
              startTime.alternate,
              startTime
            ), inProgressRoot = inProgressLanes = null;
          } finally {
            executionContext = _prevExecutionContext, ReactDOMSharedInternals.p = _previousPriority, ReactSharedInternals.T = rootHasLayoutEffect;
          }
        }
        suspendedViewTransitionReason = pendingEffectsRenderEndTime;
        startTime = pendingSuspendedCommitReason;
        commitEndTime = now();
        suspendedViewTransitionReason = null === startTime ? suspendedViewTransitionReason : commitStartTime;
        startTime = commitEndTime;
        endTime = pendingDelayedCommitReason === ABORTED_VIEW_TRANSITION_COMMIT;
        rootHasLayoutEffect = workInProgressUpdateTask;
        null !== commitErrors ? logCommitErrored(
          suspendedViewTransitionReason,
          startTime,
          commitErrors,
          false,
          rootHasLayoutEffect
        ) : !supportsUserTiming || startTime <= suspendedViewTransitionReason || (rootHasLayoutEffect ? rootHasLayoutEffect.run(
          console.timeStamp.bind(
            console,
            endTime ? "Commit Interrupted View Transition" : "Commit",
            suspendedViewTransitionReason,
            startTime,
            currentTrack,
            LANES_TRACK_GROUP,
            endTime ? "error" : "secondary-dark"
          )
        ) : console.timeStamp(
          endTime ? "Commit Interrupted View Transition" : "Commit",
          suspendedViewTransitionReason,
          startTime,
          currentTrack,
          LANES_TRACK_GROUP,
          endTime ? "error" : "secondary-dark"
        ));
        pendingEffectsStatus = PENDING_AFTER_MUTATION_PHASE;
      }
    }
    function flushSpawnedWork() {
      if (pendingEffectsStatus === PENDING_SPAWNED_WORK || pendingEffectsStatus === PENDING_AFTER_MUTATION_PHASE) {
        if (pendingEffectsStatus === PENDING_SPAWNED_WORK) {
          var startViewTransitionStartTime = commitEndTime;
          commitEndTime = now();
          var endTime = commitEndTime, abortedViewTransition = pendingDelayedCommitReason === ABORTED_VIEW_TRANSITION_COMMIT;
          !supportsUserTiming || endTime <= startViewTransitionStartTime || console.timeStamp(
            abortedViewTransition ? "Interrupted View Transition" : "Starting Animation",
            startViewTransitionStartTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            abortedViewTransition ? " error" : "secondary-light"
          );
          pendingDelayedCommitReason !== ABORTED_VIEW_TRANSITION_COMMIT && (pendingDelayedCommitReason = ANIMATION_STARTED_COMMIT);
        }
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        requestPaint();
        startViewTransitionStartTime = pendingEffectsRoot;
        var finishedWork = pendingFinishedWork;
        endTime = pendingEffectsLanes;
        abortedViewTransition = pendingRecoverableErrors;
        var rootDidHavePassiveEffects = 0 !== finishedWork.actualDuration || 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256);
        rootDidHavePassiveEffects ? pendingEffectsStatus = PENDING_PASSIVE_PHASE : (pendingEffectsStatus = NO_PENDING_EFFECTS, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(
          startViewTransitionStartTime,
          startViewTransitionStartTime.pendingLanes
        ), nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null);
        var remainingLanes = startViewTransitionStartTime.pendingLanes;
        0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
        rootDidHavePassiveEffects || commitDoubleInvokeEffectsInDEV(startViewTransitionStartTime);
        remainingLanes = lanesToEventPriority(endTime);
        finishedWork = finishedWork.stateNode;
        if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
          try {
            var didError = 128 === (finishedWork.current.flags & 128);
            switch (remainingLanes) {
              case DiscreteEventPriority:
                var schedulerPriority = ImmediatePriority;
                break;
              case ContinuousEventPriority:
                schedulerPriority = UserBlockingPriority;
                break;
              case DefaultEventPriority:
                schedulerPriority = NormalPriority$1;
                break;
              case IdleEventPriority:
                schedulerPriority = IdlePriority;
                break;
              default:
                schedulerPriority = NormalPriority$1;
            }
            injectedHook.onCommitFiberRoot(
              rendererID,
              finishedWork,
              schedulerPriority,
              didError
            );
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
        isDevToolsPresent && startViewTransitionStartTime.memoizedUpdaters.clear();
        onCommitRoot();
        if (null !== abortedViewTransition) {
          didError = ReactSharedInternals.T;
          schedulerPriority = ReactDOMSharedInternals.p;
          ReactDOMSharedInternals.p = DiscreteEventPriority;
          ReactSharedInternals.T = null;
          try {
            var onRecoverableError = startViewTransitionStartTime.onRecoverableError;
            for (finishedWork = 0; finishedWork < abortedViewTransition.length; finishedWork++) {
              var recoverableError = abortedViewTransition[finishedWork], errorInfo = makeErrorInfo(recoverableError.stack);
              runWithFiberInDEV(
                recoverableError.source,
                onRecoverableError,
                recoverableError.value,
                errorInfo
              );
            }
          } finally {
            ReactSharedInternals.T = didError, ReactDOMSharedInternals.p = schedulerPriority;
          }
        }
        0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
        ensureRootIsScheduled(startViewTransitionStartTime);
        remainingLanes = startViewTransitionStartTime.pendingLanes;
        0 !== (endTime & 261930) && 0 !== (remainingLanes & 42) ? (nestedUpdateScheduled = true, startViewTransitionStartTime === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = startViewTransitionStartTime)) : nestedUpdateCount = 0;
        rootDidHavePassiveEffects || finalizeRender(endTime, commitEndTime);
        flushSyncWorkAcrossRoots_impl(0);
      }
    }
    function makeErrorInfo(componentStack) {
      componentStack = { componentStack };
      Object.defineProperty(componentStack, "digest", {
        get: function() {
          console.error(
            'You are accessing "digest" from the errorInfo object passed to onRecoverableError. This property is no longer provided as part of errorInfo but can be accessed as a property of the Error instance itself.'
          );
        }
      });
      return componentStack;
    }
    function releaseRootPooledCache(root3, remainingLanes) {
      0 === (root3.pooledCacheLanes &= remainingLanes) && (remainingLanes = root3.pooledCache, null != remainingLanes && (root3.pooledCache = null, releaseCache(remainingLanes)));
    }
    function flushPendingEffects() {
      flushMutationEffects();
      flushLayoutEffects();
      flushSpawnedWork();
      return flushPassiveEffects();
    }
    function flushPassiveEffects() {
      if (pendingEffectsStatus !== PENDING_PASSIVE_PHASE) return false;
      var root3 = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
      pendingEffectsRemainingLanes = 0;
      var renderPriority = lanesToEventPriority(pendingEffectsLanes), priority = DefaultEventPriority > renderPriority ? DefaultEventPriority : renderPriority;
      renderPriority = ReactSharedInternals.T;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = priority;
        ReactSharedInternals.T = null;
        var transitions = pendingPassiveTransitions;
        pendingPassiveTransitions = null;
        priority = pendingEffectsRoot;
        var lanes = pendingEffectsLanes;
        pendingEffectsStatus = NO_PENDING_EFFECTS;
        pendingFinishedWork = pendingEffectsRoot = null;
        pendingEffectsLanes = 0;
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
          throw Error("Cannot flush passive effects while already rendering.");
        setCurrentTrackFromLanes(lanes);
        isFlushingPassiveEffects = true;
        didScheduleUpdateDuringPassiveEffects = false;
        var passiveEffectStartTime = 0;
        commitErrors = null;
        passiveEffectStartTime = now$1();
        if (pendingDelayedCommitReason === ANIMATION_STARTED_COMMIT)
          logAnimatingPhase(
            commitEndTime,
            passiveEffectStartTime,
            animatingTask
          );
        else {
          var startTime = commitEndTime, endTime = passiveEffectStartTime, delayedUntilPaint = pendingDelayedCommitReason === DELAYED_PASSIVE_COMMIT;
          !supportsUserTiming || endTime <= startTime || (workInProgressUpdateTask ? workInProgressUpdateTask.run(
            console.timeStamp.bind(
              console,
              delayedUntilPaint ? "Waiting for Paint" : "Waiting",
              startTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "secondary-light"
            )
          ) : console.timeStamp(
            delayedUntilPaint ? "Waiting for Paint" : "Waiting",
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-light"
          ));
        }
        startTime = executionContext;
        executionContext |= CommitContext;
        var finishedWork = priority.current;
        resetComponentEffectTimers();
        commitPassiveUnmountOnFiber(finishedWork);
        var finishedWork$jscomp$0 = priority.current;
        finishedWork = pendingEffectsRenderEndTime;
        resetComponentEffectTimers();
        commitPassiveMountOnFiber(
          priority,
          finishedWork$jscomp$0,
          lanes,
          transitions,
          finishedWork
        );
        commitDoubleInvokeEffectsInDEV(priority);
        executionContext = startTime;
        var passiveEffectsEndTime = now$1();
        finishedWork$jscomp$0 = passiveEffectStartTime;
        finishedWork = workInProgressUpdateTask;
        null !== commitErrors ? logCommitErrored(
          finishedWork$jscomp$0,
          passiveEffectsEndTime,
          commitErrors,
          true,
          finishedWork
        ) : !supportsUserTiming || passiveEffectsEndTime <= finishedWork$jscomp$0 || (finishedWork ? finishedWork.run(
          console.timeStamp.bind(
            console,
            "Remaining Effects",
            finishedWork$jscomp$0,
            passiveEffectsEndTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-dark"
          )
        ) : console.timeStamp(
          "Remaining Effects",
          finishedWork$jscomp$0,
          passiveEffectsEndTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "secondary-dark"
        ));
        finalizeRender(lanes, passiveEffectsEndTime);
        flushSyncWorkAcrossRoots_impl(0, false);
        didScheduleUpdateDuringPassiveEffects ? priority === rootWithPassiveNestedUpdates ? nestedPassiveUpdateCount++ : (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = priority) : nestedPassiveUpdateCount = 0;
        didScheduleUpdateDuringPassiveEffects = isFlushingPassiveEffects = false;
        if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
          try {
            injectedHook.onPostCommitFiberRoot(rendererID, priority);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
        var stateNode = priority.current.stateNode;
        stateNode.effectDuration = 0;
        stateNode.passiveEffectDuration = 0;
        return true;
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root3, remainingLanes);
      }
    }
    function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
      sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
      recordEffectError(sourceFiber);
      sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
      rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
      null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
    }
    function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) {
      isRunningInsertionEffect = false;
      if (3 === sourceFiber.tag)
        captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
      else {
        for (; null !== nearestMountedAncestor; ) {
          if (3 === nearestMountedAncestor.tag) {
            captureCommitPhaseErrorOnRoot(
              nearestMountedAncestor,
              sourceFiber,
              error
            );
            return;
          }
          if (1 === nearestMountedAncestor.tag) {
            var instance = nearestMountedAncestor.stateNode;
            if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
              sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
              recordEffectError(sourceFiber);
              error = createClassErrorUpdate(2);
              instance = enqueueUpdate(nearestMountedAncestor, error, 2);
              null !== instance && (initializeClassErrorUpdate(
                error,
                instance,
                nearestMountedAncestor,
                sourceFiber
              ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
              return;
            }
          }
          nearestMountedAncestor = nearestMountedAncestor.return;
        }
        console.error(
          "Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Potential causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s",
          error
        );
      }
    }
    function attachPingListener(root3, wakeable, lanes) {
      var pingCache = root3.pingCache;
      if (null === pingCache) {
        pingCache = root3.pingCache = new PossiblyWeakMap();
        var threadIDs = /* @__PURE__ */ new Set();
        pingCache.set(wakeable, threadIDs);
      } else
        threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
      threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), pingCache = pingSuspendedRoot.bind(null, root3, wakeable, lanes), isDevToolsPresent && restorePendingUpdaters(root3, lanes), wakeable.then(pingCache, pingCache));
    }
    function pingSuspendedRoot(root3, wakeable, pingedLanes) {
      var pingCache = root3.pingCache;
      null !== pingCache && pingCache.delete(wakeable);
      root3.pingedLanes |= root3.suspendedLanes & pingedLanes;
      root3.warmLanes &= ~pingedLanes;
      0 !== (pingedLanes & 127) ? 0 > blockingUpdateTime && (blockingClampTime = blockingUpdateTime = now(), blockingUpdateTask = createTask("Promise Resolved"), blockingUpdateType = PINGED_UPDATE) : 0 !== (pingedLanes & 4194048) && 0 > transitionUpdateTime && (transitionClampTime = transitionUpdateTime = now(), transitionUpdateTask = createTask("Promise Resolved"), transitionUpdateType = PINGED_UPDATE);
      isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && console.error(
        "A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n  /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act"
      );
      workInProgressRoot === root3 && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS ? (executionContext & RenderContext) === NoContext && prepareFreshStack(root3, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
      ensureRootIsScheduled(root3);
    }
    function retryTimedOutBoundary(boundaryFiber, retryLane) {
      0 === retryLane && (retryLane = claimNextRetryLane());
      boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
      null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
    }
    function retryDehydratedSuspenseBoundary(boundaryFiber) {
      var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
      null !== suspenseState && (retryLane = suspenseState.retryLane);
      retryTimedOutBoundary(boundaryFiber, retryLane);
    }
    function resolveRetryWakeable(boundaryFiber, wakeable) {
      var retryLane = 0;
      switch (boundaryFiber.tag) {
        case 31:
        case 13:
          var retryCache = boundaryFiber.stateNode;
          var suspenseState = boundaryFiber.memoizedState;
          null !== suspenseState && (retryLane = suspenseState.retryLane);
          break;
        case 19:
          retryCache = boundaryFiber.stateNode;
          break;
        case 22:
          retryCache = boundaryFiber.stateNode._retryCache;
          break;
        default:
          throw Error(
            "Pinged unknown suspense boundary type. This is probably a bug in React."
          );
      }
      null !== retryCache && retryCache.delete(wakeable);
      retryTimedOutBoundary(boundaryFiber, retryLane);
    }
    function recursivelyTraverseAndDoubleInvokeEffectsInDEV(root$jscomp$0, parentFiber, isInStrictMode) {
      if (0 !== (parentFiber.subtreeFlags & 67117056))
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var root3 = root$jscomp$0, fiber = parentFiber, isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
          isStrictModeFiber = isInStrictMode || isStrictModeFiber;
          22 !== fiber.tag ? fiber.flags & 67108864 ? isStrictModeFiber && runWithFiberInDEV(
            fiber,
            doubleInvokeEffectsOnFiber,
            root3,
            fiber
          ) : recursivelyTraverseAndDoubleInvokeEffectsInDEV(
            root3,
            fiber,
            isStrictModeFiber
          ) : null === fiber.memoizedState && (isStrictModeFiber && fiber.flags & 8192 ? runWithFiberInDEV(
            fiber,
            doubleInvokeEffectsOnFiber,
            root3,
            fiber
          ) : fiber.subtreeFlags & 67108864 && runWithFiberInDEV(
            fiber,
            recursivelyTraverseAndDoubleInvokeEffectsInDEV,
            root3,
            fiber,
            isStrictModeFiber
          ));
          parentFiber = parentFiber.sibling;
        }
    }
    function doubleInvokeEffectsOnFiber(root3, fiber) {
      setIsStrictModeForDevtools(true);
      try {
        disappearLayoutEffects(fiber), disconnectPassiveEffect(fiber), reappearLayoutEffects(root3, fiber.alternate, fiber, false), reconnectPassiveEffects(root3, fiber, 0, null, false, 0);
      } finally {
        setIsStrictModeForDevtools(false);
      }
    }
    function commitDoubleInvokeEffectsInDEV(root3) {
      var doubleInvokeEffects = true;
      root3.current.mode & (StrictLegacyMode | StrictEffectsMode) || (doubleInvokeEffects = false);
      recursivelyTraverseAndDoubleInvokeEffectsInDEV(
        root3,
        root3.current,
        doubleInvokeEffects
      );
    }
    function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
      if ((executionContext & RenderContext) === NoContext) {
        var tag = fiber.tag;
        if (3 === tag || 1 === tag || 0 === tag || 11 === tag || 14 === tag || 15 === tag) {
          tag = getComponentNameFromFiber(fiber) || "ReactComponent";
          if (null !== didWarnStateUpdateForNotYetMountedComponent) {
            if (didWarnStateUpdateForNotYetMountedComponent.has(tag)) return;
            didWarnStateUpdateForNotYetMountedComponent.add(tag);
          } else didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([tag]);
          runWithFiberInDEV(fiber, function() {
            console.error(
              "Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously tries to update the component. Move this work to useEffect instead."
            );
          });
        }
      }
    }
    function restorePendingUpdaters(root3, lanes) {
      isDevToolsPresent && root3.memoizedUpdaters.forEach(function(schedulingFiber) {
        addFiberToLanesMap(root3, schedulingFiber, lanes);
      });
    }
    function scheduleCallback$1(priorityLevel, callback) {
      var actQueue = ReactSharedInternals.actQueue;
      return null !== actQueue ? (actQueue.push(callback), fakeActCallbackNode$1) : scheduleCallback$3(priorityLevel, callback);
    }
    function warnIfUpdatesNotWrappedWithActDEV(fiber) {
      isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && runWithFiberInDEV(fiber, function() {
        console.error(
          "An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n  /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act",
          getComponentNameFromFiber(fiber)
        );
      });
    }
    function ensureRootIsScheduled(root3) {
      root3 !== lastScheduledRoot && null === root3.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root3 : lastScheduledRoot = lastScheduledRoot.next = root3);
      mightHavePendingSyncWork = true;
      null !== ReactSharedInternals.actQueue ? didScheduleMicrotask_act || (didScheduleMicrotask_act = true, scheduleImmediateRootScheduleTask()) : didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
    }
    function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
      if (!isFlushingWork && mightHavePendingSyncWork) {
        isFlushingWork = true;
        do {
          var didPerformSomeWork = false;
          for (var root3 = firstScheduledRoot; null !== root3; ) {
            if (0 !== syncTransitionLanes) {
              var pendingLanes = root3.pendingLanes;
              if (0 === pendingLanes) var nextLanes = 0;
              else {
                var suspendedLanes = root3.suspendedLanes, pingedLanes = root3.pingedLanes;
                nextLanes = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
                nextLanes &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
                nextLanes = nextLanes & 201326741 ? nextLanes & 201326741 | 1 : nextLanes ? nextLanes | 2 : 0;
              }
              0 !== nextLanes && (didPerformSomeWork = true, performSyncWorkOnRoot(root3, nextLanes));
            } else
              nextLanes = workInProgressRootRenderLanes, nextLanes = getNextLanes(
                root3,
                root3 === workInProgressRoot ? nextLanes : 0,
                null !== root3.cancelPendingCommit || root3.timeoutHandle !== noTimeout
              ), 0 === (nextLanes & 3) || checkIfRootIsPrerendering(root3, nextLanes) || (didPerformSomeWork = true, performSyncWorkOnRoot(root3, nextLanes));
            root3 = root3.next;
          }
        } while (didPerformSomeWork);
        isFlushingWork = false;
      }
    }
    function processRootScheduleInImmediateTask() {
      schedulerEvent = window.event;
      processRootScheduleInMicrotask();
    }
    function processRootScheduleInMicrotask() {
      mightHavePendingSyncWork = didScheduleMicrotask_act = didScheduleMicrotask = false;
      var syncTransitionLanes = 0;
      0 !== currentEventTransitionLane && shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane);
      for (var currentTime = now$1(), prev = null, root3 = firstScheduledRoot; null !== root3; ) {
        var next = root3.next, nextLanes = scheduleTaskForRootDuringMicrotask(root3, currentTime);
        if (0 === nextLanes)
          root3.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
        else if (prev = root3, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
          mightHavePendingSyncWork = true;
        root3 = next;
      }
      pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE || flushSyncWorkAcrossRoots_impl(syncTransitionLanes);
      0 !== currentEventTransitionLane && (currentEventTransitionLane = 0);
    }
    function scheduleTaskForRootDuringMicrotask(root3, currentTime) {
      for (var suspendedLanes = root3.suspendedLanes, pingedLanes = root3.pingedLanes, expirationTimes = root3.expirationTimes, lanes = root3.pendingLanes & -62914561; 0 < lanes; ) {
        var index2 = 31 - clz32(lanes), lane = 1 << index2, expirationTime = expirationTimes[index2];
        if (-1 === expirationTime) {
          if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
            expirationTimes[index2] = computeExpirationTime(lane, currentTime);
        } else expirationTime <= currentTime && (root3.expiredLanes |= lane);
        lanes &= ~lane;
      }
      currentTime = workInProgressRoot;
      suspendedLanes = workInProgressRootRenderLanes;
      suspendedLanes = getNextLanes(
        root3,
        root3 === currentTime ? suspendedLanes : 0,
        null !== root3.cancelPendingCommit || root3.timeoutHandle !== noTimeout
      );
      pingedLanes = root3.callbackNode;
      if (0 === suspendedLanes || root3 === currentTime && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root3.cancelPendingCommit)
        return null !== pingedLanes && cancelCallback(pingedLanes), root3.callbackNode = null, root3.callbackPriority = 0;
      if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root3, suspendedLanes)) {
        currentTime = suspendedLanes & -suspendedLanes;
        if (currentTime !== root3.callbackPriority || null !== ReactSharedInternals.actQueue && pingedLanes !== fakeActCallbackNode)
          cancelCallback(pingedLanes);
        else return currentTime;
        switch (lanesToEventPriority(suspendedLanes)) {
          case DiscreteEventPriority:
          case ContinuousEventPriority:
            suspendedLanes = UserBlockingPriority;
            break;
          case DefaultEventPriority:
            suspendedLanes = NormalPriority$1;
            break;
          case IdleEventPriority:
            suspendedLanes = IdlePriority;
            break;
          default:
            suspendedLanes = NormalPriority$1;
        }
        pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root3);
        null !== ReactSharedInternals.actQueue ? (ReactSharedInternals.actQueue.push(pingedLanes), suspendedLanes = fakeActCallbackNode) : suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
        root3.callbackPriority = currentTime;
        root3.callbackNode = suspendedLanes;
        return currentTime;
      }
      null !== pingedLanes && cancelCallback(pingedLanes);
      root3.callbackPriority = 2;
      root3.callbackNode = null;
      return 2;
    }
    function performWorkOnRootViaSchedulerTask(root3, didTimeout) {
      nestedUpdateScheduled = currentUpdateIsNested = false;
      schedulerEvent = window.event;
      if (pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE)
        return root3.callbackNode = null, root3.callbackPriority = 0, null;
      var originalCallbackNode = root3.callbackNode;
      pendingDelayedCommitReason === IMMEDIATE_COMMIT && (pendingDelayedCommitReason = DELAYED_PASSIVE_COMMIT);
      if (flushPendingEffects() && root3.callbackNode !== originalCallbackNode)
        return null;
      var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
      workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
        root3,
        root3 === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
        null !== root3.cancelPendingCommit || root3.timeoutHandle !== noTimeout
      );
      if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
      performWorkOnRoot(
        root3,
        workInProgressRootRenderLanes$jscomp$0,
        didTimeout
      );
      scheduleTaskForRootDuringMicrotask(root3, now$1());
      return null != root3.callbackNode && root3.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root3) : null;
    }
    function performSyncWorkOnRoot(root3, lanes) {
      if (flushPendingEffects()) return null;
      currentUpdateIsNested = nestedUpdateScheduled;
      nestedUpdateScheduled = false;
      performWorkOnRoot(root3, lanes, true);
    }
    function cancelCallback(callbackNode) {
      callbackNode !== fakeActCallbackNode && null !== callbackNode && cancelCallback$1(callbackNode);
    }
    function scheduleImmediateRootScheduleTask() {
      null !== ReactSharedInternals.actQueue && ReactSharedInternals.actQueue.push(function() {
        processRootScheduleInMicrotask();
        return null;
      });
      scheduleMicrotask(function() {
        (executionContext & (RenderContext | CommitContext)) !== NoContext ? scheduleCallback$3(
          ImmediatePriority,
          processRootScheduleInImmediateTask
        ) : processRootScheduleInMicrotask();
      });
    }
    function requestTransitionLane() {
      if (0 === currentEventTransitionLane) {
        var actionScopeLane = currentEntangledLane;
        0 === actionScopeLane && (actionScopeLane = nextTransitionUpdateLane, nextTransitionUpdateLane <<= 1, 0 === (nextTransitionUpdateLane & 261888) && (nextTransitionUpdateLane = 256));
        currentEventTransitionLane = actionScopeLane;
      }
      return currentEventTransitionLane;
    }
    function coerceFormActionProp(actionProp) {
      if (null == actionProp || "symbol" === typeof actionProp || "boolean" === typeof actionProp)
        return null;
      if ("function" === typeof actionProp) return actionProp;
      checkAttributeStringCoercion(actionProp, "action");
      return sanitizeURL("" + actionProp);
    }
    function createFormDataWithSubmitter(form, submitter) {
      var temp = submitter.ownerDocument.createElement("input");
      temp.name = submitter.name;
      temp.value = submitter.value;
      form.id && temp.setAttribute("form", form.id);
      submitter.parentNode.insertBefore(temp, submitter);
      form = new FormData(form);
      temp.parentNode.removeChild(temp);
      return form;
    }
    function extractEvents$1(dispatchQueue, domEventName, maybeTargetInst, nativeEvent, nativeEventTarget) {
      if ("submit" === domEventName && maybeTargetInst && maybeTargetInst.stateNode === nativeEventTarget) {
        var action = coerceFormActionProp(
          (nativeEventTarget[internalPropsKey] || null).action
        ), submitter = nativeEvent.submitter;
        submitter && (domEventName = (domEventName = submitter[internalPropsKey] || null) ? coerceFormActionProp(domEventName.formAction) : submitter.getAttribute("formAction"), null !== domEventName && (action = domEventName, submitter = null));
        var event = new SyntheticEvent(
          "action",
          "action",
          null,
          nativeEvent,
          nativeEventTarget
        );
        dispatchQueue.push({
          event,
          listeners: [
            {
              instance: null,
              listener: function() {
                if (nativeEvent.defaultPrevented) {
                  if (0 !== currentEventTransitionLane) {
                    var formData = submitter ? createFormDataWithSubmitter(
                      nativeEventTarget,
                      submitter
                    ) : new FormData(nativeEventTarget), pendingState = {
                      pending: true,
                      data: formData,
                      method: nativeEventTarget.method,
                      action
                    };
                    Object.freeze(pendingState);
                    startHostTransition(
                      maybeTargetInst,
                      pendingState,
                      null,
                      formData
                    );
                  }
                } else
                  "function" === typeof action && (event.preventDefault(), formData = submitter ? createFormDataWithSubmitter(
                    nativeEventTarget,
                    submitter
                  ) : new FormData(nativeEventTarget), pendingState = {
                    pending: true,
                    data: formData,
                    method: nativeEventTarget.method,
                    action
                  }, Object.freeze(pendingState), startHostTransition(
                    maybeTargetInst,
                    pendingState,
                    action,
                    formData
                  ));
              },
              currentTarget: nativeEventTarget
            }
          ]
        });
      }
    }
    function executeDispatch(event, listener, currentTarget) {
      event.currentTarget = currentTarget;
      try {
        listener(event);
      } catch (error) {
        reportGlobalError(error);
      }
      event.currentTarget = null;
    }
    function processDispatchQueue(dispatchQueue, eventSystemFlags) {
      eventSystemFlags = 0 !== (eventSystemFlags & 4);
      for (var i = 0; i < dispatchQueue.length; i++) {
        var _dispatchQueue$i = dispatchQueue[i];
        a: {
          var previousInstance = void 0, event = _dispatchQueue$i.event;
          _dispatchQueue$i = _dispatchQueue$i.listeners;
          if (eventSystemFlags)
            for (var i$jscomp$0 = _dispatchQueue$i.length - 1; 0 <= i$jscomp$0; i$jscomp$0--) {
              var _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget;
              _dispatchListeners$i = _dispatchListeners$i.listener;
              if (instance !== previousInstance && event.isPropagationStopped())
                break a;
              null !== instance ? runWithFiberInDEV(
                instance,
                executeDispatch,
                event,
                _dispatchListeners$i,
                currentTarget
              ) : executeDispatch(event, _dispatchListeners$i, currentTarget);
              previousInstance = instance;
            }
          else
            for (i$jscomp$0 = 0; i$jscomp$0 < _dispatchQueue$i.length; i$jscomp$0++) {
              _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0];
              instance = _dispatchListeners$i.instance;
              currentTarget = _dispatchListeners$i.currentTarget;
              _dispatchListeners$i = _dispatchListeners$i.listener;
              if (instance !== previousInstance && event.isPropagationStopped())
                break a;
              null !== instance ? runWithFiberInDEV(
                instance,
                executeDispatch,
                event,
                _dispatchListeners$i,
                currentTarget
              ) : executeDispatch(event, _dispatchListeners$i, currentTarget);
              previousInstance = instance;
            }
        }
      }
    }
    function listenToNonDelegatedEvent(domEventName, targetElement) {
      nonDelegatedEvents.has(domEventName) || console.error(
        'Did not expect a listenToNonDelegatedEvent() call for "%s". This is a bug in React. Please file an issue.',
        domEventName
      );
      var listenerSet = targetElement[internalEventHandlersKey];
      void 0 === listenerSet && (listenerSet = targetElement[internalEventHandlersKey] = /* @__PURE__ */ new Set());
      var listenerSetKey = domEventName + "__bubble";
      listenerSet.has(listenerSetKey) || (addTrappedEventListener(targetElement, domEventName, 2, false), listenerSet.add(listenerSetKey));
    }
    function listenToNativeEvent(domEventName, isCapturePhaseListener, target) {
      nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener && console.error(
        'Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. This is a bug in React. Please file an issue.',
        domEventName
      );
      var eventSystemFlags = 0;
      isCapturePhaseListener && (eventSystemFlags |= 4);
      addTrappedEventListener(
        target,
        domEventName,
        eventSystemFlags,
        isCapturePhaseListener
      );
    }
    function listenToAllSupportedEvents(rootContainerElement) {
      if (!rootContainerElement[listeningMarker]) {
        rootContainerElement[listeningMarker] = true;
        allNativeEvents.forEach(function(domEventName) {
          "selectionchange" !== domEventName && (nonDelegatedEvents.has(domEventName) || listenToNativeEvent(domEventName, false, rootContainerElement), listenToNativeEvent(domEventName, true, rootContainerElement));
        });
        var ownerDocument = 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
        null === ownerDocument || ownerDocument[listeningMarker] || (ownerDocument[listeningMarker] = true, listenToNativeEvent("selectionchange", false, ownerDocument));
      }
    }
    function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener) {
      switch (getEventPriority(domEventName)) {
        case DiscreteEventPriority:
          var listenerWrapper = dispatchDiscreteEvent;
          break;
        case ContinuousEventPriority:
          listenerWrapper = dispatchContinuousEvent;
          break;
        default:
          listenerWrapper = dispatchEvent;
      }
      eventSystemFlags = listenerWrapper.bind(
        null,
        domEventName,
        eventSystemFlags,
        targetContainer
      );
      listenerWrapper = void 0;
      !passiveBrowserEventsSupported || "touchstart" !== domEventName && "touchmove" !== domEventName && "wheel" !== domEventName || (listenerWrapper = true);
      isCapturePhaseListener ? void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
        capture: true,
        passive: listenerWrapper
      }) : targetContainer.addEventListener(domEventName, eventSystemFlags, true) : void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
        passive: listenerWrapper
      }) : targetContainer.addEventListener(
        domEventName,
        eventSystemFlags,
        false
      );
    }
    function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst$jscomp$0, targetContainer) {
      var ancestorInst = targetInst$jscomp$0;
      if (0 === (eventSystemFlags & 1) && 0 === (eventSystemFlags & 2) && null !== targetInst$jscomp$0)
        a: for (; ; ) {
          if (null === targetInst$jscomp$0) return;
          var nodeTag = targetInst$jscomp$0.tag;
          if (3 === nodeTag || 4 === nodeTag) {
            var container = targetInst$jscomp$0.stateNode.containerInfo;
            if (container === targetContainer) break;
            if (4 === nodeTag)
              for (nodeTag = targetInst$jscomp$0.return; null !== nodeTag; ) {
                var grandTag = nodeTag.tag;
                if ((3 === grandTag || 4 === grandTag) && nodeTag.stateNode.containerInfo === targetContainer)
                  return;
                nodeTag = nodeTag.return;
              }
            for (; null !== container; ) {
              nodeTag = getClosestInstanceFromNode(container);
              if (null === nodeTag) return;
              grandTag = nodeTag.tag;
              if (5 === grandTag || 6 === grandTag || 26 === grandTag || 27 === grandTag) {
                targetInst$jscomp$0 = ancestorInst = nodeTag;
                continue a;
              }
              container = container.parentNode;
            }
          }
          targetInst$jscomp$0 = targetInst$jscomp$0.return;
        }
      batchedUpdates$1(function() {
        var targetInst = ancestorInst, nativeEventTarget = getEventTarget(nativeEvent), dispatchQueue = [];
        a: {
          var reactName = topLevelEventsToReactNames.get(domEventName);
          if (void 0 !== reactName) {
            var SyntheticEventCtor = SyntheticEvent, reactEventType = domEventName;
            switch (domEventName) {
              case "keypress":
                if (0 === getEventCharCode(nativeEvent)) break a;
              case "keydown":
              case "keyup":
                SyntheticEventCtor = SyntheticKeyboardEvent;
                break;
              case "focusin":
                reactEventType = "focus";
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "focusout":
                reactEventType = "blur";
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "beforeblur":
              case "afterblur":
                SyntheticEventCtor = SyntheticFocusEvent;
                break;
              case "click":
                if (2 === nativeEvent.button) break a;
              case "auxclick":
              case "dblclick":
              case "mousedown":
              case "mousemove":
              case "mouseup":
              case "mouseout":
              case "mouseover":
              case "contextmenu":
                SyntheticEventCtor = SyntheticMouseEvent;
                break;
              case "drag":
              case "dragend":
              case "dragenter":
              case "dragexit":
              case "dragleave":
              case "dragover":
              case "dragstart":
              case "drop":
                SyntheticEventCtor = SyntheticDragEvent;
                break;
              case "touchcancel":
              case "touchend":
              case "touchmove":
              case "touchstart":
                SyntheticEventCtor = SyntheticTouchEvent;
                break;
              case ANIMATION_END:
              case ANIMATION_ITERATION:
              case ANIMATION_START:
                SyntheticEventCtor = SyntheticAnimationEvent;
                break;
              case TRANSITION_END:
                SyntheticEventCtor = SyntheticTransitionEvent;
                break;
              case "scroll":
              case "scrollend":
                SyntheticEventCtor = SyntheticUIEvent;
                break;
              case "wheel":
                SyntheticEventCtor = SyntheticWheelEvent;
                break;
              case "copy":
              case "cut":
              case "paste":
                SyntheticEventCtor = SyntheticClipboardEvent;
                break;
              case "gotpointercapture":
              case "lostpointercapture":
              case "pointercancel":
              case "pointerdown":
              case "pointermove":
              case "pointerout":
              case "pointerover":
              case "pointerup":
                SyntheticEventCtor = SyntheticPointerEvent;
                break;
              case "toggle":
              case "beforetoggle":
                SyntheticEventCtor = SyntheticToggleEvent;
            }
            var inCapturePhase = 0 !== (eventSystemFlags & 4), accumulateTargetOnly = !inCapturePhase && ("scroll" === domEventName || "scrollend" === domEventName), reactEventName = inCapturePhase ? null !== reactName ? reactName + "Capture" : null : reactName;
            inCapturePhase = [];
            for (var instance = targetInst, lastHostComponent; null !== instance; ) {
              var _instance2 = instance;
              lastHostComponent = _instance2.stateNode;
              _instance2 = _instance2.tag;
              5 !== _instance2 && 26 !== _instance2 && 27 !== _instance2 || null === lastHostComponent || null === reactEventName || (_instance2 = getListener(instance, reactEventName), null != _instance2 && inCapturePhase.push(
                createDispatchListener(
                  instance,
                  _instance2,
                  lastHostComponent
                )
              ));
              if (accumulateTargetOnly) break;
              instance = instance.return;
            }
            0 < inCapturePhase.length && (reactName = new SyntheticEventCtor(
              reactName,
              reactEventType,
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({
              event: reactName,
              listeners: inCapturePhase
            }));
          }
        }
        if (0 === (eventSystemFlags & 7)) {
          a: {
            reactName = "mouseover" === domEventName || "pointerover" === domEventName;
            SyntheticEventCtor = "mouseout" === domEventName || "pointerout" === domEventName;
            if (reactName && nativeEvent !== currentReplayingEvent && (reactEventType = nativeEvent.relatedTarget || nativeEvent.fromElement) && (getClosestInstanceFromNode(reactEventType) || reactEventType[internalContainerInstanceKey]))
              break a;
            if (SyntheticEventCtor || reactName) {
              reactName = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget : (reactName = nativeEventTarget.ownerDocument) ? reactName.defaultView || reactName.parentWindow : window;
              if (SyntheticEventCtor) {
                if (reactEventType = nativeEvent.relatedTarget || nativeEvent.toElement, SyntheticEventCtor = targetInst, reactEventType = reactEventType ? getClosestInstanceFromNode(reactEventType) : null, null !== reactEventType && (accumulateTargetOnly = getNearestMountedFiber(reactEventType), inCapturePhase = reactEventType.tag, reactEventType !== accumulateTargetOnly || 5 !== inCapturePhase && 27 !== inCapturePhase && 6 !== inCapturePhase))
                  reactEventType = null;
              } else SyntheticEventCtor = null, reactEventType = targetInst;
              if (SyntheticEventCtor !== reactEventType) {
                inCapturePhase = SyntheticMouseEvent;
                _instance2 = "onMouseLeave";
                reactEventName = "onMouseEnter";
                instance = "mouse";
                if ("pointerout" === domEventName || "pointerover" === domEventName)
                  inCapturePhase = SyntheticPointerEvent, _instance2 = "onPointerLeave", reactEventName = "onPointerEnter", instance = "pointer";
                accumulateTargetOnly = null == SyntheticEventCtor ? reactName : getNodeFromInstance(SyntheticEventCtor);
                lastHostComponent = null == reactEventType ? reactName : getNodeFromInstance(reactEventType);
                reactName = new inCapturePhase(
                  _instance2,
                  instance + "leave",
                  SyntheticEventCtor,
                  nativeEvent,
                  nativeEventTarget
                );
                reactName.target = accumulateTargetOnly;
                reactName.relatedTarget = lastHostComponent;
                _instance2 = null;
                getClosestInstanceFromNode(nativeEventTarget) === targetInst && (inCapturePhase = new inCapturePhase(
                  reactEventName,
                  instance + "enter",
                  reactEventType,
                  nativeEvent,
                  nativeEventTarget
                ), inCapturePhase.target = lastHostComponent, inCapturePhase.relatedTarget = accumulateTargetOnly, _instance2 = inCapturePhase);
                accumulateTargetOnly = _instance2;
                if (SyntheticEventCtor && reactEventType)
                  b: {
                    inCapturePhase = getParent;
                    reactEventName = SyntheticEventCtor;
                    instance = reactEventType;
                    lastHostComponent = 0;
                    for (_instance2 = reactEventName; _instance2; _instance2 = inCapturePhase(_instance2))
                      lastHostComponent++;
                    _instance2 = 0;
                    for (var tempB = instance; tempB; tempB = inCapturePhase(tempB))
                      _instance2++;
                    for (; 0 < lastHostComponent - _instance2; )
                      reactEventName = inCapturePhase(reactEventName), lastHostComponent--;
                    for (; 0 < _instance2 - lastHostComponent; )
                      instance = inCapturePhase(instance), _instance2--;
                    for (; lastHostComponent--; ) {
                      if (reactEventName === instance || null !== instance && reactEventName === instance.alternate) {
                        inCapturePhase = reactEventName;
                        break b;
                      }
                      reactEventName = inCapturePhase(reactEventName);
                      instance = inCapturePhase(instance);
                    }
                    inCapturePhase = null;
                  }
                else inCapturePhase = null;
                null !== SyntheticEventCtor && accumulateEnterLeaveListenersForEvent(
                  dispatchQueue,
                  reactName,
                  SyntheticEventCtor,
                  inCapturePhase,
                  false
                );
                null !== reactEventType && null !== accumulateTargetOnly && accumulateEnterLeaveListenersForEvent(
                  dispatchQueue,
                  accumulateTargetOnly,
                  reactEventType,
                  inCapturePhase,
                  true
                );
              }
            }
          }
          a: {
            reactName = targetInst ? getNodeFromInstance(targetInst) : window;
            SyntheticEventCtor = reactName.nodeName && reactName.nodeName.toLowerCase();
            if ("select" === SyntheticEventCtor || "input" === SyntheticEventCtor && "file" === reactName.type)
              var getTargetInstFunc = getTargetInstForChangeEvent;
            else if (isTextInputElement(reactName))
              if (isInputEventSupported)
                getTargetInstFunc = getTargetInstForInputOrChangeEvent;
              else {
                getTargetInstFunc = getTargetInstForInputEventPolyfill;
                var handleEventFunc = handleEventsForInputEventPolyfill;
              }
            else
              SyntheticEventCtor = reactName.nodeName, !SyntheticEventCtor || "input" !== SyntheticEventCtor.toLowerCase() || "checkbox" !== reactName.type && "radio" !== reactName.type ? targetInst && isCustomElement(targetInst.elementType) && (getTargetInstFunc = getTargetInstForChangeEvent) : getTargetInstFunc = getTargetInstForClickEvent;
            if (getTargetInstFunc && (getTargetInstFunc = getTargetInstFunc(domEventName, targetInst))) {
              createAndAccumulateChangeEvent(
                dispatchQueue,
                getTargetInstFunc,
                nativeEvent,
                nativeEventTarget
              );
              break a;
            }
            handleEventFunc && handleEventFunc(domEventName, reactName, targetInst);
            "focusout" === domEventName && targetInst && "number" === reactName.type && null != targetInst.memoizedProps.value && setDefaultValue(reactName, "number", reactName.value);
          }
          handleEventFunc = targetInst ? getNodeFromInstance(targetInst) : window;
          switch (domEventName) {
            case "focusin":
              if (isTextInputElement(handleEventFunc) || "true" === handleEventFunc.contentEditable)
                activeElement = handleEventFunc, activeElementInst = targetInst, lastSelection = null;
              break;
            case "focusout":
              lastSelection = activeElementInst = activeElement = null;
              break;
            case "mousedown":
              mouseDown = true;
              break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
              mouseDown = false;
              constructSelectEvent(
                dispatchQueue,
                nativeEvent,
                nativeEventTarget
              );
              break;
            case "selectionchange":
              if (skipSelectionChangeEvent) break;
            case "keydown":
            case "keyup":
              constructSelectEvent(
                dispatchQueue,
                nativeEvent,
                nativeEventTarget
              );
          }
          var fallbackData;
          if (canUseCompositionEvent)
            b: {
              switch (domEventName) {
                case "compositionstart":
                  var eventType = "onCompositionStart";
                  break b;
                case "compositionend":
                  eventType = "onCompositionEnd";
                  break b;
                case "compositionupdate":
                  eventType = "onCompositionUpdate";
                  break b;
              }
              eventType = void 0;
            }
          else
            isComposing ? isFallbackCompositionEnd(domEventName, nativeEvent) && (eventType = "onCompositionEnd") : "keydown" === domEventName && nativeEvent.keyCode === START_KEYCODE && (eventType = "onCompositionStart");
          eventType && (useFallbackCompositionData && "ko" !== nativeEvent.locale && (isComposing || "onCompositionStart" !== eventType ? "onCompositionEnd" === eventType && isComposing && (fallbackData = getData()) : (root2 = nativeEventTarget, startText = "value" in root2 ? root2.value : root2.textContent, isComposing = true)), handleEventFunc = accumulateTwoPhaseListeners(
            targetInst,
            eventType
          ), 0 < handleEventFunc.length && (eventType = new SyntheticCompositionEvent(
            eventType,
            domEventName,
            null,
            nativeEvent,
            nativeEventTarget
          ), dispatchQueue.push({
            event: eventType,
            listeners: handleEventFunc
          }), fallbackData ? eventType.data = fallbackData : (fallbackData = getDataFromCustomEvent(nativeEvent), null !== fallbackData && (eventType.data = fallbackData))));
          if (fallbackData = canUseTextInputEvent ? getNativeBeforeInputChars(domEventName, nativeEvent) : getFallbackBeforeInputChars(domEventName, nativeEvent))
            eventType = accumulateTwoPhaseListeners(
              targetInst,
              "onBeforeInput"
            ), 0 < eventType.length && (handleEventFunc = new SyntheticInputEvent(
              "onBeforeInput",
              "beforeinput",
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({
              event: handleEventFunc,
              listeners: eventType
            }), handleEventFunc.data = fallbackData);
          extractEvents$1(
            dispatchQueue,
            domEventName,
            targetInst,
            nativeEvent,
            nativeEventTarget
          );
        }
        processDispatchQueue(dispatchQueue, eventSystemFlags);
      });
    }
    function createDispatchListener(instance, listener, currentTarget) {
      return {
        instance,
        listener,
        currentTarget
      };
    }
    function accumulateTwoPhaseListeners(targetFiber, reactName) {
      for (var captureName = reactName + "Capture", listeners = []; null !== targetFiber; ) {
        var _instance3 = targetFiber, stateNode = _instance3.stateNode;
        _instance3 = _instance3.tag;
        5 !== _instance3 && 26 !== _instance3 && 27 !== _instance3 || null === stateNode || (_instance3 = getListener(targetFiber, captureName), null != _instance3 && listeners.unshift(
          createDispatchListener(targetFiber, _instance3, stateNode)
        ), _instance3 = getListener(targetFiber, reactName), null != _instance3 && listeners.push(
          createDispatchListener(targetFiber, _instance3, stateNode)
        ));
        if (3 === targetFiber.tag) return listeners;
        targetFiber = targetFiber.return;
      }
      return [];
    }
    function getParent(inst) {
      if (null === inst) return null;
      do
        inst = inst.return;
      while (inst && 5 !== inst.tag && 27 !== inst.tag);
      return inst ? inst : null;
    }
    function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target, common2, inCapturePhase) {
      for (var registrationName = event._reactName, listeners = []; null !== target && target !== common2; ) {
        var _instance4 = target, alternate = _instance4.alternate, stateNode = _instance4.stateNode;
        _instance4 = _instance4.tag;
        if (null !== alternate && alternate === common2) break;
        5 !== _instance4 && 26 !== _instance4 && 27 !== _instance4 || null === stateNode || (alternate = stateNode, inCapturePhase ? (stateNode = getListener(target, registrationName), null != stateNode && listeners.unshift(
          createDispatchListener(target, stateNode, alternate)
        )) : inCapturePhase || (stateNode = getListener(target, registrationName), null != stateNode && listeners.push(
          createDispatchListener(target, stateNode, alternate)
        )));
        target = target.return;
      }
      0 !== listeners.length && dispatchQueue.push({ event, listeners });
    }
    function validatePropertiesInDevelopment(type2, props) {
      validateProperties$2(type2, props);
      "input" !== type2 && "textarea" !== type2 && "select" !== type2 || null == props || null !== props.value || didWarnValueNull || (didWarnValueNull = true, "select" === type2 && props.multiple ? console.error(
        "`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.",
        type2
      ) : console.error(
        "`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.",
        type2
      ));
      var eventRegistry = {
        registrationNameDependencies,
        possibleRegistrationNames
      };
      isCustomElement(type2) || "string" === typeof props.is || warnUnknownProperties(type2, props, eventRegistry);
      props.contentEditable && !props.suppressContentEditableWarning && null != props.children && console.error(
        "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."
      );
    }
    function warnForPropDifference(propName, serverValue, clientValue, serverDifferences) {
      serverValue !== clientValue && (clientValue = normalizeMarkupForTextOrAttribute(clientValue), normalizeMarkupForTextOrAttribute(serverValue) !== clientValue && (serverDifferences[propName] = serverValue));
    }
    function warnForExtraAttributes(domElement, attributeNames, serverDifferences) {
      attributeNames.forEach(function(attributeName) {
        serverDifferences[getPropNameFromAttributeName(attributeName)] = "style" === attributeName ? getStylesObjectFromElement(domElement) : domElement.getAttribute(attributeName);
      });
    }
    function warnForInvalidEventListener(registrationName, listener) {
      false === listener ? console.error(
        "Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.",
        registrationName,
        registrationName,
        registrationName
      ) : console.error(
        "Expected `%s` listener to be a function, instead got a value of `%s` type.",
        registrationName,
        typeof listener
      );
    }
    function normalizeHTML(parent, html2) {
      parent = parent.namespaceURI === MATH_NAMESPACE || parent.namespaceURI === SVG_NAMESPACE ? parent.ownerDocument.createElementNS(
        parent.namespaceURI,
        parent.tagName
      ) : parent.ownerDocument.createElement(parent.tagName);
      parent.innerHTML = html2;
      return parent.innerHTML;
    }
    function normalizeMarkupForTextOrAttribute(markup) {
      willCoercionThrow(markup) && (console.error(
        "The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before using it here.",
        typeName(markup)
      ), testStringCoercion(markup));
      return ("string" === typeof markup ? markup : "" + markup).replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
    }
    function checkForUnmatchedText(serverText, clientText) {
      clientText = normalizeMarkupForTextOrAttribute(clientText);
      return normalizeMarkupForTextOrAttribute(serverText) === clientText ? true : false;
    }
    function setProp(domElement, tag, key, value, props, prevValue) {
      switch (key) {
        case "children":
          if ("string" === typeof value)
            validateTextNesting(value, tag, false), "body" === tag || "textarea" === tag && "" === value || setTextContent(domElement, value);
          else if ("number" === typeof value || "bigint" === typeof value)
            validateTextNesting("" + value, tag, false), "body" !== tag && setTextContent(domElement, "" + value);
          break;
        case "className":
          setValueForKnownAttribute(domElement, "class", value);
          break;
        case "tabIndex":
          setValueForKnownAttribute(domElement, "tabindex", value);
          break;
        case "dir":
        case "role":
        case "viewBox":
        case "width":
        case "height":
          setValueForKnownAttribute(domElement, key, value);
          break;
        case "style":
          setValueForStyles(domElement, value, prevValue);
          break;
        case "data":
          if ("object" !== tag) {
            setValueForKnownAttribute(domElement, "data", value);
            break;
          }
        case "src":
        case "href":
          if ("" === value && ("a" !== tag || "href" !== key)) {
            "src" === key ? console.error(
              'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              key,
              key
            ) : console.error(
              'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              key,
              key
            );
            domElement.removeAttribute(key);
            break;
          }
          if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value) {
            domElement.removeAttribute(key);
            break;
          }
          checkAttributeStringCoercion(value, key);
          value = sanitizeURL("" + value);
          domElement.setAttribute(key, value);
          break;
        case "action":
        case "formAction":
          null != value && ("form" === tag ? "formAction" === key ? console.error(
            "You can only pass the formAction prop to <input> or <button>. Use the action prop on <form>."
          ) : "function" === typeof value && (null == props.encType && null == props.method || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
            "Cannot specify a encType or method for a form that specifies a function as the action. React provides those automatically. They will get overridden."
          )), null == props.target || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
            "Cannot specify a target for a form that specifies a function as the action. The function will always be executed in the same window."
          ))) : "input" === tag || "button" === tag ? "action" === key ? console.error(
            "You can only pass the action prop to <form>. Use the formAction prop on <input> or <button>."
          ) : "input" !== tag || "submit" === props.type || "image" === props.type || didWarnFormActionType ? "button" !== tag || null == props.type || "submit" === props.type || didWarnFormActionType ? "function" === typeof value && (null == props.name || didWarnFormActionName || (didWarnFormActionName = true, console.error(
            'Cannot specify a "name" prop for a button that specifies a function as a formAction. React needs it to encode which action should be invoked. It will get overridden.'
          )), null == props.formEncType && null == props.formMethod || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
            "Cannot specify a formEncType or formMethod for a button that specifies a function as a formAction. React provides those automatically. They will get overridden."
          )), null == props.formTarget || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
            "Cannot specify a formTarget for a button that specifies a function as a formAction. The function will always be executed in the same window."
          ))) : (didWarnFormActionType = true, console.error(
            'A button can only specify a formAction along with type="submit" or no type.'
          )) : (didWarnFormActionType = true, console.error(
            'An input can only specify a formAction along with type="submit" or type="image".'
          )) : "action" === key ? console.error(
            "You can only pass the action prop to <form>."
          ) : console.error(
            "You can only pass the formAction prop to <input> or <button>."
          ));
          if ("function" === typeof value) {
            domElement.setAttribute(
              key,
              "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
            );
            break;
          } else
            "function" === typeof prevValue && ("formAction" === key ? ("input" !== tag && setProp(domElement, tag, "name", props.name, props, null), setProp(
              domElement,
              tag,
              "formEncType",
              props.formEncType,
              props,
              null
            ), setProp(
              domElement,
              tag,
              "formMethod",
              props.formMethod,
              props,
              null
            ), setProp(
              domElement,
              tag,
              "formTarget",
              props.formTarget,
              props,
              null
            )) : (setProp(
              domElement,
              tag,
              "encType",
              props.encType,
              props,
              null
            ), setProp(domElement, tag, "method", props.method, props, null), setProp(
              domElement,
              tag,
              "target",
              props.target,
              props,
              null
            )));
          if (null == value || "symbol" === typeof value || "boolean" === typeof value) {
            domElement.removeAttribute(key);
            break;
          }
          checkAttributeStringCoercion(value, key);
          value = sanitizeURL("" + value);
          domElement.setAttribute(key, value);
          break;
        case "onClick":
          null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), domElement.onclick = noop$1);
          break;
        case "onScroll":
          null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scroll", domElement));
          break;
        case "onScrollEnd":
          null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scrollend", domElement));
          break;
        case "dangerouslySetInnerHTML":
          if (null != value) {
            if ("object" !== typeof value || !("__html" in value))
              throw Error(
                "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
              );
            key = value.__html;
            if (null != key) {
              if (null != props.children)
                throw Error(
                  "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
                );
              domElement.innerHTML = key;
            }
          }
          break;
        case "multiple":
          domElement.multiple = value && "function" !== typeof value && "symbol" !== typeof value;
          break;
        case "muted":
          domElement.muted = value && "function" !== typeof value && "symbol" !== typeof value;
          break;
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          break;
        case "autoFocus":
          break;
        case "xlinkHref":
          if (null == value || "function" === typeof value || "boolean" === typeof value || "symbol" === typeof value) {
            domElement.removeAttribute("xlink:href");
            break;
          }
          checkAttributeStringCoercion(value, key);
          key = sanitizeURL("" + value);
          domElement.setAttributeNS(xlinkNamespace, "xlink:href", key);
          break;
        case "contentEditable":
        case "spellCheck":
        case "draggable":
        case "value":
        case "autoReverse":
        case "externalResourcesRequired":
        case "focusable":
        case "preserveAlpha":
          null != value && "function" !== typeof value && "symbol" !== typeof value ? (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, "" + value)) : domElement.removeAttribute(key);
          break;
        case "inert":
          "" !== value || didWarnForNewBooleanPropsWithEmptyValue[key] || (didWarnForNewBooleanPropsWithEmptyValue[key] = true, console.error(
            "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
            key
          ));
        case "allowFullScreen":
        case "async":
        case "autoPlay":
        case "controls":
        case "default":
        case "defer":
        case "disabled":
        case "disablePictureInPicture":
        case "disableRemotePlayback":
        case "formNoValidate":
        case "hidden":
        case "loop":
        case "noModule":
        case "noValidate":
        case "open":
        case "playsInline":
        case "readOnly":
        case "required":
        case "reversed":
        case "scoped":
        case "seamless":
        case "itemScope":
          value && "function" !== typeof value && "symbol" !== typeof value ? domElement.setAttribute(key, "") : domElement.removeAttribute(key);
          break;
        case "capture":
        case "download":
          true === value ? domElement.setAttribute(key, "") : false !== value && null != value && "function" !== typeof value && "symbol" !== typeof value ? (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, value)) : domElement.removeAttribute(key);
          break;
        case "cols":
        case "rows":
        case "size":
        case "span":
          null != value && "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value ? (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, value)) : domElement.removeAttribute(key);
          break;
        case "rowSpan":
        case "start":
          null == value || "function" === typeof value || "symbol" === typeof value || isNaN(value) ? domElement.removeAttribute(key) : (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, value));
          break;
        case "popover":
          listenToNonDelegatedEvent("beforetoggle", domElement);
          listenToNonDelegatedEvent("toggle", domElement);
          setValueForAttribute(domElement, "popover", value);
          break;
        case "xlinkActuate":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:actuate",
            value
          );
          break;
        case "xlinkArcrole":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:arcrole",
            value
          );
          break;
        case "xlinkRole":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:role",
            value
          );
          break;
        case "xlinkShow":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:show",
            value
          );
          break;
        case "xlinkTitle":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:title",
            value
          );
          break;
        case "xlinkType":
          setValueForNamespacedAttribute(
            domElement,
            xlinkNamespace,
            "xlink:type",
            value
          );
          break;
        case "xmlBase":
          setValueForNamespacedAttribute(
            domElement,
            xmlNamespace,
            "xml:base",
            value
          );
          break;
        case "xmlLang":
          setValueForNamespacedAttribute(
            domElement,
            xmlNamespace,
            "xml:lang",
            value
          );
          break;
        case "xmlSpace":
          setValueForNamespacedAttribute(
            domElement,
            xmlNamespace,
            "xml:space",
            value
          );
          break;
        case "is":
          null != prevValue && console.error(
            'Cannot update the "is" prop after it has been initialized.'
          );
          setValueForAttribute(domElement, "is", value);
          break;
        case "innerText":
        case "textContent":
          break;
        case "popoverTarget":
          didWarnPopoverTargetObject || null == value || "object" !== typeof value || (didWarnPopoverTargetObject = true, console.error(
            "The `popoverTarget` prop expects the ID of an Element as a string. Received %s instead.",
            value
          ));
        default:
          !(2 < key.length) || "o" !== key[0] && "O" !== key[0] || "n" !== key[1] && "N" !== key[1] ? (key = getAttributeAlias(key), setValueForAttribute(domElement, key, value)) : registrationNameDependencies.hasOwnProperty(key) && null != value && "function" !== typeof value && warnForInvalidEventListener(key, value);
      }
    }
    function setPropOnCustomElement(domElement, tag, key, value, props, prevValue) {
      switch (key) {
        case "style":
          setValueForStyles(domElement, value, prevValue);
          break;
        case "dangerouslySetInnerHTML":
          if (null != value) {
            if ("object" !== typeof value || !("__html" in value))
              throw Error(
                "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
              );
            key = value.__html;
            if (null != key) {
              if (null != props.children)
                throw Error(
                  "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
                );
              domElement.innerHTML = key;
            }
          }
          break;
        case "children":
          "string" === typeof value ? setTextContent(domElement, value) : ("number" === typeof value || "bigint" === typeof value) && setTextContent(domElement, "" + value);
          break;
        case "onScroll":
          null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scroll", domElement));
          break;
        case "onScrollEnd":
          null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scrollend", domElement));
          break;
        case "onClick":
          null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), domElement.onclick = noop$1);
          break;
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "innerHTML":
        case "ref":
          break;
        case "innerText":
        case "textContent":
          break;
        default:
          if (registrationNameDependencies.hasOwnProperty(key))
            null != value && "function" !== typeof value && warnForInvalidEventListener(key, value);
          else
            a: {
              if ("o" === key[0] && "n" === key[1] && (props = key.endsWith("Capture"), tag = key.slice(2, props ? key.length - 7 : void 0), prevValue = domElement[internalPropsKey] || null, prevValue = null != prevValue ? prevValue[key] : null, "function" === typeof prevValue && domElement.removeEventListener(tag, prevValue, props), "function" === typeof value)) {
                "function" !== typeof prevValue && null !== prevValue && (key in domElement ? domElement[key] = null : domElement.hasAttribute(key) && domElement.removeAttribute(key));
                domElement.addEventListener(tag, value, props);
                break a;
              }
              key in domElement ? domElement[key] = value : true === value ? domElement.setAttribute(key, "") : setValueForAttribute(domElement, key, value);
            }
      }
    }
    function setInitialProperties(domElement, tag, props) {
      validatePropertiesInDevelopment(tag, props);
      switch (tag) {
        case "div":
        case "span":
        case "svg":
        case "path":
        case "a":
        case "g":
        case "p":
        case "li":
          break;
        case "img":
          listenToNonDelegatedEvent("error", domElement);
          listenToNonDelegatedEvent("load", domElement);
          var hasSrc = false, hasSrcSet = false, propKey;
          for (propKey in props)
            if (props.hasOwnProperty(propKey)) {
              var propValue = props[propKey];
              if (null != propValue)
                switch (propKey) {
                  case "src":
                    hasSrc = true;
                    break;
                  case "srcSet":
                    hasSrcSet = true;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  default:
                    setProp(domElement, tag, propKey, propValue, props, null);
                }
            }
          hasSrcSet && setProp(domElement, tag, "srcSet", props.srcSet, props, null);
          hasSrc && setProp(domElement, tag, "src", props.src, props, null);
          return;
        case "input":
          checkControlledValueProps("input", props);
          listenToNonDelegatedEvent("invalid", domElement);
          var defaultValue = propKey = propValue = hasSrcSet = null, checked = null, defaultChecked = null;
          for (hasSrc in props)
            if (props.hasOwnProperty(hasSrc)) {
              var _propValue = props[hasSrc];
              if (null != _propValue)
                switch (hasSrc) {
                  case "name":
                    hasSrcSet = _propValue;
                    break;
                  case "type":
                    propValue = _propValue;
                    break;
                  case "checked":
                    checked = _propValue;
                    break;
                  case "defaultChecked":
                    defaultChecked = _propValue;
                    break;
                  case "value":
                    propKey = _propValue;
                    break;
                  case "defaultValue":
                    defaultValue = _propValue;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    if (null != _propValue)
                      throw Error(
                        tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                      );
                    break;
                  default:
                    setProp(domElement, tag, hasSrc, _propValue, props, null);
                }
            }
          validateInputProps(domElement, props);
          initInput(
            domElement,
            propKey,
            defaultValue,
            checked,
            defaultChecked,
            propValue,
            hasSrcSet,
            false
          );
          return;
        case "select":
          checkControlledValueProps("select", props);
          listenToNonDelegatedEvent("invalid", domElement);
          hasSrc = propValue = propKey = null;
          for (hasSrcSet in props)
            if (props.hasOwnProperty(hasSrcSet) && (defaultValue = props[hasSrcSet], null != defaultValue))
              switch (hasSrcSet) {
                case "value":
                  propKey = defaultValue;
                  break;
                case "defaultValue":
                  propValue = defaultValue;
                  break;
                case "multiple":
                  hasSrc = defaultValue;
                default:
                  setProp(
                    domElement,
                    tag,
                    hasSrcSet,
                    defaultValue,
                    props,
                    null
                  );
              }
          validateSelectProps(domElement, props);
          tag = propKey;
          props = propValue;
          domElement.multiple = !!hasSrc;
          null != tag ? updateOptions(domElement, !!hasSrc, tag, false) : null != props && updateOptions(domElement, !!hasSrc, props, true);
          return;
        case "textarea":
          checkControlledValueProps("textarea", props);
          listenToNonDelegatedEvent("invalid", domElement);
          propKey = hasSrcSet = hasSrc = null;
          for (propValue in props)
            if (props.hasOwnProperty(propValue) && (defaultValue = props[propValue], null != defaultValue))
              switch (propValue) {
                case "value":
                  hasSrc = defaultValue;
                  break;
                case "defaultValue":
                  hasSrcSet = defaultValue;
                  break;
                case "children":
                  propKey = defaultValue;
                  break;
                case "dangerouslySetInnerHTML":
                  if (null != defaultValue)
                    throw Error(
                      "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                    );
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    propValue,
                    defaultValue,
                    props,
                    null
                  );
              }
          validateTextareaProps(domElement, props);
          initTextarea(domElement, hasSrc, hasSrcSet, propKey);
          return;
        case "option":
          validateOptionProps(domElement, props);
          for (checked in props)
            if (props.hasOwnProperty(checked) && (hasSrc = props[checked], null != hasSrc))
              switch (checked) {
                case "selected":
                  domElement.selected = hasSrc && "function" !== typeof hasSrc && "symbol" !== typeof hasSrc;
                  break;
                default:
                  setProp(domElement, tag, checked, hasSrc, props, null);
              }
          return;
        case "dialog":
          listenToNonDelegatedEvent("beforetoggle", domElement);
          listenToNonDelegatedEvent("toggle", domElement);
          listenToNonDelegatedEvent("cancel", domElement);
          listenToNonDelegatedEvent("close", domElement);
          break;
        case "iframe":
        case "object":
          listenToNonDelegatedEvent("load", domElement);
          break;
        case "video":
        case "audio":
          for (hasSrc = 0; hasSrc < mediaEventTypes.length; hasSrc++)
            listenToNonDelegatedEvent(mediaEventTypes[hasSrc], domElement);
          break;
        case "image":
          listenToNonDelegatedEvent("error", domElement);
          listenToNonDelegatedEvent("load", domElement);
          break;
        case "details":
          listenToNonDelegatedEvent("toggle", domElement);
          break;
        case "embed":
        case "source":
        case "link":
          listenToNonDelegatedEvent("error", domElement), listenToNonDelegatedEvent("load", domElement);
        case "area":
        case "base":
        case "br":
        case "col":
        case "hr":
        case "keygen":
        case "meta":
        case "param":
        case "track":
        case "wbr":
        case "menuitem":
          for (defaultChecked in props)
            if (props.hasOwnProperty(defaultChecked) && (hasSrc = props[defaultChecked], null != hasSrc))
              switch (defaultChecked) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                  );
                default:
                  setProp(domElement, tag, defaultChecked, hasSrc, props, null);
              }
          return;
        default:
          if (isCustomElement(tag)) {
            for (_propValue in props)
              props.hasOwnProperty(_propValue) && (hasSrc = props[_propValue], void 0 !== hasSrc && setPropOnCustomElement(
                domElement,
                tag,
                _propValue,
                hasSrc,
                props,
                void 0
              ));
            return;
          }
      }
      for (defaultValue in props)
        props.hasOwnProperty(defaultValue) && (hasSrc = props[defaultValue], null != hasSrc && setProp(domElement, tag, defaultValue, hasSrc, props, null));
    }
    function updateProperties(domElement, tag, lastProps, nextProps) {
      validatePropertiesInDevelopment(tag, nextProps);
      switch (tag) {
        case "div":
        case "span":
        case "svg":
        case "path":
        case "a":
        case "g":
        case "p":
        case "li":
          break;
        case "input":
          var name2 = null, type2 = null, value = null, defaultValue = null, lastDefaultValue = null, checked = null, defaultChecked = null;
          for (propKey in lastProps) {
            var lastProp = lastProps[propKey];
            if (lastProps.hasOwnProperty(propKey) && null != lastProp)
              switch (propKey) {
                case "checked":
                  break;
                case "value":
                  break;
                case "defaultValue":
                  lastDefaultValue = lastProp;
                default:
                  nextProps.hasOwnProperty(propKey) || setProp(
                    domElement,
                    tag,
                    propKey,
                    null,
                    nextProps,
                    lastProp
                  );
              }
          }
          for (var _propKey8 in nextProps) {
            var propKey = nextProps[_propKey8];
            lastProp = lastProps[_propKey8];
            if (nextProps.hasOwnProperty(_propKey8) && (null != propKey || null != lastProp))
              switch (_propKey8) {
                case "type":
                  type2 = propKey;
                  break;
                case "name":
                  name2 = propKey;
                  break;
                case "checked":
                  checked = propKey;
                  break;
                case "defaultChecked":
                  defaultChecked = propKey;
                  break;
                case "value":
                  value = propKey;
                  break;
                case "defaultValue":
                  defaultValue = propKey;
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != propKey)
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  break;
                default:
                  propKey !== lastProp && setProp(
                    domElement,
                    tag,
                    _propKey8,
                    propKey,
                    nextProps,
                    lastProp
                  );
              }
          }
          tag = "checkbox" === lastProps.type || "radio" === lastProps.type ? null != lastProps.checked : null != lastProps.value;
          nextProps = "checkbox" === nextProps.type || "radio" === nextProps.type ? null != nextProps.checked : null != nextProps.value;
          tag || !nextProps || didWarnUncontrolledToControlled || (console.error(
            "A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://react.dev/link/controlled-components"
          ), didWarnUncontrolledToControlled = true);
          !tag || nextProps || didWarnControlledToUncontrolled || (console.error(
            "A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://react.dev/link/controlled-components"
          ), didWarnControlledToUncontrolled = true);
          updateInput(
            domElement,
            value,
            defaultValue,
            lastDefaultValue,
            checked,
            defaultChecked,
            type2,
            name2
          );
          return;
        case "select":
          propKey = value = defaultValue = _propKey8 = null;
          for (type2 in lastProps)
            if (lastDefaultValue = lastProps[type2], lastProps.hasOwnProperty(type2) && null != lastDefaultValue)
              switch (type2) {
                case "value":
                  break;
                case "multiple":
                  propKey = lastDefaultValue;
                default:
                  nextProps.hasOwnProperty(type2) || setProp(
                    domElement,
                    tag,
                    type2,
                    null,
                    nextProps,
                    lastDefaultValue
                  );
              }
          for (name2 in nextProps)
            if (type2 = nextProps[name2], lastDefaultValue = lastProps[name2], nextProps.hasOwnProperty(name2) && (null != type2 || null != lastDefaultValue))
              switch (name2) {
                case "value":
                  _propKey8 = type2;
                  break;
                case "defaultValue":
                  defaultValue = type2;
                  break;
                case "multiple":
                  value = type2;
                default:
                  type2 !== lastDefaultValue && setProp(
                    domElement,
                    tag,
                    name2,
                    type2,
                    nextProps,
                    lastDefaultValue
                  );
              }
          nextProps = defaultValue;
          tag = value;
          lastProps = propKey;
          null != _propKey8 ? updateOptions(domElement, !!tag, _propKey8, false) : !!lastProps !== !!tag && (null != nextProps ? updateOptions(domElement, !!tag, nextProps, true) : updateOptions(domElement, !!tag, tag ? [] : "", false));
          return;
        case "textarea":
          propKey = _propKey8 = null;
          for (defaultValue in lastProps)
            if (name2 = lastProps[defaultValue], lastProps.hasOwnProperty(defaultValue) && null != name2 && !nextProps.hasOwnProperty(defaultValue))
              switch (defaultValue) {
                case "value":
                  break;
                case "children":
                  break;
                default:
                  setProp(domElement, tag, defaultValue, null, nextProps, name2);
              }
          for (value in nextProps)
            if (name2 = nextProps[value], type2 = lastProps[value], nextProps.hasOwnProperty(value) && (null != name2 || null != type2))
              switch (value) {
                case "value":
                  _propKey8 = name2;
                  break;
                case "defaultValue":
                  propKey = name2;
                  break;
                case "children":
                  break;
                case "dangerouslySetInnerHTML":
                  if (null != name2)
                    throw Error(
                      "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                    );
                  break;
                default:
                  name2 !== type2 && setProp(domElement, tag, value, name2, nextProps, type2);
              }
          updateTextarea(domElement, _propKey8, propKey);
          return;
        case "option":
          for (var _propKey13 in lastProps)
            if (_propKey8 = lastProps[_propKey13], lastProps.hasOwnProperty(_propKey13) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey13))
              switch (_propKey13) {
                case "selected":
                  domElement.selected = false;
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    _propKey13,
                    null,
                    nextProps,
                    _propKey8
                  );
              }
          for (lastDefaultValue in nextProps)
            if (_propKey8 = nextProps[lastDefaultValue], propKey = lastProps[lastDefaultValue], nextProps.hasOwnProperty(lastDefaultValue) && _propKey8 !== propKey && (null != _propKey8 || null != propKey))
              switch (lastDefaultValue) {
                case "selected":
                  domElement.selected = _propKey8 && "function" !== typeof _propKey8 && "symbol" !== typeof _propKey8;
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    lastDefaultValue,
                    _propKey8,
                    nextProps,
                    propKey
                  );
              }
          return;
        case "img":
        case "link":
        case "area":
        case "base":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "keygen":
        case "meta":
        case "param":
        case "source":
        case "track":
        case "wbr":
        case "menuitem":
          for (var _propKey15 in lastProps)
            _propKey8 = lastProps[_propKey15], lastProps.hasOwnProperty(_propKey15) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey15) && setProp(
              domElement,
              tag,
              _propKey15,
              null,
              nextProps,
              _propKey8
            );
          for (checked in nextProps)
            if (_propKey8 = nextProps[checked], propKey = lastProps[checked], nextProps.hasOwnProperty(checked) && _propKey8 !== propKey && (null != _propKey8 || null != propKey))
              switch (checked) {
                case "children":
                case "dangerouslySetInnerHTML":
                  if (null != _propKey8)
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  break;
                default:
                  setProp(
                    domElement,
                    tag,
                    checked,
                    _propKey8,
                    nextProps,
                    propKey
                  );
              }
          return;
        default:
          if (isCustomElement(tag)) {
            for (var _propKey17 in lastProps)
              _propKey8 = lastProps[_propKey17], lastProps.hasOwnProperty(_propKey17) && void 0 !== _propKey8 && !nextProps.hasOwnProperty(_propKey17) && setPropOnCustomElement(
                domElement,
                tag,
                _propKey17,
                void 0,
                nextProps,
                _propKey8
              );
            for (defaultChecked in nextProps)
              _propKey8 = nextProps[defaultChecked], propKey = lastProps[defaultChecked], !nextProps.hasOwnProperty(defaultChecked) || _propKey8 === propKey || void 0 === _propKey8 && void 0 === propKey || setPropOnCustomElement(
                domElement,
                tag,
                defaultChecked,
                _propKey8,
                nextProps,
                propKey
              );
            return;
          }
      }
      for (var _propKey19 in lastProps)
        _propKey8 = lastProps[_propKey19], lastProps.hasOwnProperty(_propKey19) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey19) && setProp(domElement, tag, _propKey19, null, nextProps, _propKey8);
      for (lastProp in nextProps)
        _propKey8 = nextProps[lastProp], propKey = lastProps[lastProp], !nextProps.hasOwnProperty(lastProp) || _propKey8 === propKey || null == _propKey8 && null == propKey || setProp(domElement, tag, lastProp, _propKey8, nextProps, propKey);
    }
    function getPropNameFromAttributeName(attrName) {
      switch (attrName) {
        case "class":
          return "className";
        case "for":
          return "htmlFor";
        default:
          return attrName;
      }
    }
    function getStylesObjectFromElement(domElement) {
      var serverValueInObjectForm = {};
      domElement = domElement.style;
      for (var i = 0; i < domElement.length; i++) {
        var styleName = domElement[i];
        serverValueInObjectForm[styleName] = domElement.getPropertyValue(styleName);
      }
      return serverValueInObjectForm;
    }
    function diffHydratedStyles(domElement, value$jscomp$0, serverDifferences) {
      if (null != value$jscomp$0 && "object" !== typeof value$jscomp$0)
        console.error(
          "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
        );
      else {
        var clientValue;
        var delimiter = clientValue = "", styleName;
        for (styleName in value$jscomp$0)
          if (value$jscomp$0.hasOwnProperty(styleName)) {
            var value = value$jscomp$0[styleName];
            null != value && "boolean" !== typeof value && "" !== value && (0 === styleName.indexOf("--") ? (checkCSSPropertyStringCoercion(value, styleName), clientValue += delimiter + styleName + ":" + ("" + value).trim()) : "number" !== typeof value || 0 === value || unitlessNumbers.has(styleName) ? (checkCSSPropertyStringCoercion(value, styleName), clientValue += delimiter + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-") + ":" + ("" + value).trim()) : clientValue += delimiter + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-") + ":" + value + "px", delimiter = ";");
          }
        clientValue = clientValue || null;
        value$jscomp$0 = domElement.getAttribute("style");
        value$jscomp$0 !== clientValue && (clientValue = normalizeMarkupForTextOrAttribute(clientValue), normalizeMarkupForTextOrAttribute(value$jscomp$0) !== clientValue && (serverDifferences.style = getStylesObjectFromElement(domElement)));
      }
    }
    function hydrateAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            return;
        }
      else if (null != value)
        switch (typeof value) {
          case "function":
          case "symbol":
          case "boolean":
            break;
          default:
            if (checkAttributeStringCoercion(value, propKey), domElement === "" + value)
              return;
        }
      warnForPropDifference(propKey, domElement, value, serverDifferences);
    }
    function hydrateBooleanAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement) {
        switch (typeof value) {
          case "function":
          case "symbol":
            return;
        }
        if (!value) return;
      } else
        switch (typeof value) {
          case "function":
          case "symbol":
            break;
          default:
            if (value) return;
        }
      warnForPropDifference(propKey, domElement, value, serverDifferences);
    }
    function hydrateBooleanishAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
            return;
        }
      else if (null != value)
        switch (typeof value) {
          case "function":
          case "symbol":
            break;
          default:
            if (checkAttributeStringCoercion(value, attributeName), domElement === "" + value)
              return;
        }
      warnForPropDifference(propKey, domElement, value, serverDifferences);
    }
    function hydrateNumericAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            return;
          default:
            if (isNaN(value)) return;
        }
      else if (null != value)
        switch (typeof value) {
          case "function":
          case "symbol":
          case "boolean":
            break;
          default:
            if (!isNaN(value) && (checkAttributeStringCoercion(value, propKey), domElement === "" + value))
              return;
        }
      warnForPropDifference(propKey, domElement, value, serverDifferences);
    }
    function hydrateSanitizedAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
      extraAttributes.delete(attributeName);
      domElement = domElement.getAttribute(attributeName);
      if (null === domElement)
        switch (typeof value) {
          case "undefined":
          case "function":
          case "symbol":
          case "boolean":
            return;
        }
      else if (null != value)
        switch (typeof value) {
          case "function":
          case "symbol":
          case "boolean":
            break;
          default:
            if (checkAttributeStringCoercion(value, propKey), attributeName = sanitizeURL("" + value), domElement === attributeName)
              return;
        }
      warnForPropDifference(propKey, domElement, value, serverDifferences);
    }
    function diffHydratedProperties(domElement, tag, props, hostContext) {
      for (var serverDifferences = {}, extraAttributes = /* @__PURE__ */ new Set(), attributes = domElement.attributes, i = 0; i < attributes.length; i++)
        switch (attributes[i].name.toLowerCase()) {
          case "value":
            break;
          case "checked":
            break;
          case "selected":
            break;
          default:
            extraAttributes.add(attributes[i].name);
        }
      if (isCustomElement(tag))
        for (var propKey in props) {
          if (props.hasOwnProperty(propKey)) {
            var value = props[propKey];
            if (null != value) {
              if (registrationNameDependencies.hasOwnProperty(propKey))
                "function" !== typeof value && warnForInvalidEventListener(propKey, value);
              else if (true !== props.suppressHydrationWarning)
                switch (propKey) {
                  case "children":
                    "string" !== typeof value && "number" !== typeof value || warnForPropDifference(
                      "children",
                      domElement.textContent,
                      value,
                      serverDifferences
                    );
                    continue;
                  case "suppressContentEditableWarning":
                  case "suppressHydrationWarning":
                  case "defaultValue":
                  case "defaultChecked":
                  case "innerHTML":
                  case "ref":
                    continue;
                  case "dangerouslySetInnerHTML":
                    attributes = domElement.innerHTML;
                    value = value ? value.__html : void 0;
                    null != value && (value = normalizeHTML(domElement, value), warnForPropDifference(
                      propKey,
                      attributes,
                      value,
                      serverDifferences
                    ));
                    continue;
                  case "style":
                    extraAttributes.delete(propKey);
                    diffHydratedStyles(domElement, value, serverDifferences);
                    continue;
                  case "offsetParent":
                  case "offsetTop":
                  case "offsetLeft":
                  case "offsetWidth":
                  case "offsetHeight":
                  case "isContentEditable":
                  case "outerText":
                  case "outerHTML":
                    extraAttributes.delete(propKey.toLowerCase());
                    console.error(
                      "Assignment to read-only property will result in a no-op: `%s`",
                      propKey
                    );
                    continue;
                  case "className":
                    extraAttributes.delete("class");
                    attributes = getValueForAttributeOnCustomComponent(
                      domElement,
                      "class",
                      value
                    );
                    warnForPropDifference(
                      "className",
                      attributes,
                      value,
                      serverDifferences
                    );
                    continue;
                  default:
                    hostContext.context === HostContextNamespaceNone && "svg" !== tag && "math" !== tag ? extraAttributes.delete(propKey.toLowerCase()) : extraAttributes.delete(propKey), attributes = getValueForAttributeOnCustomComponent(
                      domElement,
                      propKey,
                      value
                    ), warnForPropDifference(
                      propKey,
                      attributes,
                      value,
                      serverDifferences
                    );
                }
            }
          }
        }
      else
        for (value in props)
          if (props.hasOwnProperty(value) && (propKey = props[value], null != propKey)) {
            if (registrationNameDependencies.hasOwnProperty(value))
              "function" !== typeof propKey && warnForInvalidEventListener(value, propKey);
            else if (true !== props.suppressHydrationWarning)
              switch (value) {
                case "children":
                  "string" !== typeof propKey && "number" !== typeof propKey || warnForPropDifference(
                    "children",
                    domElement.textContent,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "suppressContentEditableWarning":
                case "suppressHydrationWarning":
                case "value":
                case "checked":
                case "selected":
                case "defaultValue":
                case "defaultChecked":
                case "innerHTML":
                case "ref":
                  continue;
                case "dangerouslySetInnerHTML":
                  attributes = domElement.innerHTML;
                  propKey = propKey ? propKey.__html : void 0;
                  null != propKey && (propKey = normalizeHTML(domElement, propKey), attributes !== propKey && (serverDifferences[value] = { __html: attributes }));
                  continue;
                case "className":
                  hydrateAttribute(
                    domElement,
                    value,
                    "class",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "tabIndex":
                  hydrateAttribute(
                    domElement,
                    value,
                    "tabindex",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "style":
                  extraAttributes.delete(value);
                  diffHydratedStyles(domElement, propKey, serverDifferences);
                  continue;
                case "multiple":
                  extraAttributes.delete(value);
                  warnForPropDifference(
                    value,
                    domElement.multiple,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "muted":
                  extraAttributes.delete(value);
                  warnForPropDifference(
                    value,
                    domElement.muted,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "autoFocus":
                  extraAttributes.delete("autofocus");
                  warnForPropDifference(
                    value,
                    domElement.autofocus,
                    propKey,
                    serverDifferences
                  );
                  continue;
                case "data":
                  if ("object" !== tag) {
                    extraAttributes.delete(value);
                    attributes = domElement.getAttribute("data");
                    warnForPropDifference(
                      value,
                      attributes,
                      propKey,
                      serverDifferences
                    );
                    continue;
                  }
                case "src":
                case "href":
                  if (!("" !== propKey || "a" === tag && "href" === value || "object" === tag && "data" === value)) {
                    "src" === value ? console.error(
                      'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                      value,
                      value
                    ) : console.error(
                      'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                      value,
                      value
                    );
                    continue;
                  }
                  hydrateSanitizedAttribute(
                    domElement,
                    value,
                    value,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "action":
                case "formAction":
                  attributes = domElement.getAttribute(value);
                  if ("function" === typeof propKey) {
                    extraAttributes.delete(value.toLowerCase());
                    "formAction" === value ? (extraAttributes.delete("name"), extraAttributes.delete("formenctype"), extraAttributes.delete("formmethod"), extraAttributes.delete("formtarget")) : (extraAttributes.delete("enctype"), extraAttributes.delete("method"), extraAttributes.delete("target"));
                    continue;
                  } else if (attributes === EXPECTED_FORM_ACTION_URL) {
                    extraAttributes.delete(value.toLowerCase());
                    warnForPropDifference(
                      value,
                      "function",
                      propKey,
                      serverDifferences
                    );
                    continue;
                  }
                  hydrateSanitizedAttribute(
                    domElement,
                    value,
                    value.toLowerCase(),
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkHref":
                  hydrateSanitizedAttribute(
                    domElement,
                    value,
                    "xlink:href",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "contentEditable":
                  hydrateBooleanishAttribute(
                    domElement,
                    value,
                    "contenteditable",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "spellCheck":
                  hydrateBooleanishAttribute(
                    domElement,
                    value,
                    "spellcheck",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "draggable":
                case "autoReverse":
                case "externalResourcesRequired":
                case "focusable":
                case "preserveAlpha":
                  hydrateBooleanishAttribute(
                    domElement,
                    value,
                    value,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "allowFullScreen":
                case "async":
                case "autoPlay":
                case "controls":
                case "default":
                case "defer":
                case "disabled":
                case "disablePictureInPicture":
                case "disableRemotePlayback":
                case "formNoValidate":
                case "hidden":
                case "loop":
                case "noModule":
                case "noValidate":
                case "open":
                case "playsInline":
                case "readOnly":
                case "required":
                case "reversed":
                case "scoped":
                case "seamless":
                case "itemScope":
                  hydrateBooleanAttribute(
                    domElement,
                    value,
                    value.toLowerCase(),
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "capture":
                case "download":
                  a: {
                    i = domElement;
                    var attributeName = attributes = value, serverDifferences$jscomp$0 = serverDifferences;
                    extraAttributes.delete(attributeName);
                    i = i.getAttribute(attributeName);
                    if (null === i)
                      switch (typeof propKey) {
                        case "undefined":
                        case "function":
                        case "symbol":
                          break a;
                        default:
                          if (false === propKey) break a;
                      }
                    else if (null != propKey)
                      switch (typeof propKey) {
                        case "function":
                        case "symbol":
                          break;
                        case "boolean":
                          if (true === propKey && "" === i) break a;
                          break;
                        default:
                          if (checkAttributeStringCoercion(propKey, attributes), i === "" + propKey)
                            break a;
                      }
                    warnForPropDifference(
                      attributes,
                      i,
                      propKey,
                      serverDifferences$jscomp$0
                    );
                  }
                  continue;
                case "cols":
                case "rows":
                case "size":
                case "span":
                  a: {
                    i = domElement;
                    attributeName = attributes = value;
                    serverDifferences$jscomp$0 = serverDifferences;
                    extraAttributes.delete(attributeName);
                    i = i.getAttribute(attributeName);
                    if (null === i)
                      switch (typeof propKey) {
                        case "undefined":
                        case "function":
                        case "symbol":
                        case "boolean":
                          break a;
                        default:
                          if (isNaN(propKey) || 1 > propKey) break a;
                      }
                    else if (null != propKey)
                      switch (typeof propKey) {
                        case "function":
                        case "symbol":
                        case "boolean":
                          break;
                        default:
                          if (!(isNaN(propKey) || 1 > propKey) && (checkAttributeStringCoercion(propKey, attributes), i === "" + propKey))
                            break a;
                      }
                    warnForPropDifference(
                      attributes,
                      i,
                      propKey,
                      serverDifferences$jscomp$0
                    );
                  }
                  continue;
                case "rowSpan":
                  hydrateNumericAttribute(
                    domElement,
                    value,
                    "rowspan",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "start":
                  hydrateNumericAttribute(
                    domElement,
                    value,
                    value,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xHeight":
                  hydrateAttribute(
                    domElement,
                    value,
                    "x-height",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkActuate":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xlink:actuate",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkArcrole":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xlink:arcrole",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkRole":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xlink:role",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkShow":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xlink:show",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkTitle":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xlink:title",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xlinkType":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xlink:type",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xmlBase":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xml:base",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xmlLang":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xml:lang",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "xmlSpace":
                  hydrateAttribute(
                    domElement,
                    value,
                    "xml:space",
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                case "inert":
                  "" !== propKey || didWarnForNewBooleanPropsWithEmptyValue[value] || (didWarnForNewBooleanPropsWithEmptyValue[value] = true, console.error(
                    "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
                    value
                  ));
                  hydrateBooleanAttribute(
                    domElement,
                    value,
                    value,
                    propKey,
                    extraAttributes,
                    serverDifferences
                  );
                  continue;
                default:
                  if (!(2 < value.length) || "o" !== value[0] && "O" !== value[0] || "n" !== value[1] && "N" !== value[1]) {
                    i = getAttributeAlias(value);
                    attributes = false;
                    hostContext.context === HostContextNamespaceNone && "svg" !== tag && "math" !== tag ? extraAttributes.delete(i.toLowerCase()) : (attributeName = value.toLowerCase(), attributeName = possibleStandardNames.hasOwnProperty(
                      attributeName
                    ) ? possibleStandardNames[attributeName] || null : null, null !== attributeName && attributeName !== value && (attributes = true, extraAttributes.delete(attributeName)), extraAttributes.delete(i));
                    a: if (attributeName = domElement, serverDifferences$jscomp$0 = i, i = propKey, isAttributeNameSafe(serverDifferences$jscomp$0))
                      if (attributeName.hasAttribute(serverDifferences$jscomp$0))
                        attributeName = attributeName.getAttribute(
                          serverDifferences$jscomp$0
                        ), checkAttributeStringCoercion(
                          i,
                          serverDifferences$jscomp$0
                        ), i = attributeName === "" + i ? i : attributeName;
                      else {
                        switch (typeof i) {
                          case "function":
                          case "symbol":
                            break a;
                          case "boolean":
                            if (attributeName = serverDifferences$jscomp$0.toLowerCase().slice(0, 5), "data-" !== attributeName && "aria-" !== attributeName)
                              break a;
                        }
                        i = void 0 === i ? void 0 : null;
                      }
                    else i = void 0;
                    attributes || warnForPropDifference(
                      value,
                      i,
                      propKey,
                      serverDifferences
                    );
                  }
              }
          }
      0 < extraAttributes.size && true !== props.suppressHydrationWarning && warnForExtraAttributes(domElement, extraAttributes, serverDifferences);
      return 0 === Object.keys(serverDifferences).length ? null : serverDifferences;
    }
    function propNamesListJoin(list2, combinator) {
      switch (list2.length) {
        case 0:
          return "";
        case 1:
          return list2[0];
        case 2:
          return list2[0] + " " + combinator + " " + list2[1];
        default:
          return list2.slice(0, -1).join(", ") + ", " + combinator + " " + list2[list2.length - 1];
      }
    }
    function isLikelyStaticResource(initiatorType) {
      switch (initiatorType) {
        case "css":
        case "script":
        case "font":
        case "img":
        case "image":
        case "input":
        case "link":
          return true;
        default:
          return false;
      }
    }
    function estimateBandwidth() {
      if ("function" === typeof performance.getEntriesByType) {
        for (var count = 0, bits = 0, resourceEntries = performance.getEntriesByType("resource"), i = 0; i < resourceEntries.length; i++) {
          var entry = resourceEntries[i], transferSize = entry.transferSize, initiatorType = entry.initiatorType, duration = entry.duration;
          if (transferSize && duration && isLikelyStaticResource(initiatorType)) {
            initiatorType = 0;
            duration = entry.responseEnd;
            for (i += 1; i < resourceEntries.length; i++) {
              var overlapEntry = resourceEntries[i], overlapStartTime = overlapEntry.startTime;
              if (overlapStartTime > duration) break;
              var overlapTransferSize = overlapEntry.transferSize, overlapInitiatorType = overlapEntry.initiatorType;
              overlapTransferSize && isLikelyStaticResource(overlapInitiatorType) && (overlapEntry = overlapEntry.responseEnd, initiatorType += overlapTransferSize * (overlapEntry < duration ? 1 : (duration - overlapStartTime) / (overlapEntry - overlapStartTime)));
            }
            --i;
            bits += 8 * (transferSize + initiatorType) / (entry.duration / 1e3);
            count++;
            if (10 < count) break;
          }
        }
        if (0 < count) return bits / count / 1e6;
      }
      return navigator.connection && (count = navigator.connection.downlink, "number" === typeof count) ? count : 5;
    }
    function getOwnerDocumentFromRootContainer(rootContainerElement) {
      return 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
    }
    function getOwnHostContext(namespaceURI) {
      switch (namespaceURI) {
        case SVG_NAMESPACE:
          return HostContextNamespaceSvg;
        case MATH_NAMESPACE:
          return HostContextNamespaceMath;
        default:
          return HostContextNamespaceNone;
      }
    }
    function getChildHostContextProd(parentNamespace, type2) {
      if (parentNamespace === HostContextNamespaceNone)
        switch (type2) {
          case "svg":
            return HostContextNamespaceSvg;
          case "math":
            return HostContextNamespaceMath;
          default:
            return HostContextNamespaceNone;
        }
      return parentNamespace === HostContextNamespaceSvg && "foreignObject" === type2 ? HostContextNamespaceNone : parentNamespace;
    }
    function shouldSetTextContent(type2, props) {
      return "textarea" === type2 || "noscript" === type2 || "string" === typeof props.children || "number" === typeof props.children || "bigint" === typeof props.children || "object" === typeof props.dangerouslySetInnerHTML && null !== props.dangerouslySetInnerHTML && null != props.dangerouslySetInnerHTML.__html;
    }
    function shouldAttemptEagerTransition() {
      var event = window.event;
      if (event && "popstate" === event.type) {
        if (event === currentPopstateTransitionEvent) return false;
        currentPopstateTransitionEvent = event;
        return true;
      }
      currentPopstateTransitionEvent = null;
      return false;
    }
    function resolveEventType() {
      var event = window.event;
      return event && event !== schedulerEvent ? event.type : null;
    }
    function resolveEventTimeStamp() {
      var event = window.event;
      return event && event !== schedulerEvent ? event.timeStamp : -1.1;
    }
    function handleErrorInNextTick(error) {
      setTimeout(function() {
        throw error;
      });
    }
    function commitMount(domElement, type2, newProps) {
      switch (type2) {
        case "button":
        case "input":
        case "select":
        case "textarea":
          newProps.autoFocus && domElement.focus();
          break;
        case "img":
          newProps.src ? domElement.src = newProps.src : newProps.srcSet && (domElement.srcset = newProps.srcSet);
      }
    }
    function commitHydratedInstance() {
    }
    function commitUpdate(domElement, type2, oldProps, newProps) {
      updateProperties(domElement, type2, oldProps, newProps);
      domElement[internalPropsKey] = newProps;
    }
    function resetTextContent(domElement) {
      setTextContent(domElement, "");
    }
    function commitTextUpdate(textInstance, oldText, newText) {
      textInstance.nodeValue = newText;
    }
    function warnForReactChildrenConflict(container) {
      if (!container.__reactWarnedAboutChildrenConflict) {
        var props = container[internalPropsKey] || null;
        if (null !== props) {
          var fiber = getInstanceFromNode(container);
          null !== fiber && ("string" === typeof props.children || "number" === typeof props.children ? (container.__reactWarnedAboutChildrenConflict = true, runWithFiberInDEV(fiber, function() {
            console.error(
              'Cannot use a ref on a React element as a container to `createRoot` or `createPortal` if that element also sets "children" text content using React. It should be a leaf with no children. Otherwise it\'s ambiguous which children should be used.'
            );
          })) : null != props.dangerouslySetInnerHTML && (container.__reactWarnedAboutChildrenConflict = true, runWithFiberInDEV(fiber, function() {
            console.error(
              'Cannot use a ref on a React element as a container to `createRoot` or `createPortal` if that element also sets "dangerouslySetInnerHTML" using React. It should be a leaf with no children. Otherwise it\'s ambiguous which children should be used.'
            );
          })));
        }
      }
    }
    function isSingletonScope(type2) {
      return "head" === type2;
    }
    function removeChild(parentInstance, child) {
      parentInstance.removeChild(child);
    }
    function removeChildFromContainer(container, child) {
      (9 === container.nodeType ? container.body : "HTML" === container.nodeName ? container.ownerDocument.body : container).removeChild(child);
    }
    function clearHydrationBoundary(parentInstance, hydrationInstance) {
      var node2 = hydrationInstance, depth = 0;
      do {
        var nextNode = node2.nextSibling;
        parentInstance.removeChild(node2);
        if (nextNode && 8 === nextNode.nodeType)
          if (node2 = nextNode.data, node2 === SUSPENSE_END_DATA || node2 === ACTIVITY_END_DATA) {
            if (0 === depth) {
              parentInstance.removeChild(nextNode);
              retryIfBlockedOn(hydrationInstance);
              return;
            }
            depth--;
          } else if (node2 === SUSPENSE_START_DATA || node2 === SUSPENSE_PENDING_START_DATA || node2 === SUSPENSE_QUEUED_START_DATA || node2 === SUSPENSE_FALLBACK_START_DATA || node2 === ACTIVITY_START_DATA)
            depth++;
          else if (node2 === PREAMBLE_CONTRIBUTION_HTML)
            releaseSingletonInstance(
              parentInstance.ownerDocument.documentElement
            );
          else if (node2 === PREAMBLE_CONTRIBUTION_HEAD) {
            node2 = parentInstance.ownerDocument.head;
            releaseSingletonInstance(node2);
            for (var node$jscomp$0 = node2.firstChild; node$jscomp$0; ) {
              var nextNode$jscomp$0 = node$jscomp$0.nextSibling, nodeName = node$jscomp$0.nodeName;
              node$jscomp$0[internalHoistableMarker] || "SCRIPT" === nodeName || "STYLE" === nodeName || "LINK" === nodeName && "stylesheet" === node$jscomp$0.rel.toLowerCase() || node2.removeChild(node$jscomp$0);
              node$jscomp$0 = nextNode$jscomp$0;
            }
          } else
            node2 === PREAMBLE_CONTRIBUTION_BODY && releaseSingletonInstance(parentInstance.ownerDocument.body);
        node2 = nextNode;
      } while (node2);
      retryIfBlockedOn(hydrationInstance);
    }
    function hideOrUnhideDehydratedBoundary(suspenseInstance, isHidden) {
      var node2 = suspenseInstance;
      suspenseInstance = 0;
      do {
        var nextNode = node2.nextSibling;
        1 === node2.nodeType ? isHidden ? (node2._stashedDisplay = node2.style.display, node2.style.display = "none") : (node2.style.display = node2._stashedDisplay || "", "" === node2.getAttribute("style") && node2.removeAttribute("style")) : 3 === node2.nodeType && (isHidden ? (node2._stashedText = node2.nodeValue, node2.nodeValue = "") : node2.nodeValue = node2._stashedText || "");
        if (nextNode && 8 === nextNode.nodeType)
          if (node2 = nextNode.data, node2 === SUSPENSE_END_DATA)
            if (0 === suspenseInstance) break;
            else suspenseInstance--;
          else
            node2 !== SUSPENSE_START_DATA && node2 !== SUSPENSE_PENDING_START_DATA && node2 !== SUSPENSE_QUEUED_START_DATA && node2 !== SUSPENSE_FALLBACK_START_DATA || suspenseInstance++;
        node2 = nextNode;
      } while (node2);
    }
    function hideDehydratedBoundary(suspenseInstance) {
      hideOrUnhideDehydratedBoundary(suspenseInstance, true);
    }
    function hideInstance(instance) {
      instance = instance.style;
      "function" === typeof instance.setProperty ? instance.setProperty("display", "none", "important") : instance.display = "none";
    }
    function hideTextInstance(textInstance) {
      textInstance.nodeValue = "";
    }
    function unhideDehydratedBoundary(dehydratedInstance) {
      hideOrUnhideDehydratedBoundary(dehydratedInstance, false);
    }
    function unhideInstance(instance, props) {
      props = props[STYLE];
      props = void 0 !== props && null !== props && props.hasOwnProperty("display") ? props.display : null;
      instance.style.display = null == props || "boolean" === typeof props ? "" : ("" + props).trim();
    }
    function unhideTextInstance(textInstance, text2) {
      textInstance.nodeValue = text2;
    }
    function clearContainerSparingly(container) {
      var nextNode = container.firstChild;
      nextNode && 10 === nextNode.nodeType && (nextNode = nextNode.nextSibling);
      for (; nextNode; ) {
        var node2 = nextNode;
        nextNode = nextNode.nextSibling;
        switch (node2.nodeName) {
          case "HTML":
          case "HEAD":
          case "BODY":
            clearContainerSparingly(node2);
            detachDeletedInstance(node2);
            continue;
          case "SCRIPT":
          case "STYLE":
            continue;
          case "LINK":
            if ("stylesheet" === node2.rel.toLowerCase()) continue;
        }
        container.removeChild(node2);
      }
    }
    function canHydrateInstance(instance, type2, props, inRootOrSingleton) {
      for (; 1 === instance.nodeType; ) {
        var anyProps = props;
        if (instance.nodeName.toLowerCase() !== type2.toLowerCase()) {
          if (!inRootOrSingleton && ("INPUT" !== instance.nodeName || "hidden" !== instance.type))
            break;
        } else if (!inRootOrSingleton)
          if ("input" === type2 && "hidden" === instance.type) {
            checkAttributeStringCoercion(anyProps.name, "name");
            var name2 = null == anyProps.name ? null : "" + anyProps.name;
            if ("hidden" === anyProps.type && instance.getAttribute("name") === name2)
              return instance;
          } else return instance;
        else if (!instance[internalHoistableMarker])
          switch (type2) {
            case "meta":
              if (!instance.hasAttribute("itemprop")) break;
              return instance;
            case "link":
              name2 = instance.getAttribute("rel");
              if ("stylesheet" === name2 && instance.hasAttribute("data-precedence"))
                break;
              else if (name2 !== anyProps.rel || instance.getAttribute("href") !== (null == anyProps.href || "" === anyProps.href ? null : anyProps.href) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin) || instance.getAttribute("title") !== (null == anyProps.title ? null : anyProps.title))
                break;
              return instance;
            case "style":
              if (instance.hasAttribute("data-precedence")) break;
              return instance;
            case "script":
              name2 = instance.getAttribute("src");
              if ((name2 !== (null == anyProps.src ? null : anyProps.src) || instance.getAttribute("type") !== (null == anyProps.type ? null : anyProps.type) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin)) && name2 && instance.hasAttribute("async") && !instance.hasAttribute("itemprop"))
                break;
              return instance;
            default:
              return instance;
          }
        instance = getNextHydratable(instance.nextSibling);
        if (null === instance) break;
      }
      return null;
    }
    function canHydrateTextInstance(instance, text2, inRootOrSingleton) {
      if ("" === text2) return null;
      for (; 3 !== instance.nodeType; ) {
        if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
          return null;
        instance = getNextHydratable(instance.nextSibling);
        if (null === instance) return null;
      }
      return instance;
    }
    function canHydrateHydrationBoundary(instance, inRootOrSingleton) {
      for (; 8 !== instance.nodeType; ) {
        if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
          return null;
        instance = getNextHydratable(instance.nextSibling);
        if (null === instance) return null;
      }
      return instance;
    }
    function isSuspenseInstancePending(instance) {
      return instance.data === SUSPENSE_PENDING_START_DATA || instance.data === SUSPENSE_QUEUED_START_DATA;
    }
    function isSuspenseInstanceFallback(instance) {
      return instance.data === SUSPENSE_FALLBACK_START_DATA || instance.data === SUSPENSE_PENDING_START_DATA && instance.ownerDocument.readyState !== DOCUMENT_READY_STATE_LOADING;
    }
    function registerSuspenseInstanceRetry(instance, callback) {
      var ownerDocument = instance.ownerDocument;
      if (instance.data === SUSPENSE_QUEUED_START_DATA)
        instance._reactRetry = callback;
      else if (instance.data !== SUSPENSE_PENDING_START_DATA || ownerDocument.readyState !== DOCUMENT_READY_STATE_LOADING)
        callback();
      else {
        var listener = function() {
          callback();
          ownerDocument.removeEventListener("DOMContentLoaded", listener);
        };
        ownerDocument.addEventListener("DOMContentLoaded", listener);
        instance._reactRetry = listener;
      }
    }
    function getNextHydratable(node2) {
      for (; null != node2; node2 = node2.nextSibling) {
        var nodeType = node2.nodeType;
        if (1 === nodeType || 3 === nodeType) break;
        if (8 === nodeType) {
          nodeType = node2.data;
          if (nodeType === SUSPENSE_START_DATA || nodeType === SUSPENSE_FALLBACK_START_DATA || nodeType === SUSPENSE_PENDING_START_DATA || nodeType === SUSPENSE_QUEUED_START_DATA || nodeType === ACTIVITY_START_DATA || nodeType === FORM_STATE_IS_MATCHING || nodeType === FORM_STATE_IS_NOT_MATCHING)
            break;
          if (nodeType === SUSPENSE_END_DATA || nodeType === ACTIVITY_END_DATA)
            return null;
        }
      }
      return node2;
    }
    function describeHydratableInstanceForDevWarnings(instance) {
      if (1 === instance.nodeType) {
        for (var JSCompiler_temp_const = instance.nodeName.toLowerCase(), serverDifferences = {}, attributes = instance.attributes, i = 0; i < attributes.length; i++) {
          var attr = attributes[i];
          serverDifferences[getPropNameFromAttributeName(attr.name)] = "style" === attr.name.toLowerCase() ? getStylesObjectFromElement(instance) : attr.value;
        }
        return { type: JSCompiler_temp_const, props: serverDifferences };
      }
      return 8 === instance.nodeType ? instance.data === ACTIVITY_START_DATA ? { type: "Activity", props: {} } : { type: "Suspense", props: {} } : instance.nodeValue;
    }
    function diffHydratedTextForDevWarnings(textInstance, text2, parentProps) {
      return null === parentProps || true !== parentProps[SUPPRESS_HYDRATION_WARNING] ? (textInstance.nodeValue === text2 ? textInstance = null : (text2 = normalizeMarkupForTextOrAttribute(text2), textInstance = normalizeMarkupForTextOrAttribute(textInstance.nodeValue) === text2 ? null : textInstance.nodeValue), textInstance) : null;
    }
    function getNextHydratableInstanceAfterHydrationBoundary(hydrationInstance) {
      hydrationInstance = hydrationInstance.nextSibling;
      for (var depth = 0; hydrationInstance; ) {
        if (8 === hydrationInstance.nodeType) {
          var data = hydrationInstance.data;
          if (data === SUSPENSE_END_DATA || data === ACTIVITY_END_DATA) {
            if (0 === depth)
              return getNextHydratable(hydrationInstance.nextSibling);
            depth--;
          } else
            data !== SUSPENSE_START_DATA && data !== SUSPENSE_FALLBACK_START_DATA && data !== SUSPENSE_PENDING_START_DATA && data !== SUSPENSE_QUEUED_START_DATA && data !== ACTIVITY_START_DATA || depth++;
        }
        hydrationInstance = hydrationInstance.nextSibling;
      }
      return null;
    }
    function getParentHydrationBoundary(targetInstance) {
      targetInstance = targetInstance.previousSibling;
      for (var depth = 0; targetInstance; ) {
        if (8 === targetInstance.nodeType) {
          var data = targetInstance.data;
          if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_QUEUED_START_DATA || data === ACTIVITY_START_DATA) {
            if (0 === depth) return targetInstance;
            depth--;
          } else
            data !== SUSPENSE_END_DATA && data !== ACTIVITY_END_DATA || depth++;
        }
        targetInstance = targetInstance.previousSibling;
      }
      return null;
    }
    function commitHydratedContainer(container) {
      retryIfBlockedOn(container);
    }
    function commitHydratedActivityInstance(activityInstance) {
      retryIfBlockedOn(activityInstance);
    }
    function commitHydratedSuspenseInstance(suspenseInstance) {
      retryIfBlockedOn(suspenseInstance);
    }
    function resolveSingletonInstance(type2, props, rootContainerInstance, hostContext, validateDOMNestingDev) {
      validateDOMNestingDev && validateDOMNesting(type2, hostContext.ancestorInfo);
      props = getOwnerDocumentFromRootContainer(rootContainerInstance);
      switch (type2) {
        case "html":
          type2 = props.documentElement;
          if (!type2)
            throw Error(
              "React expected an <html> element (document.documentElement) to exist in the Document but one was not found. React never removes the documentElement for any Document it renders into so the cause is likely in some other script running on this page."
            );
          return type2;
        case "head":
          type2 = props.head;
          if (!type2)
            throw Error(
              "React expected a <head> element (document.head) to exist in the Document but one was not found. React never removes the head for any Document it renders into so the cause is likely in some other script running on this page."
            );
          return type2;
        case "body":
          type2 = props.body;
          if (!type2)
            throw Error(
              "React expected a <body> element (document.body) to exist in the Document but one was not found. React never removes the body for any Document it renders into so the cause is likely in some other script running on this page."
            );
          return type2;
        default:
          throw Error(
            "resolveSingletonInstance was called with an element type that is not supported. This is a bug in React."
          );
      }
    }
    function acquireSingletonInstance(type2, props, instance, internalInstanceHandle) {
      if (!instance[internalContainerInstanceKey] && getInstanceFromNode(instance)) {
        var tagName = instance.tagName.toLowerCase();
        console.error(
          "You are mounting a new %s component when a previous one has not first unmounted. It is an error to render more than one %s component at a time and attributes and children of these components will likely fail in unpredictable ways. Please only render a single instance of <%s> and if you need to mount a new one, ensure any previous ones have unmounted first.",
          tagName,
          tagName,
          tagName
        );
      }
      switch (type2) {
        case "html":
        case "head":
        case "body":
          break;
        default:
          console.error(
            "acquireSingletonInstance was called with an element type that is not supported. This is a bug in React."
          );
      }
      for (tagName = instance.attributes; tagName.length; )
        instance.removeAttributeNode(tagName[0]);
      setInitialProperties(instance, type2, props);
      instance[internalInstanceKey] = internalInstanceHandle;
      instance[internalPropsKey] = props;
    }
    function releaseSingletonInstance(instance) {
      for (var attributes = instance.attributes; attributes.length; )
        instance.removeAttributeNode(attributes[0]);
      detachDeletedInstance(instance);
    }
    function getHoistableRoot(container) {
      return "function" === typeof container.getRootNode ? container.getRootNode() : 9 === container.nodeType ? container : container.ownerDocument;
    }
    function preconnectAs(rel, href, crossOrigin) {
      var ownerDocument = globalDocument;
      if (ownerDocument && "string" === typeof href && href) {
        var limitedEscapedHref = escapeSelectorAttributeValueInsideDoubleQuotes(href);
        limitedEscapedHref = 'link[rel="' + rel + '"][href="' + limitedEscapedHref + '"]';
        "string" === typeof crossOrigin && (limitedEscapedHref += '[crossorigin="' + crossOrigin + '"]');
        preconnectsSet.has(limitedEscapedHref) || (preconnectsSet.add(limitedEscapedHref), rel = { rel, crossOrigin, href }, null === ownerDocument.querySelector(limitedEscapedHref) && (href = ownerDocument.createElement("link"), setInitialProperties(href, "link", rel), markNodeAsHoistable(href), ownerDocument.head.appendChild(href)));
      }
    }
    function getResource(type2, currentProps, pendingProps, currentResource) {
      var resourceRoot = (resourceRoot = rootInstanceStackCursor.current) ? getHoistableRoot(resourceRoot) : null;
      if (!resourceRoot)
        throw Error(
          '"resourceRoot" was expected to exist. This is a bug in React.'
        );
      switch (type2) {
        case "meta":
        case "title":
          return null;
        case "style":
          return "string" === typeof pendingProps.precedence && "string" === typeof pendingProps.href ? (pendingProps = getStyleKey(pendingProps.href), currentProps = getResourcesFromRoot(resourceRoot).hoistableStyles, currentResource = currentProps.get(pendingProps), currentResource || (currentResource = {
            type: "style",
            instance: null,
            count: 0,
            state: null
          }, currentProps.set(pendingProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
        case "link":
          if ("stylesheet" === pendingProps.rel && "string" === typeof pendingProps.href && "string" === typeof pendingProps.precedence) {
            type2 = getStyleKey(pendingProps.href);
            var _styles = getResourcesFromRoot(resourceRoot).hoistableStyles, _resource = _styles.get(type2);
            if (!_resource && (resourceRoot = resourceRoot.ownerDocument || resourceRoot, _resource = {
              type: "stylesheet",
              instance: null,
              count: 0,
              state: { loading: NotLoaded, preload: null }
            }, _styles.set(type2, _resource), (_styles = resourceRoot.querySelector(
              getStylesheetSelectorFromKey(type2)
            )) && !_styles._p && (_resource.instance = _styles, _resource.state.loading = Loaded | Inserted), !preloadPropsMap.has(type2))) {
              var preloadProps = {
                rel: "preload",
                as: "style",
                href: pendingProps.href,
                crossOrigin: pendingProps.crossOrigin,
                integrity: pendingProps.integrity,
                media: pendingProps.media,
                hrefLang: pendingProps.hrefLang,
                referrerPolicy: pendingProps.referrerPolicy
              };
              preloadPropsMap.set(type2, preloadProps);
              _styles || preloadStylesheet(
                resourceRoot,
                type2,
                preloadProps,
                _resource.state
              );
            }
            if (currentProps && null === currentResource)
              throw pendingProps = "\n\n  - " + describeLinkForResourceErrorDEV(currentProps) + "\n  + " + describeLinkForResourceErrorDEV(pendingProps), Error(
                "Expected <link> not to update to be updated to a stylesheet with precedence. Check the `rel`, `href`, and `precedence` props of this component. Alternatively, check whether two different <link> components render in the same slot or share the same key." + pendingProps
              );
            return _resource;
          }
          if (currentProps && null !== currentResource)
            throw pendingProps = "\n\n  - " + describeLinkForResourceErrorDEV(currentProps) + "\n  + " + describeLinkForResourceErrorDEV(pendingProps), Error(
              "Expected stylesheet with precedence to not be updated to a different kind of <link>. Check the `rel`, `href`, and `precedence` props of this component. Alternatively, check whether two different <link> components render in the same slot or share the same key." + pendingProps
            );
          return null;
        case "script":
          return currentProps = pendingProps.async, pendingProps = pendingProps.src, "string" === typeof pendingProps && currentProps && "function" !== typeof currentProps && "symbol" !== typeof currentProps ? (pendingProps = getScriptKey(pendingProps), currentProps = getResourcesFromRoot(resourceRoot).hoistableScripts, currentResource = currentProps.get(pendingProps), currentResource || (currentResource = {
            type: "script",
            instance: null,
            count: 0,
            state: null
          }, currentProps.set(pendingProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
        default:
          throw Error(
            'getResource encountered a type it did not expect: "' + type2 + '". this is a bug in React.'
          );
      }
    }
    function describeLinkForResourceErrorDEV(props) {
      var describedProps = 0, description = "<link";
      "string" === typeof props.rel ? (describedProps++, description += ' rel="' + props.rel + '"') : hasOwnProperty2.call(props, "rel") && (describedProps++, description += ' rel="' + (null === props.rel ? "null" : "invalid type " + typeof props.rel) + '"');
      "string" === typeof props.href ? (describedProps++, description += ' href="' + props.href + '"') : hasOwnProperty2.call(props, "href") && (describedProps++, description += ' href="' + (null === props.href ? "null" : "invalid type " + typeof props.href) + '"');
      "string" === typeof props.precedence ? (describedProps++, description += ' precedence="' + props.precedence + '"') : hasOwnProperty2.call(props, "precedence") && (describedProps++, description += " precedence={" + (null === props.precedence ? "null" : "invalid type " + typeof props.precedence) + "}");
      Object.getOwnPropertyNames(props).length > describedProps && (description += " ...");
      return description + " />";
    }
    function getStyleKey(href) {
      return 'href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"';
    }
    function getStylesheetSelectorFromKey(key) {
      return 'link[rel="stylesheet"][' + key + "]";
    }
    function stylesheetPropsFromRawProps(rawProps) {
      return assign({}, rawProps, {
        "data-precedence": rawProps.precedence,
        precedence: null
      });
    }
    function preloadStylesheet(ownerDocument, key, preloadProps, state) {
      ownerDocument.querySelector(
        'link[rel="preload"][as="style"][' + key + "]"
      ) ? state.loading = Loaded : (key = ownerDocument.createElement("link"), state.preload = key, key.addEventListener("load", function() {
        return state.loading |= Loaded;
      }), key.addEventListener("error", function() {
        return state.loading |= Errored;
      }), setInitialProperties(key, "link", preloadProps), markNodeAsHoistable(key), ownerDocument.head.appendChild(key));
    }
    function getScriptKey(src2) {
      return '[src="' + escapeSelectorAttributeValueInsideDoubleQuotes(src2) + '"]';
    }
    function getScriptSelectorFromKey(key) {
      return "script[async]" + key;
    }
    function acquireResource(hoistableRoot, resource, props) {
      resource.count++;
      if (null === resource.instance)
        switch (resource.type) {
          case "style":
            var instance = hoistableRoot.querySelector(
              'style[data-href~="' + escapeSelectorAttributeValueInsideDoubleQuotes(props.href) + '"]'
            );
            if (instance)
              return resource.instance = instance, markNodeAsHoistable(instance), instance;
            var styleProps = assign({}, props, {
              "data-href": props.href,
              "data-precedence": props.precedence,
              href: null,
              precedence: null
            });
            instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement("style");
            markNodeAsHoistable(instance);
            setInitialProperties(instance, "style", styleProps);
            insertStylesheet(instance, props.precedence, hoistableRoot);
            return resource.instance = instance;
          case "stylesheet":
            styleProps = getStyleKey(props.href);
            var _instance = hoistableRoot.querySelector(
              getStylesheetSelectorFromKey(styleProps)
            );
            if (_instance)
              return resource.state.loading |= Inserted, resource.instance = _instance, markNodeAsHoistable(_instance), _instance;
            instance = stylesheetPropsFromRawProps(props);
            (styleProps = preloadPropsMap.get(styleProps)) && adoptPreloadPropsForStylesheet(instance, styleProps);
            _instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement("link");
            markNodeAsHoistable(_instance);
            var linkInstance = _instance;
            linkInstance._p = new Promise(function(resolve, reject) {
              linkInstance.onload = resolve;
              linkInstance.onerror = reject;
            });
            setInitialProperties(_instance, "link", instance);
            resource.state.loading |= Inserted;
            insertStylesheet(_instance, props.precedence, hoistableRoot);
            return resource.instance = _instance;
          case "script":
            _instance = getScriptKey(props.src);
            if (styleProps = hoistableRoot.querySelector(
              getScriptSelectorFromKey(_instance)
            ))
              return resource.instance = styleProps, markNodeAsHoistable(styleProps), styleProps;
            instance = props;
            if (styleProps = preloadPropsMap.get(_instance))
              instance = assign({}, props), adoptPreloadPropsForScript(instance, styleProps);
            hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
            styleProps = hoistableRoot.createElement("script");
            markNodeAsHoistable(styleProps);
            setInitialProperties(styleProps, "link", instance);
            hoistableRoot.head.appendChild(styleProps);
            return resource.instance = styleProps;
          case "void":
            return null;
          default:
            throw Error(
              'acquireResource encountered a resource type it did not expect: "' + resource.type + '". this is a bug in React.'
            );
        }
      else
        "stylesheet" === resource.type && (resource.state.loading & Inserted) === NotLoaded && (instance = resource.instance, resource.state.loading |= Inserted, insertStylesheet(instance, props.precedence, hoistableRoot));
      return resource.instance;
    }
    function insertStylesheet(instance, precedence, root3) {
      for (var nodes = root3.querySelectorAll(
        'link[rel="stylesheet"][data-precedence],style[data-precedence]'
      ), last = nodes.length ? nodes[nodes.length - 1] : null, prior = last, i = 0; i < nodes.length; i++) {
        var node2 = nodes[i];
        if (node2.dataset.precedence === precedence) prior = node2;
        else if (prior !== last) break;
      }
      prior ? prior.parentNode.insertBefore(instance, prior.nextSibling) : (precedence = 9 === root3.nodeType ? root3.head : root3, precedence.insertBefore(instance, precedence.firstChild));
    }
    function adoptPreloadPropsForStylesheet(stylesheetProps, preloadProps) {
      null == stylesheetProps.crossOrigin && (stylesheetProps.crossOrigin = preloadProps.crossOrigin);
      null == stylesheetProps.referrerPolicy && (stylesheetProps.referrerPolicy = preloadProps.referrerPolicy);
      null == stylesheetProps.title && (stylesheetProps.title = preloadProps.title);
    }
    function adoptPreloadPropsForScript(scriptProps, preloadProps) {
      null == scriptProps.crossOrigin && (scriptProps.crossOrigin = preloadProps.crossOrigin);
      null == scriptProps.referrerPolicy && (scriptProps.referrerPolicy = preloadProps.referrerPolicy);
      null == scriptProps.integrity && (scriptProps.integrity = preloadProps.integrity);
    }
    function getHydratableHoistableCache(type2, keyAttribute, ownerDocument) {
      if (null === tagCaches) {
        var cache = /* @__PURE__ */ new Map();
        var caches = tagCaches = /* @__PURE__ */ new Map();
        caches.set(ownerDocument, cache);
      } else
        caches = tagCaches, cache = caches.get(ownerDocument), cache || (cache = /* @__PURE__ */ new Map(), caches.set(ownerDocument, cache));
      if (cache.has(type2)) return cache;
      cache.set(type2, null);
      ownerDocument = ownerDocument.getElementsByTagName(type2);
      for (caches = 0; caches < ownerDocument.length; caches++) {
        var node2 = ownerDocument[caches];
        if (!(node2[internalHoistableMarker] || node2[internalInstanceKey] || "link" === type2 && "stylesheet" === node2.getAttribute("rel")) && node2.namespaceURI !== SVG_NAMESPACE) {
          var nodeKey = node2.getAttribute(keyAttribute) || "";
          nodeKey = type2 + nodeKey;
          var existing = cache.get(nodeKey);
          existing ? existing.push(node2) : cache.set(nodeKey, [node2]);
        }
      }
      return cache;
    }
    function mountHoistable(hoistableRoot, type2, instance) {
      hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
      hoistableRoot.head.insertBefore(
        instance,
        "title" === type2 ? hoistableRoot.querySelector("head > title") : null
      );
    }
    function isHostHoistableType(type2, props, hostContext) {
      var outsideHostContainerContext = !hostContext.ancestorInfo.containerTagInScope;
      if (hostContext.context === HostContextNamespaceSvg || null != props.itemProp)
        return !outsideHostContainerContext || null == props.itemProp || "meta" !== type2 && "title" !== type2 && "style" !== type2 && "link" !== type2 && "script" !== type2 || console.error(
          "Cannot render a <%s> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <%s> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.",
          type2,
          type2
        ), false;
      switch (type2) {
        case "meta":
        case "title":
          return true;
        case "style":
          if ("string" !== typeof props.precedence || "string" !== typeof props.href || "" === props.href) {
            outsideHostContainerContext && console.error(
              'Cannot render a <style> outside the main document without knowing its precedence and a unique href key. React can hoist and deduplicate <style> tags if you provide a `precedence` prop along with an `href` prop that does not conflict with the `href` values used in any other hoisted <style> or <link rel="stylesheet" ...> tags.  Note that hoisting <style> tags is considered an advanced feature that most will not use directly. Consider moving the <style> tag to the <head> or consider adding a `precedence="default"` and `href="some unique resource identifier"`.'
            );
            break;
          }
          return true;
        case "link":
          if ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href || props.onLoad || props.onError) {
            if ("stylesheet" === props.rel && "string" === typeof props.precedence) {
              type2 = props.href;
              var onError = props.onError, disabled = props.disabled;
              hostContext = [];
              props.onLoad && hostContext.push("`onLoad`");
              onError && hostContext.push("`onError`");
              null != disabled && hostContext.push("`disabled`");
              onError = propNamesListJoin(hostContext, "and");
              onError += 1 === hostContext.length ? " prop" : " props";
              disabled = 1 === hostContext.length ? "an " + onError : "the " + onError;
              hostContext.length && console.error(
                'React encountered a <link rel="stylesheet" href="%s" ... /> with a `precedence` prop that also included %s. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.',
                type2,
                disabled,
                onError
              );
            }
            outsideHostContainerContext && ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href ? console.error(
              "Cannot render a <link> outside the main document without a `rel` and `href` prop. Try adding a `rel` and/or `href` prop to this <link> or moving the link into the <head> tag"
            ) : (props.onError || props.onLoad) && console.error(
              "Cannot render a <link> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>."
            ));
            break;
          }
          switch (props.rel) {
            case "stylesheet":
              return type2 = props.precedence, props = props.disabled, "string" !== typeof type2 && outsideHostContainerContext && console.error(
                'Cannot render a <link rel="stylesheet" /> outside the main document without knowing its precedence. Consider adding precedence="default" or moving it into the root <head> tag.'
              ), "string" === typeof type2 && null == props;
            default:
              return true;
          }
        case "script":
          type2 = props.async && "function" !== typeof props.async && "symbol" !== typeof props.async;
          if (!type2 || props.onLoad || props.onError || !props.src || "string" !== typeof props.src) {
            outsideHostContainerContext && (type2 ? props.onLoad || props.onError ? console.error(
              "Cannot render a <script> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>."
            ) : console.error(
              "Cannot render a <script> outside the main document without `async={true}` and a non-empty `src` prop. Ensure there is a valid `src` and either make the script async or move it into the root <head> tag or somewhere in the <body>."
            ) : console.error(
              'Cannot render a sync or defer <script> outside the main document without knowing its order. Try adding async="" or moving it into the root <head> tag.'
            ));
            break;
          }
          return true;
        case "noscript":
        case "template":
          outsideHostContainerContext && console.error(
            "Cannot render <%s> outside the main document. Try moving it into the root <head> tag.",
            type2
          );
      }
      return false;
    }
    function preloadResource(resource) {
      return "stylesheet" === resource.type && (resource.state.loading & Settled) === NotLoaded ? false : true;
    }
    function suspendResource(state, hoistableRoot, resource, props) {
      if ("stylesheet" === resource.type && ("string" !== typeof props.media || false !== matchMedia(props.media).matches) && (resource.state.loading & Inserted) === NotLoaded) {
        if (null === resource.instance) {
          var key = getStyleKey(props.href), instance = hoistableRoot.querySelector(
            getStylesheetSelectorFromKey(key)
          );
          if (instance) {
            hoistableRoot = instance._p;
            null !== hoistableRoot && "object" === typeof hoistableRoot && "function" === typeof hoistableRoot.then && (state.count++, state = onUnsuspend.bind(state), hoistableRoot.then(state, state));
            resource.state.loading |= Inserted;
            resource.instance = instance;
            markNodeAsHoistable(instance);
            return;
          }
          instance = hoistableRoot.ownerDocument || hoistableRoot;
          props = stylesheetPropsFromRawProps(props);
          (key = preloadPropsMap.get(key)) && adoptPreloadPropsForStylesheet(props, key);
          instance = instance.createElement("link");
          markNodeAsHoistable(instance);
          var linkInstance = instance;
          linkInstance._p = new Promise(function(resolve, reject) {
            linkInstance.onload = resolve;
            linkInstance.onerror = reject;
          });
          setInitialProperties(instance, "link", props);
          resource.instance = instance;
        }
        null === state.stylesheets && (state.stylesheets = /* @__PURE__ */ new Map());
        state.stylesheets.set(resource, hoistableRoot);
        (hoistableRoot = resource.state.preload) && (resource.state.loading & Settled) === NotLoaded && (state.count++, resource = onUnsuspend.bind(state), hoistableRoot.addEventListener("load", resource), hoistableRoot.addEventListener("error", resource));
      }
    }
    function waitForCommitToBeReady(state, timeoutOffset) {
      state.stylesheets && 0 === state.count && insertSuspendedStylesheets(state, state.stylesheets);
      return 0 < state.count || 0 < state.imgCount ? function(commit) {
        var stylesheetTimer = setTimeout(function() {
          state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets);
          if (state.unsuspend) {
            var unsuspend = state.unsuspend;
            state.unsuspend = null;
            unsuspend();
          }
        }, SUSPENSEY_STYLESHEET_TIMEOUT + timeoutOffset);
        0 < state.imgBytes && 0 === estimatedBytesWithinLimit && (estimatedBytesWithinLimit = 125 * estimateBandwidth() * SUSPENSEY_IMAGE_TIME_ESTIMATE);
        var imgTimer = setTimeout(
          function() {
            state.waitingForImages = false;
            if (0 === state.count && (state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets), state.unsuspend)) {
              var unsuspend = state.unsuspend;
              state.unsuspend = null;
              unsuspend();
            }
          },
          (state.imgBytes > estimatedBytesWithinLimit ? 50 : SUSPENSEY_IMAGE_TIMEOUT) + timeoutOffset
        );
        state.unsuspend = commit;
        return function() {
          state.unsuspend = null;
          clearTimeout(stylesheetTimer);
          clearTimeout(imgTimer);
        };
      } : null;
    }
    function onUnsuspend() {
      this.count--;
      if (0 === this.count && (0 === this.imgCount || !this.waitingForImages)) {
        if (this.stylesheets)
          insertSuspendedStylesheets(this, this.stylesheets);
        else if (this.unsuspend) {
          var unsuspend = this.unsuspend;
          this.unsuspend = null;
          unsuspend();
        }
      }
    }
    function insertSuspendedStylesheets(state, resources) {
      state.stylesheets = null;
      null !== state.unsuspend && (state.count++, precedencesByRoot = /* @__PURE__ */ new Map(), resources.forEach(insertStylesheetIntoRoot, state), precedencesByRoot = null, onUnsuspend.call(state));
    }
    function insertStylesheetIntoRoot(root3, resource) {
      if (!(resource.state.loading & Inserted)) {
        var precedences = precedencesByRoot.get(root3);
        if (precedences) var last = precedences.get(LAST_PRECEDENCE);
        else {
          precedences = /* @__PURE__ */ new Map();
          precedencesByRoot.set(root3, precedences);
          for (var nodes = root3.querySelectorAll(
            "link[data-precedence],style[data-precedence]"
          ), i = 0; i < nodes.length; i++) {
            var node2 = nodes[i];
            if ("LINK" === node2.nodeName || "not all" !== node2.getAttribute("media"))
              precedences.set(node2.dataset.precedence, node2), last = node2;
          }
          last && precedences.set(LAST_PRECEDENCE, last);
        }
        nodes = resource.instance;
        node2 = nodes.getAttribute("data-precedence");
        i = precedences.get(node2) || last;
        i === last && precedences.set(LAST_PRECEDENCE, nodes);
        precedences.set(node2, nodes);
        this.count++;
        last = onUnsuspend.bind(this);
        nodes.addEventListener("load", last);
        nodes.addEventListener("error", last);
        i ? i.parentNode.insertBefore(nodes, i.nextSibling) : (root3 = 9 === root3.nodeType ? root3.head : root3, root3.insertBefore(nodes, root3.firstChild));
        resource.state.loading |= Inserted;
      }
    }
    function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator, formState) {
      this.tag = 1;
      this.containerInfo = containerInfo;
      this.pingCache = this.current = this.pendingChildren = null;
      this.timeoutHandle = noTimeout;
      this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
      this.callbackPriority = 0;
      this.expirationTimes = createLaneMap(-1);
      this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
      this.entanglements = createLaneMap(0);
      this.hiddenUpdates = createLaneMap(null);
      this.identifierPrefix = identifierPrefix;
      this.onUncaughtError = onUncaughtError;
      this.onCaughtError = onCaughtError;
      this.onRecoverableError = onRecoverableError;
      this.pooledCache = null;
      this.pooledCacheLanes = 0;
      this.formState = formState;
      this.incompleteTransitions = /* @__PURE__ */ new Map();
      this.passiveEffectDuration = this.effectDuration = -0;
      this.memoizedUpdaters = /* @__PURE__ */ new Set();
      containerInfo = this.pendingUpdatersLaneMap = [];
      for (tag = 0; 31 > tag; tag++) containerInfo.push(/* @__PURE__ */ new Set());
      this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()";
    }
    function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, formState, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator) {
      containerInfo = new FiberRootNode(
        containerInfo,
        tag,
        hydrate,
        identifierPrefix,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        onDefaultTransitionIndicator,
        formState
      );
      tag = ConcurrentMode;
      true === isStrictMode && (tag |= StrictLegacyMode | StrictEffectsMode);
      tag |= ProfileMode;
      isStrictMode = createFiber(3, null, null, tag);
      containerInfo.current = isStrictMode;
      isStrictMode.stateNode = containerInfo;
      tag = createCache();
      retainCache(tag);
      containerInfo.pooledCache = tag;
      retainCache(tag);
      isStrictMode.memoizedState = {
        element: initialChildren,
        isDehydrated: hydrate,
        cache: tag
      };
      initializeUpdateQueue(isStrictMode);
      return containerInfo;
    }
    function getContextForSubtree(parentComponent) {
      if (!parentComponent) return emptyContextObject;
      parentComponent = emptyContextObject;
      return parentComponent;
    }
    function updateContainerImpl(rootFiber, lane, element2, container, parentComponent, callback) {
      if (injectedHook && "function" === typeof injectedHook.onScheduleFiberRoot)
        try {
          injectedHook.onScheduleFiberRoot(rendererID, container, element2);
        } catch (err) {
          hasLoggedError || (hasLoggedError = true, console.error(
            "React instrumentation encountered an error: %o",
            err
          ));
        }
      parentComponent = getContextForSubtree(parentComponent);
      null === container.context ? container.context = parentComponent : container.pendingContext = parentComponent;
      isRendering && null !== current && !didWarnAboutNestedUpdates && (didWarnAboutNestedUpdates = true, console.error(
        "Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.",
        getComponentNameFromFiber(current) || "Unknown"
      ));
      container = createUpdate(lane);
      container.payload = { element: element2 };
      callback = void 0 === callback ? null : callback;
      null !== callback && ("function" !== typeof callback && console.error(
        "Expected the last optional `callback` argument to be a function. Instead received: %s.",
        callback
      ), container.callback = callback);
      element2 = enqueueUpdate(rootFiber, container, lane);
      null !== element2 && (startUpdateTimerByLane(lane, "root.render()", null), scheduleUpdateOnFiber(element2, rootFiber, lane), entangleTransitions(element2, rootFiber, lane));
    }
    function markRetryLaneImpl(fiber, retryLane) {
      fiber = fiber.memoizedState;
      if (null !== fiber && null !== fiber.dehydrated) {
        var a = fiber.retryLane;
        fiber.retryLane = 0 !== a && a < retryLane ? a : retryLane;
      }
    }
    function markRetryLaneIfNotHydrated(fiber, retryLane) {
      markRetryLaneImpl(fiber, retryLane);
      (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
    }
    function attemptContinuousHydration(fiber) {
      if (13 === fiber.tag || 31 === fiber.tag) {
        var root3 = enqueueConcurrentRenderForLane(fiber, 67108864);
        null !== root3 && scheduleUpdateOnFiber(root3, fiber, 67108864);
        markRetryLaneIfNotHydrated(fiber, 67108864);
      }
    }
    function attemptHydrationAtCurrentPriority(fiber) {
      if (13 === fiber.tag || 31 === fiber.tag) {
        var lane = requestUpdateLane(fiber);
        lane = getBumpedLaneForHydrationByLane(lane);
        var root3 = enqueueConcurrentRenderForLane(fiber, lane);
        null !== root3 && scheduleUpdateOnFiber(root3, fiber, lane);
        markRetryLaneIfNotHydrated(fiber, lane);
      }
    }
    function getCurrentFiberForDevTools() {
      return current;
    }
    function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
      var prevTransition = ReactSharedInternals.T;
      ReactSharedInternals.T = null;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = DiscreteEventPriority, dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
      var prevTransition = ReactSharedInternals.T;
      ReactSharedInternals.T = null;
      var previousPriority = ReactDOMSharedInternals.p;
      try {
        ReactDOMSharedInternals.p = ContinuousEventPriority, dispatchEvent(domEventName, eventSystemFlags, container, nativeEvent);
      } finally {
        ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
      }
    }
    function dispatchEvent(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      if (_enabled) {
        var blockedOn = findInstanceBlockingEvent(nativeEvent);
        if (null === blockedOn)
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            return_targetInst,
            targetContainer
          ), clearIfContinuousEvent(domEventName, nativeEvent);
        else if (queueIfContinuousEvent(
          blockedOn,
          domEventName,
          eventSystemFlags,
          targetContainer,
          nativeEvent
        ))
          nativeEvent.stopPropagation();
        else if (clearIfContinuousEvent(domEventName, nativeEvent), eventSystemFlags & 4 && -1 < discreteReplayableEvents.indexOf(domEventName)) {
          for (; null !== blockedOn; ) {
            var fiber = getInstanceFromNode(blockedOn);
            if (null !== fiber)
              switch (fiber.tag) {
                case 3:
                  fiber = fiber.stateNode;
                  if (fiber.current.memoizedState.isDehydrated) {
                    var lanes = getHighestPriorityLanes(fiber.pendingLanes);
                    if (0 !== lanes) {
                      var root3 = fiber;
                      root3.pendingLanes |= 2;
                      for (root3.entangledLanes |= 2; lanes; ) {
                        var lane = 1 << 31 - clz32(lanes);
                        root3.entanglements[1] |= lane;
                        lanes &= ~lane;
                      }
                      ensureRootIsScheduled(fiber);
                      (executionContext & (RenderContext | CommitContext)) === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS, flushSyncWorkAcrossRoots_impl(0));
                    }
                  }
                  break;
                case 31:
                case 13:
                  root3 = enqueueConcurrentRenderForLane(fiber, 2), null !== root3 && scheduleUpdateOnFiber(root3, fiber, 2), flushSyncWork$1(), markRetryLaneIfNotHydrated(fiber, 2);
              }
            fiber = findInstanceBlockingEvent(nativeEvent);
            null === fiber && dispatchEventForPluginEventSystem(
              domEventName,
              eventSystemFlags,
              nativeEvent,
              return_targetInst,
              targetContainer
            );
            if (fiber === blockedOn) break;
            blockedOn = fiber;
          }
          null !== blockedOn && nativeEvent.stopPropagation();
        } else
          dispatchEventForPluginEventSystem(
            domEventName,
            eventSystemFlags,
            nativeEvent,
            null,
            targetContainer
          );
      }
    }
    function findInstanceBlockingEvent(nativeEvent) {
      nativeEvent = getEventTarget(nativeEvent);
      return findInstanceBlockingTarget(nativeEvent);
    }
    function findInstanceBlockingTarget(targetNode) {
      return_targetInst = null;
      targetNode = getClosestInstanceFromNode(targetNode);
      if (null !== targetNode) {
        var nearestMounted = getNearestMountedFiber(targetNode);
        if (null === nearestMounted) targetNode = null;
        else {
          var tag = nearestMounted.tag;
          if (13 === tag) {
            targetNode = getSuspenseInstanceFromFiber(nearestMounted);
            if (null !== targetNode) return targetNode;
            targetNode = null;
          } else if (31 === tag) {
            targetNode = getActivityInstanceFromFiber(nearestMounted);
            if (null !== targetNode) return targetNode;
            targetNode = null;
          } else if (3 === tag) {
            if (nearestMounted.stateNode.current.memoizedState.isDehydrated)
              return 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
            targetNode = null;
          } else nearestMounted !== targetNode && (targetNode = null);
        }
      }
      return_targetInst = targetNode;
      return null;
    }
    function getEventPriority(domEventName) {
      switch (domEventName) {
        case "beforetoggle":
        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 "toggle":
        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 DiscreteEventPriority;
        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 "touchmove":
        case "wheel":
        case "mouseenter":
        case "mouseleave":
        case "pointerenter":
        case "pointerleave":
          return ContinuousEventPriority;
        case "message":
          switch (getCurrentPriorityLevel()) {
            case ImmediatePriority:
              return DiscreteEventPriority;
            case UserBlockingPriority:
              return ContinuousEventPriority;
            case NormalPriority$1:
            case LowPriority:
              return DefaultEventPriority;
            case IdlePriority:
              return IdleEventPriority;
            default:
              return DefaultEventPriority;
          }
        default:
          return DefaultEventPriority;
      }
    }
    function clearIfContinuousEvent(domEventName, nativeEvent) {
      switch (domEventName) {
        case "focusin":
        case "focusout":
          queuedFocus = null;
          break;
        case "dragenter":
        case "dragleave":
          queuedDrag = null;
          break;
        case "mouseover":
        case "mouseout":
          queuedMouse = null;
          break;
        case "pointerover":
        case "pointerout":
          queuedPointers.delete(nativeEvent.pointerId);
          break;
        case "gotpointercapture":
        case "lostpointercapture":
          queuedPointerCaptures.delete(nativeEvent.pointerId);
      }
    }
    function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      if (null === existingQueuedEvent || existingQueuedEvent.nativeEvent !== nativeEvent)
        return existingQueuedEvent = {
          blockedOn,
          domEventName,
          eventSystemFlags,
          nativeEvent,
          targetContainers: [targetContainer]
        }, null !== blockedOn && (blockedOn = getInstanceFromNode(blockedOn), null !== blockedOn && attemptContinuousHydration(blockedOn)), existingQueuedEvent;
      existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
      blockedOn = existingQueuedEvent.targetContainers;
      null !== targetContainer && -1 === blockedOn.indexOf(targetContainer) && blockedOn.push(targetContainer);
      return existingQueuedEvent;
    }
    function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
      switch (domEventName) {
        case "focusin":
          return queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedFocus,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "dragenter":
          return queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedDrag,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "mouseover":
          return queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
            queuedMouse,
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ), true;
        case "pointerover":
          var pointerId = nativeEvent.pointerId;
          queuedPointers.set(
            pointerId,
            accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedPointers.get(pointerId) || null,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            )
          );
          return true;
        case "gotpointercapture":
          return pointerId = nativeEvent.pointerId, queuedPointerCaptures.set(
            pointerId,
            accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedPointerCaptures.get(pointerId) || null,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            )
          ), true;
      }
      return false;
    }
    function attemptExplicitHydrationTarget(queuedTarget) {
      var targetInst = getClosestInstanceFromNode(queuedTarget.target);
      if (null !== targetInst) {
        var nearestMounted = getNearestMountedFiber(targetInst);
        if (null !== nearestMounted) {
          if (targetInst = nearestMounted.tag, 13 === targetInst) {
            if (targetInst = getSuspenseInstanceFromFiber(nearestMounted), null !== targetInst) {
              queuedTarget.blockedOn = targetInst;
              runWithPriority(queuedTarget.priority, function() {
                attemptHydrationAtCurrentPriority(nearestMounted);
              });
              return;
            }
          } else if (31 === targetInst) {
            if (targetInst = getActivityInstanceFromFiber(nearestMounted), null !== targetInst) {
              queuedTarget.blockedOn = targetInst;
              runWithPriority(queuedTarget.priority, function() {
                attemptHydrationAtCurrentPriority(nearestMounted);
              });
              return;
            }
          } else if (3 === targetInst && nearestMounted.stateNode.current.memoizedState.isDehydrated) {
            queuedTarget.blockedOn = 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
            return;
          }
        }
      }
      queuedTarget.blockedOn = null;
    }
    function attemptReplayContinuousQueuedEvent(queuedEvent) {
      if (null !== queuedEvent.blockedOn) return false;
      for (var targetContainers = queuedEvent.targetContainers; 0 < targetContainers.length; ) {
        var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent);
        if (null === nextBlockedOn) {
          nextBlockedOn = queuedEvent.nativeEvent;
          var nativeEventClone = new nextBlockedOn.constructor(
            nextBlockedOn.type,
            nextBlockedOn
          ), event = nativeEventClone;
          null !== currentReplayingEvent && console.error(
            "Expected currently replaying event to be null. This error is likely caused by a bug in React. Please file an issue."
          );
          currentReplayingEvent = event;
          nextBlockedOn.target.dispatchEvent(nativeEventClone);
          null === currentReplayingEvent && console.error(
            "Expected currently replaying event to not be null. This error is likely caused by a bug in React. Please file an issue."
          );
          currentReplayingEvent = null;
        } else
          return targetContainers = getInstanceFromNode(nextBlockedOn), null !== targetContainers && attemptContinuousHydration(targetContainers), queuedEvent.blockedOn = nextBlockedOn, false;
        targetContainers.shift();
      }
      return true;
    }
    function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map) {
      attemptReplayContinuousQueuedEvent(queuedEvent) && map.delete(key);
    }
    function replayUnblockedEvents() {
      hasScheduledReplayAttempt = false;
      null !== queuedFocus && attemptReplayContinuousQueuedEvent(queuedFocus) && (queuedFocus = null);
      null !== queuedDrag && attemptReplayContinuousQueuedEvent(queuedDrag) && (queuedDrag = null);
      null !== queuedMouse && attemptReplayContinuousQueuedEvent(queuedMouse) && (queuedMouse = null);
      queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
      queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
    }
    function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
      queuedEvent.blockedOn === unblocked && (queuedEvent.blockedOn = null, hasScheduledReplayAttempt || (hasScheduledReplayAttempt = true, Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        replayUnblockedEvents
      )));
    }
    function scheduleReplayQueueIfNeeded(formReplayingQueue) {
      lastScheduledReplayQueue !== formReplayingQueue && (lastScheduledReplayQueue = formReplayingQueue, Scheduler.unstable_scheduleCallback(
        Scheduler.unstable_NormalPriority,
        function() {
          lastScheduledReplayQueue === formReplayingQueue && (lastScheduledReplayQueue = null);
          for (var i = 0; i < formReplayingQueue.length; i += 3) {
            var form = formReplayingQueue[i], submitterOrAction = formReplayingQueue[i + 1], formData = formReplayingQueue[i + 2];
            if ("function" !== typeof submitterOrAction)
              if (null === findInstanceBlockingTarget(submitterOrAction || form))
                continue;
              else break;
            var formInst = getInstanceFromNode(form);
            null !== formInst && (formReplayingQueue.splice(i, 3), i -= 3, form = {
              pending: true,
              data: formData,
              method: form.method,
              action: submitterOrAction
            }, Object.freeze(form), startHostTransition(
              formInst,
              form,
              submitterOrAction,
              formData
            ));
          }
        }
      ));
    }
    function retryIfBlockedOn(unblocked) {
      function unblock(queuedEvent) {
        return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
      }
      null !== queuedFocus && scheduleCallbackIfUnblocked(queuedFocus, unblocked);
      null !== queuedDrag && scheduleCallbackIfUnblocked(queuedDrag, unblocked);
      null !== queuedMouse && scheduleCallbackIfUnblocked(queuedMouse, unblocked);
      queuedPointers.forEach(unblock);
      queuedPointerCaptures.forEach(unblock);
      for (var i = 0; i < queuedExplicitHydrationTargets.length; i++) {
        var queuedTarget = queuedExplicitHydrationTargets[i];
        queuedTarget.blockedOn === unblocked && (queuedTarget.blockedOn = null);
      }
      for (; 0 < queuedExplicitHydrationTargets.length && (i = queuedExplicitHydrationTargets[0], null === i.blockedOn); )
        attemptExplicitHydrationTarget(i), null === i.blockedOn && queuedExplicitHydrationTargets.shift();
      i = (unblocked.ownerDocument || unblocked).$$reactFormReplay;
      if (null != i)
        for (queuedTarget = 0; queuedTarget < i.length; queuedTarget += 3) {
          var form = i[queuedTarget], submitterOrAction = i[queuedTarget + 1], formProps = form[internalPropsKey] || null;
          if ("function" === typeof submitterOrAction)
            formProps || scheduleReplayQueueIfNeeded(i);
          else if (formProps) {
            var action = null;
            if (submitterOrAction && submitterOrAction.hasAttribute("formAction"))
              if (form = submitterOrAction, formProps = submitterOrAction[internalPropsKey] || null)
                action = formProps.formAction;
              else {
                if (null !== findInstanceBlockingTarget(form)) continue;
              }
            else action = formProps.action;
            "function" === typeof action ? i[queuedTarget + 1] = action : (i.splice(queuedTarget, 3), queuedTarget -= 3);
            scheduleReplayQueueIfNeeded(i);
          }
        }
    }
    function defaultOnDefaultTransitionIndicator() {
      function handleNavigate(event) {
        event.canIntercept && "react-transition" === event.info && event.intercept({
          handler: function() {
            return new Promise(function(resolve) {
              return pendingResolve = resolve;
            });
          },
          focusReset: "manual",
          scroll: "manual"
        });
      }
      function handleNavigateComplete() {
        null !== pendingResolve && (pendingResolve(), pendingResolve = null);
        isCancelled || setTimeout(startFakeNavigation, 20);
      }
      function startFakeNavigation() {
        if (!isCancelled && !navigation.transition) {
          var currentEntry = navigation.currentEntry;
          currentEntry && null != currentEntry.url && navigation.navigate(currentEntry.url, {
            state: currentEntry.getState(),
            info: "react-transition",
            history: "replace"
          });
        }
      }
      if ("object" === typeof navigation) {
        var isCancelled = false, pendingResolve = null;
        navigation.addEventListener("navigate", handleNavigate);
        navigation.addEventListener("navigatesuccess", handleNavigateComplete);
        navigation.addEventListener("navigateerror", handleNavigateComplete);
        setTimeout(startFakeNavigation, 100);
        return function() {
          isCancelled = true;
          navigation.removeEventListener("navigate", handleNavigate);
          navigation.removeEventListener(
            "navigatesuccess",
            handleNavigateComplete
          );
          navigation.removeEventListener(
            "navigateerror",
            handleNavigateComplete
          );
          null !== pendingResolve && (pendingResolve(), pendingResolve = null);
        };
      }
    }
    function ReactDOMRoot(internalRoot) {
      this._internalRoot = internalRoot;
    }
    function ReactDOMHydrationRoot(internalRoot) {
      this._internalRoot = internalRoot;
    }
    function warnIfReactDOMContainerInDEV(container) {
      container[internalContainerInstanceKey] && (container._reactRootContainer ? console.error(
        "You are calling ReactDOMClient.createRoot() on a container that was previously passed to ReactDOM.render(). This is not supported."
      ) : console.error(
        "You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it."
      ));
    }
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
    var Scheduler = requireScheduler(), React2 = requireReact(), ReactDOM = requireReactDom(), assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.element"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
    var REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity");
    var REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel");
    var MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, NotPending = Object.freeze({
      pending: false,
      data: null,
      method: null,
      action: null
    }), valueStack = [];
    var fiberStack = [];
    var index$jscomp$0 = -1, contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
    disabledLog.__reactDisabledLog = true;
    var prefix, suffix, reentry = false;
    var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)();
    var current = null, isRendering = false, hasOwnProperty2 = Object.prototype.hasOwnProperty, scheduleCallback$3 = Scheduler.unstable_scheduleCallback, cancelCallback$1 = Scheduler.unstable_cancelCallback, shouldYield = Scheduler.unstable_shouldYield, requestPaint = Scheduler.unstable_requestPaint, now$1 = Scheduler.unstable_now, getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel, ImmediatePriority = Scheduler.unstable_ImmediatePriority, UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler.unstable_NormalPriority, LowPriority = Scheduler.unstable_LowPriority, IdlePriority = Scheduler.unstable_IdlePriority, log$1 = Scheduler.log, unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, hasLoggedError = false, isDevToolsPresent = "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2, nextTransitionUpdateLane = 256, nextTransitionDeferredLane = 262144, nextRetryLane = 4194304, DiscreteEventPriority = 2, ContinuousEventPriority = 8, DefaultEventPriority = 32, IdleEventPriority = 268435456, randomKey = Math.random().toString(36).slice(2), internalInstanceKey = "__reactFiber$" + randomKey, internalPropsKey = "__reactProps$" + randomKey, internalContainerInstanceKey = "__reactContainer$" + randomKey, internalEventHandlersKey = "__reactEvents$" + randomKey, internalEventHandlerListenersKey = "__reactListeners$" + randomKey, internalEventHandlesSetKey = "__reactHandles$" + randomKey, internalRootNodeResourcesKey = "__reactResources$" + randomKey, internalHoistableMarker = "__reactMarker$" + randomKey, allNativeEvents = /* @__PURE__ */ new Set(), registrationNameDependencies = {}, possibleRegistrationNames = {}, hasReadOnlyValue = {
      button: true,
      checkbox: true,
      image: true,
      hidden: true,
      radio: true,
      reset: true,
      submit: true
    }, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
      "^[: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]*$"
    ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n"\\]/g, didWarnValueDefaultValue$1 = false, didWarnCheckedDefaultChecked = false, didWarnSelectedSetOnOption = false, didWarnInvalidChild = false, didWarnInvalidInnerHTML = false;
    var didWarnValueDefaultValue = false;
    var valuePropNames = ["value", "defaultValue"], didWarnValDefaultVal = false, needsEscaping = /["'&<>\n\t]|^\s|\s$/, specialTags = "address applet area article aside base basefont bgsound blockquote body br button caption center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p param plaintext pre script section select source style summary table tbody td template textarea tfoot th thead title tr track ul wbr xmp".split(
      " "
    ), inScopeTags = "applet caption html table td th marquee object template foreignObject desc title".split(
      " "
    ), buttonScopeTags = inScopeTags.concat(["button"]), impliedEndTags = "dd dt li option optgroup p rp rt".split(" "), emptyAncestorInfoDev = {
      current: null,
      formTag: null,
      aTagInScope: null,
      buttonTagInScope: null,
      nobrTagInScope: null,
      pTagInButtonScope: null,
      listItemTagAutoclosing: null,
      dlItemTagAutoclosing: null,
      containerTagInScope: null,
      implicitRootScope: false
    }, didWarn = {}, shorthandToLonghand = {
      animation: "animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationPlayState animationTimingFunction".split(
        " "
      ),
      background: "backgroundAttachment backgroundClip backgroundColor backgroundImage backgroundOrigin backgroundPositionX backgroundPositionY backgroundRepeat backgroundSize".split(
        " "
      ),
      backgroundPosition: ["backgroundPositionX", "backgroundPositionY"],
      border: "borderBottomColor borderBottomStyle borderBottomWidth borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeftColor borderLeftStyle borderLeftWidth borderRightColor borderRightStyle borderRightWidth borderTopColor borderTopStyle borderTopWidth".split(
        " "
      ),
      borderBlockEnd: [
        "borderBlockEndColor",
        "borderBlockEndStyle",
        "borderBlockEndWidth"
      ],
      borderBlockStart: [
        "borderBlockStartColor",
        "borderBlockStartStyle",
        "borderBlockStartWidth"
      ],
      borderBottom: [
        "borderBottomColor",
        "borderBottomStyle",
        "borderBottomWidth"
      ],
      borderColor: [
        "borderBottomColor",
        "borderLeftColor",
        "borderRightColor",
        "borderTopColor"
      ],
      borderImage: [
        "borderImageOutset",
        "borderImageRepeat",
        "borderImageSlice",
        "borderImageSource",
        "borderImageWidth"
      ],
      borderInlineEnd: [
        "borderInlineEndColor",
        "borderInlineEndStyle",
        "borderInlineEndWidth"
      ],
      borderInlineStart: [
        "borderInlineStartColor",
        "borderInlineStartStyle",
        "borderInlineStartWidth"
      ],
      borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"],
      borderRadius: [
        "borderBottomLeftRadius",
        "borderBottomRightRadius",
        "borderTopLeftRadius",
        "borderTopRightRadius"
      ],
      borderRight: [
        "borderRightColor",
        "borderRightStyle",
        "borderRightWidth"
      ],
      borderStyle: [
        "borderBottomStyle",
        "borderLeftStyle",
        "borderRightStyle",
        "borderTopStyle"
      ],
      borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"],
      borderWidth: [
        "borderBottomWidth",
        "borderLeftWidth",
        "borderRightWidth",
        "borderTopWidth"
      ],
      columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
      columns: ["columnCount", "columnWidth"],
      flex: ["flexBasis", "flexGrow", "flexShrink"],
      flexFlow: ["flexDirection", "flexWrap"],
      font: "fontFamily fontFeatureSettings fontKerning fontLanguageOverride fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontVariantAlternates fontVariantCaps fontVariantEastAsian fontVariantLigatures fontVariantNumeric fontVariantPosition fontWeight lineHeight".split(
        " "
      ),
      fontVariant: "fontVariantAlternates fontVariantCaps fontVariantEastAsian fontVariantLigatures fontVariantNumeric fontVariantPosition".split(
        " "
      ),
      gap: ["columnGap", "rowGap"],
      grid: "gridAutoColumns gridAutoFlow gridAutoRows gridTemplateAreas gridTemplateColumns gridTemplateRows".split(
        " "
      ),
      gridArea: [
        "gridColumnEnd",
        "gridColumnStart",
        "gridRowEnd",
        "gridRowStart"
      ],
      gridColumn: ["gridColumnEnd", "gridColumnStart"],
      gridColumnGap: ["columnGap"],
      gridGap: ["columnGap", "rowGap"],
      gridRow: ["gridRowEnd", "gridRowStart"],
      gridRowGap: ["rowGap"],
      gridTemplate: [
        "gridTemplateAreas",
        "gridTemplateColumns",
        "gridTemplateRows"
      ],
      listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
      margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"],
      marker: ["markerEnd", "markerMid", "markerStart"],
      mask: "maskClip maskComposite maskImage maskMode maskOrigin maskPositionX maskPositionY maskRepeat maskSize".split(
        " "
      ),
      maskPosition: ["maskPositionX", "maskPositionY"],
      outline: ["outlineColor", "outlineStyle", "outlineWidth"],
      overflow: ["overflowX", "overflowY"],
      padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"],
      placeContent: ["alignContent", "justifyContent"],
      placeItems: ["alignItems", "justifyItems"],
      placeSelf: ["alignSelf", "justifySelf"],
      textDecoration: [
        "textDecorationColor",
        "textDecorationLine",
        "textDecorationStyle"
      ],
      textEmphasis: ["textEmphasisColor", "textEmphasisStyle"],
      transition: [
        "transitionDelay",
        "transitionDuration",
        "transitionProperty",
        "transitionTimingFunction"
      ],
      wordWrap: ["overflowWrap"]
    }, uppercasePattern = /([A-Z])/g, msPattern$1 = /^ms-/, badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, msPattern = /^-ms-/, hyphenPattern = /-(.)/g, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = false, warnedForInfinityValue = false, unitlessNumbers = new Set(
      "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
        " "
      )
    ), MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML", SVG_NAMESPACE = "http://www.w3.org/2000/svg", aliases = /* @__PURE__ */ new Map([
      ["acceptCharset", "accept-charset"],
      ["htmlFor", "for"],
      ["httpEquiv", "http-equiv"],
      ["crossOrigin", "crossorigin"],
      ["accentHeight", "accent-height"],
      ["alignmentBaseline", "alignment-baseline"],
      ["arabicForm", "arabic-form"],
      ["baselineShift", "baseline-shift"],
      ["capHeight", "cap-height"],
      ["clipPath", "clip-path"],
      ["clipRule", "clip-rule"],
      ["colorInterpolation", "color-interpolation"],
      ["colorInterpolationFilters", "color-interpolation-filters"],
      ["colorProfile", "color-profile"],
      ["colorRendering", "color-rendering"],
      ["dominantBaseline", "dominant-baseline"],
      ["enableBackground", "enable-background"],
      ["fillOpacity", "fill-opacity"],
      ["fillRule", "fill-rule"],
      ["floodColor", "flood-color"],
      ["floodOpacity", "flood-opacity"],
      ["fontFamily", "font-family"],
      ["fontSize", "font-size"],
      ["fontSizeAdjust", "font-size-adjust"],
      ["fontStretch", "font-stretch"],
      ["fontStyle", "font-style"],
      ["fontVariant", "font-variant"],
      ["fontWeight", "font-weight"],
      ["glyphName", "glyph-name"],
      ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
      ["glyphOrientationVertical", "glyph-orientation-vertical"],
      ["horizAdvX", "horiz-adv-x"],
      ["horizOriginX", "horiz-origin-x"],
      ["imageRendering", "image-rendering"],
      ["letterSpacing", "letter-spacing"],
      ["lightingColor", "lighting-color"],
      ["markerEnd", "marker-end"],
      ["markerMid", "marker-mid"],
      ["markerStart", "marker-start"],
      ["overlinePosition", "overline-position"],
      ["overlineThickness", "overline-thickness"],
      ["paintOrder", "paint-order"],
      ["panose-1", "panose-1"],
      ["pointerEvents", "pointer-events"],
      ["renderingIntent", "rendering-intent"],
      ["shapeRendering", "shape-rendering"],
      ["stopColor", "stop-color"],
      ["stopOpacity", "stop-opacity"],
      ["strikethroughPosition", "strikethrough-position"],
      ["strikethroughThickness", "strikethrough-thickness"],
      ["strokeDasharray", "stroke-dasharray"],
      ["strokeDashoffset", "stroke-dashoffset"],
      ["strokeLinecap", "stroke-linecap"],
      ["strokeLinejoin", "stroke-linejoin"],
      ["strokeMiterlimit", "stroke-miterlimit"],
      ["strokeOpacity", "stroke-opacity"],
      ["strokeWidth", "stroke-width"],
      ["textAnchor", "text-anchor"],
      ["textDecoration", "text-decoration"],
      ["textRendering", "text-rendering"],
      ["transformOrigin", "transform-origin"],
      ["underlinePosition", "underline-position"],
      ["underlineThickness", "underline-thickness"],
      ["unicodeBidi", "unicode-bidi"],
      ["unicodeRange", "unicode-range"],
      ["unitsPerEm", "units-per-em"],
      ["vAlphabetic", "v-alphabetic"],
      ["vHanging", "v-hanging"],
      ["vIdeographic", "v-ideographic"],
      ["vMathematical", "v-mathematical"],
      ["vectorEffect", "vector-effect"],
      ["vertAdvY", "vert-adv-y"],
      ["vertOriginX", "vert-origin-x"],
      ["vertOriginY", "vert-origin-y"],
      ["wordSpacing", "word-spacing"],
      ["writingMode", "writing-mode"],
      ["xmlnsXlink", "xmlns:xlink"],
      ["xHeight", "x-height"]
    ]), possibleStandardNames = {
      accept: "accept",
      acceptcharset: "acceptCharset",
      "accept-charset": "acceptCharset",
      accesskey: "accessKey",
      action: "action",
      allowfullscreen: "allowFullScreen",
      alt: "alt",
      as: "as",
      async: "async",
      autocapitalize: "autoCapitalize",
      autocomplete: "autoComplete",
      autocorrect: "autoCorrect",
      autofocus: "autoFocus",
      autoplay: "autoPlay",
      autosave: "autoSave",
      capture: "capture",
      cellpadding: "cellPadding",
      cellspacing: "cellSpacing",
      challenge: "challenge",
      charset: "charSet",
      checked: "checked",
      children: "children",
      cite: "cite",
      class: "className",
      classid: "classID",
      classname: "className",
      cols: "cols",
      colspan: "colSpan",
      content: "content",
      contenteditable: "contentEditable",
      contextmenu: "contextMenu",
      controls: "controls",
      controlslist: "controlsList",
      coords: "coords",
      crossorigin: "crossOrigin",
      dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
      data: "data",
      datetime: "dateTime",
      default: "default",
      defaultchecked: "defaultChecked",
      defaultvalue: "defaultValue",
      defer: "defer",
      dir: "dir",
      disabled: "disabled",
      disablepictureinpicture: "disablePictureInPicture",
      disableremoteplayback: "disableRemotePlayback",
      download: "download",
      draggable: "draggable",
      enctype: "encType",
      enterkeyhint: "enterKeyHint",
      fetchpriority: "fetchPriority",
      for: "htmlFor",
      form: "form",
      formmethod: "formMethod",
      formaction: "formAction",
      formenctype: "formEncType",
      formnovalidate: "formNoValidate",
      formtarget: "formTarget",
      frameborder: "frameBorder",
      headers: "headers",
      height: "height",
      hidden: "hidden",
      high: "high",
      href: "href",
      hreflang: "hrefLang",
      htmlfor: "htmlFor",
      httpequiv: "httpEquiv",
      "http-equiv": "httpEquiv",
      icon: "icon",
      id: "id",
      imagesizes: "imageSizes",
      imagesrcset: "imageSrcSet",
      inert: "inert",
      innerhtml: "innerHTML",
      inputmode: "inputMode",
      integrity: "integrity",
      is: "is",
      itemid: "itemID",
      itemprop: "itemProp",
      itemref: "itemRef",
      itemscope: "itemScope",
      itemtype: "itemType",
      keyparams: "keyParams",
      keytype: "keyType",
      kind: "kind",
      label: "label",
      lang: "lang",
      list: "list",
      loop: "loop",
      low: "low",
      manifest: "manifest",
      marginwidth: "marginWidth",
      marginheight: "marginHeight",
      max: "max",
      maxlength: "maxLength",
      media: "media",
      mediagroup: "mediaGroup",
      method: "method",
      min: "min",
      minlength: "minLength",
      multiple: "multiple",
      muted: "muted",
      name: "name",
      nomodule: "noModule",
      nonce: "nonce",
      novalidate: "noValidate",
      open: "open",
      optimum: "optimum",
      pattern: "pattern",
      placeholder: "placeholder",
      playsinline: "playsInline",
      poster: "poster",
      preload: "preload",
      profile: "profile",
      radiogroup: "radioGroup",
      readonly: "readOnly",
      referrerpolicy: "referrerPolicy",
      rel: "rel",
      required: "required",
      reversed: "reversed",
      role: "role",
      rows: "rows",
      rowspan: "rowSpan",
      sandbox: "sandbox",
      scope: "scope",
      scoped: "scoped",
      scrolling: "scrolling",
      seamless: "seamless",
      selected: "selected",
      shape: "shape",
      size: "size",
      sizes: "sizes",
      span: "span",
      spellcheck: "spellCheck",
      src: "src",
      srcdoc: "srcDoc",
      srclang: "srcLang",
      srcset: "srcSet",
      start: "start",
      step: "step",
      style: "style",
      summary: "summary",
      tabindex: "tabIndex",
      target: "target",
      title: "title",
      type: "type",
      usemap: "useMap",
      value: "value",
      width: "width",
      wmode: "wmode",
      wrap: "wrap",
      about: "about",
      accentheight: "accentHeight",
      "accent-height": "accentHeight",
      accumulate: "accumulate",
      additive: "additive",
      alignmentbaseline: "alignmentBaseline",
      "alignment-baseline": "alignmentBaseline",
      allowreorder: "allowReorder",
      alphabetic: "alphabetic",
      amplitude: "amplitude",
      arabicform: "arabicForm",
      "arabic-form": "arabicForm",
      ascent: "ascent",
      attributename: "attributeName",
      attributetype: "attributeType",
      autoreverse: "autoReverse",
      azimuth: "azimuth",
      basefrequency: "baseFrequency",
      baselineshift: "baselineShift",
      "baseline-shift": "baselineShift",
      baseprofile: "baseProfile",
      bbox: "bbox",
      begin: "begin",
      bias: "bias",
      by: "by",
      calcmode: "calcMode",
      capheight: "capHeight",
      "cap-height": "capHeight",
      clip: "clip",
      clippath: "clipPath",
      "clip-path": "clipPath",
      clippathunits: "clipPathUnits",
      cliprule: "clipRule",
      "clip-rule": "clipRule",
      color: "color",
      colorinterpolation: "colorInterpolation",
      "color-interpolation": "colorInterpolation",
      colorinterpolationfilters: "colorInterpolationFilters",
      "color-interpolation-filters": "colorInterpolationFilters",
      colorprofile: "colorProfile",
      "color-profile": "colorProfile",
      colorrendering: "colorRendering",
      "color-rendering": "colorRendering",
      contentscripttype: "contentScriptType",
      contentstyletype: "contentStyleType",
      cursor: "cursor",
      cx: "cx",
      cy: "cy",
      d: "d",
      datatype: "datatype",
      decelerate: "decelerate",
      descent: "descent",
      diffuseconstant: "diffuseConstant",
      direction: "direction",
      display: "display",
      divisor: "divisor",
      dominantbaseline: "dominantBaseline",
      "dominant-baseline": "dominantBaseline",
      dur: "dur",
      dx: "dx",
      dy: "dy",
      edgemode: "edgeMode",
      elevation: "elevation",
      enablebackground: "enableBackground",
      "enable-background": "enableBackground",
      end: "end",
      exponent: "exponent",
      externalresourcesrequired: "externalResourcesRequired",
      fill: "fill",
      fillopacity: "fillOpacity",
      "fill-opacity": "fillOpacity",
      fillrule: "fillRule",
      "fill-rule": "fillRule",
      filter: "filter",
      filterres: "filterRes",
      filterunits: "filterUnits",
      floodopacity: "floodOpacity",
      "flood-opacity": "floodOpacity",
      floodcolor: "floodColor",
      "flood-color": "floodColor",
      focusable: "focusable",
      fontfamily: "fontFamily",
      "font-family": "fontFamily",
      fontsize: "fontSize",
      "font-size": "fontSize",
      fontsizeadjust: "fontSizeAdjust",
      "font-size-adjust": "fontSizeAdjust",
      fontstretch: "fontStretch",
      "font-stretch": "fontStretch",
      fontstyle: "fontStyle",
      "font-style": "fontStyle",
      fontvariant: "fontVariant",
      "font-variant": "fontVariant",
      fontweight: "fontWeight",
      "font-weight": "fontWeight",
      format: "format",
      from: "from",
      fx: "fx",
      fy: "fy",
      g1: "g1",
      g2: "g2",
      glyphname: "glyphName",
      "glyph-name": "glyphName",
      glyphorientationhorizontal: "glyphOrientationHorizontal",
      "glyph-orientation-horizontal": "glyphOrientationHorizontal",
      glyphorientationvertical: "glyphOrientationVertical",
      "glyph-orientation-vertical": "glyphOrientationVertical",
      glyphref: "glyphRef",
      gradienttransform: "gradientTransform",
      gradientunits: "gradientUnits",
      hanging: "hanging",
      horizadvx: "horizAdvX",
      "horiz-adv-x": "horizAdvX",
      horizoriginx: "horizOriginX",
      "horiz-origin-x": "horizOriginX",
      ideographic: "ideographic",
      imagerendering: "imageRendering",
      "image-rendering": "imageRendering",
      in2: "in2",
      in: "in",
      inlist: "inlist",
      intercept: "intercept",
      k1: "k1",
      k2: "k2",
      k3: "k3",
      k4: "k4",
      k: "k",
      kernelmatrix: "kernelMatrix",
      kernelunitlength: "kernelUnitLength",
      kerning: "kerning",
      keypoints: "keyPoints",
      keysplines: "keySplines",
      keytimes: "keyTimes",
      lengthadjust: "lengthAdjust",
      letterspacing: "letterSpacing",
      "letter-spacing": "letterSpacing",
      lightingcolor: "lightingColor",
      "lighting-color": "lightingColor",
      limitingconeangle: "limitingConeAngle",
      local: "local",
      markerend: "markerEnd",
      "marker-end": "markerEnd",
      markerheight: "markerHeight",
      markermid: "markerMid",
      "marker-mid": "markerMid",
      markerstart: "markerStart",
      "marker-start": "markerStart",
      markerunits: "markerUnits",
      markerwidth: "markerWidth",
      mask: "mask",
      maskcontentunits: "maskContentUnits",
      maskunits: "maskUnits",
      mathematical: "mathematical",
      mode: "mode",
      numoctaves: "numOctaves",
      offset: "offset",
      opacity: "opacity",
      operator: "operator",
      order: "order",
      orient: "orient",
      orientation: "orientation",
      origin: "origin",
      overflow: "overflow",
      overlineposition: "overlinePosition",
      "overline-position": "overlinePosition",
      overlinethickness: "overlineThickness",
      "overline-thickness": "overlineThickness",
      paintorder: "paintOrder",
      "paint-order": "paintOrder",
      panose1: "panose1",
      "panose-1": "panose1",
      pathlength: "pathLength",
      patterncontentunits: "patternContentUnits",
      patterntransform: "patternTransform",
      patternunits: "patternUnits",
      pointerevents: "pointerEvents",
      "pointer-events": "pointerEvents",
      points: "points",
      pointsatx: "pointsAtX",
      pointsaty: "pointsAtY",
      pointsatz: "pointsAtZ",
      popover: "popover",
      popovertarget: "popoverTarget",
      popovertargetaction: "popoverTargetAction",
      prefix: "prefix",
      preservealpha: "preserveAlpha",
      preserveaspectratio: "preserveAspectRatio",
      primitiveunits: "primitiveUnits",
      property: "property",
      r: "r",
      radius: "radius",
      refx: "refX",
      refy: "refY",
      renderingintent: "renderingIntent",
      "rendering-intent": "renderingIntent",
      repeatcount: "repeatCount",
      repeatdur: "repeatDur",
      requiredextensions: "requiredExtensions",
      requiredfeatures: "requiredFeatures",
      resource: "resource",
      restart: "restart",
      result: "result",
      results: "results",
      rotate: "rotate",
      rx: "rx",
      ry: "ry",
      scale: "scale",
      security: "security",
      seed: "seed",
      shaperendering: "shapeRendering",
      "shape-rendering": "shapeRendering",
      slope: "slope",
      spacing: "spacing",
      specularconstant: "specularConstant",
      specularexponent: "specularExponent",
      speed: "speed",
      spreadmethod: "spreadMethod",
      startoffset: "startOffset",
      stddeviation: "stdDeviation",
      stemh: "stemh",
      stemv: "stemv",
      stitchtiles: "stitchTiles",
      stopcolor: "stopColor",
      "stop-color": "stopColor",
      stopopacity: "stopOpacity",
      "stop-opacity": "stopOpacity",
      strikethroughposition: "strikethroughPosition",
      "strikethrough-position": "strikethroughPosition",
      strikethroughthickness: "strikethroughThickness",
      "strikethrough-thickness": "strikethroughThickness",
      string: "string",
      stroke: "stroke",
      strokedasharray: "strokeDasharray",
      "stroke-dasharray": "strokeDasharray",
      strokedashoffset: "strokeDashoffset",
      "stroke-dashoffset": "strokeDashoffset",
      strokelinecap: "strokeLinecap",
      "stroke-linecap": "strokeLinecap",
      strokelinejoin: "strokeLinejoin",
      "stroke-linejoin": "strokeLinejoin",
      strokemiterlimit: "strokeMiterlimit",
      "stroke-miterlimit": "strokeMiterlimit",
      strokewidth: "strokeWidth",
      "stroke-width": "strokeWidth",
      strokeopacity: "strokeOpacity",
      "stroke-opacity": "strokeOpacity",
      suppresscontenteditablewarning: "suppressContentEditableWarning",
      suppresshydrationwarning: "suppressHydrationWarning",
      surfacescale: "surfaceScale",
      systemlanguage: "systemLanguage",
      tablevalues: "tableValues",
      targetx: "targetX",
      targety: "targetY",
      textanchor: "textAnchor",
      "text-anchor": "textAnchor",
      textdecoration: "textDecoration",
      "text-decoration": "textDecoration",
      textlength: "textLength",
      textrendering: "textRendering",
      "text-rendering": "textRendering",
      to: "to",
      transform: "transform",
      transformorigin: "transformOrigin",
      "transform-origin": "transformOrigin",
      typeof: "typeof",
      u1: "u1",
      u2: "u2",
      underlineposition: "underlinePosition",
      "underline-position": "underlinePosition",
      underlinethickness: "underlineThickness",
      "underline-thickness": "underlineThickness",
      unicode: "unicode",
      unicodebidi: "unicodeBidi",
      "unicode-bidi": "unicodeBidi",
      unicoderange: "unicodeRange",
      "unicode-range": "unicodeRange",
      unitsperem: "unitsPerEm",
      "units-per-em": "unitsPerEm",
      unselectable: "unselectable",
      valphabetic: "vAlphabetic",
      "v-alphabetic": "vAlphabetic",
      values: "values",
      vectoreffect: "vectorEffect",
      "vector-effect": "vectorEffect",
      version: "version",
      vertadvy: "vertAdvY",
      "vert-adv-y": "vertAdvY",
      vertoriginx: "vertOriginX",
      "vert-origin-x": "vertOriginX",
      vertoriginy: "vertOriginY",
      "vert-origin-y": "vertOriginY",
      vhanging: "vHanging",
      "v-hanging": "vHanging",
      videographic: "vIdeographic",
      "v-ideographic": "vIdeographic",
      viewbox: "viewBox",
      viewtarget: "viewTarget",
      visibility: "visibility",
      vmathematical: "vMathematical",
      "v-mathematical": "vMathematical",
      vocab: "vocab",
      widths: "widths",
      wordspacing: "wordSpacing",
      "word-spacing": "wordSpacing",
      writingmode: "writingMode",
      "writing-mode": "writingMode",
      x1: "x1",
      x2: "x2",
      x: "x",
      xchannelselector: "xChannelSelector",
      xheight: "xHeight",
      "x-height": "xHeight",
      xlinkactuate: "xlinkActuate",
      "xlink:actuate": "xlinkActuate",
      xlinkarcrole: "xlinkArcrole",
      "xlink:arcrole": "xlinkArcrole",
      xlinkhref: "xlinkHref",
      "xlink:href": "xlinkHref",
      xlinkrole: "xlinkRole",
      "xlink:role": "xlinkRole",
      xlinkshow: "xlinkShow",
      "xlink:show": "xlinkShow",
      xlinktitle: "xlinkTitle",
      "xlink:title": "xlinkTitle",
      xlinktype: "xlinkType",
      "xlink:type": "xlinkType",
      xmlbase: "xmlBase",
      "xml:base": "xmlBase",
      xmllang: "xmlLang",
      "xml:lang": "xmlLang",
      xmlns: "xmlns",
      "xml:space": "xmlSpace",
      xmlnsxlink: "xmlnsXlink",
      "xmlns:xlink": "xmlnsXlink",
      xmlspace: "xmlSpace",
      y1: "y1",
      y2: "y2",
      y: "y",
      ychannelselector: "yChannelSelector",
      z: "z",
      zoomandpan: "zoomAndPan"
    }, ariaProperties = {
      "aria-current": 0,
      "aria-description": 0,
      "aria-details": 0,
      "aria-disabled": 0,
      "aria-hidden": 0,
      "aria-invalid": 0,
      "aria-keyshortcuts": 0,
      "aria-label": 0,
      "aria-roledescription": 0,
      "aria-autocomplete": 0,
      "aria-checked": 0,
      "aria-expanded": 0,
      "aria-haspopup": 0,
      "aria-level": 0,
      "aria-modal": 0,
      "aria-multiline": 0,
      "aria-multiselectable": 0,
      "aria-orientation": 0,
      "aria-placeholder": 0,
      "aria-pressed": 0,
      "aria-readonly": 0,
      "aria-required": 0,
      "aria-selected": 0,
      "aria-sort": 0,
      "aria-valuemax": 0,
      "aria-valuemin": 0,
      "aria-valuenow": 0,
      "aria-valuetext": 0,
      "aria-atomic": 0,
      "aria-busy": 0,
      "aria-live": 0,
      "aria-relevant": 0,
      "aria-dropeffect": 0,
      "aria-grabbed": 0,
      "aria-activedescendant": 0,
      "aria-colcount": 0,
      "aria-colindex": 0,
      "aria-colspan": 0,
      "aria-controls": 0,
      "aria-describedby": 0,
      "aria-errormessage": 0,
      "aria-flowto": 0,
      "aria-labelledby": 0,
      "aria-owns": 0,
      "aria-posinset": 0,
      "aria-rowcount": 0,
      "aria-rowindex": 0,
      "aria-rowspan": 0,
      "aria-setsize": 0,
      "aria-braillelabel": 0,
      "aria-brailleroledescription": 0,
      "aria-colindextext": 0,
      "aria-rowindextext": 0
    }, warnedProperties$1 = {}, rARIA$1 = RegExp(
      "^(aria)-[: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]*$"
    ), rARIACamel$1 = RegExp(
      "^(aria)[A-Z][: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]*$"
    ), didWarnValueNull = false, warnedProperties = {}, EVENT_NAME_REGEX = /^on./, INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/, rARIA = RegExp(
      "^(aria)-[: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]*$"
    ), rARIACamel = RegExp(
      "^(aria)[A-Z][: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]*$"
    ), isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i, currentReplayingEvent = null, restoreTarget = null, restoreQueue = null, isInsideEventHandler = false, canUseDOM = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), passiveBrowserEventsSupported = false;
    if (canUseDOM)
      try {
        var options$jscomp$0 = {};
        Object.defineProperty(options$jscomp$0, "passive", {
          get: function() {
            passiveBrowserEventsSupported = true;
          }
        });
        window.addEventListener("test", options$jscomp$0, options$jscomp$0);
        window.removeEventListener("test", options$jscomp$0, options$jscomp$0);
      } catch (e) {
        passiveBrowserEventsSupported = false;
      }
    var root2 = null, startText = null, fallbackText = null, EventInterface = {
      eventPhase: 0,
      bubbles: 0,
      cancelable: 0,
      timeStamp: function(event) {
        return event.timeStamp || Date.now();
      },
      defaultPrevented: 0,
      isTrusted: 0
    }, SyntheticEvent = createSyntheticEvent(EventInterface), UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }), SyntheticUIEvent = createSyntheticEvent(UIEventInterface), lastMovementX, lastMovementY, lastMouseEvent, MouseEventInterface = assign({}, UIEventInterface, {
      screenX: 0,
      screenY: 0,
      clientX: 0,
      clientY: 0,
      pageX: 0,
      pageY: 0,
      ctrlKey: 0,
      shiftKey: 0,
      altKey: 0,
      metaKey: 0,
      getModifierState: getEventModifierState,
      button: 0,
      buttons: 0,
      relatedTarget: function(event) {
        return void 0 === event.relatedTarget ? event.fromElement === event.srcElement ? event.toElement : event.fromElement : event.relatedTarget;
      },
      movementX: function(event) {
        if ("movementX" in event) return event.movementX;
        event !== lastMouseEvent && (lastMouseEvent && "mousemove" === event.type ? (lastMovementX = event.screenX - lastMouseEvent.screenX, lastMovementY = event.screenY - lastMouseEvent.screenY) : lastMovementY = lastMovementX = 0, lastMouseEvent = event);
        return lastMovementX;
      },
      movementY: function(event) {
        return "movementY" in event ? event.movementY : lastMovementY;
      }
    }), SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface), DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }), SyntheticDragEvent = createSyntheticEvent(DragEventInterface), FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }), SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface), AnimationEventInterface = assign({}, EventInterface, {
      animationName: 0,
      elapsedTime: 0,
      pseudoElement: 0
    }), SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface), ClipboardEventInterface = assign({}, EventInterface, {
      clipboardData: function(event) {
        return "clipboardData" in event ? event.clipboardData : window.clipboardData;
      }
    }), SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface), CompositionEventInterface = assign({}, EventInterface, { data: 0 }), SyntheticCompositionEvent = createSyntheticEvent(
      CompositionEventInterface
    ), SyntheticInputEvent = SyntheticCompositionEvent, normalizeKey = {
      Esc: "Escape",
      Spacebar: " ",
      Left: "ArrowLeft",
      Up: "ArrowUp",
      Right: "ArrowRight",
      Down: "ArrowDown",
      Del: "Delete",
      Win: "OS",
      Menu: "ContextMenu",
      Apps: "ContextMenu",
      Scroll: "ScrollLock",
      MozPrintableKey: "Unidentified"
    }, translateToKey = {
      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"
    }, modifierKeyToProp = {
      Alt: "altKey",
      Control: "ctrlKey",
      Meta: "metaKey",
      Shift: "shiftKey"
    }, KeyboardEventInterface = assign({}, UIEventInterface, {
      key: function(nativeEvent) {
        if (nativeEvent.key) {
          var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
          if ("Unidentified" !== key) return key;
        }
        return "keypress" === nativeEvent.type ? (nativeEvent = getEventCharCode(nativeEvent), 13 === nativeEvent ? "Enter" : String.fromCharCode(nativeEvent)) : "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : "";
      },
      code: 0,
      location: 0,
      ctrlKey: 0,
      shiftKey: 0,
      altKey: 0,
      metaKey: 0,
      repeat: 0,
      locale: 0,
      getModifierState: getEventModifierState,
      charCode: function(event) {
        return "keypress" === event.type ? getEventCharCode(event) : 0;
      },
      keyCode: function(event) {
        return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
      },
      which: function(event) {
        return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
      }
    }), SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface), PointerEventInterface = assign({}, MouseEventInterface, {
      pointerId: 0,
      width: 0,
      height: 0,
      pressure: 0,
      tangentialPressure: 0,
      tiltX: 0,
      tiltY: 0,
      twist: 0,
      pointerType: 0,
      isPrimary: 0
    }), SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface), TouchEventInterface = assign({}, UIEventInterface, {
      touches: 0,
      targetTouches: 0,
      changedTouches: 0,
      altKey: 0,
      metaKey: 0,
      ctrlKey: 0,
      shiftKey: 0,
      getModifierState: getEventModifierState
    }), SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface), TransitionEventInterface = assign({}, EventInterface, {
      propertyName: 0,
      elapsedTime: 0,
      pseudoElement: 0
    }), SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface), WheelEventInterface = assign({}, MouseEventInterface, {
      deltaX: function(event) {
        return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
      },
      deltaY: function(event) {
        return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
      },
      deltaZ: 0,
      deltaMode: 0
    }), SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface), ToggleEventInterface = assign({}, EventInterface, {
      newState: 0,
      oldState: 0
    }), SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface), END_KEYCODES = [9, 13, 27, 32], START_KEYCODE = 229, canUseCompositionEvent = canUseDOM && "CompositionEvent" in window, documentMode = null;
    canUseDOM && "documentMode" in document && (documentMode = document.documentMode);
    var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode, useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && 8 < documentMode && 11 >= documentMode), SPACEBAR_CODE = 32, SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE), hasSpaceKeypress = false, isComposing = false, supportedInputTypes = {
      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
    }, activeElement$1 = null, activeElementInst$1 = null, isInputEventSupported = false;
    canUseDOM && (isInputEventSupported = isEventSupported("input") && (!document.documentMode || 9 < document.documentMode));
    var objectIs = "function" === typeof Object.is ? Object.is : is, skipSelectionChangeEvent = canUseDOM && "documentMode" in document && 11 >= document.documentMode, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = false, vendorPrefixes = {
      animationend: makePrefixMap("Animation", "AnimationEnd"),
      animationiteration: makePrefixMap("Animation", "AnimationIteration"),
      animationstart: makePrefixMap("Animation", "AnimationStart"),
      transitionrun: makePrefixMap("Transition", "TransitionRun"),
      transitionstart: makePrefixMap("Transition", "TransitionStart"),
      transitioncancel: makePrefixMap("Transition", "TransitionCancel"),
      transitionend: makePrefixMap("Transition", "TransitionEnd")
    }, prefixedEventNames = {}, style = {};
    canUseDOM && (style = document.createElement("div").style, "AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation, delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition);
    var ANIMATION_END = getVendorPrefixedEventName("animationend"), ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"), ANIMATION_START = getVendorPrefixedEventName("animationstart"), TRANSITION_RUN = getVendorPrefixedEventName("transitionrun"), TRANSITION_START = getVendorPrefixedEventName("transitionstart"), TRANSITION_CANCEL = getVendorPrefixedEventName("transitioncancel"), TRANSITION_END = getVendorPrefixedEventName("transitionend"), topLevelEventsToReactNames = /* @__PURE__ */ new Map(), simpleEventPluginEvents = "abort auxClick beforeToggle 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(
      " "
    );
    simpleEventPluginEvents.push("scrollEnd");
    var lastResetTime = 0;
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var localPerformance = performance;
      var getCurrentTime = function() {
        return localPerformance.now();
      };
    } else {
      var localDate = Date;
      getCurrentTime = function() {
        return localDate.now();
      };
    }
    var reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
          error
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process && "function" === typeof process.emit) {
        process.emit("uncaughtException", error);
        return;
      }
      console.error(error);
    }, OMITTED_PROP_ERROR = "This object has been omitted by React in the console log to avoid sending too much data from the server. Try logging smaller or more specific objects.", EMPTY_ARRAY = 0, COMPLEX_ARRAY = 1, PRIMITIVE_ARRAY = 2, ENTRIES_ARRAY = 3, REMOVED = "– ", ADDED = "+ ", UNCHANGED = "  ", supportsUserTiming = "undefined" !== typeof console && "function" === typeof console.timeStamp && "undefined" !== typeof performance && "function" === typeof performance.measure, COMPONENTS_TRACK = "Components ⚛", LANES_TRACK_GROUP = "Scheduler ⚛", currentTrack = "Blocking", alreadyWarnedForDeepEquality = false, reusableComponentDevToolDetails = {
      color: "primary",
      properties: null,
      tooltipText: "",
      track: COMPONENTS_TRACK
    }, reusableComponentOptions = {
      start: -0,
      end: -0,
      detail: { devtools: reusableComponentDevToolDetails }
    }, resuableChangedPropsEntry = ["Changed Props", ""], DEEP_EQUALITY_WARNING = "This component received deeply equal props. It might benefit from useMemo or the React Compiler in its owner.", reusableDeeplyEqualPropsEntry = ["Changed Props", DEEP_EQUALITY_WARNING], OffscreenVisible = 1, OffscreenPassiveEffectsConnected = 2, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, emptyContextObject = {};
    Object.freeze(emptyContextObject);
    var resolveFamily2 = null, failedBoundaries = null, NoMode = 0, ConcurrentMode = 1, ProfileMode = 2, StrictLegacyMode = 8, StrictEffectsMode = 16, SuspenseyImagesMode = 32;
    var hasBadMapPolyfill = false;
    try {
      var nonExtensibleObject = Object.preventExtensions({});
      /* @__PURE__ */ new Map([[nonExtensibleObject, null]]);
      /* @__PURE__ */ new Set([nonExtensibleObject]);
    } catch (e$3) {
      hasBadMapPolyfill = true;
    }
    var CapturedStacks = /* @__PURE__ */ new WeakMap(), forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(
      "Hydration Mismatch Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
    ), valueCursor = createCursor(null);
    var rendererCursorDEV = createCursor(null);
    var rendererSigil = {};
    var currentlyRenderingFiber$1 = null, lastContextDependency = null, isDisallowedContextReadInDEV = false, AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
      var listeners = [], signal = this.signal = {
        aborted: false,
        addEventListener: function(type2, listener) {
          listeners.push(listener);
        }
      };
      this.abort = function() {
        signal.aborted = true;
        listeners.forEach(function(listener) {
          return listener();
        });
      };
    }, scheduleCallback$2 = Scheduler.unstable_scheduleCallback, NormalPriority = Scheduler.unstable_NormalPriority, CacheContext = {
      $$typeof: REACT_CONTEXT_TYPE,
      Consumer: null,
      Provider: null,
      _currentValue: null,
      _currentValue2: null,
      _threadCount: 0,
      _currentRenderer: null,
      _currentRenderer2: null
    }, now = Scheduler.unstable_now, createTask = console.createTask ? console.createTask : function() {
      return null;
    }, SPAWNED_UPDATE = 1, PINGED_UPDATE = 2, renderStartTime = -0, commitStartTime = -0, commitEndTime = -0, commitErrors = null, profilerStartTime = -1.1, profilerEffectDuration = -0, componentEffectDuration = -0, componentEffectStartTime = -1.1, componentEffectEndTime = -1.1, componentEffectErrors = null, componentEffectSpawnedUpdate = false, blockingClampTime = -0, blockingUpdateTime = -1.1, blockingUpdateTask = null, blockingUpdateType = 0, blockingUpdateMethodName = null, blockingUpdateComponentName = null, blockingEventTime = -1.1, blockingEventType = null, blockingEventRepeatTime = -1.1, blockingSuspendedTime = -1.1, transitionClampTime = -0, transitionStartTime = -1.1, transitionUpdateTime = -1.1, transitionUpdateType = 0, transitionUpdateTask = null, transitionUpdateMethodName = null, transitionUpdateComponentName = null, transitionEventTime = -1.1, transitionEventType = null, transitionEventRepeatTime = -1.1, transitionSuspendedTime = -1.1, retryClampTime = -0, idleClampTime = -0, animatingLanes = 0, animatingTask = null, yieldReason = 0, yieldStartTime = -1.1, currentUpdateIsNested = false, nestedUpdateScheduled = false, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, prevOnStartTransitionFinish = ReactSharedInternals.S;
    ReactSharedInternals.S = function(transition, returnValue) {
      globalMostRecentTransitionTime = now$1();
      if ("object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then) {
        if (0 > transitionStartTime && 0 > transitionUpdateTime) {
          transitionStartTime = now();
          var newEventTime = resolveEventTimeStamp(), newEventType = resolveEventType();
          if (newEventTime !== transitionEventRepeatTime || newEventType !== transitionEventType)
            transitionEventRepeatTime = -1.1;
          transitionEventTime = newEventTime;
          transitionEventType = newEventType;
        }
        entangleAsyncAction(transition, returnValue);
      }
      null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
    };
    var resumedCache = createCursor(null), ReactStrictModeWarnings = {
      recordUnsafeLifecycleWarnings: function() {
      },
      flushPendingUnsafeLifecycleWarnings: function() {
      },
      recordLegacyContextWarning: function() {
      },
      flushLegacyContextWarning: function() {
      },
      discardPendingWarnings: function() {
      }
    }, pendingComponentWillMountWarnings = [], pendingUNSAFE_ComponentWillMountWarnings = [], pendingComponentWillReceivePropsWarnings = [], pendingUNSAFE_ComponentWillReceivePropsWarnings = [], pendingComponentWillUpdateWarnings = [], pendingUNSAFE_ComponentWillUpdateWarnings = [], didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set();
    ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) {
      didWarnAboutUnsafeLifecycles.has(fiber.type) || ("function" === typeof instance.componentWillMount && true !== instance.componentWillMount.__suppressDeprecationWarning && pendingComponentWillMountWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance.UNSAFE_componentWillMount && pendingUNSAFE_ComponentWillMountWarnings.push(fiber), "function" === typeof instance.componentWillReceiveProps && true !== instance.componentWillReceiveProps.__suppressDeprecationWarning && pendingComponentWillReceivePropsWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance.UNSAFE_componentWillReceiveProps && pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber), "function" === typeof instance.componentWillUpdate && true !== instance.componentWillUpdate.__suppressDeprecationWarning && pendingComponentWillUpdateWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance.UNSAFE_componentWillUpdate && pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber));
    };
    ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
      var componentWillMountUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingComponentWillMountWarnings.length && (pendingComponentWillMountWarnings.forEach(function(fiber) {
        componentWillMountUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingComponentWillMountWarnings = []);
      var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingUNSAFE_ComponentWillMountWarnings.length && (pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
        UNSAFE_componentWillMountUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingUNSAFE_ComponentWillMountWarnings = []);
      var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingComponentWillReceivePropsWarnings.length && (pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
        componentWillReceivePropsUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingComponentWillReceivePropsWarnings = []);
      var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingUNSAFE_ComponentWillReceivePropsWarnings.length && (pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(
        function(fiber) {
          UNSAFE_componentWillReceivePropsUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }
      ), pendingUNSAFE_ComponentWillReceivePropsWarnings = []);
      var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingComponentWillUpdateWarnings.length && (pendingComponentWillUpdateWarnings.forEach(function(fiber) {
        componentWillUpdateUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingComponentWillUpdateWarnings = []);
      var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
      0 < pendingUNSAFE_ComponentWillUpdateWarnings.length && (pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
        UNSAFE_componentWillUpdateUniqueNames.add(
          getComponentNameFromFiber(fiber) || "Component"
        );
        didWarnAboutUnsafeLifecycles.add(fiber.type);
      }), pendingUNSAFE_ComponentWillUpdateWarnings = []);
      if (0 < UNSAFE_componentWillMountUniqueNames.size) {
        var sortedNames = setToSortedString(
          UNSAFE_componentWillMountUniqueNames
        );
        console.error(
          "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s",
          sortedNames
        );
      }
      0 < UNSAFE_componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
        UNSAFE_componentWillReceivePropsUniqueNames
      ), console.error(
        "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < UNSAFE_componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(
        UNSAFE_componentWillUpdateUniqueNames
      ), console.error(
        "Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < componentWillMountUniqueNames.size && (sortedNames = setToSortedString(componentWillMountUniqueNames), console.warn(
        "componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
        componentWillReceivePropsUniqueNames
      ), console.warn(
        "componentWillReceiveProps has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
        sortedNames
      ));
      0 < componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(componentWillUpdateUniqueNames), console.warn(
        "componentWillUpdate has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
        sortedNames
      ));
    };
    var pendingLegacyContextWarning = /* @__PURE__ */ new Map(), didWarnAboutLegacyContext = /* @__PURE__ */ new Set();
    ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) {
      var strictRoot = null;
      for (var node2 = fiber; null !== node2; )
        node2.mode & StrictLegacyMode && (strictRoot = node2), node2 = node2.return;
      null === strictRoot ? console.error(
        "Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue."
      ) : !didWarnAboutLegacyContext.has(fiber.type) && (node2 = pendingLegacyContextWarning.get(strictRoot), null != fiber.type.contextTypes || null != fiber.type.childContextTypes || null !== instance && "function" === typeof instance.getChildContext) && (void 0 === node2 && (node2 = [], pendingLegacyContextWarning.set(strictRoot, node2)), node2.push(fiber));
    };
    ReactStrictModeWarnings.flushLegacyContextWarning = function() {
      pendingLegacyContextWarning.forEach(function(fiberArray) {
        if (0 !== fiberArray.length) {
          var firstFiber = fiberArray[0], uniqueNames = /* @__PURE__ */ new Set();
          fiberArray.forEach(function(fiber) {
            uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
            didWarnAboutLegacyContext.add(fiber.type);
          });
          var sortedNames = setToSortedString(uniqueNames);
          runWithFiberInDEV(firstFiber, function() {
            console.error(
              "Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://react.dev/link/legacy-context",
              sortedNames
            );
          });
        }
      });
    };
    ReactStrictModeWarnings.discardPendingWarnings = function() {
      pendingComponentWillMountWarnings = [];
      pendingUNSAFE_ComponentWillMountWarnings = [];
      pendingComponentWillReceivePropsWarnings = [];
      pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
      pendingComponentWillUpdateWarnings = [];
      pendingUNSAFE_ComponentWillUpdateWarnings = [];
      pendingLegacyContextWarning = /* @__PURE__ */ new Map();
    };
    var callComponent = {
      react_stack_bottom_frame: function(Component, props, secondArg) {
        var wasRendering = isRendering;
        isRendering = true;
        try {
          return Component(props, secondArg);
        } finally {
          isRendering = wasRendering;
        }
      }
    }, callComponentInDEV = callComponent.react_stack_bottom_frame.bind(callComponent), callRender = {
      react_stack_bottom_frame: function(instance) {
        var wasRendering = isRendering;
        isRendering = true;
        try {
          return instance.render();
        } finally {
          isRendering = wasRendering;
        }
      }
    }, callRenderInDEV = callRender.react_stack_bottom_frame.bind(callRender), callComponentDidMount = {
      react_stack_bottom_frame: function(finishedWork, instance) {
        try {
          instance.componentDidMount();
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
    }, callComponentDidMountInDEV = callComponentDidMount.react_stack_bottom_frame.bind(
      callComponentDidMount
    ), callComponentDidUpdate = {
      react_stack_bottom_frame: function(finishedWork, instance, prevProps, prevState, snapshot) {
        try {
          instance.componentDidUpdate(prevProps, prevState, snapshot);
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
    }, callComponentDidUpdateInDEV = callComponentDidUpdate.react_stack_bottom_frame.bind(
      callComponentDidUpdate
    ), callComponentDidCatch = {
      react_stack_bottom_frame: function(instance, errorInfo) {
        var stack = errorInfo.stack;
        instance.componentDidCatch(errorInfo.value, {
          componentStack: null !== stack ? stack : ""
        });
      }
    }, callComponentDidCatchInDEV = callComponentDidCatch.react_stack_bottom_frame.bind(
      callComponentDidCatch
    ), callComponentWillUnmount = {
      react_stack_bottom_frame: function(current2, nearestMountedAncestor, instance) {
        try {
          instance.componentWillUnmount();
        } catch (error) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error);
        }
      }
    }, callComponentWillUnmountInDEV = callComponentWillUnmount.react_stack_bottom_frame.bind(
      callComponentWillUnmount
    ), callCreate = {
      react_stack_bottom_frame: function(effect) {
        var create2 = effect.create;
        effect = effect.inst;
        create2 = create2();
        return effect.destroy = create2;
      }
    }, callCreateInDEV = callCreate.react_stack_bottom_frame.bind(callCreate), callDestroy = {
      react_stack_bottom_frame: function(current2, nearestMountedAncestor, destroy) {
        try {
          destroy();
        } catch (error) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error);
        }
      }
    }, callDestroyInDEV = callDestroy.react_stack_bottom_frame.bind(callDestroy), callLazyInit = {
      react_stack_bottom_frame: function(lazy) {
        var init2 = lazy._init;
        return init2(lazy._payload);
      }
    }, callLazyInitInDEV = callLazyInit.react_stack_bottom_frame.bind(callLazyInit), SuspenseException = Error(
      "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
    ), SuspenseyCommitException = Error(
      "Suspense Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
    ), SuspenseActionException = Error(
      "Suspense Exception: This is not a real error! It's an implementation detail of `useActionState` to interrupt the current render. You must either rethrow it immediately, or move the `useActionState` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary."
    ), noopSuspenseyCommitThenable = {
      then: function() {
        console.error(
          'Internal React error: A listener was unexpectedly attached to a "noop" thenable. This is a bug in React. Please file an issue.'
        );
      }
    }, suspendedThenable = null, needsToResetSuspendedThenableDEV = false, thenableState$1 = null, thenableIndexCounter$1 = 0, currentDebugInfo = null, didWarnAboutMaps;
    var didWarnAboutGenerators = didWarnAboutMaps = false;
    var ownerHasKeyUseWarning = {};
    var ownerHasFunctionTypeWarning = {};
    var ownerHasSymbolTypeWarning = {};
    warnForMissingKey = function(returnFiber, workInProgress2, child) {
      if (null !== child && "object" === typeof child && child._store && (!child._store.validated && null == child.key || 2 === child._store.validated)) {
        if ("object" !== typeof child._store)
          throw Error(
            "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."
          );
        child._store.validated = 1;
        var componentName2 = getComponentNameFromFiber(returnFiber), componentKey = componentName2 || "null";
        if (!ownerHasKeyUseWarning[componentKey]) {
          ownerHasKeyUseWarning[componentKey] = true;
          child = child._owner;
          returnFiber = returnFiber._debugOwner;
          var currentComponentErrorInfo = "";
          returnFiber && "number" === typeof returnFiber.tag && (componentKey = getComponentNameFromFiber(returnFiber)) && (currentComponentErrorInfo = "\n\nCheck the render method of `" + componentKey + "`.");
          currentComponentErrorInfo || componentName2 && (currentComponentErrorInfo = "\n\nCheck the top-level render call using <" + componentName2 + ">.");
          var childOwnerAppendix = "";
          null != child && returnFiber !== child && (componentName2 = null, "number" === typeof child.tag ? componentName2 = getComponentNameFromFiber(child) : "string" === typeof child.name && (componentName2 = child.name), componentName2 && (childOwnerAppendix = " It was passed a child from " + componentName2 + "."));
          runWithFiberInDEV(workInProgress2, function() {
            console.error(
              'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
              currentComponentErrorInfo,
              childOwnerAppendix
            );
          });
        }
      }
    };
    var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), UpdateState = 0, ReplaceState = 1, ForceUpdate = 2, CaptureUpdate = 3, hasForceUpdate = false;
    var didWarnUpdateInsideUpdate = false;
    var currentlyProcessingQueue = null;
    var didReadFromEntangledAsyncAction = false, currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, SubtreeSuspenseContextMask = 1, ForceSuspenseFallback = 2, suspenseStackCursor = createCursor(0), NoFlags = 0, HasEffect = 1, Insertion = 2, Layout = 4, Passive = 8, didWarnUncachedGetSnapshot;
    var didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set();
    var didWarnAboutUseWrappedInTryCatch = /* @__PURE__ */ new Set();
    var didWarnAboutAsyncClientComponent = /* @__PURE__ */ new Set();
    var didWarnAboutUseFormState = /* @__PURE__ */ new Set();
    var renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0, RE_RENDER_LIMIT = 25, currentHookNameInDev = null, hookTypesDev = null, hookTypesUpdateIndexDev = -1, ignorePreviousDependencies = false, ContextOnlyDispatcher = {
      readContext,
      use,
      useCallback: throwInvalidHookError,
      useContext: throwInvalidHookError,
      useEffect: throwInvalidHookError,
      useImperativeHandle: throwInvalidHookError,
      useLayoutEffect: throwInvalidHookError,
      useInsertionEffect: throwInvalidHookError,
      useMemo: throwInvalidHookError,
      useReducer: throwInvalidHookError,
      useRef: throwInvalidHookError,
      useState: throwInvalidHookError,
      useDebugValue: throwInvalidHookError,
      useDeferredValue: throwInvalidHookError,
      useTransition: throwInvalidHookError,
      useSyncExternalStore: throwInvalidHookError,
      useId: throwInvalidHookError,
      useHostTransitionStatus: throwInvalidHookError,
      useFormState: throwInvalidHookError,
      useActionState: throwInvalidHookError,
      useOptimistic: throwInvalidHookError,
      useMemoCache: throwInvalidHookError,
      useCacheRefresh: throwInvalidHookError
    };
    ContextOnlyDispatcher.useEffectEvent = throwInvalidHookError;
    var HooksDispatcherOnMountInDEV = null, HooksDispatcherOnMountWithHookTypesInDEV = null, HooksDispatcherOnUpdateInDEV = null, HooksDispatcherOnRerenderInDEV = null, InvalidNestedHooksDispatcherOnMountInDEV = null, InvalidNestedHooksDispatcherOnUpdateInDEV = null, InvalidNestedHooksDispatcherOnRerenderInDEV = null;
    HooksDispatcherOnMountInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        mountHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountEffect(create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        mountEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        return mountLayoutEffect(create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        mountHookTypesDev();
        checkDepsAreArrayDev(deps);
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function(initialValue) {
        currentHookNameInDev = "useRef";
        mountHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function(initialState2) {
        currentHookNameInDev = "useState";
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountState(initialState2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        mountHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        mountHookTypesDev();
        return mountDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        mountHookTypesDev();
        return mountTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        mountHookTypesDev();
        return mountSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        mountHookTypesDev();
        return mountId();
      },
      useFormState: function(action, initialState2) {
        currentHookNameInDev = "useFormState";
        mountHookTypesDev();
        warnOnUseFormStateInDev();
        return mountActionState(action, initialState2);
      },
      useActionState: function(action, initialState2) {
        currentHookNameInDev = "useActionState";
        mountHookTypesDev();
        return mountActionState(action, initialState2);
      },
      useOptimistic: function(passthrough) {
        currentHookNameInDev = "useOptimistic";
        mountHookTypesDev();
        return mountOptimistic(passthrough);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        mountHookTypesDev();
        return mountRefresh();
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        mountHookTypesDev();
        return mountEvent(callback);
      }
    };
    HooksDispatcherOnMountWithHookTypesInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        updateHookTypesDev();
        return mountCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        updateHookTypesDev();
        return mountEffect(create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        updateHookTypesDev();
        return mountImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        updateHookTypesDev();
        mountEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        updateHookTypesDev();
        return mountLayoutEffect(create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function(initialValue) {
        currentHookNameInDev = "useRef";
        updateHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function(initialState2) {
        currentHookNameInDev = "useState";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountState(initialState2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        updateHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        updateHookTypesDev();
        return mountDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        updateHookTypesDev();
        return mountTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        updateHookTypesDev();
        return mountSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        updateHookTypesDev();
        return mountId();
      },
      useActionState: function(action, initialState2) {
        currentHookNameInDev = "useActionState";
        updateHookTypesDev();
        return mountActionState(action, initialState2);
      },
      useFormState: function(action, initialState2) {
        currentHookNameInDev = "useFormState";
        updateHookTypesDev();
        warnOnUseFormStateInDev();
        return mountActionState(action, initialState2);
      },
      useOptimistic: function(passthrough) {
        currentHookNameInDev = "useOptimistic";
        updateHookTypesDev();
        return mountOptimistic(passthrough);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return mountRefresh();
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        updateHookTypesDev();
        return mountEvent(callback);
      }
    };
    HooksDispatcherOnUpdateInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        updateHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        updateHookTypesDev();
        return updateDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        updateHookTypesDev();
        return updateTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        updateHookTypesDev();
        warnOnUseFormStateInDev();
        return updateActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        updateHookTypesDev();
        return updateActionState(action);
      },
      useOptimistic: function(passthrough, reducer2) {
        currentHookNameInDev = "useOptimistic";
        updateHookTypesDev();
        return updateOptimistic(passthrough, reducer2);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    HooksDispatcherOnRerenderInDEV = {
      readContext: function(context) {
        return readContext(context);
      },
      use,
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
        try {
          return rerenderReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
        try {
          return rerenderReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        updateHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        updateHookTypesDev();
        return rerenderDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        updateHookTypesDev();
        return rerenderTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        updateHookTypesDev();
        warnOnUseFormStateInDev();
        return rerenderActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        updateHookTypesDev();
        return rerenderActionState(action);
      },
      useOptimistic: function(passthrough, reducer2) {
        currentHookNameInDev = "useOptimistic";
        updateHookTypesDev();
        return rerenderOptimistic(passthrough, reducer2);
      },
      useHostTransitionStatus,
      useMemoCache,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    InvalidNestedHooksDispatcherOnMountInDEV = {
      readContext: function(context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      use: function(usable) {
        warnInvalidHookAccess();
        return use(usable);
      },
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountEffect(create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        warnInvalidHookAccess();
        mountHookTypesDev();
        mountEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountLayoutEffect(create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function(initialValue) {
        currentHookNameInDev = "useRef";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountRef(initialValue);
      },
      useState: function(initialState2) {
        currentHookNameInDev = "useState";
        warnInvalidHookAccess();
        mountHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
        try {
          return mountState(initialState2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        warnInvalidHookAccess();
        mountHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountId();
      },
      useFormState: function(action, initialState2) {
        currentHookNameInDev = "useFormState";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountActionState(action, initialState2);
      },
      useActionState: function(action, initialState2) {
        currentHookNameInDev = "useActionState";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountActionState(action, initialState2);
      },
      useOptimistic: function(passthrough) {
        currentHookNameInDev = "useOptimistic";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountOptimistic(passthrough);
      },
      useMemoCache: function(size) {
        warnInvalidHookAccess();
        return useMemoCache(size);
      },
      useHostTransitionStatus,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        mountHookTypesDev();
        return mountRefresh();
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        warnInvalidHookAccess();
        mountHookTypesDev();
        return mountEvent(callback);
      }
    };
    InvalidNestedHooksDispatcherOnUpdateInDEV = {
      readContext: function(context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      use: function(usable) {
        warnInvalidHookAccess();
        return use(usable);
      },
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateActionState(action);
      },
      useOptimistic: function(passthrough, reducer2) {
        currentHookNameInDev = "useOptimistic";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateOptimistic(passthrough, reducer2);
      },
      useMemoCache: function(size) {
        warnInvalidHookAccess();
        return useMemoCache(size);
      },
      useHostTransitionStatus,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    InvalidNestedHooksDispatcherOnRerenderInDEV = {
      readContext: function(context) {
        warnInvalidContextAccess();
        return readContext(context);
      },
      use: function(usable) {
        warnInvalidHookAccess();
        return use(usable);
      },
      useCallback: function(callback, deps) {
        currentHookNameInDev = "useCallback";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateCallback(callback, deps);
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return readContext(context);
      },
      useEffect: function(create2, deps) {
        currentHookNameInDev = "useEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        updateEffectImpl(2048, Passive, create2, deps);
      },
      useImperativeHandle: function(ref2, create2, deps) {
        currentHookNameInDev = "useImperativeHandle";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateImperativeHandle(ref2, create2, deps);
      },
      useInsertionEffect: function(create2, deps) {
        currentHookNameInDev = "useInsertionEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Insertion, create2, deps);
      },
      useLayoutEffect: function(create2, deps) {
        currentHookNameInDev = "useLayoutEffect";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEffectImpl(4, Layout, create2, deps);
      },
      useMemo: function(create2, deps) {
        currentHookNameInDev = "useMemo";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return updateMemo(create2, deps);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useReducer: function(reducer2, initialArg, init2) {
        currentHookNameInDev = "useReducer";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return rerenderReducer(reducer2, initialArg, init2);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useRef: function() {
        currentHookNameInDev = "useRef";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useState: function() {
        currentHookNameInDev = "useState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
        try {
          return rerenderReducer(basicStateReducer);
        } finally {
          ReactSharedInternals.H = prevDispatcher;
        }
      },
      useDebugValue: function() {
        currentHookNameInDev = "useDebugValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
      },
      useDeferredValue: function(value, initialValue) {
        currentHookNameInDev = "useDeferredValue";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderDeferredValue(value, initialValue);
      },
      useTransition: function() {
        currentHookNameInDev = "useTransition";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderTransition();
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        currentHookNameInDev = "useSyncExternalStore";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateSyncExternalStore(
          subscribe,
          getSnapshot,
          getServerSnapshot
        );
      },
      useId: function() {
        currentHookNameInDev = "useId";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useFormState: function(action) {
        currentHookNameInDev = "useFormState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderActionState(action);
      },
      useActionState: function(action) {
        currentHookNameInDev = "useActionState";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderActionState(action);
      },
      useOptimistic: function(passthrough, reducer2) {
        currentHookNameInDev = "useOptimistic";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return rerenderOptimistic(passthrough, reducer2);
      },
      useMemoCache: function(size) {
        warnInvalidHookAccess();
        return useMemoCache(size);
      },
      useHostTransitionStatus,
      useCacheRefresh: function() {
        currentHookNameInDev = "useCacheRefresh";
        updateHookTypesDev();
        return updateWorkInProgressHook().memoizedState;
      },
      useEffectEvent: function(callback) {
        currentHookNameInDev = "useEffectEvent";
        warnInvalidHookAccess();
        updateHookTypesDev();
        return updateEvent(callback);
      }
    };
    var fakeInternalInstance = {};
    var didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set();
    var didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
    var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
    var didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
    var didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutContextTypes$1 = /* @__PURE__ */ new Set();
    var didWarnAboutChildContextTypes = /* @__PURE__ */ new Set();
    var didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
    var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
    Object.freeze(fakeInternalInstance);
    var classComponentUpdater = {
      enqueueSetState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(inst), update = createUpdate(lane);
        update.payload = payload;
        void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update.callback = callback);
        payload = enqueueUpdate(inst, update, lane);
        null !== payload && (startUpdateTimerByLane(lane, "this.setState()", inst), scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
      },
      enqueueReplaceState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(inst), update = createUpdate(lane);
        update.tag = ReplaceState;
        update.payload = payload;
        void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update.callback = callback);
        payload = enqueueUpdate(inst, update, lane);
        null !== payload && (startUpdateTimerByLane(lane, "this.replaceState()", inst), scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
      },
      enqueueForceUpdate: function(inst, callback) {
        inst = inst._reactInternals;
        var lane = requestUpdateLane(inst), update = createUpdate(lane);
        update.tag = ForceUpdate;
        void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update.callback = callback);
        callback = enqueueUpdate(inst, update, lane);
        null !== callback && (startUpdateTimerByLane(lane, "this.forceUpdate()", inst), scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
      }
    }, componentName = null, errorBoundaryName = null, SelectiveHydrationException = Error(
      "This is not a real error. It's an implementation detail of React's selective hydration feature. If this leaks into userspace, it's a bug in React. Please file an issue."
    ), didReceiveUpdate = false;
    var didWarnAboutBadClass = {};
    var didWarnAboutContextTypeOnFunctionComponent = {};
    var didWarnAboutContextTypes = {};
    var didWarnAboutGetDerivedStateOnFunctionComponent = {};
    var didWarnAboutReassigningProps = false;
    var didWarnAboutRevealOrder = {};
    var didWarnAboutTailOptions = {};
    var SUSPENDED_MARKER = {
      dehydrated: null,
      treeContext: null,
      retryLane: 0,
      hydrationErrors: null
    }, hasWarnedAboutUsingNoValuePropOnContextProvider = false, didWarnAboutUndefinedSnapshotBeforeUpdate = null;
    didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set();
    var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, inProgressLanes = null, inProgressRoot = null, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, inHydratedSubtree = false, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
      getCacheForType: function(resourceType) {
        var cache = readContext(CacheContext), cacheForType = cache.data.get(resourceType);
        void 0 === cacheForType && (cacheForType = resourceType(), cache.data.set(resourceType, cacheForType));
        return cacheForType;
      },
      cacheSignal: function() {
        return readContext(CacheContext).controller.signal;
      },
      getOwner: function() {
        return current;
      }
    };
    if ("function" === typeof Symbol && Symbol.for) {
      var symbolFor = Symbol.for;
      symbolFor("selector.component");
      symbolFor("selector.has_pseudo_class");
      symbolFor("selector.role");
      symbolFor("selector.test_id");
      symbolFor("selector.text");
    }
    var commitHooks = [], PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, NoContext = 0, RenderContext = 2, CommitContext = 4, RootInProgress = 0, RootFatalErrored = 1, RootErrored = 2, RootSuspended = 3, RootSuspendedWithDelay = 4, RootSuspendedAtTheShell = 6, RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, NotSuspended = 0, SuspendedOnError = 1, SuspendedOnData = 2, SuspendedOnImmediate = 3, SuspendedOnInstance = 4, SuspendedOnInstanceAndReadyToContinue = 5, SuspendedOnDeprecatedThrowPromise = 6, SuspendedAndReadyToContinue = 7, SuspendedOnHydration = 8, SuspendedOnAction = 9, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = RootInProgress, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, globalMostRecentTransitionTime = 0, FALLBACK_THROTTLE_MS = 300, workInProgressRootRenderTargetTime = Infinity, RENDER_TIMEOUT_MS = 500, workInProgressTransitions = null, workInProgressUpdateTask = null, legacyErrorBoundariesThatAlreadyFailed = null, IMMEDIATE_COMMIT = 0, ABORTED_VIEW_TRANSITION_COMMIT = 1, DELAYED_PASSIVE_COMMIT = 2, ANIMATION_STARTED_COMMIT = 3, NO_PENDING_EFFECTS = 0, PENDING_MUTATION_PHASE = 1, PENDING_LAYOUT_PHASE = 2, PENDING_AFTER_MUTATION_PHASE = 3, PENDING_SPAWNED_WORK = 4, PENDING_PASSIVE_PHASE = 5, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingEffectsRenderEndTime = -0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, pendingSuspendedCommitReason = null, pendingDelayedCommitReason = IMMEDIATE_COMMIT, pendingSuspendedViewTransitionReason = null, NESTED_UPDATE_LIMIT = 50, nestedUpdateCount = 0, rootWithNestedUpdates = null, isFlushingPassiveEffects = false, didScheduleUpdateDuringPassiveEffects = false, NESTED_PASSIVE_UPDATE_LIMIT = 50, nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, isRunningInsertionEffect = false, didWarnStateUpdateForNotYetMountedComponent = null, didWarnAboutUpdateInRender = false;
    var didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set();
    var fakeActCallbackNode$1 = {}, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, didScheduleMicrotask_act = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, fakeActCallbackNode = {};
    (function() {
      for (var i = 0; i < simpleEventPluginEvents.length; i++) {
        var eventName = simpleEventPluginEvents[i], domEventName = eventName.toLowerCase();
        eventName = eventName[0].toUpperCase() + eventName.slice(1);
        registerSimpleEvent(domEventName, "on" + eventName);
      }
      registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
      registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
      registerSimpleEvent(ANIMATION_START, "onAnimationStart");
      registerSimpleEvent("dblclick", "onDoubleClick");
      registerSimpleEvent("focusin", "onFocus");
      registerSimpleEvent("focusout", "onBlur");
      registerSimpleEvent(TRANSITION_RUN, "onTransitionRun");
      registerSimpleEvent(TRANSITION_START, "onTransitionStart");
      registerSimpleEvent(TRANSITION_CANCEL, "onTransitionCancel");
      registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
    })();
    registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
    registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
    registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
    registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
    registerTwoPhaseEvent(
      "onChange",
      "change click focusin focusout input keydown keyup selectionchange".split(
        " "
      )
    );
    registerTwoPhaseEvent(
      "onSelect",
      "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
        " "
      )
    );
    registerTwoPhaseEvent("onBeforeInput", [
      "compositionend",
      "keypress",
      "textInput",
      "paste"
    ]);
    registerTwoPhaseEvent(
      "onCompositionEnd",
      "compositionend focusout keydown keypress keyup mousedown".split(" ")
    );
    registerTwoPhaseEvent(
      "onCompositionStart",
      "compositionstart focusout keydown keypress keyup mousedown".split(" ")
    );
    registerTwoPhaseEvent(
      "onCompositionUpdate",
      "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
    );
    var mediaEventTypes = "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(
      " "
    ), nonDelegatedEvents = new Set(
      "beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mediaEventTypes)
    ), listeningMarker = "_reactListening" + Math.random().toString(36).slice(2), didWarnControlledToUncontrolled = false, didWarnUncontrolledToControlled = false, didWarnFormActionType = false, didWarnFormActionName = false, didWarnFormActionTarget = false, didWarnFormActionMethod = false, didWarnPopoverTargetObject = false;
    var didWarnForNewBooleanPropsWithEmptyValue = {};
    var NORMALIZE_NEWLINES_REGEX = /\r\n?/g, NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g, xlinkNamespace = "http://www.w3.org/1999/xlink", xmlNamespace = "http://www.w3.org/XML/1998/namespace", EXPECTED_FORM_ACTION_URL = "javascript:throw new Error('React form unexpectedly submitted.')", SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning", ACTIVITY_START_DATA = "&", ACTIVITY_END_DATA = "/&", SUSPENSE_START_DATA = "$", SUSPENSE_END_DATA = "/$", SUSPENSE_PENDING_START_DATA = "$?", SUSPENSE_QUEUED_START_DATA = "$~", SUSPENSE_FALLBACK_START_DATA = "$!", PREAMBLE_CONTRIBUTION_HTML = "html", PREAMBLE_CONTRIBUTION_BODY = "body", PREAMBLE_CONTRIBUTION_HEAD = "head", FORM_STATE_IS_MATCHING = "F!", FORM_STATE_IS_NOT_MATCHING = "F", DOCUMENT_READY_STATE_LOADING = "loading", STYLE = "style", HostContextNamespaceNone = 0, HostContextNamespaceSvg = 1, HostContextNamespaceMath = 2, eventsEnabled = null, selectionInformation = null, warnedUnknownTags = { dialog: true, webview: true }, currentPopstateTransitionEvent = null, schedulerEvent = void 0, scheduleTimeout = "function" === typeof setTimeout ? setTimeout : void 0, cancelTimeout = "function" === typeof clearTimeout ? clearTimeout : void 0, noTimeout = -1, localPromise = "function" === typeof Promise ? Promise : void 0, scheduleMicrotask = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof localPromise ? function(callback) {
      return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
    } : scheduleTimeout, previousHydratableOnEnteringScopedSingleton = null, NotLoaded = 0, Loaded = 1, Errored = 2, Settled = 3, Inserted = 4, preloadPropsMap = /* @__PURE__ */ new Map(), preconnectsSet = /* @__PURE__ */ new Set(), previousDispatcher = ReactDOMSharedInternals.d;
    ReactDOMSharedInternals.d = {
      f: function() {
        var previousWasRendering = previousDispatcher.f(), wasRendering = flushSyncWork$1();
        return previousWasRendering || wasRendering;
      },
      r: function(form) {
        var formInst = getInstanceFromNode(form);
        null !== formInst && 5 === formInst.tag && "form" === formInst.type ? requestFormReset$1(formInst) : previousDispatcher.r(form);
      },
      D: function(href) {
        previousDispatcher.D(href);
        preconnectAs("dns-prefetch", href, null);
      },
      C: function(href, crossOrigin) {
        previousDispatcher.C(href, crossOrigin);
        preconnectAs("preconnect", href, crossOrigin);
      },
      L: function(href, as, options) {
        previousDispatcher.L(href, as, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && href && as) {
          var preloadSelector = 'link[rel="preload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"]';
          "image" === as ? options && options.imageSrcSet ? (preloadSelector += '[imagesrcset="' + escapeSelectorAttributeValueInsideDoubleQuotes(
            options.imageSrcSet
          ) + '"]', "string" === typeof options.imageSizes && (preloadSelector += '[imagesizes="' + escapeSelectorAttributeValueInsideDoubleQuotes(
            options.imageSizes
          ) + '"]')) : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]' : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]';
          var key = preloadSelector;
          switch (as) {
            case "style":
              key = getStyleKey(href);
              break;
            case "script":
              key = getScriptKey(href);
          }
          preloadPropsMap.has(key) || (href = assign(
            {
              rel: "preload",
              href: "image" === as && options && options.imageSrcSet ? void 0 : href,
              as
            },
            options
          ), preloadPropsMap.set(key, href), null !== ownerDocument.querySelector(preloadSelector) || "style" === as && ownerDocument.querySelector(
            getStylesheetSelectorFromKey(key)
          ) || "script" === as && ownerDocument.querySelector(getScriptSelectorFromKey(key)) || (as = ownerDocument.createElement("link"), setInitialProperties(as, "link", href), markNodeAsHoistable(as), ownerDocument.head.appendChild(as)));
        }
      },
      m: function(href, options) {
        previousDispatcher.m(href, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && href) {
          var as = options && "string" === typeof options.as ? options.as : "script", preloadSelector = 'link[rel="modulepreload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"][href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]', key = preloadSelector;
          switch (as) {
            case "audioworklet":
            case "paintworklet":
            case "serviceworker":
            case "sharedworker":
            case "worker":
            case "script":
              key = getScriptKey(href);
          }
          if (!preloadPropsMap.has(key) && (href = assign({ rel: "modulepreload", href }, options), preloadPropsMap.set(key, href), null === ownerDocument.querySelector(preloadSelector))) {
            switch (as) {
              case "audioworklet":
              case "paintworklet":
              case "serviceworker":
              case "sharedworker":
              case "worker":
              case "script":
                if (ownerDocument.querySelector(getScriptSelectorFromKey(key)))
                  return;
            }
            as = ownerDocument.createElement("link");
            setInitialProperties(as, "link", href);
            markNodeAsHoistable(as);
            ownerDocument.head.appendChild(as);
          }
        }
      },
      X: function(src2, options) {
        previousDispatcher.X(src2, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && src2) {
          var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key = getScriptKey(src2), resource = scripts.get(key);
          resource || (resource = ownerDocument.querySelector(
            getScriptSelectorFromKey(key)
          ), resource || (src2 = assign({ src: src2, async: true }, options), (options = preloadPropsMap.get(key)) && adoptPreloadPropsForScript(src2, options), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src2), ownerDocument.head.appendChild(resource)), resource = {
            type: "script",
            instance: resource,
            count: 1,
            state: null
          }, scripts.set(key, resource));
        }
      },
      S: function(href, precedence, options) {
        previousDispatcher.S(href, precedence, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && href) {
          var styles2 = getResourcesFromRoot(ownerDocument).hoistableStyles, key = getStyleKey(href);
          precedence = precedence || "default";
          var resource = styles2.get(key);
          if (!resource) {
            var state = { loading: NotLoaded, preload: null };
            if (resource = ownerDocument.querySelector(
              getStylesheetSelectorFromKey(key)
            ))
              state.loading = Loaded | Inserted;
            else {
              href = assign(
                {
                  rel: "stylesheet",
                  href,
                  "data-precedence": precedence
                },
                options
              );
              (options = preloadPropsMap.get(key)) && adoptPreloadPropsForStylesheet(href, options);
              var link2 = resource = ownerDocument.createElement("link");
              markNodeAsHoistable(link2);
              setInitialProperties(link2, "link", href);
              link2._p = new Promise(function(resolve, reject) {
                link2.onload = resolve;
                link2.onerror = reject;
              });
              link2.addEventListener("load", function() {
                state.loading |= Loaded;
              });
              link2.addEventListener("error", function() {
                state.loading |= Errored;
              });
              state.loading |= Inserted;
              insertStylesheet(resource, precedence, ownerDocument);
            }
            resource = {
              type: "stylesheet",
              instance: resource,
              count: 1,
              state
            };
            styles2.set(key, resource);
          }
        }
      },
      M: function(src2, options) {
        previousDispatcher.M(src2, options);
        var ownerDocument = globalDocument;
        if (ownerDocument && src2) {
          var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key = getScriptKey(src2), resource = scripts.get(key);
          resource || (resource = ownerDocument.querySelector(
            getScriptSelectorFromKey(key)
          ), resource || (src2 = assign({ src: src2, async: true, type: "module" }, options), (options = preloadPropsMap.get(key)) && adoptPreloadPropsForScript(src2, options), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src2), ownerDocument.head.appendChild(resource)), resource = {
            type: "script",
            instance: resource,
            count: 1,
            state: null
          }, scripts.set(key, resource));
        }
      }
    };
    var globalDocument = "undefined" === typeof document ? null : document, tagCaches = null, SUSPENSEY_STYLESHEET_TIMEOUT = 6e4, SUSPENSEY_IMAGE_TIMEOUT = 800, SUSPENSEY_IMAGE_TIME_ESTIMATE = 500, estimatedBytesWithinLimit = 0, LAST_PRECEDENCE = null, precedencesByRoot = null, NotPendingTransition = NotPending, HostTransitionContext = {
      $$typeof: REACT_CONTEXT_TYPE,
      Provider: null,
      Consumer: null,
      _currentValue: NotPendingTransition,
      _currentValue2: NotPendingTransition,
      _threadCount: 0
    }, badgeFormat = "%c%s%c", badgeStyle = "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px", resetStyle = "", pad2 = " ", bind2 = Function.prototype.bind;
    var didWarnAboutNestedUpdates = false;
    var overrideHookState = null, overrideHookStateDeletePath = null, overrideHookStateRenamePath = null, overrideProps = null, overridePropsDeletePath = null, overridePropsRenamePath = null, scheduleUpdate = null, scheduleRetry = null, setErrorHandler = null, setSuspenseHandler = null;
    overrideHookState = function(fiber, id, path, value) {
      id = findHook(fiber, id);
      null !== id && (path = copyWithSetImpl(id.memoizedState, path, 0, value), id.memoizedState = path, id.baseState = path, fiber.memoizedProps = assign({}, fiber.memoizedProps), path = enqueueConcurrentRenderForLane(fiber, 2), null !== path && scheduleUpdateOnFiber(path, fiber, 2));
    };
    overrideHookStateDeletePath = function(fiber, id, path) {
      id = findHook(fiber, id);
      null !== id && (path = copyWithDeleteImpl(id.memoizedState, path, 0), id.memoizedState = path, id.baseState = path, fiber.memoizedProps = assign({}, fiber.memoizedProps), path = enqueueConcurrentRenderForLane(fiber, 2), null !== path && scheduleUpdateOnFiber(path, fiber, 2));
    };
    overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) {
      id = findHook(fiber, id);
      null !== id && (oldPath = copyWithRename(id.memoizedState, oldPath, newPath), id.memoizedState = oldPath, id.baseState = oldPath, fiber.memoizedProps = assign({}, fiber.memoizedProps), oldPath = enqueueConcurrentRenderForLane(fiber, 2), null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2));
    };
    overrideProps = function(fiber, path, value) {
      fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path, 0, value);
      fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
      path = enqueueConcurrentRenderForLane(fiber, 2);
      null !== path && scheduleUpdateOnFiber(path, fiber, 2);
    };
    overridePropsDeletePath = function(fiber, path) {
      fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path, 0);
      fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
      path = enqueueConcurrentRenderForLane(fiber, 2);
      null !== path && scheduleUpdateOnFiber(path, fiber, 2);
    };
    overridePropsRenamePath = function(fiber, oldPath, newPath) {
      fiber.pendingProps = copyWithRename(
        fiber.memoizedProps,
        oldPath,
        newPath
      );
      fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
      oldPath = enqueueConcurrentRenderForLane(fiber, 2);
      null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2);
    };
    scheduleUpdate = function(fiber) {
      var root3 = enqueueConcurrentRenderForLane(fiber, 2);
      null !== root3 && scheduleUpdateOnFiber(root3, fiber, 2);
    };
    scheduleRetry = function(fiber) {
      var lane = claimNextRetryLane(), root3 = enqueueConcurrentRenderForLane(fiber, lane);
      null !== root3 && scheduleUpdateOnFiber(root3, fiber, lane);
    };
    setErrorHandler = function(newShouldErrorImpl) {
      shouldErrorImpl = newShouldErrorImpl;
    };
    setSuspenseHandler = function(newShouldSuspendImpl) {
      shouldSuspendImpl = newShouldSuspendImpl;
    };
    var _enabled = true, return_targetInst = null, hasScheduledReplayAttempt = false, queuedFocus = null, queuedDrag = null, queuedMouse = null, queuedPointers = /* @__PURE__ */ new Map(), queuedPointerCaptures = /* @__PURE__ */ new Map(), queuedExplicitHydrationTargets = [], discreteReplayableEvents = "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".split(
      " "
    ), lastScheduledReplayQueue = null;
    ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children) {
      var root3 = this._internalRoot;
      if (null === root3) throw Error("Cannot update an unmounted root.");
      var args = arguments;
      "function" === typeof args[1] ? console.error(
        "does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."
      ) : isValidContainer(args[1]) ? console.error(
        "You passed a container to the second argument of root.render(...). You don't need to pass it again since you already passed it to create the root."
      ) : "undefined" !== typeof args[1] && console.error(
        "You passed a second argument to root.render(...) but it only accepts one argument."
      );
      args = children;
      var current2 = root3.current, lane = requestUpdateLane(current2);
      updateContainerImpl(current2, lane, args, root3, null, null);
    };
    ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
      var args = arguments;
      "function" === typeof args[0] && console.error(
        "does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."
      );
      args = this._internalRoot;
      if (null !== args) {
        this._internalRoot = null;
        var container = args.containerInfo;
        (executionContext & (RenderContext | CommitContext)) !== NoContext && console.error(
          "Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition."
        );
        updateContainerImpl(args.current, 2, null, args, null, null);
        flushSyncWork$1();
        container[internalContainerInstanceKey] = null;
      }
    };
    ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = function(target) {
      if (target) {
        var updatePriority = resolveUpdatePriority();
        target = { blockedOn: null, target, priority: updatePriority };
        for (var i = 0; i < queuedExplicitHydrationTargets.length && 0 !== updatePriority && updatePriority < queuedExplicitHydrationTargets[i].priority; i++) ;
        queuedExplicitHydrationTargets.splice(i, 0, target);
        0 === i && attemptExplicitHydrationTarget(target);
      }
    };
    (function() {
      var isomorphicReactPackageVersion = React2.version;
      if ("19.2.4" !== isomorphicReactPackageVersion)
        throw Error(
          'Incompatible React versions: The "react" and "react-dom" packages must have the exact same version. Instead got:\n  - react:      ' + (isomorphicReactPackageVersion + "\n  - react-dom:  19.2.4\nLearn more: https://react.dev/warnings/version-mismatch")
        );
    })();
    "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error(
      "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://react.dev/link/react-polyfills"
    );
    ReactDOMSharedInternals.findDOMNode = function(componentOrElement) {
      var fiber = componentOrElement._reactInternals;
      if (void 0 === fiber) {
        if ("function" === typeof componentOrElement.render)
          throw Error("Unable to find node on an unmounted component.");
        componentOrElement = Object.keys(componentOrElement).join(",");
        throw Error(
          "Argument appears to not be a ReactComponent. Keys: " + componentOrElement
        );
      }
      componentOrElement = findCurrentFiberUsingSlowPath(fiber);
      componentOrElement = null !== componentOrElement ? findCurrentHostFiberImpl(componentOrElement) : null;
      componentOrElement = null === componentOrElement ? null : componentOrElement.stateNode;
      return componentOrElement;
    };
    if (!(function() {
      var internals = {
        bundleType: 1,
        version: "19.2.4",
        rendererPackageName: "react-dom",
        currentDispatcherRef: ReactSharedInternals,
        reconcilerVersion: "19.2.4"
      };
      internals.overrideHookState = overrideHookState;
      internals.overrideHookStateDeletePath = overrideHookStateDeletePath;
      internals.overrideHookStateRenamePath = overrideHookStateRenamePath;
      internals.overrideProps = overrideProps;
      internals.overridePropsDeletePath = overridePropsDeletePath;
      internals.overridePropsRenamePath = overridePropsRenamePath;
      internals.scheduleUpdate = scheduleUpdate;
      internals.scheduleRetry = scheduleRetry;
      internals.setErrorHandler = setErrorHandler;
      internals.setSuspenseHandler = setSuspenseHandler;
      internals.scheduleRefresh = scheduleRefresh;
      internals.scheduleRoot = scheduleRoot;
      internals.setRefreshHandler = setRefreshHandler;
      internals.getCurrentFiber = getCurrentFiberForDevTools;
      return injectInternals(internals);
    })() && canUseDOM && window.top === window.self && (-1 < navigator.userAgent.indexOf("Chrome") && -1 === navigator.userAgent.indexOf("Edge") || -1 < navigator.userAgent.indexOf("Firefox"))) {
      var protocol = window.location.protocol;
      /^(https?|file):$/.test(protocol) && console.info(
        "%cDownload the React DevTools for a better development experience: https://react.dev/link/react-devtools" + ("file:" === protocol ? "\nYou might need to use a local HTTP server (instead of file://): https://react.dev/link/react-devtools-faq" : ""),
        "font-weight:bold"
      );
    }
    reactDomClient_development.createRoot = function(container, options) {
      if (!isValidContainer(container))
        throw Error("Target container is not a DOM element.");
      warnIfReactDOMContainerInDEV(container);
      var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError;
      null !== options && void 0 !== options && (options.hydrate ? console.warn(
        "hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead."
      ) : "object" === typeof options && null !== options && options.$$typeof === REACT_ELEMENT_TYPE && console.error(
        "You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:\n\n  let root = createRoot(domContainer);\n  root.render(<App />);"
      ), true === options.unstable_strictMode && (isStrictMode = true), void 0 !== options.identifierPrefix && (identifierPrefix = options.identifierPrefix), void 0 !== options.onUncaughtError && (onUncaughtError = options.onUncaughtError), void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError), void 0 !== options.onRecoverableError && (onRecoverableError = options.onRecoverableError));
      options = createFiberRoot(
        container,
        1,
        false,
        null,
        null,
        isStrictMode,
        identifierPrefix,
        null,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        defaultOnDefaultTransitionIndicator
      );
      container[internalContainerInstanceKey] = options.current;
      listenToAllSupportedEvents(container);
      return new ReactDOMRoot(options);
    };
    reactDomClient_development.hydrateRoot = function(container, initialChildren, options) {
      if (!isValidContainer(container))
        throw Error("Target container is not a DOM element.");
      warnIfReactDOMContainerInDEV(container);
      void 0 === initialChildren && console.error(
        "Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)"
      );
      var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError, formState = null;
      null !== options && void 0 !== options && (true === options.unstable_strictMode && (isStrictMode = true), void 0 !== options.identifierPrefix && (identifierPrefix = options.identifierPrefix), void 0 !== options.onUncaughtError && (onUncaughtError = options.onUncaughtError), void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError), void 0 !== options.onRecoverableError && (onRecoverableError = options.onRecoverableError), void 0 !== options.formState && (formState = options.formState));
      initialChildren = createFiberRoot(
        container,
        1,
        true,
        initialChildren,
        null != options ? options : null,
        isStrictMode,
        identifierPrefix,
        formState,
        onUncaughtError,
        onCaughtError,
        onRecoverableError,
        defaultOnDefaultTransitionIndicator
      );
      initialChildren.context = getContextForSubtree(null);
      options = initialChildren.current;
      isStrictMode = requestUpdateLane(options);
      isStrictMode = getBumpedLaneForHydrationByLane(isStrictMode);
      identifierPrefix = createUpdate(isStrictMode);
      identifierPrefix.callback = null;
      enqueueUpdate(options, identifierPrefix, isStrictMode);
      startUpdateTimerByLane(isStrictMode, "hydrateRoot()", null);
      options = isStrictMode;
      initialChildren.current.lanes = options;
      markRootUpdated$1(initialChildren, options);
      ensureRootIsScheduled(initialChildren);
      container[internalContainerInstanceKey] = initialChildren.current;
      listenToAllSupportedEvents(container);
      return new ReactDOMHydrationRoot(initialChildren);
    };
    reactDomClient_development.version = "19.2.4";
    "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
  })();
  return reactDomClient_development;
}
var hasRequiredClient;
function requireClient() {
  if (hasRequiredClient) return client.exports;
  hasRequiredClient = 1;
  function checkDCE() {
    if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
      return;
    }
    if (process.env.NODE_ENV !== "production") {
      throw new Error("^_^");
    }
    try {
      __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
    } catch (err) {
      console.error(err);
    }
  }
  if (process.env.NODE_ENV === "production") {
    checkDCE();
    client.exports = requireReactDomClient_production();
  } else {
    client.exports = requireReactDomClient_development();
  }
  return client.exports;
}
var clientExports = requireClient();
const CONTENT_TYPE_STYLES = {
  wallpapers: {
    badge: "from-cyan-400/90 to-sky-500/90",
    overlay: "from-sky-950/10 via-slate-950/12 to-slate-950/92",
    glow: "group-hover:shadow-[0_0_28px_rgba(34,211,238,0.18)]"
  },
  skins: {
    badge: "from-orange-400/90 to-amber-500/90",
    overlay: "from-orange-950/10 via-slate-950/12 to-slate-950/92",
    glow: "group-hover:shadow-[0_0_28px_rgba(251,146,60,0.18)]"
  },
  photography: {
    badge: "from-emerald-400/90 to-teal-500/90",
    overlay: "from-emerald-950/10 via-slate-950/12 to-slate-950/92",
    glow: "group-hover:shadow-[0_0_28px_rgba(16,185,129,0.18)]"
  },
  other: {
    badge: "from-fuchsia-400/90 to-rose-500/90",
    overlay: "from-rose-950/10 via-slate-950/12 to-slate-950/92",
    glow: "group-hover:shadow-[0_0_28px_rgba(244,114,182,0.18)]"
  },
  default: {
    badge: "from-cyan-400/90 to-orange-400/90",
    overlay: "from-slate-900/10 via-slate-950/12 to-slate-950/92",
    glow: "group-hover:shadow-[0_0_28px_rgba(125,211,252,0.16)]"
  }
};
const countFormatter = new Intl.NumberFormat();
function formatArtworkCount(count) {
  return `${countFormatter.format(Number(count || 0))} artworks`;
}
function CategoryCard$1({ category, index: index2 = 0 }) {
  const contentTypeSlug = category?.content_type?.slug || "default";
  const contentTypeName = category?.content_type?.name || "Category";
  const styles2 = CONTENT_TYPE_STYLES[contentTypeSlug] || CONTENT_TYPE_STYLES.default;
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: category?.url || "/categories",
      "aria-label": `Browse ${category?.name || "category"} category`,
      className: [
        "group relative block cursor-pointer rounded-2xl overflow-hidden",
        "transition duration-300 ease-out hover:-translate-y-1 hover:scale-[1.01]",
        styles2.glow
      ].join(" "),
      style: { animationDelay: `${Math.min(index2, 8) * 60}ms` }
    },
    /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[4/5] overflow-hidden rounded-2xl border border-white/10 bg-slate-950/80" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: category?.cover_image,
        alt: `Cover artwork for ${category?.name || "category"}`,
        loading: "lazy",
        className: "h-full w-full object-cover transition duration-500 group-hover:scale-110"
      }
    ), /* @__PURE__ */ React.createElement("div", { className: `absolute inset-0 bg-gradient-to-b ${styles2.overlay} transition duration-500 group-hover:from-black/20 group-hover:to-black/90` }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(255,255,255,0.22),transparent_42%)] opacity-0 transition duration-500 group-hover:opacity-100" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 flex items-center justify-between gap-3 p-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full bg-gradient-to-r ${styles2.badge} px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-950 shadow-[0_10px_24px_rgba(0,0,0,0.24)]` }, contentTypeName), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/25 px-3 py-1 text-[11px] font-medium uppercase tracking-[0.18em] text-white/78 backdrop-blur" }, formatArtworkCount(category?.artwork_count))), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/30 p-4 backdrop-blur-md transition duration-300 group-hover:border-white/20 group-hover:bg-black/42" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 h-px w-14 bg-gradient-to-r from-white/70 to-transparent transition duration-300 group-hover:w-24" }), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold tracking-[-0.02em] text-white sm:text-xl" }, category?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Explore ", category?.name, " across wallpapers, skins, themes, and digital art collections."))))
  );
}
function Pagination$1({ meta, onPageChange }) {
  const current = meta?.current_page ?? 1;
  const lastPage = meta?.last_page ?? 1;
  if (lastPage <= 1) return null;
  const pages2 = buildPages(current, lastPage);
  const go = (page) => {
    if (page < 1 || page > lastPage || page === current) return;
    if (onPageChange) {
      onPageChange(page);
    } else {
      const url = new URL(window.location.href);
      url.searchParams.set("page", page);
      window.location.href = url.toString();
    }
  };
  return /* @__PURE__ */ React.createElement("nav", { "aria-label": "Pagination", className: "flex items-center justify-center gap-1.5" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => go(current - 1),
      disabled: current <= 1,
      className: "inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 text-zinc-400 transition-colors hover:border-white/20 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",
      "aria-label": "Previous page"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none" }, /* @__PURE__ */ React.createElement("path", { d: "M10 4L6 8l4 4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))
  ), pages2.map(
    (p, i) => p === "..." ? /* @__PURE__ */ React.createElement("span", { key: `dots-${i}`, className: "px-1 text-xs text-zinc-600" }, "…") : /* @__PURE__ */ React.createElement(
      "button",
      {
        key: p,
        onClick: () => go(p),
        "aria-current": p === current ? "page" : void 0,
        className: [
          "inline-flex h-9 min-w-[2.25rem] items-center justify-center rounded-xl text-sm font-medium transition-colors",
          p === current ? "bg-sky-600/20 text-sky-300 border border-sky-500/30" : "border border-white/10 text-zinc-400 hover:border-white/20 hover:text-white"
        ].join(" ")
      },
      p
    )
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => go(current + 1),
      disabled: current >= lastPage,
      className: "inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 text-zinc-400 transition-colors hover:border-white/20 hover:text-white disabled:opacity-30 disabled:cursor-not-allowed",
      "aria-label": "Next page"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "none" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4l4 4-4 4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))
  ));
}
function buildPages(current, last) {
  if (last <= 7) {
    return Array.from({ length: last }, (_2, i) => i + 1);
  }
  const pages2 = /* @__PURE__ */ new Set([1, 2, current - 1, current, current + 1, last - 1, last]);
  const sorted = [...pages2].filter((p) => p >= 1 && p <= last).sort((a, b2) => a - b2);
  const result = [];
  for (let i = 0; i < sorted.length; i++) {
    if (i > 0 && sorted[i] - sorted[i - 1] > 1) {
      result.push("...");
    }
    result.push(sorted[i]);
  }
  return result;
}
const SORT_OPTIONS$1 = [
  { value: "popular", label: "Popular" },
  { value: "az", label: "A-Z" },
  { value: "artworks", label: "Most artworks" }
];
const PAGE_SIZE = 24;
const numberFormatter$1 = new Intl.NumberFormat();
function normalizeInitialData(initialData) {
  if (!initialData || typeof initialData !== "object") {
    return {
      data: [],
      meta: { current_page: 1, last_page: 1, per_page: PAGE_SIZE, total: 0 },
      summary: { total_categories: 0, total_artworks: 0 },
      popular_categories: [],
      request: { query: "", sort: "popular", page: 1 }
    };
  }
  return {
    data: Array.isArray(initialData.data) ? initialData.data : [],
    meta: initialData.meta || { current_page: 1, last_page: 1, per_page: PAGE_SIZE, total: 0 },
    summary: initialData.summary || { total_categories: 0, total_artworks: 0 },
    popular_categories: Array.isArray(initialData.popular_categories) ? initialData.popular_categories : [],
    request: initialData.request || { query: "", sort: "popular", page: 1 }
  };
}
function LoadingGrid() {
  return /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4" }, Array.from({ length: 8 }).map((_2, index2) => /* @__PURE__ */ React.createElement("div", { key: index2, className: "aspect-[4/5] animate-pulse rounded-2xl border border-white/8 bg-white/[0.04]" })));
}
function EmptyState$5({ query }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/14 bg-black/20 px-6 py-14 text-center backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-white/35" }, "No matching categories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, 'Nothing matched "', query, '"'), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm leading-7 text-white/58" }, "Try a shorter term or switch sorting to browse the full category directory again."));
}
function ErrorState({ onRetry }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-rose-400/20 bg-rose-500/8 px-6 py-14 text-center shadow-[0_30px_70px_rgba(0,0,0,0.2)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-rose-200/70" }, "Unable to load categories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, "The directory API did not respond cleanly."), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm leading-7 text-white/58" }, "Refresh the list and try again. If this persists, the API route or cache payload needs inspection."), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onRetry,
      className: "mt-6 inline-flex items-center justify-center rounded-full border border-rose-300/35 bg-rose-400/12 px-5 py-3 text-sm font-semibold text-rose-100 transition hover:border-rose-200/55 hover:bg-rose-400/20"
    },
    "Retry request"
  ));
}
function getInitialPage() {
  if (typeof window === "undefined") {
    return 1;
  }
  const rawPage = Number(new URL(window.location.href).searchParams.get("page") || 1);
  if (!Number.isFinite(rawPage) || rawPage < 1) {
    return 1;
  }
  return Math.floor(rawPage);
}
function getInitialSort() {
  if (typeof window === "undefined") {
    return "popular";
  }
  const sort = new URL(window.location.href).searchParams.get("sort") || "popular";
  return SORT_OPTIONS$1.some((option) => option.value === sort) ? sort : "popular";
}
function getInitialSearchQuery() {
  if (typeof window === "undefined") {
    return "";
  }
  return new URL(window.location.href).searchParams.get("q") || "";
}
function syncQueryState({ page, sort, query }) {
  if (typeof window === "undefined") {
    return;
  }
  const url = new URL(window.location.href);
  if (page <= 1) {
    url.searchParams.delete("page");
  } else {
    url.searchParams.set("page", String(page));
  }
  if (sort === "popular") {
    url.searchParams.delete("sort");
  } else {
    url.searchParams.set("sort", sort);
  }
  if (query.trim() === "") {
    url.searchParams.delete("q");
  } else {
    url.searchParams.set("q", query);
  }
  window.history.replaceState({}, "", url.toString());
}
function CategoriesPage({ apiUrl: apiUrl2 = "/api/categories", pageTitle = "Categories", pageDescription = "", initialData = null }) {
  const bootstrap = normalizeInitialData(initialData);
  const hasInitialData = initialData !== null;
  const initialRequestRef = reactExports.useRef(hasInitialData ? bootstrap.request : null);
  const [categories, setCategories] = reactExports.useState(() => hasInitialData ? bootstrap.data : []);
  const [popularCategories, setPopularCategories] = reactExports.useState(() => hasInitialData ? bootstrap.popular_categories : []);
  const [meta, setMeta] = reactExports.useState(() => hasInitialData ? bootstrap.meta : { current_page: 1, last_page: 1, per_page: PAGE_SIZE, total: 0 });
  const [summary, setSummary] = reactExports.useState(() => hasInitialData ? bootstrap.summary : { total_categories: 0, total_artworks: 0 });
  const [loading, setLoading] = reactExports.useState(() => !hasInitialData);
  const [loadingMore, setLoadingMore] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(false);
  const [searchQuery, setSearchQuery] = reactExports.useState(() => hasInitialData ? bootstrap.request.query || "" : getInitialSearchQuery());
  const [sort, setSort] = reactExports.useState(() => hasInitialData ? bootstrap.request.sort || "popular" : getInitialSort());
  const [currentPage, setCurrentPage] = reactExports.useState(() => hasInitialData ? bootstrap.request.page || 1 : getInitialPage());
  const deferredQuery = reactExports.useDeferredValue(searchQuery);
  const sentinelRef = reactExports.useRef(null);
  const loadCategories = async ({ signal, page, query, activeSort, append: append2 = false }) => {
    if (append2) {
      setLoadingMore(true);
    } else {
      setLoading(true);
    }
    setError(false);
    try {
      const params = new URLSearchParams({
        page: String(page),
        per_page: String(PAGE_SIZE),
        sort: activeSort
      });
      if (query.trim() !== "") {
        params.set("q", query.trim());
      }
      const response = await fetch(`${apiUrl2}?${params.toString()}`, {
        headers: {
          Accept: "application/json",
          "X-Requested-With": "XMLHttpRequest"
        },
        credentials: "same-origin",
        signal
      });
      if (!response.ok) {
        throw new Error("Failed to load categories");
      }
      const payload = await response.json();
      const nextCategories = Array.isArray(payload?.data) ? payload.data : [];
      setCategories((previous2) => {
        if (!append2) {
          return nextCategories;
        }
        const seenIds = new Set(previous2.map((category) => category.id));
        const merged = [...previous2];
        nextCategories.forEach((category) => {
          if (!seenIds.has(category.id)) {
            merged.push(category);
          }
        });
        return merged;
      });
      setPopularCategories(Array.isArray(payload?.popular_categories) ? payload.popular_categories : []);
      setMeta(payload?.meta || { current_page: 1, last_page: 1, per_page: PAGE_SIZE, total: 0 });
      setSummary(payload?.summary || { total_categories: 0, total_artworks: 0 });
      if ((payload?.meta?.current_page ?? page) !== currentPage) {
        setCurrentPage(payload?.meta?.current_page ?? page);
      }
    } catch (requestError) {
      if (requestError?.name !== "AbortError") {
        setError(true);
      }
    } finally {
      if (!signal?.aborted || signal === void 0) {
        setLoading(false);
        setLoadingMore(false);
      }
    }
  };
  reactExports.useEffect(() => {
    const initialRequest = initialRequestRef.current;
    if (initialRequest) {
      const sameQuery = (initialRequest.query || "") === deferredQuery;
      const sameSort = (initialRequest.sort || "popular") === sort;
      const samePage = Number(initialRequest.page || 1) === currentPage;
      initialRequestRef.current = null;
      if (sameQuery && sameSort && samePage) {
        return void 0;
      }
    }
    const controller = new AbortController();
    void loadCategories({
      signal: controller.signal,
      page: currentPage,
      query: deferredQuery,
      activeSort: sort,
      append: false
    });
    return () => controller.abort();
  }, [apiUrl2, deferredQuery, sort]);
  reactExports.useEffect(() => {
    syncQueryState({ page: currentPage, sort, query: deferredQuery });
  }, [currentPage, deferredQuery, sort]);
  const handlePageChange = (page) => {
    setCategories([]);
    setCurrentPage(page);
    void loadCategories({
      page,
      query: deferredQuery,
      activeSort: sort,
      append: false
    });
    if (typeof window !== "undefined") {
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };
  reactExports.useEffect(() => {
    const sentinel = sentinelRef.current;
    const hasMore = meta.current_page < meta.last_page;
    if (!sentinel || loading || loadingMore || error || !hasMore) {
      return void 0;
    }
    const observer = new IntersectionObserver((entries) => {
      const firstEntry = entries[0];
      if (!firstEntry?.isIntersecting) {
        return;
      }
      const nextPage = meta.current_page + 1;
      setCurrentPage(nextPage);
      void loadCategories({
        page: nextPage,
        query: deferredQuery,
        activeSort: sort,
        append: true
      });
    }, { rootMargin: "320px 0px" });
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [deferredQuery, error, loading, loadingMore, meta.current_page, meta.last_page, sort]);
  const handleRetry = () => {
    void loadCategories({
      page: currentPage,
      query: deferredQuery,
      activeSort: sort,
      append: false
    });
  };
  const loadedCount = categories.length;
  const showingStart = loadedCount > 0 ? 1 : 0;
  const showingEnd = loadedCount;
  const hasMorePages = meta.current_page < meta.last_page;
  return /* @__PURE__ */ React.createElement("div", { className: "pb-24 text-white" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[28rem] bg-[radial-gradient(circle_at_top_left,rgba(34,211,238,0.12),transparent_38%),radial-gradient(circle_at_top_right,rgba(249,115,22,0.14),transparent_34%)]" }), /* @__PURE__ */ React.createElement("div", { className: "relative w-full px-6 pb-8 pt-14 sm:px-8 sm:pt-20 xl:px-10 2xl:px-14 lg:pt-24" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 lg:grid-cols-[minmax(0,1.2fr)_20rem] lg:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.24em] text-white/50 backdrop-blur-sm" }, "Category directory"), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 max-w-4xl text-4xl font-semibold tracking-[-0.05em] text-white sm:text-5xl lg:text-6xl" }, pageTitle), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-2xl text-base leading-8 text-white/62 sm:text-lg" }, pageDescription || "Browse all wallpapers, skins, themes and digital art categories")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-3 lg:grid-cols-1" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/22 p-5 backdrop-blur-md shadow-[0_24px_60px_rgba(0,0,0,0.24)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-white/40" }, "Categories"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, numberFormatter$1.format(summary.total_categories))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/22 p-5 backdrop-blur-md shadow-[0_24px_60px_rgba(0,0,0,0.24)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-white/40" }, "Artworks indexed"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, numberFormatter$1.format(summary.total_artworks))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/22 p-5 backdrop-blur-md shadow-[0_24px_60px_rgba(0,0,0,0.24)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-white/40" }, "View"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Grid")))), /* @__PURE__ */ React.createElement("div", { className: "mt-10 rounded-[30px] border border-white/10 bg-black/25 p-4 shadow-[0_30px_80px_rgba(0,0,0,0.25)] backdrop-blur-xl sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_16rem] lg:items-center" }, /* @__PURE__ */ React.createElement("label", { className: "relative block" }, /* @__PURE__ */ React.createElement("span", { className: "pointer-events-none absolute left-4 top-1/2 -translate-y-1/2 text-white/35" }, /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M8.5 3a5.5 5.5 0 1 0 3.473 9.765l3.63 3.63a.75.75 0 1 0 1.06-1.06l-3.63-3.63A5.5 5.5 0 0 0 8.5 3Zm-4 5.5a4 4 0 1 1 8 0 4 4 0 0 1-8 0Z", clipRule: "evenodd" }))), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: searchQuery,
      onChange: (event) => {
        const value = event.target.value;
        reactExports.startTransition(() => {
          setSearchQuery(value);
          setCurrentPage(1);
        });
      },
      placeholder: "Search categories",
      "aria-label": "Search categories",
      className: "h-14 w-full rounded-2xl border border-white/10 bg-white/[0.04] pl-12 pr-4 text-sm text-white placeholder:text-white/28 focus:border-cyan-300/45 focus:outline-none focus:ring-2 focus:ring-cyan-300/15"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.2em] text-white/38" }, "Sort by"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: sort,
      onChange: (value) => {
        setSort(value);
        setCurrentPage(1);
      },
      id: "categories-sort",
      options: SORT_OPTIONS$1.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )))))), /* @__PURE__ */ React.createElement("section", { className: "w-full px-6 sm:px-8 xl:px-10 2xl:px-14" }, !loading && !error && deferredQuery.trim() === "" && popularCategories.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mb-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_24px_60px_rgba(0,0,0,0.18)] backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.22em] text-white/38" }, "Popular categories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Start with the busiest destinations")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, popularCategories.map((category) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: category.id,
      href: category.url,
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-black/20 px-4 py-2 text-sm text-white/72 transition hover:border-white/20 hover:bg-white/[0.05] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("span", null, category.name),
    /* @__PURE__ */ React.createElement("span", { className: "text-white/38" }, numberFormatter$1.format(category.artwork_count))
  ))))), /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.22em] text-white/38" }, "Directory results"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, numberFormatter$1.format(meta.total), " categories visible")), !loading && !error && meta.total > 0 ? /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/52" }, "Showing ", numberFormatter$1.format(showingStart), " to ", numberFormatter$1.format(showingEnd), " of ", numberFormatter$1.format(meta.total), " categories.") : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/52" }, "Browse all wallpapers, skins, themes and digital art categories.")), loading && /* @__PURE__ */ React.createElement(LoadingGrid, null), !loading && error && /* @__PURE__ */ React.createElement(ErrorState, { onRetry: handleRetry }), !loading && !error && meta.total === 0 && /* @__PURE__ */ React.createElement(EmptyState$5, { query: deferredQuery }), !loading && !error && meta.total > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-6 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5" }, categories.map((category, index2) => /* @__PURE__ */ React.createElement(CategoryCard$1, { key: category.id, category, index: index2 }))), /* @__PURE__ */ React.createElement("div", { ref: sentinelRef, className: "h-6 w-full", "aria-hidden": "true" }), loadingMore && /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex items-center justify-center gap-3 rounded-2xl border border-white/8 bg-black/18 px-4 py-4 text-sm text-white/56 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("span", { className: "h-2.5 w-2.5 animate-pulse rounded-full bg-cyan-300" }), "Loading more categories"), /* @__PURE__ */ React.createElement("div", { className: "mt-10 flex flex-col items-center justify-center gap-3 rounded-[24px] border border-white/8 bg-black/18 px-4 py-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/46" }, "Loaded through page ", numberFormatter$1.format(meta.current_page), " of ", numberFormatter$1.format(meta.last_page)), /* @__PURE__ */ React.createElement(Pagination$1, { meta, onPageChange: handlePageChange }), hasMorePages && /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.2em] text-white/28" }, "Scroll to load the next page automatically")))));
}
if (typeof document !== "undefined") {
  const mountElement = document.getElementById("categories-page-root");
  if (mountElement) {
    let props = {};
    try {
      const propsElement = document.getElementById("categories-page-props");
      props = propsElement ? JSON.parse(propsElement.textContent || "{}") : {};
    } catch {
      props = {};
    }
    clientExports.createRoot(mountElement).render(/* @__PURE__ */ React.createElement(CategoriesPage, { ...props }));
  }
}
const __vite_glob_0_40 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CategoriesPage
}, Symbol.toStringTag, { value: "Module" }));
function MetricCard$1({ label, value, delta, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-slate-500` })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, Number(value || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-300" }, Number(delta || 0).toLocaleString(), " in the selected range"));
}
function TimelineChart({ timeline }) {
  const safeTimeline = Array.isArray(timeline) ? timeline : [];
  const maxValue = safeTimeline.reduce((largest, item) => Math.max(largest, item.views || 0, item.likes || 0, item.saves || 0), 0) || 1;
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Timeline"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Engagement trend")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, safeTimeline.length, " days")), safeTimeline.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex h-64 items-end gap-2 overflow-x-auto rounded-[24px] border border-white/10 bg-slate-950/40 px-4 py-5" }, safeTimeline.map((point2) => /* @__PURE__ */ React.createElement("div", { key: point2.date, className: "flex min-w-[32px] flex-1 flex-col items-center justify-end gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-end gap-1" }, /* @__PURE__ */ React.createElement("div", { className: "w-1/3 rounded-t-full bg-sky-300/80", style: { height: `${Math.max(6, (point2.views || 0) / maxValue * 100)}%` }, title: `Views: ${point2.views || 0}` }), /* @__PURE__ */ React.createElement("div", { className: "w-1/3 rounded-t-full bg-emerald-300/75", style: { height: `${Math.max(6, (point2.likes || 0) / maxValue * 100)}%` }, title: `Likes: ${point2.likes || 0}` }), /* @__PURE__ */ React.createElement("div", { className: "w-1/3 rounded-t-full bg-amber-300/75", style: { height: `${Math.max(6, (point2.saves || 0) / maxValue * 100)}%` }, title: `Saves: ${point2.saves || 0}` })), /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, String(point2.date || "").slice(5))))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "Analytics are enabled, but there are not enough daily snapshots yet to render a timeline."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 text-xs font-semibold uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "h-2.5 w-2.5 rounded-full bg-sky-300/80" }), "Views"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "h-2.5 w-2.5 rounded-full bg-emerald-300/75" }), "Likes"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "h-2.5 w-2.5 rounded-full bg-amber-300/75" }), "Saves")));
}
function CollectionAnalytics() {
  const { props } = X$1();
  const collection = props.collection || {};
  const analytics = props.analytics || {};
  const totals = analytics.totals || {};
  const range2 = analytics.range || {};
  const topArtworks = Array.isArray(analytics.top_artworks) ? analytics.top_artworks : [];
  const seo = props.seo || {};
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, seo.title || `${collection.title || "Collection"} Analytics — Skinbase`), /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description || "Collection analytics overview." }), seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null, /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots || "noindex,follow" })), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[32rem] opacity-95", style: { background: "radial-gradient(circle at 14% 14%, rgba(56,189,248,0.18), transparent 26%), radial-gradient(circle at 86% 18%, rgba(16,185,129,0.16), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, props.dashboardUrl ? /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Dashboard") : null, props.historyUrl ? /* @__PURE__ */ React.createElement("a", { href: props.historyUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[11px]" }), "History") : null, collection.manage_url ? /* @__PURE__ */ React.createElement("a", { href: collection.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[11px]" }), "Manage") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Performance"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, collection.title || "Collection analytics"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "Review activity velocity, audience response, and the artworks carrying the most discovery value over the last ", range2.days || 30, " days.")), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-5 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Views", value: totals.views, delta: range2.views_delta, icon: "fa-eye" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Likes", value: totals.likes, delta: range2.likes_delta, icon: "fa-heart" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Follows", value: totals.follows, delta: range2.follows_delta, icon: "fa-bell" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Saves", value: totals.saves, delta: range2.saves_delta, icon: "fa-bookmark" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Comments", value: totals.comments, delta: range2.comments_delta, icon: "fa-comments" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Submissions", value: totals.submissions, delta: totals.submissions, icon: "fa-inbox" })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-6" }, /* @__PURE__ */ React.createElement(TimelineChart, { timeline: analytics.timeline }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Artworks"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Top artwork drivers")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, topArtworks.length)), topArtworks.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, topArtworks.map((artwork) => /* @__PURE__ */ React.createElement("div", { key: artwork.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-slate-950/40" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square bg-slate-950/60" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-3xl" }))), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-2 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Views: ", Number(artwork.views || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Favs: ", Number(artwork.favourites || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Shares: ", Number(artwork.shares || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Rank: ", Number(artwork.ranking_score || 0).toFixed(1))))))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "Attach or publish more artworks before artwork-level ranking can be surfaced here."))))));
}
const __vite_glob_0_41 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionAnalytics
}, Symbol.toStringTag, { value: "Module" }));
const STYLES = {
  public: "border-emerald-400/25 bg-emerald-400/10 text-emerald-100",
  unlisted: "border-amber-300/25 bg-amber-300/10 text-amber-100",
  private: "border-white/15 bg-white/6 text-slate-200"
};
const LABELS$1 = {
  public: "Public",
  unlisted: "Unlisted",
  private: "Private"
};
function CollectionVisibilityBadge({ visibility, className = "" }) {
  const value = String(visibility || "public").toLowerCase();
  const label = LABELS$1[value] || "Public";
  const style = STYLES[value] || STYLES.public;
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] ${style} ${className}`.trim() }, label);
}
async function requestJson$o(url, { method = "GET", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    const message = payload?.message || "Request failed.";
    throw new Error(message);
  }
  return payload;
}
function formatUpdated(value) {
  if (!value) return "Updated recently";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Updated recently";
  return new Intl.DateTimeFormat(void 0, {
    month: "short",
    day: "numeric",
    year: "numeric"
  }).format(date);
}
function StatPill$1({ icon, label, value }) {
  return /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.05] px-2.5 py-1 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-[10px] text-slate-400` }), /* @__PURE__ */ React.createElement("span", { className: "text-white" }, value), /* @__PURE__ */ React.createElement("span", null, label));
}
function CoverMedia({ collection, isOwner }) {
  const coverImage = collection?.cover_image;
  const coverMaturity = !isOwner && collection?.cover_image_maturity ? collection.cover_image_maturity : null;
  const shouldBlur = Boolean(coverMaturity?.should_blur);
  const isMature = Boolean(coverMaturity?.is_mature_effective);
  if (!coverImage) {
    return /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[16/10] items-center justify-center bg-[linear-gradient(135deg,rgba(8,17,31,1),rgba(15,23,42,1),rgba(8,17,31,1))] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-4xl" }));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/10] overflow-hidden bg-slate-950" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: coverImage,
      alt: collection?.title || "Collection cover",
      className: `h-full w-full object-cover transition-[transform,filter] duration-500 group-hover:scale-[1.04] ${shouldBlur ? "scale-[1.02] blur-xl" : ""}`,
      loading: "lazy"
    }
  ), isMature ? /* @__PURE__ */ React.createElement("div", { className: "absolute left-3 top-3 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Mature cover") : null, shouldBlur ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-3 bottom-3 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your settings") : null);
}
function CollectionCard({ collection, isOwner, onDelete, onToggleFeature, onMoveUp, onMoveDown, canMoveUp, canMoveDown, busy = false, saveContext = null, saveContextMeta = null }) {
  const [saved, setSaved] = React.useState(Boolean(collection?.saved));
  const [saveBusy, setSaveBusy] = React.useState(false);
  React.useEffect(() => {
    setSaved(Boolean(collection?.saved));
    setSaveBusy(false);
  }, [collection?.id, collection?.saved]);
  function handleDelete(event) {
    event.preventDefault();
    event.stopPropagation();
    onDelete?.(collection);
  }
  function stop(event) {
    event.stopPropagation();
  }
  function handleToggleFeature(event) {
    event.preventDefault();
    event.stopPropagation();
    onToggleFeature?.(collection);
  }
  async function handleSaveToggle(event) {
    event.preventDefault();
    event.stopPropagation();
    if (saveBusy) return;
    const targetUrl = saved ? collection?.unsave_url : collection?.save_url;
    if (!targetUrl) {
      if (collection?.login_url) {
        window.location.assign(collection.login_url);
      }
      return;
    }
    setSaveBusy(true);
    try {
      const payload = await requestJson$o(targetUrl, {
        method: saved ? "DELETE" : "POST",
        body: saved ? void 0 : {
          context: saveContext,
          context_meta: saveContextMeta || void 0
        }
      });
      setSaved(Boolean(payload?.saved));
    } catch (error) {
      window.console?.error?.(error);
    } finally {
      setSaveBusy(false);
    }
  }
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: collection?.url || "#",
      className: `group relative overflow-hidden rounded-[28px] border border-white/10 bg-white/[0.04] shadow-[0_22px_60px_rgba(2,6,23,0.22)] transition-all duration-200 hover:-translate-y-1 hover:border-sky-300/30 hover:bg-white/[0.06] ${busy ? "opacity-70" : ""} lg:max-w-[360px] lg:mx-auto`
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.12),transparent_34%),radial-gradient(circle_at_bottom_right,rgba(249,115,22,0.12),transparent_28%)] opacity-0 transition duration-300 group-hover:opacity-100" }),
    /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(CoverMedia, { collection, isOwner }), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex flex-wrap items-center gap-2" }, collection?.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/25 bg-amber-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Featured") : null, collection?.mode === "smart" ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-sky-300/25 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Smart") : null, !isOwner && collection?.program_key ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-lime-300/25 bg-lime-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-lime-100" }, "Program · ", collection.program_key) : null, !isOwner && collection?.partner_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, "Partner · ", collection.partner_label) : null, !isOwner && collection?.sponsorship_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Sponsor · ", collection.sponsorship_label) : null, isOwner ? /* @__PURE__ */ React.createElement(CollectionVisibilityBadge, { visibility: collection?.visibility }) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h3", { className: "truncate text-lg font-semibold tracking-[-0.03em] text-white" }, collection?.title), collection?.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm text-slate-300" }, collection.subtitle) : null, collection?.owner?.name ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm text-slate-400" }, "Curated by ", collection.owner.name, collection?.owner?.username ? ` • @${collection.owner.username}` : "") : null, /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, (collection?.artworks_count ?? 0).toLocaleString(), " artworks"))), collection?.description_excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 line-clamp-2 text-sm leading-relaxed text-slate-300" }, collection.description_excerpt) : collection?.smart_summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 line-clamp-2 text-sm leading-relaxed text-slate-300" }, collection.smart_summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(StatPill$1, { icon: "fa-heart", label: "likes", value: (collection?.likes_count ?? 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatPill$1, { icon: "fa-bell", label: "followers", value: (collection?.followers_count ?? 0).toLocaleString() }), collection?.collaborators_count > 1 ? /* @__PURE__ */ React.createElement(StatPill$1, { icon: "fa-user-group", label: "curators", value: (collection?.collaborators_count ?? 0).toLocaleString() }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, collection?.is_featured ? "Featured" : "Updated", " ", formatUpdated(collection?.featured_at || collection?.updated_at)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2", onClick: stop }, !isOwner && (collection?.save_url || collection?.unsave_url || collection?.login_url) ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: handleSaveToggle,
        disabled: saveBusy,
        className: `inline-flex items-center gap-2 rounded-full border px-3 py-2 text-[11px] font-semibold uppercase tracking-[0.14em] transition ${saved ? "border-violet-300/20 bg-violet-400/10 text-violet-100 hover:bg-violet-400/15" : "border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.08]"} disabled:opacity-60`
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${saveBusy ? "fa-circle-notch fa-spin" : saved ? "fa-bookmark" : "fa-bookmark"} text-[11px]` }),
      saved ? "Saved" : "Save"
    ) : null, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-[11px]" }), "Open"))), isOwner ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2", onClick: stop }, collection?.visibility === "public" ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: handleToggleFeature,
        className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] transition ${collection?.is_featured ? "border-amber-300/25 bg-amber-300/10 text-amber-100 hover:bg-amber-300/15" : "border-sky-300/20 bg-sky-400/10 text-sky-100 hover:bg-sky-400/15"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${collection?.is_featured ? "fa-star" : "fa-sparkles"} fa-fw` }),
      collection?.is_featured ? "Featured" : "Feature"
    ) : null, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: collection?.edit_url || collection?.manage_url || "#",
        className: "inline-flex items-center gap-2 rounded-xl border border-white/12 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-slate-100 transition hover:bg-white/[0.09]"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw" }),
      "Edit"
    ), /* @__PURE__ */ React.createElement(
      "a",
      {
        href: collection?.manage_url || collection?.edit_url || "#",
        className: "inline-flex items-center gap-2 rounded-xl border border-sky-300/20 bg-sky-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100 transition hover:bg-sky-400/15"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip fa-fw" }),
      "Manage Artworks"
    ), onMoveUp ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: !canMoveUp,
        onClick: (event) => {
          event.preventDefault();
          event.stopPropagation();
          onMoveUp(collection);
        },
        className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${canMoveUp ? "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.09]" : "border-white/8 bg-white/[0.03] text-slate-500"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up fa-fw" }),
      "Up"
    ) : null, onMoveDown ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled: !canMoveDown,
        onClick: (event) => {
          event.preventDefault();
          event.stopPropagation();
          onMoveDown(collection);
        },
        className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${canMoveDown ? "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.09]" : "border-white/8 bg-white/[0.03] text-slate-500"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down fa-fw" }),
      "Down"
    ) : null, collection?.delete_url ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: handleDelete,
        className: "inline-flex items-center gap-2 rounded-xl border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 transition hover:bg-rose-400/15"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can fa-fw" }),
      "Delete"
    ) : null) : null))
  );
}
const DEFAULT_SEARCH_FILTERS = {
  q: "",
  type: "",
  visibility: "",
  lifecycle_state: "",
  workflow_state: "",
  health_state: "",
  placement_eligibility: ""
};
const DEFAULT_BULK_FORM = {
  action: "archive",
  campaign_key: "",
  campaign_label: "",
  lifecycle_state: "archived"
};
function getCsrfToken$e() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function titleize$1(value) {
  return String(value || "").split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}
function buildSearchUrl(baseUrl, filters) {
  const url = new URL(baseUrl, window.location.origin);
  Object.entries(filters || {}).forEach(([key, value]) => {
    if (value === "" || value === null || value === void 0) {
      return;
    }
    url.searchParams.set(key, String(value));
  });
  return url.toString();
}
async function fetchSearchResults(baseUrl, filters) {
  const response = await fetch(buildSearchUrl(baseUrl, filters), {
    method: "GET",
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Search failed.");
  }
  return payload;
}
async function requestJson$n(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$e(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed.");
  }
  return payload;
}
function SummaryCard$4({ label, value, icon, tone = "sky" }) {
  const toneClasses2 = {
    sky: "border-sky-300/15 bg-sky-400/10 text-sky-100",
    amber: "border-amber-300/15 bg-amber-400/10 text-amber-100",
    rose: "border-rose-300/15 bg-rose-400/10 text-rose-100",
    emerald: "border-emerald-300/15 bg-emerald-400/10 text-emerald-100"
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex h-12 w-12 items-center justify-center rounded-2xl border ${toneClasses2[tone] || toneClasses2.sky}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon}` })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold tracking-[-0.04em] text-white" }, value));
}
function CollectionStrip({ title, eyebrow, collections, emptyLabel, endpoints }) {
  function resolve(pattern, collectionId) {
    return pattern ? pattern.replace("__COLLECTION__", String(collectionId)) : null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.24)] backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, eyebrow), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, title)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, collections.length)), collections.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 xl:grid-cols-2" }, collections.map((collection) => /* @__PURE__ */ React.createElement("div", { key: collection.id, className: "space-y-3" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: true }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, resolve(endpoints?.managePattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.managePattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[10px]" }), "Manage") : null, resolve(endpoints?.analyticsPattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.analyticsPattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column fa-fw text-[10px]" }), "Analytics") : null, resolve(endpoints?.historyPattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.historyPattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[10px]" }), "History") : null)))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, emptyLabel));
}
function WarningList({ warnings, endpoints }) {
  function resolve(pattern, collectionId) {
    return pattern ? pattern.replace("__COLLECTION__", String(collectionId)) : null;
  }
  if (!warnings.length) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.24)] backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Health"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Warnings and blockers")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, warnings.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, warnings.map((warning) => /* @__PURE__ */ React.createElement("div", { key: warning.collection_id, className: "rounded-[24px] border border-white/10 bg-[#0d1726] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-lg font-semibold text-white" }, warning.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "State: ", warning.health?.health_state || "unknown")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-xs font-semibold text-amber-100" }, warning.health?.health_score ?? "n/a")), Array.isArray(warning.health?.flags) && warning.health.flags.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, warning.health.flags.map((flag) => /* @__PURE__ */ React.createElement("span", { key: flag, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-300" }, flag))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, resolve(endpoints?.managePattern, warning.collection_id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.managePattern, warning.collection_id), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[10px]" }), "Manage") : null, resolve(endpoints?.healthPattern, warning.collection_id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.healthPattern, warning.collection_id), className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-xs font-semibold text-amber-100 transition hover:bg-amber-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-heart fa-fw text-[10px]" }), "Health JSON") : null)))));
}
function SearchField({ label, value, onChange, children }) {
  return /* @__PURE__ */ React.createElement("label", { className: "block space-y-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, label), children || /* @__PURE__ */ React.createElement(
    "input",
    {
      value,
      onChange,
      className: "w-full rounded-2xl border border-white/10 bg-[#09111d] px-4 py-3 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-sky-300/40"
    }
  ));
}
function BulkActionsPanel({
  selectedCount,
  totalCount,
  form,
  onFormChange,
  onApply,
  onClear,
  onToggleAll,
  busy,
  error,
  notice
}) {
  if (!selectedCount && !notice && !error) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-white/10 bg-[#0d1726] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Bulk actions"), /* @__PURE__ */ React.createElement("h3", { className: "mt-1 text-lg font-semibold text-white" }, "Apply safe actions to selected collections")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-xs font-semibold" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onToggleAll, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-slate-200 transition hover:bg-white/[0.07]" }, selectedCount === totalCount && totalCount > 0 ? "Clear visible" : "Select visible"), selectedCount ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClear, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-slate-200 transition hover:bg-white/[0.07]" }, "Clear selection") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs font-semibold uppercase tracking-[0.12em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-sky-100" }, selectedCount, " selected")), notice || error ? /* @__PURE__ */ React.createElement("div", { className: `mt-4 rounded-2xl px-4 py-3 text-sm ${error ? "border border-rose-300/20 bg-rose-400/10 text-rose-100" : "border border-emerald-300/20 bg-emerald-400/10 text-emerald-100"}` }, error || notice) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-4" }, /* @__PURE__ */ React.createElement(SearchField, { label: "Action" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.action, onChange: (val) => onFormChange("action", val), searchable: false, options: [{ value: "archive", label: "Archive" }, { value: "assign_campaign", label: "Assign campaign" }, { value: "update_lifecycle", label: "Update lifecycle" }, { value: "request_ai_review", label: "Request AI review" }, { value: "mark_editorial_review", label: "Mark editorial review" }] })), form.action === "assign_campaign" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SearchField, { label: "Campaign key" }, /* @__PURE__ */ React.createElement("input", { value: form.campaign_key, onChange: (event) => onFormChange("campaign_key", event.target.value), placeholder: "spring-launch", className: "w-full rounded-2xl border border-white/10 bg-[#09111d] px-4 py-3 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-sky-300/40" })), /* @__PURE__ */ React.createElement(SearchField, { label: "Campaign label" }, /* @__PURE__ */ React.createElement("input", { value: form.campaign_label, onChange: (event) => onFormChange("campaign_label", event.target.value), placeholder: "Spring Launch", className: "w-full rounded-2xl border border-white/10 bg-[#09111d] px-4 py-3 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-sky-300/40" }))) : null, form.action === "update_lifecycle" ? /* @__PURE__ */ React.createElement(SearchField, { label: "Lifecycle state" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.lifecycle_state, onChange: (val) => onFormChange("lifecycle_state", val), searchable: false, options: [{ value: "draft", label: "Draft" }, { value: "published", label: "Published" }, { value: "archived", label: "Archived" }] })) : null, /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onApply, disabled: busy || !selectedCount, className: "inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles fa-fw text-[12px]" }), "Apply action"))));
}
function SearchResults({ state, endpoints, selectedIds, onToggleSelected }) {
  function resolve(pattern, collectionId) {
    return pattern ? pattern.replace("__COLLECTION__", String(collectionId)) : null;
  }
  if (!state.hasSearched) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "Run a search to slice your collection library by workflow, health, visibility, and placement readiness.");
  }
  if (state.error) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-rose-300/20 bg-rose-400/10 px-6 py-4 text-sm text-rose-100" }, state.error);
  }
  if (!state.collections.length) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "No collections matched the current filters.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, Object.entries(state.filters || {}).filter(([, value]) => value !== "" && value !== null && value !== void 0).map(([key, value]) => /* @__PURE__ */ React.createElement("span", { key, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-300" }, titleize$1(key), ": ", value === "1" ? "Eligible" : value === "0" ? "Blocked" : titleize$1(value)))), state.meta ? /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, state.meta.total || state.collections.length, " results") : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-2" }, state.collections.map((collection) => /* @__PURE__ */ React.createElement("div", { key: collection.id, className: "space-y-3 rounded-[28px] border border-white/10 bg-[#0d1726] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.12em] text-slate-400" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: selectedIds.includes(collection.id),
      onChange: () => onToggleSelected(collection.id),
      label: "Select"
    }
  ))), /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: true }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-400" }, collection.workflow_state ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "Workflow: ", titleize$1(collection.workflow_state)) : null, collection.health_state ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "Health: ", titleize$1(collection.health_state)) : null, collection.placement_eligibility === true ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-1 text-emerald-100" }, "Placement Eligible") : null, collection.placement_eligibility === false ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-rose-100" }, "Placement Blocked") : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, resolve(endpoints?.managePattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.managePattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[10px]" }), "Manage") : null, resolve(endpoints?.analyticsPattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.analyticsPattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column fa-fw text-[10px]" }), "Analytics") : null, resolve(endpoints?.historyPattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.historyPattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[10px]" }), "History") : null, resolve(endpoints?.healthPattern, collection.id) ? /* @__PURE__ */ React.createElement("a", { href: resolve(endpoints.healthPattern, collection.id), className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-xs font-semibold text-amber-100 transition hover:bg-amber-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-heart fa-fw text-[10px]" }), "Health") : null)))));
}
function CollectionDashboard() {
  const { props } = X$1();
  const [summary, setSummary] = React.useState(props.summary || {});
  const topPerforming = Array.isArray(props.topPerforming) ? props.topPerforming : [];
  const needsAttention = Array.isArray(props.needsAttention) ? props.needsAttention : [];
  const expiringCampaigns = Array.isArray(props.expiringCampaigns) ? props.expiringCampaigns : [];
  const healthWarnings = Array.isArray(props.healthWarnings) ? props.healthWarnings : [];
  const filterOptions = props.filterOptions || {};
  const endpoints = props.endpoints || {};
  const seo = props.seo || {};
  const [searchFilters, setSearchFilters] = React.useState(DEFAULT_SEARCH_FILTERS);
  const [searchState, setSearchState] = React.useState({
    busy: false,
    error: "",
    collections: [],
    meta: null,
    filters: null,
    hasSearched: false
  });
  const [selectedIds, setSelectedIds] = React.useState([]);
  const [bulkForm, setBulkForm] = React.useState(DEFAULT_BULK_FORM);
  const [bulkState, setBulkState] = React.useState({ busy: false, error: "", notice: "" });
  React.useEffect(() => {
    setSummary(props.summary || {});
  }, [props.summary]);
  React.useEffect(() => {
    const visibleIds = new Set((searchState.collections || []).map((collection) => Number(collection.id)));
    setSelectedIds((current) => current.filter((id) => visibleIds.has(Number(id))));
  }, [searchState.collections]);
  function updateFilter(key, value) {
    setSearchFilters((current) => ({
      ...current,
      [key]: value
    }));
  }
  async function handleSearch(event) {
    event.preventDefault();
    if (!endpoints.search) {
      setSearchState({ busy: false, error: "Search endpoint is unavailable.", collections: [], meta: null, filters: null, hasSearched: true });
      return;
    }
    setSearchState((current) => ({ ...current, busy: true, error: "", hasSearched: true }));
    try {
      const payload = await fetchSearchResults(endpoints.search, searchFilters);
      setSearchState({
        busy: false,
        error: "",
        collections: Array.isArray(payload.collections) ? payload.collections : [],
        meta: payload.meta || null,
        filters: payload.filters || { ...searchFilters },
        hasSearched: true
      });
    } catch (error) {
      setSearchState({ busy: false, error: error.message || "Search failed.", collections: [], meta: null, filters: null, hasSearched: true });
    }
  }
  function resetSearch() {
    setSearchFilters(DEFAULT_SEARCH_FILTERS);
    setSearchState({ busy: false, error: "", collections: [], meta: null, filters: null, hasSearched: false });
    setSelectedIds([]);
  }
  function updateBulkForm(key, value) {
    setBulkForm((current) => ({
      ...current,
      [key]: value
    }));
  }
  function toggleSelected(collectionId) {
    setSelectedIds((current) => current.includes(collectionId) ? current.filter((id) => id !== collectionId) : [...current, collectionId]);
  }
  function toggleSelectAllVisible() {
    const visibleIds = (searchState.collections || []).map((collection) => Number(collection.id));
    if (!visibleIds.length) {
      return;
    }
    setSelectedIds((current) => current.length === visibleIds.length && visibleIds.every((id) => current.includes(id)) ? [] : visibleIds);
  }
  async function applyBulkAction() {
    if (!selectedIds.length) {
      return;
    }
    if (!endpoints.bulkActions) {
      setBulkState({ busy: false, error: "Bulk action endpoint is unavailable.", notice: "" });
      return;
    }
    if (bulkForm.action === "archive" && !window.confirm(`Archive ${selectedIds.length} selected collection${selectedIds.length === 1 ? "" : "s"}?`)) {
      return;
    }
    const payload = {
      action: bulkForm.action,
      collection_ids: selectedIds
    };
    if (bulkForm.action === "assign_campaign") {
      payload.campaign_key = bulkForm.campaign_key;
      payload.campaign_label = bulkForm.campaign_label;
    }
    if (bulkForm.action === "update_lifecycle") {
      payload.lifecycle_state = bulkForm.lifecycle_state;
    }
    setBulkState({ busy: true, error: "", notice: "" });
    try {
      const response = await requestJson$n(endpoints.bulkActions, { method: "POST", body: payload });
      const updates = new Map((Array.isArray(response.collections) ? response.collections : []).map((collection) => [Number(collection.id), collection]));
      setSearchState((current) => ({
        ...current,
        collections: (current.collections || []).map((collection) => updates.get(Number(collection.id)) || collection)
      }));
      setSummary(response.summary || summary);
      setSelectedIds([]);
      setBulkState({ busy: false, error: "", notice: response.message || "Bulk action applied." });
    } catch (error) {
      setBulkState({ busy: false, error: error.message || "Bulk action failed.", notice: "" });
    }
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, seo.title || "Collections Dashboard — Skinbase"), /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description || "Collection lifecycle and performance dashboard." }), seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null, /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots || "noindex,follow" })), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-95", style: { background: "radial-gradient(circle at 12% 15%, rgba(56,189,248,0.18), transparent 28%), radial-gradient(circle at 84% 14%, rgba(245,158,11,0.16), transparent 26%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Operations"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, "Collections dashboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "A working view of collection health across lifecycle, submissions, quality, and campaign timing. Use it to decide what to publish, repair, archive, or promote next.")), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-5 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Total Collections", value: summary.total ?? 0, icon: "fa-layer-group", tone: "sky" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Drafts", value: summary.drafts ?? 0, icon: "fa-file", tone: "amber" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Scheduled", value: summary.scheduled ?? 0, icon: "fa-calendar-days", tone: "emerald" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Published", value: summary.published ?? 0, icon: "fa-globe", tone: "sky" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Archived", value: summary.archived ?? 0, icon: "fa-box-archive", tone: "rose" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Pending Submissions", value: summary.pending_submissions ?? 0, icon: "fa-inbox", tone: "amber" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Needs Review", value: summary.needs_review ?? 0, icon: "fa-triangle-exclamation", tone: "amber" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Duplicate Risk", value: summary.duplicate_risk ?? 0, icon: "fa-id-card", tone: "rose" }), /* @__PURE__ */ React.createElement(SummaryCard$4, { label: "Placement Blocked", value: summary.placement_blocked ?? 0, icon: "fa-ban", tone: "rose" })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.24)] backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Search"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Find the exact collections that need action")), searchState.busy ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-xs font-semibold text-sky-100" }, "Searching...") : null), /* @__PURE__ */ React.createElement("form", { onSubmit: handleSearch, className: "mt-6 grid gap-4 lg:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(SearchField, { label: "Query", value: searchFilters.q, onChange: (event) => updateFilter("q", event.target.value) }, /* @__PURE__ */ React.createElement("input", { value: searchFilters.q, onChange: (event) => updateFilter("q", event.target.value), placeholder: "Title, slug, or campaign", className: "w-full rounded-2xl border border-white/10 bg-[#09111d] px-4 py-3 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-sky-300/40" })), /* @__PURE__ */ React.createElement(SearchField, { label: "Type" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: searchFilters.type, onChange: (val) => updateFilter("type", val), placeholder: "Any type", options: (Array.isArray(filterOptions.types) ? filterOptions.types : []).map((o) => ({ value: o, label: titleize$1(o) })) })), /* @__PURE__ */ React.createElement(SearchField, { label: "Visibility" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: searchFilters.visibility, onChange: (val) => updateFilter("visibility", val), placeholder: "Any visibility", options: (Array.isArray(filterOptions.visibilities) ? filterOptions.visibilities : []).map((o) => ({ value: o, label: titleize$1(o) })) })), /* @__PURE__ */ React.createElement(SearchField, { label: "Lifecycle" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: searchFilters.lifecycle_state, onChange: (val) => updateFilter("lifecycle_state", val), placeholder: "Any lifecycle", options: (Array.isArray(filterOptions.lifecycleStates) ? filterOptions.lifecycleStates : []).map((o) => ({ value: o, label: titleize$1(o) })) })), /* @__PURE__ */ React.createElement(SearchField, { label: "Workflow" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: searchFilters.workflow_state, onChange: (val) => updateFilter("workflow_state", val), placeholder: "Any workflow", options: (Array.isArray(filterOptions.workflowStates) ? filterOptions.workflowStates : []).map((o) => ({ value: o, label: titleize$1(o) })) })), /* @__PURE__ */ React.createElement(SearchField, { label: "Health" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: searchFilters.health_state, onChange: (val) => updateFilter("health_state", val), placeholder: "Any health state", options: (Array.isArray(filterOptions.healthStates) ? filterOptions.healthStates : []).map((o) => ({ value: o, label: titleize$1(o) })) })), /* @__PURE__ */ React.createElement(SearchField, { label: "Placement" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: searchFilters.placement_eligibility, onChange: (val) => updateFilter("placement_eligibility", val), placeholder: "Any placement state", searchable: false, options: [{ value: "1", label: "Eligible" }, { value: "0", label: "Blocked" }] })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end gap-3 xl:col-span-1" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: searchState.busy, className: "inline-flex flex-1 items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass fa-fw text-[12px]" }), "Search"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetSearch, disabled: searchState.busy, className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07] disabled:cursor-not-allowed disabled:opacity-60" }, "Reset"))), /* @__PURE__ */ React.createElement(
    BulkActionsPanel,
    {
      selectedCount: selectedIds.length,
      totalCount: (searchState.collections || []).length,
      form: bulkForm,
      onFormChange: updateBulkForm,
      onApply: applyBulkAction,
      onClear: () => setSelectedIds([]),
      onToggleAll: toggleSelectAllVisible,
      busy: bulkState.busy,
      error: bulkState.error,
      notice: bulkState.notice
    }
  ), /* @__PURE__ */ React.createElement(SearchResults, { state: searchState, endpoints, selectedIds, onToggleSelected: toggleSelected })), /* @__PURE__ */ React.createElement(WarningList, { warnings: healthWarnings, endpoints }), /* @__PURE__ */ React.createElement(CollectionStrip, { title: "Top Performing", eyebrow: "Momentum", collections: topPerforming, emptyLabel: "No collections have enough activity yet to rank here.", endpoints }), /* @__PURE__ */ React.createElement(CollectionStrip, { title: "Needs Attention", eyebrow: "Quality", collections: needsAttention, emptyLabel: "No collections currently need manual intervention.", endpoints }), /* @__PURE__ */ React.createElement(CollectionStrip, { title: "Expiring Campaigns", eyebrow: "Timing", collections: expiringCampaigns, emptyLabel: "No campaigns are approaching their sunset window.", endpoints })))));
}
const __vite_glob_0_42 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionDashboard
}, Symbol.toStringTag, { value: "Module" }));
const SEARCH_SELECT_OPTIONS = {
  type: [
    { value: "personal", label: "Personal" },
    { value: "community", label: "Community" },
    { value: "editorial", label: "Editorial" }
  ],
  mode: [
    { value: "manual", label: "Manual" },
    { value: "smart", label: "Smart" }
  ],
  lifecycle_state: [
    { value: "published", label: "Published" },
    { value: "featured", label: "Featured" },
    { value: "archived", label: "Archived" }
  ],
  health_state: [
    { value: "healthy", label: "Healthy" },
    { value: "needs_metadata", label: "Needs metadata" },
    { value: "stale", label: "Stale" },
    { value: "low_content", label: "Low content" },
    { value: "broken_items", label: "Broken items" },
    { value: "weak_cover", label: "Weak cover" },
    { value: "low_engagement", label: "Low engagement" },
    { value: "duplicate_risk", label: "Duplicate risk" },
    { value: "merge_candidate", label: "Merge candidate" }
  ],
  sort: [
    { value: "trending", label: "Trending" },
    { value: "recent", label: "Recent" },
    { value: "quality", label: "Quality" },
    { value: "evergreen", label: "Evergreen" }
  ]
};
function humanizeToken$1(value) {
  return String(value || "").replaceAll("_", " ").replaceAll("-", " ").replace(/\b\w/g, (match) => match.toUpperCase());
}
function searchChipLabel(key, value) {
  if (!value) return null;
  const option = SEARCH_SELECT_OPTIONS[key]?.find((item) => item.value === value);
  const displayValue = option?.label || humanizeToken$1(value);
  return key === "q" ? `Query: ${value}` : key === "campaign_key" ? `Campaign: ${displayValue}` : key === "program_key" ? `Program: ${displayValue}` : key === "quality_tier" ? `Quality Tier: ${displayValue}` : key === "sort" ? `Sort: ${displayValue}` : `${humanizeToken$1(key)}: ${displayValue}`;
}
function buildSearchHref(filters, omitKey = null) {
  const params = new URLSearchParams();
  Object.entries(filters || {}).forEach(([key, value]) => {
    if (key === omitKey) return;
    if (value === null || value === void 0 || value === "") return;
    params.set(key, value);
  });
  const query = params.toString();
  return query ? `/collections/search?${query}` : "/collections/search";
}
function activeSearchChips(filters) {
  return Object.entries(filters || {}).filter(([, value]) => value !== null && value !== void 0 && value !== "").map(([key, value]) => ({
    key,
    label: searchChipLabel(key, value),
    href: buildSearchHref(filters, key)
  })).filter((chip) => chip.label);
}
function primarySaveContext({ search: search2, campaign, program, title, eyebrow }) {
  if (search2) {
    return {
      context: "collection_search",
      meta: {
        query: search2?.filters?.q || null,
        surface_label: "collection search"
      }
    };
  }
  if (campaign) {
    return {
      context: "campaign_landing",
      meta: {
        campaign_key: campaign.key,
        campaign_label: campaign.label,
        surface_label: campaign.label || "campaign landing"
      }
    };
  }
  if (program) {
    return {
      context: "program_landing",
      meta: {
        program_key: program.key,
        program_label: program.label,
        surface_label: program.label || "program landing"
      }
    };
  }
  if (eyebrow === "Trending") return { context: "trending_landing", meta: { surface_label: "trending collections" } };
  if (eyebrow === "Editorial") return { context: "editorial_landing", meta: { surface_label: "editorial collections" } };
  if (eyebrow === "Community") return { context: "community_landing", meta: { surface_label: "community collections" } };
  if (eyebrow === "Seasonal") return { context: "seasonal_landing", meta: { surface_label: "seasonal collections" } };
  if (title === "Recommended collections" || title === "Collections worth exploring") return { context: "recommended_landing", meta: { surface_label: "recommended collections" } };
  return {
    context: "featured_landing",
    meta: { surface_label: "featured collections" }
  };
}
function HeroStat$2({ icon, label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.05] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-[10px]` }), label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, value));
}
function EmptyState$4() {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[32px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-20 w-20 items-center justify-center rounded-[24px] border border-white/12 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass text-3xl" })), /* @__PURE__ */ React.createElement("h2", { className: "mt-5 text-2xl font-semibold text-white" }, "No featured collections yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm leading-relaxed text-slate-300" }, "Featured placement is reserved for public collections with a strong visual point of view. Check back once creators start pinning their best showcases."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex justify-center" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/",
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/12 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-house fa-fw" }),
    "Back to home"
  )));
}
function SearchPanel({ search: search2 }) {
  if (!search2) return null;
  const filters = search2.filters || {};
  const options = search2.options || {};
  const chips = activeSearchChips(filters);
  const [localFilters, setLocalFilters] = React.useState({
    q: filters.q || "",
    type: filters.type || "",
    sort: filters.sort || "trending",
    category: filters.category || "",
    mode: filters.mode || "",
    style: filters.style || "",
    lifecycle_state: filters.lifecycle_state || "",
    theme: filters.theme || "",
    health_state: filters.health_state || "",
    color: filters.color || "",
    campaign_key: filters.campaign_key || "",
    program_key: filters.program_key || "",
    quality_tier: filters.quality_tier || ""
  });
  function updateFilter(key, val) {
    setLocalFilters((curr) => ({ ...curr, [key]: val }));
  }
  function handleSubmit(event) {
    event.preventDefault();
    const params = {};
    Object.entries(localFilters).forEach(([k2, v2]) => {
      if (v2) params[k2] = v2;
    });
    At.get("/collections/search", params);
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Filters"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Search collections")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, search2?.meta?.total ?? 0, " results")), /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit, className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("input", { value: localFilters.q, onChange: (e) => updateFilter("q", e.target.value), placeholder: "Search title or summary", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35 xl:col-span-2" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.type, onChange: (val) => updateFilter("type", val), placeholder: "All types", searchable: false, options: [{ value: "personal", label: "Personal" }, { value: "community", label: "Community" }, { value: "editorial", label: "Editorial" }] }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.sort, onChange: (val) => updateFilter("sort", val), searchable: false, options: [{ value: "trending", label: "Trending" }, { value: "recent", label: "Recent" }, { value: "quality", label: "Quality" }, { value: "evergreen", label: "Evergreen" }] }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.category, onChange: (val) => updateFilter("category", val), placeholder: "Any category", options: (options.category || []).map((item) => ({ value: item.value, label: item.label })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.mode, onChange: (val) => updateFilter("mode", val), placeholder: "Any curation mode", searchable: false, options: [{ value: "manual", label: "Manual" }, { value: "smart", label: "Smart" }] }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.style, onChange: (val) => updateFilter("style", val), placeholder: "Any style signal", options: (options.style || []).map((item) => ({ value: item.value, label: item.label })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.lifecycle_state, onChange: (val) => updateFilter("lifecycle_state", val), placeholder: "Any lifecycle", searchable: false, options: [{ value: "published", label: "Published" }, { value: "featured", label: "Featured" }, { value: "archived", label: "Archived" }] }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.theme, onChange: (val) => updateFilter("theme", val), placeholder: "Any theme", options: (options.theme || []).map((item) => ({ value: item.value, label: item.label })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.health_state, onChange: (val) => updateFilter("health_state", val), placeholder: "Any quality state", searchable: false, options: [{ value: "healthy", label: "Healthy" }, { value: "needs_metadata", label: "Needs metadata" }, { value: "stale", label: "Stale" }, { value: "low_content", label: "Low content" }, { value: "broken_items", label: "Broken items" }, { value: "weak_cover", label: "Weak cover" }, { value: "low_engagement", label: "Low engagement" }, { value: "duplicate_risk", label: "Duplicate risk" }, { value: "merge_candidate", label: "Merge candidate" }] }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.color, onChange: (val) => updateFilter("color", val), placeholder: "Any color palette", options: (options.color || []).map((item) => ({ value: item.value, label: item.label })) }), /* @__PURE__ */ React.createElement("input", { value: localFilters.campaign_key, onChange: (e) => updateFilter("campaign_key", e.target.value), placeholder: "Campaign key", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35" }), /* @__PURE__ */ React.createElement("input", { value: localFilters.program_key, onChange: (e) => updateFilter("program_key", e.target.value), placeholder: "Program key", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: localFilters.quality_tier, onChange: (val) => updateFilter("quality_tier", val), placeholder: "Any quality tier", options: (options.quality_tier || []).map((item) => ({ value: item.value, label: item.label })) }), /* @__PURE__ */ React.createElement("div", { className: "md:col-span-2 xl:col-span-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass fa-fw" }), "Apply filters"), /* @__PURE__ */ React.createElement("a", { href: "/collections/search", className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left fa-fw" }), "Reset"))), chips.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, chips.map((chip) => /* @__PURE__ */ React.createElement("a", { key: chip.key, href: chip.href, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-1.5 text-xs font-semibold text-slate-200 transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, chip.label), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark text-[10px] text-slate-400" })))) : null, search2?.links?.prev || search2?.links?.next ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-sm" }, search2.links.prev ? /* @__PURE__ */ React.createElement("a", { href: search2.links.prev, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[10px]" }), "Previous") : null, search2.links.next ? /* @__PURE__ */ React.createElement("a", { href: search2.links.next, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-white transition hover:bg-white/[0.07]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right fa-fw text-[10px]" })) : null) : null);
}
function CollectionFeaturedIndex() {
  const { props } = X$1();
  const seo = props.seo || {};
  const eyebrow = props.eyebrow || "Discovery";
  const title = props.title || "Featured collections";
  const description = props.description || "A rotating set of standout galleries from across Skinbase. Some are meticulously hand-sequenced. Others are smart collections that stay fresh as the creator publishes new work.";
  const collections = Array.isArray(props.collections) ? props.collections : [];
  const communityCollections = Array.isArray(props.communityCollections) ? props.communityCollections : [];
  const editorialCollections = Array.isArray(props.editorialCollections) ? props.editorialCollections : [];
  const recentCollections = Array.isArray(props.recentCollections) ? props.recentCollections : [];
  const trendingCollections = Array.isArray(props.trendingCollections) ? props.trendingCollections : [];
  const seasonalCollections = Array.isArray(props.seasonalCollections) ? props.seasonalCollections : [];
  const campaign = props.campaign || null;
  const program = props.program || null;
  const search2 = props.search || null;
  const smartCount = collections.filter((collection) => collection?.mode === "smart").length;
  const totalArtworks = collections.reduce((sum, collection) => sum + (collection?.artworks_count || 0), 0);
  const mainSave = primarySaveContext({ search: search2, campaign, program, title, eyebrow });
  const listSchema = seo?.canonical ? {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: title,
    description,
    url: seo.canonical,
    mainEntity: {
      "@type": "ItemList",
      numberOfItems: collections.length,
      itemListElement: collections.slice(0, 18).map((collection, index2) => ({
        "@type": "ListItem",
        position: index2 + 1,
        url: collection.url,
        name: collection.title
      }))
    }
  } : null;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: seo?.title || `${title} — Skinbase`, description: seo?.description || description, jsonLd: listSchema }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[38rem] opacity-95",
      style: {
        background: "radial-gradient(circle at 12% 14%, rgba(56,189,248,0.18), transparent 28%), radial-gradient(circle at 88% 16%, rgba(249,115,22,0.18), transparent 26%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)"
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: "/", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to home"), /* @__PURE__ */ React.createElement("a", { href: "/collections/featured", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Featured"), /* @__PURE__ */ React.createElement("a", { href: "/collections/trending", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Trending"), /* @__PURE__ */ React.createElement("a", { href: "/collections/community", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Community"), /* @__PURE__ */ React.createElement("a", { href: "/collections/editorial", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Editorial"), /* @__PURE__ */ React.createElement("a", { href: "/collections/seasonal", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Seasonal")), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.18fr)_400px] xl:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, eyebrow), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, title), campaign?.badge_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, campaign.badge_label) : program?.promotion_tier ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Promotion tier: ", program.promotion_tier) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, description), campaign ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Campaign key: ", campaign.key), campaign.event_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Event: ", campaign.event_label) : null, campaign.season_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Season: ", campaign.season_key) : null, Array.isArray(campaign.active_surface_keys) && campaign.active_surface_keys.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Surfaces: ", campaign.active_surface_keys.join(", ")) : null) : program ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Program key: ", program.key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Collections: ", program.collections_count ?? collections.length), program.trust_tier ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Trust: ", program.trust_tier) : null, Array.isArray(program.partner_labels) && program.partner_labels.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Partners: ", program.partner_labels.join(", ")) : null, Array.isArray(program.sponsorship_labels) && program.sponsorship_labels.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Sponsors: ", program.sponsorship_labels.join(", ")) : null) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(HeroStat$2, { icon: "fa-layer-group", label: "Collections", value: collections.length.toLocaleString() }), /* @__PURE__ */ React.createElement(HeroStat$2, { icon: "fa-wand-magic-sparkles", label: "Smart", value: smartCount.toLocaleString() }), /* @__PURE__ */ React.createElement(HeroStat$2, { icon: "fa-images", label: "Artworks", value: totalArtworks.toLocaleString() })))), /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement(SearchPanel, { search: search2 })), /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, collections.length ? /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, collections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: mainSave.context, saveContextMeta: mainSave.meta }))) : /* @__PURE__ */ React.createElement(EmptyState$4, null)), communityCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Community"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Collaborative picks"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, communityCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "community_row", saveContextMeta: { surface_label: "community collections" } })))) : null, trendingCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Trending"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Momentum right now")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, trendingCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "trending_row", saveContextMeta: { surface_label: "trending collections" } })))) : null, editorialCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Editorial"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Staff and campaign collections")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, editorialCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "editorial_row", saveContextMeta: { surface_label: "editorial collections" } })))) : null, seasonalCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Seasonal"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Campaign and event spotlights")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, seasonalCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "seasonal_row", saveContextMeta: { surface_label: "seasonal collections" } })))) : null, recentCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10 pb-8" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Recent"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Freshly published collections")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, recentCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "recent_row", saveContextMeta: { surface_label: "recent collections" } })))) : null)));
}
const __vite_glob_0_43 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionFeaturedIndex
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$d() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function formatDateTime$2(value) {
  if (!value) return "Unknown time";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unknown time";
  return date.toLocaleString();
}
function FieldChanges({ label, value }) {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const entries = Object.entries(value).slice(0, 8);
  if (!entries.length) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 text-sm text-slate-300" }, entries.map(([key, fieldValue]) => /* @__PURE__ */ React.createElement("div", { key, className: "flex items-start justify-between gap-4 border-b border-white/5 pb-2 last:border-b-0 last:pb-0" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, key), /* @__PURE__ */ React.createElement("span", { className: "max-w-[60%] truncate text-right" }, Array.isArray(fieldValue) ? `${fieldValue.length} items` : String(fieldValue))))));
}
function buildPageUrl(pageNumber) {
  if (typeof window === "undefined") return "#";
  const url = new URL(window.location.href);
  url.searchParams.set("page", String(pageNumber));
  return url.toString();
}
function CollectionHistory() {
  const { props } = X$1();
  const collection = props.collection || {};
  const history2 = props.history || {};
  const entries = Array.isArray(history2.data) ? history2.data : [];
  const meta = history2.meta || {};
  const seo = props.seo || {};
  const [busyId, setBusyId] = React.useState(null);
  const [notice, setNotice] = React.useState("");
  async function handleRestore(entry) {
    if (!props.restorePattern || !entry?.can_restore) return;
    const confirmed = window.confirm(`Restore this collection state from history entry #${entry.id}?`);
    if (!confirmed) return;
    setBusyId(entry.id);
    setNotice("");
    try {
      const response = await fetch(props.restorePattern.replace("__HISTORY__", String(entry.id)), {
        method: "POST",
        headers: {
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$d()
        }
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || "Unable to restore this history entry right now.");
      }
      window.location.reload();
    } catch (error) {
      setNotice(error?.message || "Unable to restore this history entry right now.");
    } finally {
      setBusyId(null);
    }
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, seo.title || `${collection.title || "Collection"} History — Skinbase`), /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description || "Collection audit history." }), seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null, /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots || "noindex,follow" })), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[32rem] opacity-95", style: { background: "radial-gradient(circle at 14% 14%, rgba(56,189,248,0.16), transparent 26%), radial-gradient(circle at 84% 20%, rgba(244,63,94,0.14), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, props.dashboardUrl ? /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Dashboard") : null, props.analyticsUrl ? /* @__PURE__ */ React.createElement("a", { href: props.analyticsUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column fa-fw text-[11px]" }), "Analytics") : null, collection.manage_url ? /* @__PURE__ */ React.createElement("a", { href: collection.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[11px]" }), "Manage") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Audit"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, collection.title || "Collection history"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "A chronological log of lifecycle transitions, editorial changes, artwork operations, and moderation-adjacent actions for this collection.")), /* @__PURE__ */ React.createElement("section", { className: "mt-8 space-y-4" }, notice ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-rose-300/20 bg-rose-500/10 px-5 py-4 text-sm text-rose-100" }, notice) : null, entries.length ? entries.map((entry) => /* @__PURE__ */ React.createElement("article", { key: entry.id, className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, String(entry.action_type || "updated").replace(/_/g, " ")), entry.actor?.username ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "@", entry.actor.username) : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "System"), entry.can_restore ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-100" }, "Restorable") : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-xl font-semibold text-white" }, entry.summary || "Collection updated"), entry.can_restore && Array.isArray(entry.restore_fields) && entry.restore_fields.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs uppercase tracking-[0.18em] text-slate-400" }, "Restores: ", entry.restore_fields.join(", ")) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-end gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, formatDateTime$2(entry.created_at)), props.canRestoreHistory && entry.can_restore ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleRestore(entry),
      disabled: busyId === entry.id,
      className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-emerald-100 transition hover:bg-emerald-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left fa-fw text-[10px]" }),
    busyId === entry.id ? "Restoring…" : "Restore"
  ) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(FieldChanges, { label: "Before", value: entry.before }), /* @__PURE__ */ React.createElement(FieldChanges, { label: "After", value: entry.after })))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-14 text-sm text-slate-300" }, "No audit entries have been recorded for this collection yet.")), Number(meta.last_page || 1) > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex flex-wrap items-center justify-between gap-3 rounded-[28px] border border-white/10 bg-white/[0.04] px-5 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, (meta.current_page || 1) > 1 ? /* @__PURE__ */ React.createElement("a", { href: buildPageUrl((meta.current_page || 1) - 1), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[10px]" }), "Previous") : null, (meta.current_page || 1) < (meta.last_page || 1) ? /* @__PURE__ */ React.createElement("a", { href: buildPageUrl((meta.current_page || 1) + 1), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 font-semibold text-white transition hover:bg-white/[0.07]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right fa-fw text-[10px]" })) : null)) : null)));
}
const __vite_glob_0_44 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionHistory
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$c() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function slugify$3(value) {
  return String(value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 140);
}
function isoToLocalInput$2(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 6e4);
  return local.toISOString().slice(0, 16);
}
function localInputToIso(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return date.toISOString();
}
function formatDateTimeLabel(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return date.toLocaleString();
}
function formatStateLabel(value) {
  if (!value) return "Unknown";
  return String(value).replaceAll("_", " ").replaceAll("-", " ").replace(/\b\w/g, (match) => match.toUpperCase());
}
function healthFlagMeta(flag) {
  const tone = {
    success: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
    warning: "border-amber-300/20 bg-amber-400/10 text-amber-100",
    danger: "border-rose-300/20 bg-rose-400/10 text-rose-100",
    neutral: "border-white/10 bg-white/[0.04] text-slate-200"
  };
  const registry = {
    healthy: {
      label: "Healthy",
      description: "No active health blockers are currently recorded.",
      tone: tone.success
    },
    needs_metadata: {
      label: "Metadata is thin",
      description: "Tighten the title, summary, cover, or tagging so discovery surfaces have stronger context.",
      tone: tone.warning
    },
    stale: {
      label: "Stale collection",
      description: "This collection looks quiet. Refresh the lineup or update the presentation before promoting it again.",
      tone: tone.warning
    },
    low_content: {
      label: "Low content",
      description: "Add more artworks so the collection can support richer layouts and recommendations.",
      tone: tone.warning
    },
    broken_items: {
      label: "Broken items detected",
      description: "Some attached items are no longer safely displayable. Review attachments before featuring this set.",
      tone: tone.danger
    },
    weak_cover: {
      label: "Weak cover",
      description: "Choose a stronger cover artwork so the collection reads clearly on cards and hero rails.",
      tone: tone.warning
    },
    low_engagement: {
      label: "Low engagement",
      description: "This collection is live but underperforming. Consider adjusting ordering, title, or campaign context.",
      tone: tone.warning
    },
    attribution_incomplete: {
      label: "Attribution incomplete",
      description: "Cross-links or creator attribution need a pass before this collection is pushed harder.",
      tone: tone.warning
    },
    needs_review: {
      label: "Needs review",
      description: "Workflow or moderation state is still blocking this collection from safer public programming.",
      tone: tone.danger
    },
    duplicate_risk: {
      label: "Duplicate risk",
      description: "A similar collection may already exist. Use the merge review tools before spreading traffic across duplicates.",
      tone: tone.warning
    },
    merge_candidate: {
      label: "Merge candidate",
      description: "This collection already looks like a merge candidate. Confirm the canonical target in the review section below.",
      tone: tone.warning
    }
  };
  return registry[flag] || {
    label: formatStateLabel(flag),
    description: "Review this collection state before pushing it to wider surfaces.",
    tone: tone.neutral
  };
}
function buildInviteExpiryOptions(defaultDays) {
  const sanitizedDefault = Math.max(1, Number.parseInt(defaultDays, 10) || 7);
  const values = [sanitizedDefault, 1, 3, 7, 14, 30];
  return Array.from(new Set(values)).sort((left, right) => left - right);
}
function firstEntitySelection(options) {
  const firstType = Object.keys(options || {})[0] || "creator";
  return {
    type: firstType,
    id: options?.[firstType]?.[0]?.id || ""
  };
}
async function requestJson$m(url, { method = "GET", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$c(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    const message = payload?.message || "Request failed.";
    const error = new Error(message);
    error.payload = payload;
    throw error;
  }
  return payload;
}
function defaultRuleValue(field) {
  if (field === "created_at") {
    return { from: "", to: "" };
  }
  if (field === "is_featured" || field === "is_mature") {
    return true;
  }
  return "";
}
function operatorOptionsForField(field) {
  if (field === "created_at") {
    return [{ value: "between", label: "Between" }];
  }
  if (field === "is_featured" || field === "is_mature") {
    return [{ value: "equals", label: "Is" }];
  }
  if (field === "tags") {
    return [{ value: "equals", label: "Has tag" }];
  }
  return [
    { value: "contains", label: "Contains" },
    { value: "equals", label: "Equals" }
  ];
}
function createRule(field = "tags") {
  return {
    field,
    operator: operatorOptionsForField(field)[0]?.value || "contains",
    value: defaultRuleValue(field)
  };
}
function normalizeRule(rule, fallbackField = "tags") {
  const field = rule?.field || fallbackField;
  const operators = operatorOptionsForField(field);
  const operator = operators.some((item) => item.value === rule?.operator) ? rule.operator : operators[0]?.value || "contains";
  if (field === "created_at") {
    return {
      field,
      operator,
      value: {
        from: rule?.value?.from || "",
        to: rule?.value?.to || ""
      }
    };
  }
  if (field === "is_featured" || field === "is_mature") {
    return {
      field,
      operator,
      value: Boolean(rule?.value)
    };
  }
  return {
    field,
    operator,
    value: typeof rule?.value === "string" ? rule.value : ""
  };
}
function normalizeSmartRules(rawRules, mode = "manual") {
  if (rawRules && Array.isArray(rawRules.rules)) {
    return {
      match: rawRules.match === "any" ? "any" : "all",
      sort: rawRules.sort || "newest",
      rules: rawRules.rules.map((rule) => normalizeRule(rule)).filter(Boolean)
    };
  }
  if (mode === "smart") {
    return {
      match: "all",
      sort: "newest",
      rules: [createRule()]
    };
  }
  return {
    match: "all",
    sort: "newest",
    rules: []
  };
}
function normalizeLayoutModules(rawModules) {
  if (!Array.isArray(rawModules)) return [];
  return rawModules.map((module) => ({
    key: module?.key || "",
    label: module?.label || module?.key || "Module",
    description: module?.description || "",
    slot: module?.slot || "main",
    slots: Array.isArray(module?.slots) && module.slots.length ? module.slots : ["main"],
    enabled: module?.enabled !== false,
    locked: Boolean(module?.locked)
  })).filter((module) => module.key);
}
function humanizeField(field, smartRuleOptions) {
  const label = smartRuleOptions?.fields?.find((item) => item.value === field)?.label;
  return label || field;
}
function getFieldOptions(field, smartRuleOptions) {
  if (field === "tags") return smartRuleOptions?.tag_options || [];
  if (field === "category") return smartRuleOptions?.category_options || [];
  if (field === "subcategory") return smartRuleOptions?.subcategory_options || [];
  if (field === "medium") return smartRuleOptions?.medium_options || [];
  if (field === "style") return smartRuleOptions?.style_options || [];
  if (field === "color") return smartRuleOptions?.color_options || [];
  return [];
}
function buildRuleSummary(rule, smartRuleOptions) {
  if (!rule) return "";
  if (rule.field === "created_at") {
    const from = rule.value?.from || "any date";
    const to = rule.value?.to || "today";
    return `Created between ${from} and ${to}`;
  }
  if (rule.field === "is_featured") {
    return rule.value ? "Featured artworks only" : "Artworks not marked featured";
  }
  if (rule.field === "is_mature") {
    return rule.value ? "Mature artworks only" : "Artworks not marked mature";
  }
  if (rule.field === "tags") {
    const tag = String(rule.value || "").trim();
    return tag ? `Has tag: ${tag}` : "Tag — no value set";
  }
  const label = humanizeField(rule.field, smartRuleOptions);
  const value = String(rule.value || "").trim() || "Any value";
  return `${label} ${rule.operator} ${value}`;
}
function Field$3({ label, children, help }) {
  return /* @__PURE__ */ React.createElement("label", { className: "block space-y-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, label), children, help ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, help) : null);
}
function StatCard$7({ icon, label, value, tone = "default" }) {
  const toneClass = tone === "accent" ? "border-sky-300/20 bg-sky-400/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-white";
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[24px] border px-4 py-4 ${toneClass}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-[10px]` }), label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em]" }, value));
}
function ModeButton({ active, title, description, icon, onClick }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick,
      className: `rounded-[24px] border p-4 text-left transition ${active ? "border-sky-300/30 bg-sky-400/10 text-sky-50 shadow-[0_18px_40px_rgba(14,165,233,0.12)]" : "border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.06]"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: `flex h-11 w-11 items-center justify-center rounded-2xl border ${active ? "border-sky-300/25 bg-sky-400/10" : "border-white/10 bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold uppercase tracking-[0.14em]" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-relaxed text-slate-300" }, description)))
  );
}
function SmartPreviewArtwork({ artwork }) {
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artwork.url,
      className: "group overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04] transition hover:-translate-y-0.5 hover:bg-white/[0.06]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-950" }, /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]", loading: "lazy" })),
    /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, [artwork.content_type, artwork.category].filter(Boolean).join(" • ") || "Artwork"))
  );
}
function ArtworkPickerCard({ artwork, checked, onToggle, actionLabel = "Select" }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onToggle(artwork.id),
      className: `group w-full overflow-hidden rounded-[24px] border text-left transition ${checked ? "border-sky-300/40 bg-sky-400/10" : "border-white/10 bg-white/[0.04] hover:border-white/18 hover:bg-white/[0.06]"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-950" }, /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]", loading: "lazy" })),
    /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, [artwork.content_type, artwork.category].filter(Boolean).join(" • ") || "Artwork")), /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-6 min-w-6 items-center justify-center rounded-full border px-2 text-[10px] font-semibold uppercase tracking-[0.14em] ${checked ? "border-sky-300/40 bg-sky-400/15 text-sky-100" : "border-white/12 text-slate-400"}` }, checked ? "Added" : actionLabel)))
  );
}
function AttachedArtworkCard({ artwork, index: index2, total, onMoveUp, onMoveDown, onRemove }) {
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-950" }, /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-full w-full object-cover", loading: "lazy" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 p-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, "Position ", index2 + 1)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onMoveUp,
      disabled: index2 === 0,
      className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${index2 === 0 ? "border-white/8 bg-white/[0.03] text-slate-500" : "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up fa-fw" }),
    "Up"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onMoveDown,
      disabled: index2 === total - 1,
      className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${index2 === total - 1 ? "border-white/8 bg-white/[0.03] text-slate-500" : "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down fa-fw" }),
    "Down"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onRemove,
      className: "inline-flex items-center gap-2 rounded-xl border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 hover:bg-rose-400/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can fa-fw" }),
    "Remove"
  ))));
}
function MemberCard({ member, onRoleChange, onRemove, onAccept, onDecline, onTransfer }) {
  const expiryLabel = formatDateTimeLabel(member?.expires_at);
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("img", { src: member?.user?.avatar_url, alt: member?.user?.name || member?.user?.username, className: "h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10" }), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, member?.user?.name || member?.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, member?.role, " • ", member?.status), member?.status === "pending" && expiryLabel ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Invite expires ", expiryLabel) : null, member?.is_expired ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-amber-300" }, "Invite expired") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, member?.can_revoke ? /* @__PURE__ */ React.createElement("div", { className: "min-w-[150px]" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: member?.role,
      onChange: (value) => onRoleChange?.(member, value),
      options: [
        { value: "editor", label: "Editor" },
        { value: "contributor", label: "Contributor" },
        { value: "viewer", label: "Viewer" }
      ],
      searchable: false,
      className: "text-xs font-semibold uppercase tracking-[0.14em]"
    }
  )) : null, member?.can_accept ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onAccept?.(member), className: "rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-100" }, "Accept") : null, member?.can_decline ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onDecline?.(member), className: "rounded-xl border border-white/12 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, "Decline") : null, member?.can_transfer ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onTransfer?.(member), className: "rounded-xl border border-amber-400/20 bg-amber-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-amber-100" }, "Make owner") : null, member?.can_revoke ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onRemove?.(member), className: "rounded-xl border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100" }, "Remove") : null));
}
function SubmissionReviewCard({ submission, onApprove, onReject, onWithdraw }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, submission?.artwork?.thumb ? /* @__PURE__ */ React.createElement("img", { src: submission.artwork.thumb, alt: submission.artwork.title, className: "h-16 w-16 rounded-2xl object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, submission?.artwork?.title || "Submission"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, submission?.status, " • @", submission?.user?.username), submission?.message ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, submission.message) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, submission?.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApprove?.(submission), className: "rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-100" }, "Approve") : null, submission?.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onReject?.(submission), className: "rounded-xl border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100" }, "Reject") : null, submission?.can_withdraw ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onWithdraw?.(submission), className: "rounded-xl border border-white/12 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, "Withdraw") : null))));
}
function AiSuggestionCard({ title, body: body2, actionLabel, onAction, muted = false, children }) {
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[24px] border p-4 ${muted ? "border-dashed border-white/12 bg-white/[0.03]" : "border-white/10 bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-slate-400" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-relaxed text-slate-200" }, body2), children, actionLabel && onAction ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onAction, className: "mt-4 rounded-xl border border-sky-300/20 bg-sky-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100 transition hover:bg-sky-400/15" }, actionLabel) : null);
}
function LayoutModuleCard({ module, index: index2, total, onToggle, onSlotChange, onMoveUp, onMoveDown }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, module.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-relaxed text-slate-400" }, module.description)), /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: module.enabled,
      disabled: module.locked,
      onChange: (event) => onToggle(module.key, event.target.checked),
      label: module.locked ? "Required" : module.enabled ? "Enabled" : "Disabled"
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-[minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Placement" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: module.slot,
      onChange: (value) => onSlotChange(module.key, value),
      options: module.slots.map((slot) => ({
        value: slot,
        label: slot === "full" ? "Full width" : slot === "main" ? "Main column" : "Sidebar"
      })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onMoveUp,
      disabled: index2 === 0,
      className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${index2 === 0 ? "border-white/8 bg-white/[0.03] text-slate-500" : "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up fa-fw" }),
    "Up"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onMoveDown,
      disabled: index2 === total - 1,
      className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${index2 === total - 1 ? "border-white/8 bg-white/[0.03] text-slate-500" : "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-down fa-fw" }),
    "Down"
  ))));
}
function StudioTabButton({ active, label, icon, onClick }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick,
      className: `inline-flex items-center gap-2 rounded-full border px-4 py-2.5 text-sm font-semibold transition ${active ? "border-sky-300/25 bg-sky-400/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.07] hover:text-white"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} fa-fw text-[12px]` }),
    label
  );
}
function AdvancedSection({ title, icon, children, defaultOpen = false }) {
  const [open, setOpen] = reactExports.useState(defaultOpen);
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setOpen((prev) => !prev),
      className: "flex w-full items-center justify-between px-5 py-4 text-left transition hover:bg-white/[0.03]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-7 w-7 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04]" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-[11px] text-slate-400` })), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold tracking-[-0.01em] text-white" }, title)),
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${open ? "fa-chevron-up" : "fa-chevron-down"} text-[10px] text-slate-500 transition-transform` })
  ), open ? /* @__PURE__ */ React.createElement("div", { className: "space-y-5 border-t border-white/10 px-5 pb-6 pt-5" }, children) : null);
}
function SmartRuleRow({
  rule,
  index: index2,
  smartRuleOptions,
  onFieldChange,
  onOperatorChange,
  onValueChange,
  onRemove
}) {
  const fieldOptions = smartRuleOptions?.fields || [];
  const operatorOptions = operatorOptionsForField(rule.field);
  const valueOptions = getFieldOptions(rule.field, smartRuleOptions);
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Rule ", index2 + 1), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onRemove,
      className: "inline-flex items-center gap-2 rounded-xl border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 transition hover:bg-rose-400/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can fa-fw" }),
    "Remove"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-[1fr_180px_minmax(0,1.15fr)]" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Field" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: rule.field,
      onChange: (value) => onFieldChange(value),
      options: fieldOptions.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement(Field$3, { label: "Operator" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: rule.operator,
      onChange: (value) => onOperatorChange(value),
      options: operatorOptions.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), rule.field === "created_at" ? /* @__PURE__ */ React.createElement(Field$3, { label: "Date Range" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    DateTimePicker,
    {
      value: rule.value?.from || "",
      onChange: (nextValue) => onValueChange({ ...rule.value || {}, from: nextValue }),
      mode: "date",
      placeholder: "From date",
      clearable: true,
      className: "bg-white/[0.04]"
    }
  ), /* @__PURE__ */ React.createElement(
    DateTimePicker,
    {
      value: rule.value?.to || "",
      onChange: (nextValue) => onValueChange({ ...rule.value || {}, to: nextValue }),
      mode: "date",
      placeholder: "To date",
      clearable: true,
      className: "bg-white/[0.04]"
    }
  ))) : rule.field === "is_featured" || rule.field === "is_mature" ? /* @__PURE__ */ React.createElement(Field$3, { label: "Value" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: rule.value ? "true" : "false",
      onChange: (value) => onValueChange(value === "true"),
      options: rule.field === "is_featured" ? [
        { value: "true", label: "Featured only" },
        { value: "false", label: "Not featured" }
      ] : [
        { value: "true", label: "Mature only" },
        { value: "false", label: "Not mature" }
      ],
      searchable: false
    }
  )) : rule.field === "tags" ? /* @__PURE__ */ React.createElement(Field$3, { label: "Value", help: "Type a tag name exactly as it appears on your artworks." }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: rule.value,
      onChange: (event) => onValueChange(event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "e.g. dark-fantasy"
    }
  )) : valueOptions.length ? /* @__PURE__ */ React.createElement(Field$3, { label: "Value" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: rule.value,
      onChange: (value) => onValueChange(value),
      options: valueOptions.map((option) => ({ value: option.value, label: option.label })),
      placeholder: "Select one",
      searchable: false
    }
  )) : /* @__PURE__ */ React.createElement(Field$3, { label: "Value" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: rule.value,
      onChange: (event) => onValueChange(event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "Enter a value"
    }
  ))), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-slate-400" }, buildRuleSummary(rule, smartRuleOptions)));
}
function CollectionManage() {
  const { props } = X$1();
  const {
    mode,
    collection,
    layoutModules: initialLayoutModules,
    attachedArtworks,
    availableArtworks,
    owner,
    endpoints,
    members: initialMembers,
    submissions: initialSubmissions,
    comments: initialComments,
    duplicateCandidates: initialDuplicateCandidates,
    canonicalTarget: initialCanonicalTarget,
    linkedCollections: initialLinkedCollections,
    linkedCollectionOptions: initialLinkedCollectionOptions,
    entityLinks: initialEntityLinks,
    entityLinkOptions: initialEntityLinkOptions,
    smartPreview: initialSmartPreview,
    smartRuleOptions,
    initialMode,
    featuredLimit,
    viewer,
    inviteExpiryDays
  } = props;
  const resolvedInitialMode = collection?.mode || initialMode || "manual";
  const [collectionState, setCollectionState] = reactExports.useState(collection);
  const [form, setForm] = reactExports.useState({
    title: collection?.title || "",
    slug: collection?.slug || "",
    subtitle: collection?.subtitle || "",
    summary: collection?.summary || "",
    description: collection?.description || "",
    lifecycle_state: collection?.lifecycle_state || "draft",
    type: collection?.type || "personal",
    collaboration_mode: collection?.collaboration_mode || "closed",
    allow_submissions: Boolean(collection?.allow_submissions),
    allow_comments: collection?.allow_comments !== false,
    allow_saves: collection?.allow_saves !== false,
    event_key: collection?.event_key || "",
    event_label: collection?.event_label || "",
    season_key: collection?.season_key || "",
    banner_text: collection?.banner_text || "",
    badge_label: collection?.badge_label || "",
    spotlight_style: collection?.spotlight_style || "default",
    analytics_enabled: collection?.analytics_enabled !== false,
    presentation_style: collection?.presentation_style || "standard",
    emphasis_mode: collection?.emphasis_mode || "balanced",
    theme_token: collection?.theme_token || "default",
    series_key: collection?.series_key || "",
    series_title: collection?.series_title || "",
    series_description: collection?.series_description || "",
    series_order: collection?.series_order || "",
    campaign_key: collection?.campaign_key || "",
    campaign_label: collection?.campaign_label || "",
    commercial_eligibility: Boolean(collection?.commercial_eligibility),
    promotion_tier: collection?.promotion_tier || "",
    sponsorship_label: collection?.sponsorship_label || "",
    partner_label: collection?.partner_label || "",
    monetization_ready_status: collection?.monetization_ready_status || "",
    brand_safe_status: collection?.brand_safe_status || "",
    editorial_notes: collection?.editorial_notes || "",
    staff_commercial_notes: collection?.staff_commercial_notes || "",
    published_at: isoToLocalInput$2(collection?.published_at),
    unpublished_at: isoToLocalInput$2(collection?.unpublished_at),
    archived_at: isoToLocalInput$2(collection?.archived_at),
    expired_at: isoToLocalInput$2(collection?.expired_at),
    editorial_owner_mode: collection?.owner?.mode || "creator",
    editorial_owner_username: collection?.owner?.username || "",
    editorial_owner_label: collection?.type === "editorial" && collection?.owner?.is_system ? collection?.owner?.name || "" : "",
    visibility: collection?.visibility || "public",
    mode: resolvedInitialMode,
    sort_mode: collection?.sort_mode || (resolvedInitialMode === "smart" ? "newest" : "manual"),
    cover_artwork_id: collection?.cover_artwork_id || ""
  });
  const [slugTouched, setSlugTouched] = reactExports.useState(Boolean(collection?.slug));
  const [smartRules, setSmartRules] = reactExports.useState(normalizeSmartRules(collection?.smart_rules_json, resolvedInitialMode));
  const [smartPreview, setSmartPreview] = reactExports.useState(initialSmartPreview || null);
  const [layoutModules, setLayoutModules] = reactExports.useState(normalizeLayoutModules(collection?.layout_modules || initialLayoutModules || []));
  const [attached, setAttached] = reactExports.useState(attachedArtworks || []);
  const [available, setAvailable] = reactExports.useState(availableArtworks || []);
  const [members, setMembers] = reactExports.useState(initialMembers || []);
  const [submissions, setSubmissions] = reactExports.useState(initialSubmissions || []);
  const [comments] = reactExports.useState(initialComments || []);
  const [duplicateCandidates, setDuplicateCandidates] = reactExports.useState(initialDuplicateCandidates || []);
  const [canonicalTarget, setCanonicalTarget] = reactExports.useState(initialCanonicalTarget || null);
  const [linkedCollections, setLinkedCollections] = reactExports.useState(initialLinkedCollections || []);
  const [linkedCollectionOptions, setLinkedCollectionOptions] = reactExports.useState(initialLinkedCollectionOptions || []);
  const [selectedLinkedCollectionId, setSelectedLinkedCollectionId] = reactExports.useState(initialLinkedCollectionOptions?.[0]?.id || "");
  const [entityLinks, setEntityLinks] = reactExports.useState(initialEntityLinks || []);
  const [entityLinkOptions, setEntityLinkOptions] = reactExports.useState(initialEntityLinkOptions || {});
  const initialEntitySelection = reactExports.useMemo(() => firstEntitySelection(initialEntityLinkOptions || {}), [initialEntityLinkOptions]);
  const [selectedEntityType, setSelectedEntityType] = reactExports.useState(initialEntitySelection.type);
  const [selectedEntityId, setSelectedEntityId] = reactExports.useState(initialEntitySelection.id);
  const [entityRelationship, setEntityRelationship] = reactExports.useState("");
  const [activeTab, setActiveTab] = reactExports.useState(mode === "edit" ? "details" : "details");
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [search2, setSearch] = reactExports.useState("");
  const [inviteUsername, setInviteUsername] = reactExports.useState("");
  const [inviteRole, setInviteRole] = reactExports.useState("contributor");
  const [inviteExpiryMode, setInviteExpiryMode] = reactExports.useState("default");
  const [inviteCustomExpiry, setInviteCustomExpiry] = reactExports.useState("");
  const [saving, setSaving] = reactExports.useState(false);
  const [searching, setSearching] = reactExports.useState(false);
  const [previewing, setPreviewing] = reactExports.useState(false);
  const [featureBusy, setFeatureBusy] = reactExports.useState(false);
  const [aiState, setAiState] = reactExports.useState({ busy: "", title: null, summary: null, cover: null, grouping: null, relatedArtworks: null, tags: null, seoDescription: null, smartRulesExplanation: null, splitThemes: null, mergeIdea: null, qualityReview: null });
  const [orderDirty, setOrderDirty] = reactExports.useState(false);
  const [errors, setErrors] = reactExports.useState({});
  const [notice, setNotice] = reactExports.useState("");
  reactExports.useEffect(() => {
    const nextMode = collection?.mode || initialMode || "manual";
    setCollectionState(collection);
    setForm({
      title: collection?.title || "",
      slug: collection?.slug || "",
      subtitle: collection?.subtitle || "",
      summary: collection?.summary || "",
      description: collection?.description || "",
      lifecycle_state: collection?.lifecycle_state || "draft",
      type: collection?.type || "personal",
      collaboration_mode: collection?.collaboration_mode || "closed",
      allow_submissions: Boolean(collection?.allow_submissions),
      allow_comments: collection?.allow_comments !== false,
      allow_saves: collection?.allow_saves !== false,
      event_key: collection?.event_key || "",
      event_label: collection?.event_label || "",
      season_key: collection?.season_key || "",
      banner_text: collection?.banner_text || "",
      badge_label: collection?.badge_label || "",
      spotlight_style: collection?.spotlight_style || "default",
      analytics_enabled: collection?.analytics_enabled !== false,
      presentation_style: collection?.presentation_style || "standard",
      emphasis_mode: collection?.emphasis_mode || "balanced",
      theme_token: collection?.theme_token || "default",
      series_key: collection?.series_key || "",
      series_title: collection?.series_title || "",
      series_description: collection?.series_description || "",
      series_order: collection?.series_order || "",
      campaign_key: collection?.campaign_key || "",
      campaign_label: collection?.campaign_label || "",
      commercial_eligibility: Boolean(collection?.commercial_eligibility),
      promotion_tier: collection?.promotion_tier || "",
      sponsorship_label: collection?.sponsorship_label || "",
      partner_label: collection?.partner_label || "",
      monetization_ready_status: collection?.monetization_ready_status || "",
      brand_safe_status: collection?.brand_safe_status || "",
      editorial_notes: collection?.editorial_notes || "",
      staff_commercial_notes: collection?.staff_commercial_notes || "",
      published_at: isoToLocalInput$2(collection?.published_at),
      unpublished_at: isoToLocalInput$2(collection?.unpublished_at),
      archived_at: isoToLocalInput$2(collection?.archived_at),
      expired_at: isoToLocalInput$2(collection?.expired_at),
      editorial_owner_mode: collection?.owner?.mode || "creator",
      editorial_owner_username: collection?.owner?.username || "",
      editorial_owner_label: collection?.type === "editorial" && collection?.owner?.is_system ? collection?.owner?.name || "" : "",
      visibility: collection?.visibility || "public",
      mode: nextMode,
      sort_mode: collection?.sort_mode || (nextMode === "smart" ? "newest" : "manual"),
      cover_artwork_id: collection?.cover_artwork_id || ""
    });
    setSmartRules(normalizeSmartRules(collection?.smart_rules_json, nextMode));
    setLayoutModules(normalizeLayoutModules(collection?.layout_modules || initialLayoutModules || []));
    setSmartPreview(initialSmartPreview || null);
    setAttached(attachedArtworks || []);
    setAvailable(availableArtworks || []);
    setMembers(initialMembers || []);
    setSubmissions(initialSubmissions || []);
    setDuplicateCandidates(initialDuplicateCandidates || []);
    setCanonicalTarget(initialCanonicalTarget || null);
    setLinkedCollections(initialLinkedCollections || []);
    setLinkedCollectionOptions(initialLinkedCollectionOptions || []);
    setSelectedLinkedCollectionId(initialLinkedCollectionOptions?.[0]?.id || "");
    setEntityLinks(initialEntityLinks || []);
    setEntityLinkOptions(initialEntityLinkOptions || {});
    const nextEntitySelection = firstEntitySelection(initialEntityLinkOptions || {});
    setSelectedEntityType(nextEntitySelection.type);
    setSelectedEntityId(nextEntitySelection.id);
    setEntityRelationship("");
    setActiveTab("details");
    setSelectedIds([]);
    setAiState({ busy: "", title: null, summary: null, cover: null, grouping: null, relatedArtworks: null, tags: null, seoDescription: null, smartRulesExplanation: null, splitThemes: null, mergeIdea: null, qualityReview: null });
    setOrderDirty(false);
    setErrors({});
    setNotice("");
  }, [collection?.id, attachedArtworks, availableArtworks, initialCanonicalTarget, initialDuplicateCandidates, initialEntityLinkOptions, initialEntityLinks, initialLayoutModules, initialLinkedCollectionOptions, initialLinkedCollections, initialMembers, initialSubmissions, initialMode, initialSmartPreview]);
  const attachedCoverOptions = reactExports.useMemo(
    () => attached.map((artwork) => ({ id: artwork.id, title: artwork.title })),
    [attached]
  );
  const inviteExpiryOptions = reactExports.useMemo(() => buildInviteExpiryOptions(inviteExpiryDays), [inviteExpiryDays]);
  const smartRuleCount = smartRules?.rules?.length || 0;
  const isSmartMode = form.mode === "smart";
  const canFeature = mode === "edit" && form.visibility === "public" && (collectionState?.feature_url || collectionState?.unfeature_url || endpoints?.feature);
  const featuredCountLabel = collectionState?.is_featured ? "Featured" : `Up to ${featuredLimit} featured collections`;
  const canModerate = mode === "edit" && Boolean(viewer?.is_admin);
  const tabs = [
    { id: "details", label: "Details", icon: "fa-pen-ruler" },
    { id: "artworks", label: "Artworks", icon: "fa-images" },
    { id: "members", label: "Members", icon: "fa-user-group" },
    { id: "submissions", label: "Submissions", icon: "fa-inbox" },
    { id: "settings", label: "Settings", icon: "fa-sliders" },
    { id: "discussion", label: "Discussion", icon: "fa-comments" },
    { id: "ai", label: "AI Suggestions", icon: "fa-wand-magic-sparkles" }
  ].concat(canModerate ? [{ id: "moderation", label: "Moderation", icon: "fa-shield-halved" }] : []);
  function applyCollectionPayload(nextCollection) {
    if (!nextCollection) return;
    setCollectionState(nextCollection);
    setForm((current) => ({
      ...current,
      title: nextCollection.title ?? current.title,
      slug: nextCollection.slug ?? current.slug,
      subtitle: nextCollection.subtitle || "",
      summary: nextCollection.summary || "",
      description: nextCollection.description || "",
      lifecycle_state: nextCollection.lifecycle_state || current.lifecycle_state,
      type: nextCollection.type || current.type,
      collaboration_mode: nextCollection.collaboration_mode || current.collaboration_mode,
      allow_submissions: Boolean(nextCollection.allow_submissions),
      allow_comments: nextCollection.allow_comments !== false,
      allow_saves: nextCollection.allow_saves !== false,
      event_key: nextCollection.event_key ?? "",
      event_label: nextCollection.event_label ?? "",
      season_key: nextCollection.season_key ?? "",
      banner_text: nextCollection.banner_text ?? "",
      badge_label: nextCollection.badge_label ?? "",
      spotlight_style: nextCollection.spotlight_style || "default",
      analytics_enabled: nextCollection.analytics_enabled !== false,
      presentation_style: nextCollection.presentation_style || current.presentation_style,
      emphasis_mode: nextCollection.emphasis_mode || current.emphasis_mode,
      theme_token: nextCollection.theme_token || current.theme_token,
      series_key: nextCollection.series_key ?? "",
      series_title: nextCollection.series_title ?? "",
      series_description: nextCollection.series_description ?? "",
      series_order: nextCollection.series_order ?? "",
      campaign_key: nextCollection.campaign_key ?? "",
      campaign_label: nextCollection.campaign_label ?? "",
      commercial_eligibility: Boolean(nextCollection.commercial_eligibility),
      promotion_tier: nextCollection.promotion_tier ?? "",
      sponsorship_label: nextCollection.sponsorship_label ?? "",
      partner_label: nextCollection.partner_label ?? "",
      monetization_ready_status: nextCollection.monetization_ready_status ?? "",
      brand_safe_status: nextCollection.brand_safe_status ?? "",
      editorial_notes: nextCollection.editorial_notes ?? "",
      staff_commercial_notes: nextCollection.staff_commercial_notes ?? "",
      published_at: isoToLocalInput$2(nextCollection.published_at) || "",
      unpublished_at: isoToLocalInput$2(nextCollection.unpublished_at) || "",
      archived_at: isoToLocalInput$2(nextCollection.archived_at) || "",
      expired_at: isoToLocalInput$2(nextCollection.expired_at) || "",
      editorial_owner_mode: nextCollection?.owner?.mode || current.editorial_owner_mode,
      editorial_owner_username: nextCollection?.owner?.username || current.editorial_owner_username,
      editorial_owner_label: nextCollection?.type === "editorial" && nextCollection?.owner?.is_system ? nextCollection?.owner?.name || current.editorial_owner_label : current.editorial_owner_label,
      visibility: nextCollection.visibility || current.visibility,
      mode: nextCollection.mode || current.mode,
      sort_mode: nextCollection.sort_mode || current.sort_mode,
      cover_artwork_id: nextCollection.cover_artwork_id || ""
    }));
    if (Array.isArray(nextCollection.layout_modules)) {
      setLayoutModules(normalizeLayoutModules(nextCollection.layout_modules));
    }
  }
  function updateForm(name2, value) {
    setForm((current) => {
      const next = { ...current, [name2]: value };
      if (name2 === "title" && !slugTouched) {
        next.slug = slugify$3(value);
      }
      if (name2 === "mode") {
        next.sort_mode = value === "smart" ? smartRules?.sort || "newest" : current.sort_mode === "newest" || current.sort_mode === "oldest" || current.sort_mode === "popular" ? "manual" : current.sort_mode || "manual";
        if (value === "smart") {
          next.cover_artwork_id = "";
        }
      }
      return next;
    });
    if (name2 === "mode") {
      setSmartRules((current) => {
        if (value !== "smart") {
          return current;
        }
        const normalized = normalizeSmartRules(current, "smart");
        if (normalized.rules.length > 0) {
          return normalized;
        }
        return {
          ...normalized,
          rules: [createRule()]
        };
      });
    }
  }
  function updateSmartRule(index2, updater) {
    setSmartRules((current) => ({
      ...current,
      rules: current.rules.map((rule, ruleIndex) => ruleIndex === index2 ? updater(rule) : rule)
    }));
  }
  function addRule() {
    const defaultField = smartRuleOptions?.fields?.[0]?.value || "tags";
    setSmartRules((current) => ({
      ...current,
      rules: [...current.rules, createRule(defaultField)]
    }));
  }
  function removeRule(index2) {
    setSmartRules((current) => ({
      ...current,
      rules: current.rules.filter((_2, ruleIndex) => ruleIndex !== index2)
    }));
  }
  function buildPayload2() {
    return {
      ...form,
      sort_mode: isSmartMode ? smartRules.sort || form.sort_mode || "newest" : form.sort_mode,
      cover_artwork_id: isSmartMode ? null : form.cover_artwork_id || null,
      published_at: localInputToIso(form.published_at),
      unpublished_at: localInputToIso(form.unpublished_at),
      archived_at: localInputToIso(form.archived_at),
      expired_at: localInputToIso(form.expired_at),
      smart_rules_json: isSmartMode ? {
        match: smartRules.match,
        sort: smartRules.sort,
        rules: smartRules.rules
      } : null,
      layout_modules_json: layoutModules.map((module) => ({
        key: module.key,
        enabled: module.enabled,
        slot: module.slot
      }))
    };
  }
  function updateLayoutModule(key, updates) {
    setLayoutModules((current) => current.map((module) => module.key === key ? { ...module, ...updates } : module));
  }
  function moveLayoutModule(index2, direction) {
    const nextIndex = index2 + direction;
    if (nextIndex < 0 || nextIndex >= layoutModules.length) return;
    setLayoutModules((current) => {
      const next = [...current];
      const swap = next[index2];
      next[index2] = next[nextIndex];
      next[nextIndex] = swap;
      return next;
    });
  }
  async function handleSubmit(event) {
    event.preventDefault();
    setSaving(true);
    setErrors({});
    setNotice("");
    try {
      const payload = await requestJson$m(mode === "create" ? endpoints.store : endpoints.update, {
        method: mode === "create" ? "POST" : "PATCH",
        body: buildPayload2()
      });
      if (payload.redirect && mode === "create") {
        window.location.assign(payload.redirect);
        return;
      }
      if (payload.collection) {
        applyCollectionPayload(payload.collection);
        if (payload.collection.smart_rules_json) {
          setSmartRules(normalizeSmartRules(payload.collection.smart_rules_json, payload.collection.mode));
        }
      }
      if (payload.attachedArtworks) {
        setAttached(payload.attachedArtworks);
      }
      if (payload.members) {
        setMembers(payload.members);
      }
      if (payload.submissions) {
        setSubmissions(payload.submissions);
      }
      setNotice(isSmartMode ? "Collection saved and smart rules updated." : "Collection updated.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleSmartPreview() {
    if (!endpoints?.smartPreview) return;
    setPreviewing(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.smartPreview, {
        method: "POST",
        body: {
          smart_rules_json: {
            match: smartRules.match,
            sort: smartRules.sort,
            rules: smartRules.rules
          }
        }
      });
      setSmartPreview(payload.preview || null);
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setPreviewing(false);
    }
  }
  async function handleSearch(event) {
    event.preventDefault();
    if (!endpoints?.available) return;
    setSearching(true);
    try {
      const url = `${endpoints.available}?search=${encodeURIComponent(search2)}`;
      const payload = await requestJson$m(url);
      setAvailable(payload?.data || []);
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSearching(false);
    }
  }
  async function handleAiSuggestion(kind) {
    const endpointMap = {
      title: endpoints?.aiSuggestTitle,
      summary: endpoints?.aiSuggestSummary,
      cover: endpoints?.aiSuggestCover,
      grouping: endpoints?.aiSuggestGrouping,
      relatedArtworks: endpoints?.aiSuggestRelatedArtworks,
      tags: endpoints?.aiSuggestTags,
      seoDescription: endpoints?.aiSuggestSeoDescription,
      smartRulesExplanation: endpoints?.aiExplainSmartRules,
      splitThemes: endpoints?.aiSuggestSplitThemes,
      mergeIdea: endpoints?.aiSuggestMergeIdea
    };
    const url = endpointMap[kind];
    if (!url) return;
    setAiState((current) => ({ ...current, busy: kind }));
    try {
      const payload = await requestJson$m(url, {
        method: "POST",
        body: { draft: buildPayload2() }
      });
      setAiState((current) => ({
        ...current,
        busy: "",
        [kind]: payload?.suggestion || null
      }));
    } catch (error) {
      setAiState((current) => ({ ...current, busy: "" }));
      setErrors(error?.payload?.errors || { form: [error.message] });
    }
  }
  async function handleAiQualityReview() {
    if (!endpoints?.aiQualityReview) return;
    setAiState((current) => ({ ...current, busy: "qualityReview" }));
    try {
      const payload = await requestJson$m(endpoints.aiQualityReview);
      setAiState((current) => ({
        ...current,
        busy: "",
        qualityReview: payload?.review || null
      }));
    } catch (error) {
      setAiState((current) => ({ ...current, busy: "" }));
      setErrors(error?.payload?.errors || { form: [error.message] });
    }
  }
  function applyAiTitle() {
    if (!aiState?.title?.title) return;
    updateForm("title", aiState.title.title);
  }
  function applyAiSummary() {
    if (!aiState?.summary?.summary) return;
    updateForm("summary", aiState.summary.summary);
  }
  function applyAiCover() {
    const artworkId = aiState?.cover?.artwork?.id;
    if (!artworkId || isSmartMode) return;
    updateForm("cover_artwork_id", artworkId);
  }
  function applyAiRelatedArtworks() {
    const artworkIds = Array.isArray(aiState?.relatedArtworks?.artworks) ? aiState.relatedArtworks.artworks.map((artwork) => artwork.id) : [];
    if (!artworkIds.length) return;
    setSelectedIds((current) => Array.from(/* @__PURE__ */ new Set([...current, ...artworkIds])));
  }
  function toggleSelected(artworkId) {
    setSelectedIds((current) => current.includes(artworkId) ? current.filter((id) => id !== artworkId) : [...current, artworkId]);
  }
  async function handleAttachSelected() {
    if (!selectedIds.length || !endpoints?.attach) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.attach, {
        method: "POST",
        body: { artwork_ids: selectedIds }
      });
      setCollectionState(payload.collection);
      setAttached(payload.attachedArtworks || []);
      setAvailable(payload.availableArtworks || []);
      setSelectedIds([]);
      setNotice("Artworks added to collection.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleRemoveArtwork(artwork) {
    if (!artwork?.remove_url) return;
    if (!window.confirm(`Remove "${artwork.title}" from this collection?`)) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(artwork.remove_url, { method: "DELETE" });
      setCollectionState(payload.collection);
      setAttached(payload.attachedArtworks || []);
      setAvailable(payload.availableArtworks || []);
      setForm((current) => ({
        ...current,
        cover_artwork_id: payload.collection?.cover_artwork_id || ""
      }));
      setNotice("Artwork removed from collection.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  function moveArtwork(index2, direction) {
    const nextIndex = index2 + direction;
    if (nextIndex < 0 || nextIndex >= attached.length) return;
    setAttached((current) => {
      const next = [...current];
      const temp = next[index2];
      next[index2] = next[nextIndex];
      next[nextIndex] = temp;
      return next;
    });
    setOrderDirty(true);
  }
  async function saveArtworkOrder() {
    if (!orderDirty || !endpoints?.reorder) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.reorder, {
        method: "POST",
        body: { ordered_artwork_ids: attached.map((artwork) => artwork.id) }
      });
      setCollectionState(payload.collection);
      setAttached(payload.attachedArtworks || []);
      setOrderDirty(false);
      setNotice("Artwork order saved.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleToggleFeature() {
    const isFeatured = Boolean(collectionState?.is_featured);
    const url = isFeatured ? endpoints?.unfeature : endpoints?.feature;
    if (!url) return;
    setFeatureBusy(true);
    setErrors({});
    try {
      const payload = await requestJson$m(url, {
        method: isFeatured ? "DELETE" : "POST"
      });
      if (payload.collection) {
        applyCollectionPayload(payload.collection);
      }
      setNotice(isFeatured ? "Collection removed from featured placement." : "Collection featured on your profile.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setFeatureBusy(false);
    }
  }
  async function syncLinkedCollections(nextIds, successMessage) {
    if (!endpoints?.syncLinkedCollections) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.syncLinkedCollections, {
        method: "POST",
        body: {
          related_collection_ids: nextIds
        }
      });
      if (payload?.collection) {
        applyCollectionPayload(payload.collection);
      }
      const nextLinkedCollections = payload?.linkedCollections || [];
      const nextOptions = payload?.linkedCollectionOptions || [];
      setLinkedCollections(nextLinkedCollections);
      setLinkedCollectionOptions(nextOptions);
      setSelectedLinkedCollectionId((current) => {
        if (current && nextOptions.some((option) => String(option.id) === String(current))) {
          return current;
        }
        return nextOptions[0]?.id || "";
      });
      setNotice(successMessage);
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleAddLinkedCollection() {
    if (!selectedLinkedCollectionId) return;
    const nextIds = Array.from(/* @__PURE__ */ new Set([
      ...linkedCollections.map((item) => item.id),
      Number(selectedLinkedCollectionId)
    ]));
    await syncLinkedCollections(nextIds, "Linked collections updated.");
  }
  async function handleRemoveLinkedCollection(collectionId) {
    const nextIds = linkedCollections.map((item) => item.id).filter((id) => Number(id) !== Number(collectionId));
    await syncLinkedCollections(nextIds, "Linked collections updated.");
  }
  async function syncEntityLinks(nextLinks, successMessage) {
    if (!endpoints?.syncEntityLinks) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.syncEntityLinks, {
        method: "POST",
        body: {
          entity_links: nextLinks
        }
      });
      if (payload?.collection) {
        applyCollectionPayload(payload.collection);
      }
      const nextEntityLinks = payload?.entityLinks || [];
      const nextOptions = payload?.entityLinkOptions || {};
      setEntityLinks(nextEntityLinks);
      setEntityLinkOptions(nextOptions);
      setSelectedEntityId((current) => {
        const optionsForType = Array.isArray(nextOptions[selectedEntityType]) ? nextOptions[selectedEntityType] : [];
        if (current && optionsForType.some((option) => String(option.id) === String(current))) {
          return current;
        }
        return optionsForType[0]?.id || "";
      });
      setEntityRelationship("");
      setNotice(successMessage);
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleAddEntityLink() {
    if (!selectedEntityType || !selectedEntityId) return;
    const nextLinks = [
      ...entityLinks.map((item) => ({
        linked_type: item.linked_type,
        linked_id: item.linked_id,
        relationship_type: item.relationship_type || null
      })),
      {
        linked_type: selectedEntityType,
        linked_id: Number(selectedEntityId),
        relationship_type: entityRelationship.trim() || null
      }
    ];
    await syncEntityLinks(nextLinks, "Entity links updated.");
  }
  async function handleRemoveEntityLink(linkId) {
    const nextLinks = entityLinks.filter((item) => Number(item.id) !== Number(linkId)).map((item) => ({
      linked_type: item.linked_type,
      linked_id: item.linked_id,
      relationship_type: item.relationship_type || null
    }));
    await syncEntityLinks(nextLinks, "Entity links updated.");
  }
  function applyMergeReviewPayload(payload, successMessage) {
    if (payload?.collection) {
      applyCollectionPayload(payload.collection);
    }
    if (payload?.source) {
      applyCollectionPayload(payload.source);
    }
    if (Object.prototype.hasOwnProperty.call(payload || {}, "duplicate_candidates")) {
      setDuplicateCandidates(Array.isArray(payload?.duplicate_candidates) ? payload.duplicate_candidates : []);
    }
    if (Object.prototype.hasOwnProperty.call(payload || {}, "canonical_target")) {
      setCanonicalTarget(payload?.canonical_target || null);
    }
    if (successMessage) {
      setNotice(successMessage);
    }
  }
  async function handleCanonicalizeCandidate(candidate) {
    const targetId = candidate?.collection?.id;
    if (!targetId || !endpoints?.canonicalize) return;
    if (!window.confirm(`Designate "${candidate.collection.title}" as the canonical target for this collection?`)) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.canonicalize, {
        method: "POST",
        body: { target_collection_id: targetId }
      });
      applyMergeReviewPayload(payload, "Canonical target updated.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleMergeCandidate(candidate) {
    const targetId = candidate?.collection?.id;
    if (!targetId || !endpoints?.merge) return;
    if (!window.confirm(`Merge this collection into "${candidate.collection.title}"? This archives the current collection and moves artworks into the target.`)) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.merge, {
        method: "POST",
        body: { target_collection_id: targetId }
      });
      applyMergeReviewPayload(payload, "Collection merged into canonical target.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleRejectDuplicateCandidate(candidate) {
    const targetId = candidate?.collection?.id;
    if (!targetId || !endpoints?.rejectDuplicate) return;
    if (!window.confirm(`Mark "${candidate.collection.title}" as not a duplicate?`)) return;
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.rejectDuplicate, {
        method: "POST",
        body: { target_collection_id: targetId }
      });
      applyMergeReviewPayload(payload, "Duplicate candidate dismissed.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleDeleteCollection() {
    if (!endpoints?.delete) return;
    if (!window.confirm("Delete this collection? Artworks will remain untouched.")) return;
    setSaving(true);
    try {
      const payload = await requestJson$m(endpoints.delete, { method: "DELETE" });
      window.location.assign(payload.redirect);
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
      setSaving(false);
    }
  }
  async function handleInviteMember(event) {
    event.preventDefault();
    if (!inviteUsername || !endpoints?.inviteMember) return;
    const body2 = { username: inviteUsername, role: inviteRole };
    if (inviteExpiryMode === "custom") {
      const customExpiryIso = localInputToIso(inviteCustomExpiry);
      if (!customExpiryIso) {
        setErrors({ expires_at: ["Choose a valid invite expiry date and time."] });
        return;
      }
      body2.expires_at = customExpiryIso;
    } else if (inviteExpiryMode !== "default") {
      body2.expires_in_days = Number.parseInt(inviteExpiryMode, 10);
    }
    setSaving(true);
    setErrors({});
    try {
      const payload = await requestJson$m(endpoints.inviteMember, {
        method: "POST",
        body: body2
      });
      setMembers(payload?.members || []);
      setInviteUsername("");
      setInviteExpiryMode("default");
      setInviteCustomExpiry("");
      setNotice("Collaborator invited.");
    } catch (error) {
      setErrors(error?.payload?.errors || { form: [error.message] });
    } finally {
      setSaving(false);
    }
  }
  async function handleMemberRoleChange(member, role) {
    const url = endpoints?.memberUpdatePattern?.replace("__MEMBER__", member.id);
    if (!url) return;
    const payload = await requestJson$m(url, {
      method: "PATCH",
      body: { role }
    });
    setMembers(payload?.members || []);
  }
  async function handleRemoveMember(member) {
    const url = endpoints?.memberDeletePattern?.replace("__MEMBER__", member.id);
    if (!url) return;
    const payload = await requestJson$m(url, { method: "DELETE" });
    setMembers(payload?.members || []);
  }
  async function handleTransferMember(member) {
    const url = endpoints?.memberTransferPattern?.replace("__MEMBER__", member.id);
    if (!url) return;
    if (!window.confirm(`Transfer collection ownership to @${member?.user?.username}? You will keep editor access.`)) return;
    const payload = await requestJson$m(url, { method: "POST" });
    applyCollectionPayload(payload?.collection);
    setMembers(payload?.members || []);
    setNotice(`Ownership transferred to @${member?.user?.username}.`);
  }
  async function handleAcceptMember(member) {
    const url = endpoints?.acceptMemberPattern?.replace("__MEMBER__", member.id);
    if (!url) return;
    const payload = await requestJson$m(url, { method: "POST" });
    setMembers(payload?.members || []);
  }
  async function handleDeclineMember(member) {
    const url = endpoints?.declineMemberPattern?.replace("__MEMBER__", member.id);
    if (!url) return;
    const payload = await requestJson$m(url, { method: "POST" });
    setMembers(payload?.members || []);
  }
  async function handleSubmissionAction(submission, action) {
    const url = action === "approve" ? endpoints?.submissionApprovePattern?.replace("__SUBMISSION__", submission.id) : action === "reject" ? endpoints?.submissionRejectPattern?.replace("__SUBMISSION__", submission.id) : endpoints?.submissionDeletePattern?.replace("__SUBMISSION__", submission.id);
    if (!url) return;
    const payload = await requestJson$m(url, { method: action === "withdraw" ? "DELETE" : "POST" });
    setSubmissions(payload?.submissions || []);
  }
  async function handleModerationStatusChange(value) {
    if (!endpoints?.adminModerationUpdate) return;
    const payload = await requestJson$m(endpoints.adminModerationUpdate, {
      method: "PATCH",
      body: { moderation_status: value }
    });
    applyCollectionPayload(payload?.collection);
    setNotice(`Moderation state updated to ${value.replace("_", " ")}.`);
  }
  async function handleModerationToggle(key, value) {
    if (!endpoints?.adminInteractionsUpdate) return;
    const payload = await requestJson$m(endpoints.adminInteractionsUpdate, {
      method: "PATCH",
      body: { [key]: value }
    });
    applyCollectionPayload(payload?.collection);
    setNotice("Collection interaction settings updated.");
  }
  async function handleAdminUnfeature() {
    if (!endpoints?.adminUnfeature) return;
    const payload = await requestJson$m(endpoints.adminUnfeature, {
      method: "POST"
    });
    applyCollectionPayload(payload?.collection);
    setNotice("Collection removed from featured placement by moderation action.");
  }
  async function handleAdminRemoveMember(member) {
    const url = endpoints?.adminMemberRemovePattern?.replace("__MEMBER__", member.id);
    if (!url) return;
    const payload = await requestJson$m(url, { method: "DELETE" });
    applyCollectionPayload(payload?.collection);
    setMembers(payload?.members || []);
    setNotice("Collaborator removed by moderation action.");
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, mode === "create" ? "Create Collection — Skinbase" : `${collectionState?.title || "Collection"} — Manage Collection`), /* @__PURE__ */ React.createElement("meta", { name: "robots", content: "noindex,nofollow" })), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-95",
      style: {
        background: "radial-gradient(circle at top left, rgba(56,189,248,0.18), transparent 32%), radial-gradient(circle at 82% 10%, rgba(249,115,22,0.18), transparent 28%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)"
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: endpoints?.profileCollections || "#", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to profile collections"), collectionState?.public_url ? /* @__PURE__ */ React.createElement("a", { href: collectionState.public_url, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-eye fa-fw text-[11px]" }), "View public page") : null, mode === "edit" && endpoints?.dashboard ? /* @__PURE__ */ React.createElement("a", { href: endpoints.dashboard, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-pie fa-fw text-[11px]" }), "Dashboard") : null, mode === "edit" && endpoints?.analytics ? /* @__PURE__ */ React.createElement("a", { href: endpoints.analytics, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column fa-fw text-[11px]" }), "Analytics") : null, mode === "edit" && endpoints?.history ? /* @__PURE__ */ React.createElement("a", { href: endpoints.history, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[11px]" }), "History") : null, mode === "edit" && endpoints?.staffSurfaces ? /* @__PURE__ */ React.createElement("a", { href: endpoints.staffSurfaces, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-thumbtack fa-fw text-[11px]" }), "Staff surfaces") : null, mode === "edit" && endpoints?.staffProgramming ? /* @__PURE__ */ React.createElement("a", { href: endpoints.staffProgramming, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sliders fa-fw text-[11px]" }), "Programming studio") : null, /* @__PURE__ */ React.createElement("a", { href: "/collections/featured", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass fa-fw text-[11px]" }), "Featured collections")), mode === "edit" ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, tabs.map((tab2) => /* @__PURE__ */ React.createElement(
    StudioTabButton,
    {
      key: tab2.id,
      active: activeTab === tab2.id,
      label: tab2.label,
      icon: tab2.icon,
      onClick: () => setActiveTab(tab2.id)
    }
  ))) : null, mode !== "edit" || activeTab === "details" ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1.12fr)_420px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.24)] backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Collection Studio"), /* @__PURE__ */ React.createElement("h1", { className: "mt-2 text-3xl font-semibold tracking-[-0.04em] text-white md:text-4xl" }, mode === "create" ? "New Collection" : collectionState?.title || "Manage Collection"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-relaxed text-slate-300" }, mode === "create" ? "Give your collection a title and choose who can see it — that is all you need to get started. Expand the sections below to add descriptions, presentation options, scheduling, and more." : "Manage your collection details, artworks, members, and settings from the tabs below.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, mode === "edit" ? /* @__PURE__ */ React.createElement(CollectionVisibilityBadge, { visibility: form.visibility }) : null, collectionState?.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/25 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Featured") : null, isSmartMode ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-sky-300/25 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Smart Collection") : null)), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-100" }, notice) : null, Object.keys(errors).length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, Object.entries(errors).map(([key, messages]) => /* @__PURE__ */ React.createElement("div", { key }, Array.isArray(messages) ? messages[0] : messages))) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit, className: "mt-6 space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    ModeButton,
    {
      active: !isSmartMode,
      title: "Manual",
      description: "You choose every artwork. Control the exact order, set a cover, and tell the story your way.",
      icon: "fa-hand-sparkles",
      onClick: () => updateForm("mode", "manual")
    }
  ), /* @__PURE__ */ React.createElement(
    ModeButton,
    {
      active: isSmartMode,
      title: "Smart",
      description: "Define rules and let the collection fill automatically from your published artworks. Great for keeping series fresh.",
      icon: "fa-wand-magic-sparkles",
      onClick: () => updateForm("mode", "smart")
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Title" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: form.title,
      onChange: (event) => updateForm("title", event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "Dark Fantasy Series",
      maxLength: 120
    }
  )), /* @__PURE__ */ React.createElement(Field$3, { label: "Visibility" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => updateForm("visibility", val), searchable: false, options: [{ value: "public", label: "Public — visible to everyone" }, { value: "unlisted", label: "Unlisted — accessible by link only" }, { value: "private", label: "Private — only you can see it" }] }))), /* @__PURE__ */ React.createElement(Field$3, { label: "URL Slug", help: "Auto-generated from the title. Edit to customise the collection URL." }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: form.slug,
      onChange: (event) => {
        setSlugTouched(true);
        updateForm("slug", slugify$3(event.target.value));
      },
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "dark-fantasy-series",
      maxLength: 140
    }
  )), /* @__PURE__ */ React.createElement(Field$3, { label: "Summary", help: "A short line shown on collection cards and in search results." }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: form.summary,
      onChange: (event) => updateForm("summary", event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "Best performing sci-fi wallpapers from the last year",
      maxLength: 320
    }
  )), /* @__PURE__ */ React.createElement(AdvancedSection, { title: "Description & Presentation", icon: "fa-palette", defaultOpen: mode === "edit" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Subtitle", help: "Optional short line that sits under the title." }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: form.subtitle,
      onChange: (event) => updateForm("subtitle", event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "A moody archive of midnight environments",
      maxLength: 160
    }
  )), /* @__PURE__ */ React.createElement(Field$3, { label: "Presentation Style" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.presentation_style, onChange: (val) => updateForm("presentation_style", val), searchable: false, options: [{ value: "standard", label: "Standard" }, { value: "editorial_grid", label: "Editorial Grid" }, { value: "hero_grid", label: "Hero Grid" }, { value: "masonry", label: "Masonry" }] }))), /* @__PURE__ */ React.createElement(Field$3, { label: "Description", help: "Describe the mood, focus, or story behind this showcase." }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: form.description,
      onChange: (event) => updateForm("description", event.target.value),
      className: "min-h-[128px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "A curated selection of pieces that share a common visual language…",
      maxLength: 1e3
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Emphasis Mode" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.emphasis_mode, onChange: (val) => updateForm("emphasis_mode", val), searchable: false, options: [{ value: "cover_heavy", label: "Cover Heavy" }, { value: "balanced", label: "Balanced" }, { value: "artwork_first", label: "Artwork First" }] })), /* @__PURE__ */ React.createElement(Field$3, { label: "Theme" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.theme_token, onChange: (val) => updateForm("theme_token", val), searchable: false, options: [{ value: "default", label: "Default" }, { value: "subtle-blue", label: "Subtle Blue" }, { value: "violet", label: "Violet" }, { value: "amber", label: "Amber" }] }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, !isSmartMode ? /* @__PURE__ */ React.createElement(Field$3, { label: "Sort Order", help: "Manual keeps the display order under your direct control." }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.sort_mode, onChange: (val) => updateForm("sort_mode", val), searchable: false, options: [{ value: "manual", label: "Manual" }, { value: "newest", label: "Newest first" }, { value: "oldest", label: "Oldest first" }, { value: "popular", label: "Most popular" }] })) : /* @__PURE__ */ React.createElement(Field$3, { label: "Match Mode", help: "All rules must match, or any one rule is enough." }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: smartRules.match,
      onChange: (val) => setSmartRules((current) => ({ ...current, match: val })),
      searchable: false,
      options: [{ value: "all", label: "All rules" }, { value: "any", label: "Any rule" }]
    }
  )), !isSmartMode ? /* @__PURE__ */ React.createElement(Field$3, { label: "Cover Artwork", help: attachedCoverOptions.length ? "Choose a cover from artworks already attached to this collection." : "Attach artworks first to pick a manual cover." }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: String(form.cover_artwork_id || ""),
      onChange: (val) => updateForm("cover_artwork_id", val),
      disabled: !attachedCoverOptions.length,
      placeholder: "Automatic cover",
      options: attachedCoverOptions.map((a) => ({ value: String(a.id), label: a.title }))
    }
  )) : /* @__PURE__ */ React.createElement(Field$3, { label: "Smart Sort", help: "How matching artworks should be ordered in this collection." }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: smartRules.sort,
      onChange: (val) => {
        setSmartRules((current) => ({ ...current, sort: val }));
        updateForm("sort_mode", val);
      },
      options: smartRuleOptions?.sort_options || []
    }
  )))), /* @__PURE__ */ React.createElement(AdvancedSection, { title: "Collaboration & Access", icon: "fa-user-group", defaultOpen: mode === "edit" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Collection Type" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.type, onChange: (val) => updateForm("type", val), searchable: false, options: [{ value: "personal", label: "Personal" }, { value: "community", label: "Community" }, { value: "editorial", label: "Editorial" }] })), /* @__PURE__ */ React.createElement(Field$3, { label: "Collaboration Mode" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.collaboration_mode, onChange: (val) => updateForm("collaboration_mode", val), searchable: false, options: [{ value: "closed", label: "Closed — curated by you only" }, { value: "invite_only", label: "Invite only" }, { value: "open", label: "Open submissions" }] }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_submissions, onChange: (event) => updateForm("allow_submissions", event.target.checked), label: "Allow submissions" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_comments, onChange: (event) => updateForm("allow_comments", event.target.checked), label: "Allow comments" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_saves, onChange: (event) => updateForm("allow_saves", event.target.checked), label: "Allow saves" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.commercial_eligibility, onChange: (event) => updateForm("commercial_eligibility", event.target.checked), label: "Commercially eligible" }))), form.type === "editorial" ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Editorial Owner", help: "Choose whether this editorial lives under the current curator, another staff account, or the system identity." }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.editorial_owner_mode, onChange: (val) => updateForm("editorial_owner_mode", val), searchable: false, options: [{ value: "creator", label: "Current curator" }, { value: "staff_account", label: "Staff account" }, { value: "system", label: "System editorial identity" }] })), form.editorial_owner_mode === "staff_account" ? /* @__PURE__ */ React.createElement(Field$3, { label: "Staff Account Username", help: "Must be an admin or moderator username." }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: form.editorial_owner_username,
      onChange: (event) => updateForm("editorial_owner_username", event.target.value.trimStart()),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "skinbase-editorial",
      maxLength: 60
    }
  )) : null, form.editorial_owner_mode === "system" ? /* @__PURE__ */ React.createElement(Field$3, { label: "System Owner Label", help: "Public-facing label for system-owned editorials." }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: form.editorial_owner_label,
      onChange: (event) => updateForm("editorial_owner_label", event.target.value),
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      placeholder: "Skinbase Editorial",
      maxLength: 120
    }
  )) : null) : null), /* @__PURE__ */ React.createElement(AdvancedSection, { title: "Campaign & Events", icon: "fa-bullhorn", defaultOpen: mode === "edit" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Event Key", help: "Internal identifier used by discovery and promotion logic." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.event_key, onChange: (event) => updateForm("event_key", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Event Label" }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.event_label, onChange: (event) => updateForm("event_label", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Season Key", help: "Groups related collections by season on landing surfaces." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.season_key, onChange: (event) => updateForm("season_key", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Badge Label", help: "Short public badge on cards and headers." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.badge_label, onChange: (event) => updateForm("badge_label", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 80 }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Campaign Key", help: "Operational identifier for recommendation and placement logic." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.campaign_key, onChange: (event) => updateForm("campaign_key", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Campaign Label", help: "Public-facing campaign or promotion label." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.campaign_label, onChange: (event) => updateForm("campaign_label", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Spotlight Style", help: "Controls the visual frame for the public campaign banner." }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.spotlight_style, onChange: (val) => updateForm("spotlight_style", val), searchable: false, options: [{ value: "default", label: "Default" }, { value: "editorial", label: "Editorial" }, { value: "seasonal", label: "Seasonal" }, { value: "challenge", label: "Challenge" }, { value: "community", label: "Community" }] })), /* @__PURE__ */ React.createElement(Field$3, { label: "Banner Text", help: "Short line shown in the collection spotlight banner." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.banner_text, onChange: (event) => updateForm("banner_text", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 200 })))), /* @__PURE__ */ React.createElement(AdvancedSection, { title: "Series", icon: "fa-layer-group", defaultOpen: mode === "edit" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Series Key", help: "Use the same key across all linked collections in a series." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.series_key, onChange: (event) => updateForm("series_key", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Series Title", help: "Optional public heading shown for the whole series." }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.series_title, onChange: (event) => updateForm("series_title", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 160 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Series Order", help: "Sequence position for public next & previous navigation." }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "1", max: "9999", value: form.series_order, onChange: (event) => updateForm("series_order", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]" }))), /* @__PURE__ */ React.createElement(Field$3, { label: "Series Description", help: "Optional public intro shown on series landing pages." }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: form.series_description,
      onChange: (event) => updateForm("series_description", event.target.value),
      className: "min-h-[96px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      maxLength: 400
    }
  ))), /* @__PURE__ */ React.createElement(AdvancedSection, { title: "Scheduling & Lifecycle", icon: "fa-calendar-days", defaultOpen: mode === "edit" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Lifecycle State", help: "Draft keeps it hidden. Published makes it live. Archived retires it from active surfaces." }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.lifecycle_state, onChange: (val) => updateForm("lifecycle_state", val), searchable: false, options: [{ value: "draft", label: "Draft" }, { value: "scheduled", label: "Scheduled" }, { value: "published", label: "Published" }, { value: "featured", label: "Featured" }, { value: "archived", label: "Archived" }, { value: "expired", label: "Expired" }] })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Publish At", help: "Leave empty to publish immediately. A future time keeps it off public surfaces until it goes live." }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.published_at, onChange: (nextValue) => updateForm("published_at", nextValue), placeholder: "Publish time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$3, { label: "Unpublish At", help: "Optional automatic sunset time for seasonal or editorial collections." }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.unpublished_at, onChange: (nextValue) => updateForm("unpublished_at", nextValue), placeholder: "Unpublish time", clearable: true, className: "bg-white/[0.04]" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Archive At", help: "Optional timestamp for moving the collection to long-term archive workflows." }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.archived_at, onChange: (nextValue) => updateForm("archived_at", nextValue), placeholder: "Archive time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$3, { label: "Expire At", help: "Optional hard expiry for promotional or seasonal collections." }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.expired_at, onChange: (nextValue) => updateForm("expired_at", nextValue), placeholder: "Expiry time", clearable: true, className: "bg-white/[0.04]" })))), /* @__PURE__ */ React.createElement(AdvancedSection, { title: "Commercial & Administration", icon: "fa-briefcase", defaultOpen: mode === "edit" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Promotion Tier" }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.promotion_tier, onChange: (event) => updateForm("promotion_tier", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Monetization Status" }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.monetization_ready_status, onChange: (event) => updateForm("monetization_ready_status", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Sponsorship Label" }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.sponsorship_label, onChange: (event) => updateForm("sponsorship_label", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$3, { label: "Partner Label" }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.partner_label, onChange: (event) => updateForm("partner_label", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 120 }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Brand Safe Status" }, /* @__PURE__ */ React.createElement("input", { type: "text", value: form.brand_safe_status, onChange: (event) => updateForm("brand_safe_status", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]", maxLength: 40 })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 self-end rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.analytics_enabled, onChange: (event) => updateForm("analytics_enabled", event.target.checked), label: "Analytics enabled" }))), /* @__PURE__ */ React.createElement(Field$3, { label: "Editorial Notes", help: "Internal editorial context for campaign planning, curation rationale, and staff handoff." }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: form.editorial_notes,
      onChange: (event) => updateForm("editorial_notes", event.target.value),
      className: "min-h-[96px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]",
      maxLength: 2e3
    }
  )), canModerate ? /* @__PURE__ */ React.createElement(Field$3, { label: "Staff Commercial Notes", help: "Admin-only notes for sponsorship readiness, partner handling, and commercial review." }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: form.staff_commercial_notes,
      onChange: (event) => updateForm("staff_commercial_notes", event.target.value),
      className: "min-h-[96px] w-full rounded-2xl border border-amber-300/15 bg-amber-400/10 px-4 py-3 text-white outline-none transition focus:border-amber-300/35 focus:bg-amber-400/15",
      maxLength: 2e3
    }
  )) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: saving,
      className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${saving ? "fa-circle-notch fa-spin" : "fa-floppy-disk"} fa-fw` }),
    mode === "create" ? "Create Collection" : "Save Changes"
  ), isSmartMode ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleSmartPreview,
      disabled: previewing,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/12 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${previewing ? "fa-circle-notch fa-spin" : "fa-binoculars"} fa-fw` }),
    "Preview Matches"
  ) : null, mode === "edit" ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleDeleteCollection,
      disabled: saving,
      className: "inline-flex items-center gap-2 rounded-2xl border border-rose-400/20 bg-rose-400/10 px-5 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can fa-fw" }),
    "Delete Collection"
  ) : null))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Owner"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center gap-4 rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("img", { src: owner?.avatar_url, alt: owner?.name || owner?.username, className: "h-16 w-16 rounded-[20px] object-cover ring-1 ring-white/10" }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, owner?.name || owner?.username), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "@", owner?.username)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Presentation"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Lifecycle"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold capitalize text-white" }, String(form.lifecycle_state || "draft").replace("_", " "))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Mode"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, isSmartMode ? "Smart" : "Manual")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Visibility"), /* @__PURE__ */ React.createElement(CollectionVisibilityBadge, { visibility: form.visibility })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Feature status"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, featuredCountLabel)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Style"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, String(form.presentation_style || "standard").replace(/_/g, " "))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Analytics"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, form.analytics_enabled ? "Enabled" : "Disabled")), canFeature ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleToggleFeature,
      disabled: featureBusy,
      className: `inline-flex w-full items-center justify-center gap-2 rounded-2xl border px-4 py-3 text-sm font-semibold transition ${collectionState?.is_featured ? "border-amber-300/25 bg-amber-300/10 text-amber-100 hover:bg-amber-300/15" : "border-sky-300/25 bg-sky-400/10 text-sky-100 hover:bg-sky-400/15"} disabled:cursor-not-allowed disabled:opacity-60`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${featureBusy ? "fa-circle-notch fa-spin" : collectionState?.is_featured ? "fa-star" : "fa-sparkles"} fa-fw` }),
    collectionState?.is_featured ? "Remove from Featured" : "Feature this Collection"
  ) : null, mode === "edit" && form.visibility !== "public" ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-xs leading-relaxed text-slate-400" }, "Only public collections can be featured, liked, or followed publicly.") : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Live Stats"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-images", label: "Artworks", value: (collectionState?.artworks_count ?? attached.length ?? 0).toLocaleString(), tone: "accent" }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-eye", label: "Views", value: (collectionState?.views_count ?? 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-heart", label: "Likes", value: (collectionState?.likes_count ?? 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-bell", label: "Followers", value: (collectionState?.followers_count ?? 0).toLocaleString() })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-xs leading-relaxed text-slate-400" }, "Shares: ", (collectionState?.shares_count ?? 0).toLocaleString(), " ", collectionState?.last_activity_at ? `• Active ${new Date(collectionState.last_activity_at).toLocaleDateString()}` : ""), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-gauge-high", label: "Quality", value: collectionState?.quality_score != null ? Number(collectionState.quality_score).toFixed(1) : "Pending" }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-ranking-star", label: "Ranking", value: collectionState?.ranking_score != null ? Number(collectionState.ranking_score).toFixed(1) : "Pending" }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Series & Campaign"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Series: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, form.series_key || "Not set"), form.series_order ? ` • #${form.series_order}` : ""), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Series title: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, form.series_title || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Campaign: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, form.campaign_label || form.campaign_key || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Promotion tier: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, form.promotion_tier || "None")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Brand safety: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, form.brand_safe_status || "Unset")))), mode === "edit" ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Insight Links"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, endpoints?.dashboard ? /* @__PURE__ */ React.createElement("a", { href: endpoints.dashboard, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("span", null, "Portfolio dashboard"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500" })) : null, endpoints?.analytics ? /* @__PURE__ */ React.createElement("a", { href: endpoints.analytics, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("span", null, "Collection analytics"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500" })) : null, endpoints?.history ? /* @__PURE__ */ React.createElement("a", { href: endpoints.history, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("span", null, "Audit history"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500" })) : null, endpoints?.staffSurfaces ? /* @__PURE__ */ React.createElement("a", { href: endpoints.staffSurfaces, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("span", null, "Staff surfaces"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500" })) : null, endpoints?.staffProgramming ? /* @__PURE__ */ React.createElement("a", { href: endpoints.staffProgramming, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("span", null, "Programming studio"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500" })) : null)) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Quick Start"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Start with just a title — everything else can be filled in later. The advanced sections are there when you need them."), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "Manual"), " is great for hand-picked storytelling. ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "Smart"), " keeps a collection up to date automatically using rules you define."))))) : null, mode !== "edit" || activeTab === "artworks" ? isSmartMode ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.18fr)_420px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Smart Builder"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Define collection rules"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-relaxed text-slate-300" }, "Rules only evaluate your own artworks. This keeps smart collections creator-first and avoids pulling content from other users.")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: addRule,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus fa-fw" }),
    "Add Rule"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, smartRuleCount ? smartRules.rules.map((rule, index2) => /* @__PURE__ */ React.createElement(
    SmartRuleRow,
    {
      key: `${rule.field}-${index2}`,
      rule,
      index: index2,
      smartRuleOptions,
      onFieldChange: (field) => updateSmartRule(index2, () => normalizeRule({ field })),
      onOperatorChange: (operator) => updateSmartRule(index2, (current) => ({ ...current, operator })),
      onValueChange: (value) => updateSmartRule(index2, (current) => ({ ...current, value })),
      onRemove: () => removeRule(index2)
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center text-slate-300" }, "Add at least one rule to build a smart collection."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Preview"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Matching artworks")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleSmartPreview,
      disabled: previewing,
      className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${previewing ? "fa-circle-notch fa-spin" : "fa-arrows-rotate"} fa-fw` }),
    "Refresh Preview"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, smartPreview?.count ?? 0, " matching artworks"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-relaxed text-slate-300" }, smartPreview?.summary || "Preview the rules to see how this collection will fill automatically.")), smartPreview?.artworks?.data?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-1" }, smartPreview.artworks.data.map((artwork) => /* @__PURE__ */ React.createElement(SmartPreviewArtwork, { key: artwork.id, artwork }))) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-18 w-18 items-center justify-center rounded-[22px] border border-white/12 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles text-3xl" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-5 text-xl font-semibold text-white" }, "No matches yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-md text-sm leading-relaxed text-slate-300" }, "A smart collection can still be valid with zero results. Broaden the rules or publish more matching artworks.")))) : mode === "edit" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.18fr)_420px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Attached Artworks"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Arrange the showcase order")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: saveArtworkOrder,
      disabled: !orderDirty || saving,
      className: `inline-flex items-center gap-2 rounded-2xl border px-4 py-3 text-sm font-semibold transition ${orderDirty ? "border-sky-300/25 bg-sky-400/10 text-sky-100 hover:bg-sky-400/15" : "border-white/8 bg-white/[0.03] text-slate-500"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip fa-fw" }),
    "Save Order"
  )), attached.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3" }, attached.map((artwork, index2) => /* @__PURE__ */ React.createElement(
    AttachedArtworkCard,
    {
      key: artwork.id,
      artwork,
      index: index2,
      total: attached.length,
      onMoveUp: () => moveArtwork(index2, -1),
      onMoveDown: () => moveArtwork(index2, 1),
      onRemove: () => handleRemoveArtwork(artwork)
    }
  ))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-18 w-18 items-center justify-center rounded-[22px] border border-white/12 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images text-3xl" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-5 text-xl font-semibold text-white" }, "No artworks attached yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-md text-sm leading-relaxed text-slate-300" }, "Use the picker on the right to add artworks from your gallery. Manual ordering and cover selection become available as soon as the first piece is attached."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Artwork Picker"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Add artworks")), /* @__PURE__ */ React.createElement("form", { onSubmit: handleSearch, className: "mt-5 flex gap-3" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: search2,
      onChange: (event) => setSearch(event.target.value),
      placeholder: "Search your gallery",
      className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]"
    }
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: searching,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${searching ? "fa-circle-notch fa-spin" : "fa-magnifying-glass"} fa-fw` }),
    "Search"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, selectedIds.length ? `${selectedIds.length} selected` : "Select artworks to add"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleAttachSelected,
      disabled: !selectedIds.length || saving,
      className: `inline-flex items-center gap-2 rounded-2xl border px-4 py-2.5 text-sm font-semibold transition ${selectedIds.length ? "border-sky-300/25 bg-sky-400/10 text-sky-100 hover:bg-sky-400/15" : "border-white/8 bg-white/[0.03] text-slate-500"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus fa-fw" }),
    "Add Selected"
  )), available.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-1" }, available.map((artwork) => /* @__PURE__ */ React.createElement(
    ArtworkPickerCard,
    {
      key: artwork.id,
      artwork,
      checked: selectedIds.includes(artwork.id),
      onToggle: toggleSelected
    }
  ))) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center text-slate-300" }, "No matching artworks available to add."))) : /* @__PURE__ */ React.createElement("div", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-20 w-20 items-center justify-center rounded-[24px] border border-white/12 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${isSmartMode ? "fa-wand-magic-sparkles" : "fa-sparkles"} text-3xl` })), /* @__PURE__ */ React.createElement("h2", { className: "mt-5 text-2xl font-semibold text-white" }, isSmartMode ? "Preview it, then publish it" : "Create it first, then curate it"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm leading-relaxed text-slate-300" }, isSmartMode ? "Smart collections can be previewed before creation so you can verify the rules and tune the result set." : "Once the collection is created, this page will expand into the full curator workflow with artwork selection, manual ordering, and cover controls.")) : null, mode === "edit" && activeTab === "ai" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "AI Assistant"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Review-only suggestions"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Use lightweight AI-style suggestions to refine naming, summaries, covers, and section groupings. Nothing is applied until you choose it, and nothing is saved until you submit the form.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("title"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "title" ? "Thinking…" : "Suggest title"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("summary"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "summary" ? "Thinking…" : "Suggest summary"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("cover"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "cover" ? "Thinking…" : "Suggest cover"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("grouping"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "grouping" ? "Thinking…" : "Suggest grouping"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("relatedArtworks"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "relatedArtworks" ? "Thinking…" : "Suggest related artworks"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("tags"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "tags" ? "Thinking…" : "Suggest tags"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("seoDescription"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "seoDescription" ? "Thinking…" : "Suggest SEO description"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("smartRulesExplanation"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "smartRulesExplanation" ? "Thinking…" : "Explain smart rules"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("splitThemes"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "splitThemes" ? "Thinking…" : "Suggest split"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAiSuggestion("mergeIdea"), disabled: aiState.busy !== "", className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:opacity-60" }, aiState.busy === "mergeIdea" ? "Thinking…" : "Suggest merge idea"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleAiQualityReview, disabled: aiState.busy !== "", className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, aiState.busy === "qualityReview" ? "Reviewing…" : "Quality review"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Title",
      body: aiState?.title?.title || "No title suggestion yet.",
      actionLabel: aiState?.title?.title ? "Use title" : null,
      onAction: applyAiTitle,
      muted: !aiState?.title?.title
    },
    aiState?.title?.alternatives?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "Alternatives: ", aiState.title.alternatives.join(" • ")) : null,
    aiState?.title?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.title.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Summary",
      body: aiState?.summary?.summary || "No summary suggestion yet.",
      actionLabel: aiState?.summary?.summary ? "Use summary" : null,
      onAction: applyAiSummary,
      muted: !aiState?.summary?.summary
    },
    aiState?.summary?.seo_description ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "SEO: ", aiState.summary.seo_description) : null,
    aiState?.summary?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.summary.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Cover",
      body: aiState?.cover?.artwork?.title || "No cover suggestion yet.",
      actionLabel: aiState?.cover?.artwork?.id && !isSmartMode ? "Use cover" : null,
      onAction: applyAiCover,
      muted: !aiState?.cover?.artwork?.title
    },
    aiState?.cover?.artwork?.thumb ? /* @__PURE__ */ React.createElement("img", { src: aiState.cover.artwork.thumb, alt: aiState.cover.artwork.title, className: "mt-4 aspect-[16/10] w-full rounded-[20px] object-cover" }) : null,
    isSmartMode && aiState?.cover?.artwork?.id ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, "Smart collections resolve covers dynamically, so this suggestion is preview-only.") : null,
    aiState?.cover?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.cover.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Grouping",
      body: aiState?.grouping?.groups?.length ? "Suggested section themes for cleaner collection storytelling." : "No grouping suggestion yet.",
      muted: !aiState?.grouping?.groups?.length
    },
    aiState?.grouping?.groups?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, aiState.grouping.groups.map((group) => /* @__PURE__ */ React.createElement("div", { key: group.label, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, group.count, " suggested artworks")))) : null,
    aiState?.grouping?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.grouping.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Related Artworks",
      body: aiState?.relatedArtworks?.artworks?.length ? "Suggested from your gallery to reinforce the collection theme." : "No related artwork suggestion yet.",
      actionLabel: aiState?.relatedArtworks?.artworks?.length ? "Select suggestions" : null,
      onAction: applyAiRelatedArtworks,
      muted: !aiState?.relatedArtworks?.artworks?.length
    },
    aiState?.relatedArtworks?.artworks?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, aiState.relatedArtworks.artworks.map((artwork) => /* @__PURE__ */ React.createElement("div", { key: artwork.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-slate-200" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-12 w-12 rounded-xl object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, artwork.shared_tags?.length ? `Shared tags: ${artwork.shared_tags.join(" • ")}` : `${artwork.shared_categories} shared categories`))))) : null,
    aiState?.relatedArtworks?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.relatedArtworks.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Suggested Tags",
      body: aiState?.tags?.tags?.length ? aiState.tags.tags.join(" • ") : "No tag suggestion yet.",
      muted: !aiState?.tags?.tags?.length
    },
    aiState?.tags?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.tags.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "SEO Description",
      body: aiState?.seoDescription?.description || "No SEO description suggestion yet.",
      muted: !aiState?.seoDescription?.description
    },
    aiState?.seoDescription?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.seoDescription.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Smart Rules",
      body: aiState?.smartRulesExplanation?.explanation || "No smart rules explanation yet.",
      muted: !aiState?.smartRulesExplanation?.explanation
    },
    aiState?.smartRulesExplanation?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.smartRulesExplanation.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Split Suggestion",
      body: aiState?.splitThemes?.splits?.length ? "Two strong theme clusters were found that could become separate collections." : "No split suggestion yet.",
      muted: !aiState?.splitThemes?.splits?.length
    },
    aiState?.splitThemes?.splits?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, aiState.splitThemes.splits.map((split) => /* @__PURE__ */ React.createElement("div", { key: split.title, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, split.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, split.count, " suggested artworks")))) : null,
    aiState?.splitThemes?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.splitThemes.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Merge Idea",
      body: aiState?.mergeIdea?.idea?.title || "No merge or spin-out idea yet.",
      muted: !aiState?.mergeIdea?.idea?.title
    },
    aiState?.mergeIdea?.idea?.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-300" }, aiState.mergeIdea.idea.summary) : null,
    aiState?.mergeIdea?.rationale ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, aiState.mergeIdea.rationale) : null
  ), /* @__PURE__ */ React.createElement(
    AiSuggestionCard,
    {
      title: "Quality Review",
      body: aiState?.qualityReview ? `Quality ${Number(aiState.qualityReview.quality_score || 0).toFixed(1)} • Ranking ${Number(aiState.qualityReview.ranking_score || 0).toFixed(1)}` : "No quality review yet.",
      muted: !aiState?.qualityReview
    },
    aiState?.qualityReview?.missing_metadata?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-300" }, "Missing: ", aiState.qualityReview.missing_metadata.join(" • ")) : null,
    aiState?.qualityReview?.suggested_summary?.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "Suggested summary: ", aiState.qualityReview.suggested_summary.summary) : null,
    aiState?.qualityReview?.suggested_related_collections?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, "Related collections: ", aiState.qualityReview.suggested_related_collections.map((item) => item.title).join(" • ")) : null
  ))) : null, mode === "edit" && activeTab === "members" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Collaborators"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Team access"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Pending invites default to ", inviteExpiryDays, " days, but each invite can use a shorter or longer expiry. Ownership transfers keep the previous owner as an editor."))), /* @__PURE__ */ React.createElement("form", { onSubmit: handleInviteMember, className: "mt-5 flex flex-col gap-3 xl:flex-row xl:items-start" }, /* @__PURE__ */ React.createElement("input", { value: inviteUsername, onChange: (event) => setInviteUsername(event.target.value), placeholder: "username", className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 focus:bg-white/[0.06]" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: inviteRole, onChange: (val) => setInviteRole(val), searchable: false, options: [{ value: "editor", label: "Editor" }, { value: "contributor", label: "Contributor" }, { value: "viewer", label: "Viewer" }] }), /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 flex-1 flex-col gap-2 md:min-w-[240px]" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: inviteExpiryMode, onChange: (val) => setInviteExpiryMode(val), searchable: false, options: [{ value: "default", label: `Default (${inviteExpiryDays} days)` }, ...inviteExpiryOptions.map((days) => ({ value: String(days), label: `${days} day${days === 1 ? "" : "s"}` })), { value: "custom", label: "Custom date" }] }), inviteExpiryMode === "custom" ? /* @__PURE__ */ React.createElement(DateTimePicker, { value: inviteCustomExpiry, onChange: setInviteCustomExpiry, placeholder: "Custom expiry", clearable: true, className: "bg-white/[0.04]" }) : /* @__PURE__ */ React.createElement("p", { className: "px-1 text-xs text-slate-400" }, "Leave this on default to use the global expiry window for collaborator invites.")), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Invite")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, members.length ? members.map((member) => /* @__PURE__ */ React.createElement(
    MemberCard,
    {
      key: member.id,
      member,
      onRoleChange: handleMemberRoleChange,
      onRemove: canModerate ? handleAdminRemoveMember : handleRemoveMember,
      onAccept: handleAcceptMember,
      onDecline: handleDeclineMember,
      onTransfer: handleTransferMember
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/12 bg-white/[0.03] px-4 py-10 text-center text-sm text-slate-300" }, "No collaborators yet.")))) : null, mode === "edit" && activeTab === "submissions" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Submissions"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Incoming artworks")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, submissions.length ? submissions.map((submission) => /* @__PURE__ */ React.createElement(
    SubmissionReviewCard,
    {
      key: submission.id,
      submission,
      onApprove: (item) => handleSubmissionAction(item, "approve"),
      onReject: (item) => handleSubmissionAction(item, "reject"),
      onWithdraw: (item) => handleSubmissionAction(item, "withdraw")
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/12 bg-white/[0.03] px-4 py-10 text-center text-sm text-slate-300" }, "No submissions yet.")))) : null, mode === "edit" && activeTab === "discussion" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Discussion"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Recent comments")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, comments.length ? comments.slice(0, 6).map((comment) => /* @__PURE__ */ React.createElement("div", { key: comment.id, className: "rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, comment?.user?.display), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-relaxed text-slate-300", dangerouslySetInnerHTML: { __html: comment?.rendered_content || "" } }))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/12 bg-white/[0.03] px-4 py-10 text-center text-sm text-slate-300" }, "No comments yet.")))) : null, mode === "edit" && activeTab === "settings" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Presentation"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Mode"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, isSmartMode ? "Smart" : "Manual")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Visibility"), /* @__PURE__ */ React.createElement(CollectionVisibilityBadge, { visibility: form.visibility })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Feature status"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, featuredCountLabel)), canFeature ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleToggleFeature,
      disabled: featureBusy,
      className: `inline-flex w-full items-center justify-center gap-2 rounded-2xl border px-4 py-3 text-sm font-semibold transition ${collectionState?.is_featured ? "border-amber-300/25 bg-amber-300/10 text-amber-100 hover:bg-amber-300/15" : "border-sky-300/25 bg-sky-400/10 text-sky-100 hover:bg-sky-400/15"} disabled:cursor-not-allowed disabled:opacity-60`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${featureBusy ? "fa-circle-notch fa-spin" : collectionState?.is_featured ? "fa-star" : "fa-sparkles"} fa-fw` }),
    collectionState?.is_featured ? "Remove from Featured" : "Feature this Collection"
  ) : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Live Stats"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-images", label: "Artworks", value: (collectionState?.artworks_count ?? attached.length ?? 0).toLocaleString(), tone: "accent" }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-eye", label: "Views", value: (collectionState?.views_count ?? 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-heart", label: "Likes", value: (collectionState?.likes_count ?? 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-bell", label: "Followers", value: (collectionState?.followers_count ?? 0).toLocaleString() })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-xs leading-relaxed text-slate-400" }, "Shares: ", (collectionState?.shares_count ?? 0).toLocaleString(), " ", collectionState?.last_activity_at ? `• Active ${new Date(collectionState.last_activity_at).toLocaleDateString()}` : "")), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Health"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, "Readiness and warnings")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleAiQualityReview, disabled: aiState.busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${aiState.busy === "qualityReview" ? "fa-circle-notch fa-spin" : "fa-wand-magic-sparkles"} fa-fw` }), aiState.busy === "qualityReview" ? "Reviewing…" : "AI fix suggestions")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-heart-pulse", label: "Health", value: formatStateLabel(collectionState?.health_state), tone: "accent" }), /* @__PURE__ */ React.createElement(StatCard$7, { icon: "fa-clipboard-check", label: "Readiness", value: formatStateLabel(collectionState?.readiness_state) })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs font-semibold uppercase tracking-[0.14em]" }, /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-2 ${collectionState?.placement_eligibility ? "border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border-rose-300/20 bg-rose-400/10 text-rose-100"}` }, collectionState?.placement_eligibility ? "Placement eligible" : "Placement blocked"), collectionState?.campaign_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-slate-200" }, "Campaign · ", collectionState.campaign_key) : null, collectionState?.program_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-slate-200" }, "Program · ", collectionState.program_key) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Metadata"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, collectionState?.metadata_completeness_score !== null && collectionState?.metadata_completeness_score !== void 0 ? Number(collectionState.metadata_completeness_score).toFixed(1) : "N/A")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Editorial"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, collectionState?.editorial_readiness_score !== null && collectionState?.editorial_readiness_score !== void 0 ? Number(collectionState.editorial_readiness_score).toFixed(1) : "N/A"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (collectionState?.health_flags?.length ? collectionState.health_flags : [collectionState?.health_state].filter(Boolean)).map((flag) => {
    const meta = healthFlagMeta(flag);
    return /* @__PURE__ */ React.createElement("div", { key: flag, className: `rounded-2xl border px-4 py-3 ${meta.tone}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em]" }, meta.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-relaxed" }, meta.description));
  })), aiState?.qualityReview?.missing_metadata?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm text-sky-100" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/90" }, "Suggested fixes"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, "Focus first on: ", aiState.qualityReview.missing_metadata.join(" • ")), aiState?.qualityReview?.suggested_summary?.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-sky-100/80" }, "Suggested summary: ", aiState.qualityReview.suggested_summary.summary) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-xs leading-relaxed text-slate-400" }, "Last health check: ", formatDateTimeLabel(collectionState?.last_health_check_at) || "Not recorded yet", /* @__PURE__ */ React.createElement("br", null), "Recommendation refresh: ", formatDateTimeLabel(collectionState?.last_recommendation_refresh_at) || "Not recorded yet")), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Studio Notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Use the Details tab for metadata and publishing options, then switch to Artworks for ordering or smart rule management."), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, "Community and editorial collections work best when collaborators, submissions, and moderation are reviewed regularly.")))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Merge Review"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Compare duplicate candidates"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Review candidate overlaps, choose a canonical destination, merge when the target is final, or dismiss false positives so they stop resurfacing.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, duplicateCandidates.length, " active candidate", duplicateCandidates.length === 1 ? "" : "s")), canonicalTarget ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-amber-300/20 bg-amber-400/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Current canonical target"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold text-white" }, canonicalTarget.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-amber-100/80" }, canonicalTarget.owner?.name || canonicalTarget.owner?.username || "Collection")), canonicalTarget.manage_url ? /* @__PURE__ */ React.createElement("a", { href: canonicalTarget.manage_url, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.06] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.1]" }, "Open target", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-slate-400" })) : null)) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, duplicateCandidates.length ? duplicateCandidates.map((candidate) => /* @__PURE__ */ React.createElement("div", { key: `merge-candidate-${candidate.collection?.id}`, className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", null, candidate.collection ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: candidate.collection, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Compare"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, (candidate.comparison?.match_reasons || []).map((reason) => /* @__PURE__ */ React.createElement("span", { key: reason, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, reason.replaceAll("_", " ")))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Shared artworks: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, candidate.comparison?.shared_artworks_count ?? 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Current: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, candidate.comparison?.source_artworks_count ?? 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Target: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, candidate.comparison?.target_artworks_count ?? 0)))), candidate.decision?.action_type ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-xs text-slate-400" }, "Latest decision: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold uppercase tracking-[0.14em] text-white" }, candidate.decision.action_type.replaceAll("_", " ")), candidate.decision.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, candidate.decision.summary) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleCanonicalizeCandidate(candidate),
      disabled: saving,
      className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bullseye fa-fw" }),
    "Canonicalize here"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleMergeCandidate(candidate),
      disabled: saving || candidate.collection?.mode === "smart",
      className: "inline-flex items-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-code-merge fa-fw" }),
    "Merge into target"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleRejectDuplicateCandidate(candidate),
      disabled: saving || candidate.is_current_canonical_target,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-ban fa-fw" }),
    "Not duplicate"
  )), candidate.collection?.mode === "smart" ? /* @__PURE__ */ React.createElement("div", { className: "text-xs text-amber-200/80" }, "Smart collections can be designated as canonical but cannot receive merged artworks directly.") : null)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center text-sm text-slate-300" }, "No active duplicate candidates right now. Dismissed pairs stay suppressed until the collections change again."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Linked Collections"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Manual related collection links"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Curate a hand-picked strip of related collections for multi-part series, anthologies, and campaign bundles. These links render before recommendation-driven suggestions on the public page.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, linkedCollections.length, " linked")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-col gap-3 xl:flex-row xl:items-end" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Add manageable collection"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: selectedLinkedCollectionId,
      onChange: (value) => setSelectedLinkedCollectionId(value),
      options: linkedCollectionOptions.map((item) => ({ value: String(item.id), label: item.title })),
      placeholder: "Select a collection"
    }
  )), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleAddLinkedCollection,
      disabled: !selectedLinkedCollectionId || saving,
      className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${saving ? "fa-circle-notch fa-spin" : "fa-link"} fa-fw` }),
    "Add linked collection"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, linkedCollections.length ? linkedCollections.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "flex flex-col gap-4 rounded-[26px] border border-white/10 bg-white/[0.04] p-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-4" }, item.cover_image ? /* @__PURE__ */ React.createElement("img", { src: item.cover_image, alt: item.title, className: "h-16 w-16 rounded-[18px] object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center rounded-[18px] border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grid-2" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate text-sm text-slate-400" }, item.campaign_label || item.series_key || item.owner?.name || item.owner?.username || "Collection"))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, item.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.manage_url, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Open", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-slate-500" })) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleRemoveLinkedCollection(item.id),
      disabled: saving,
      className: "inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link-slash fa-fw" }),
    "Remove"
  )))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center text-sm text-slate-300" }, "No manual linked collections yet. Add sequels, anthologies, or campaign companions here."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Cross-Entity Links"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Creators, artworks, stories, categories, campaigns, events, and tags"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Add contextual links that turn this collection into a richer destination page. These links can point to creators, public artworks, published stories, category landings, campaign or event context, and public tag or theme pages.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, entityLinks.length, " linked entities")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3 xl:grid-cols-[180px_minmax(0,1fr)_240px_auto] xl:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Entity type"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: selectedEntityType,
      onChange: (value) => {
        const nextOptions = Array.isArray(entityLinkOptions[value]) ? entityLinkOptions[value] : [];
        setSelectedEntityType(value);
        setSelectedEntityId(String(nextOptions[0]?.id || ""));
      },
      options: [
        { value: "creator", label: "Creator" },
        { value: "artwork", label: "Artwork" },
        { value: "story", label: "Story" },
        { value: "category", label: "Category" },
        { value: "campaign", label: "Campaign" },
        { value: "event", label: "Event" },
        { value: "tag", label: "Tag or Theme" }
      ],
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Choose entity"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: selectedEntityId,
      onChange: (value) => setSelectedEntityId(value),
      options: (entityLinkOptions[selectedEntityType] || []).map((item) => ({ value: String(item.id), label: item.label })),
      placeholder: "Select an entity"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Relationship label"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: entityRelationship,
      onChange: (event) => setEntityRelationship(event.target.value),
      placeholder: "featured creator",
      className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35",
      maxLength: 80
    }
  )), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleAddEntityLink,
      disabled: !selectedEntityType || !selectedEntityId || saving,
      className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-lime-300/25 bg-lime-400/10 px-4 py-3 text-sm font-semibold text-lime-100 transition hover:bg-lime-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${saving ? "fa-circle-notch fa-spin" : "fa-diagram-project"} fa-fw` }),
    "Add link"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, entityLinks.length ? entityLinks.map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.linked_type}-${item.linked_id}-${item.id}`, className: "flex flex-col gap-4 rounded-[26px] border border-white/10 bg-white/[0.04] p-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-4" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-16 w-16 rounded-[18px] object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center rounded-[18px] border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-diagram-project" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.meta)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate text-sm text-slate-400" }, item.subtitle), item.relationship_type ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-lime-200/80" }, item.relationship_type) : null)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, item.url ? /* @__PURE__ */ React.createElement("a", { href: item.url, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Open", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-slate-500" })) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleRemoveEntityLink(item.id),
      disabled: saving,
      className: "inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link-slash fa-fw" }),
    "Remove"
  )))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-center text-sm text-slate-300" }, "No entity links yet. Connect this collection to a creator profile, a public artwork, a published story, campaign or event context, or a category landing page."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Page Modules"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Persisted collection layout"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Reorder the collection page with predefined modules. This keeps the destination page modular without turning it into a freeform page builder.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, layoutModules.filter((module) => module.enabled).length, " active modules")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, layoutModules.map((module, index2) => /* @__PURE__ */ React.createElement(
    LayoutModuleCard,
    {
      key: module.key,
      module,
      index: index2,
      total: layoutModules.length,
      onToggle: (key, enabled) => updateLayoutModule(key, { enabled }),
      onSlotChange: (key, slot) => updateLayoutModule(key, { slot }),
      onMoveUp: () => moveLayoutModule(index2, -1),
      onMoveDown: () => moveLayoutModule(index2, 1)
    }
  ))))) : null, mode === "edit" && activeTab === "moderation" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Moderation"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Admin controls"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Restrict public visibility, disable risky interactions, unfeature collections, or remove collaborators when a curation surface needs intervention.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement(Field$3, { label: "Moderation Status" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: collectionState?.moderation_status || "active",
      onChange: (value) => handleModerationStatusChange(value),
      options: [
        { value: "active", label: "Active" },
        { value: "under_review", label: "Under review" },
        { value: "restricted", label: "Restricted" },
        { value: "hidden", label: "Hidden" }
      ],
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", null, "Allow comments"), /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_comments, onChange: (event) => handleModerationToggle("allow_comments", event.target.checked) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", null, "Allow submissions"), /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_submissions, onChange: (event) => handleModerationToggle("allow_submissions", event.target.checked) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", null, "Allow saves"), /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_saves, onChange: (event) => handleModerationToggle("allow_saves", event.target.checked) })))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Rapid actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleAdminUnfeature, className: "rounded-2xl border border-amber-300/25 bg-amber-300/10 px-4 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-300/15" }, "Remove featured placement"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleModerationStatusChange("under_review"), className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Send to review"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleModerationStatusChange("restricted"), className: "rounded-2xl border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15" }, "Restrict public access")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-4 text-sm leading-relaxed text-slate-300" }, "Current state: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, (collectionState?.moderation_status || "active").replace("_", " ")))))) : null)));
}
const __vite_glob_0_45 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionManage
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$6({ icon, label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.05] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-[10px]` }), label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, value));
}
function CollectionSeriesShow() {
  const { props } = X$1();
  const seo = props.seo || {};
  const title = props.title || `Collection Series: ${props.seriesKey || ""}`;
  const description = props.description || "A connected sequence of public collections on Skinbase.";
  const collections = Array.isArray(props.collections) ? props.collections : [];
  const leadCollection = props.leadCollection || null;
  const stats = props.stats || {};
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: seo.title || `${title} — Skinbase`, description: seo.description || description }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[36rem] opacity-95", style: { background: "radial-gradient(circle at 10% 15%, rgba(59,130,246,0.18), transparent 28%), radial-gradient(circle at 84% 18%, rgba(34,197,94,0.16), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: "/collections/featured", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to collections"), leadCollection?.url ? /* @__PURE__ */ React.createElement("a", { href: leadCollection.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Lead collection") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.15fr)_400px] xl:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Series"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, description), props.seriesKey ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 inline-flex rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-300" }, props.seriesKey) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(StatCard$6, { icon: "fa-layer-group", label: "Collections", value: Number(stats.collections || collections.length).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$6, { icon: "fa-user-group", label: "Creators", value: Number(stats.owners || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$6, { icon: "fa-images", label: "Artworks", value: Number(stats.artworks || 0).toLocaleString() })))), leadCollection ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Lead Entry"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Start with the opening collection")), stats.latest_activity_at ? /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, "Latest activity ", new Date(stats.latest_activity_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 max-w-xl" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection: leadCollection, isOwner: false }))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-8 pb-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Sequence"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Public collections in order"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, collections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false })))))));
}
const __vite_glob_0_46 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionSeriesShow
}, Symbol.toStringTag, { value: "Module" }));
const IMAGE_FALLBACK = "https://files.skinbase.org/default/missing_md.webp";
const AVATAR_FALLBACK = "https://files.skinbase.org/default/avatar_default.webp";
const relativeTimeFormatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
function cx$6(...parts) {
  return parts.filter(Boolean).join(" ");
}
function formatRelativeTime(value) {
  if (!value) return "";
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const now = /* @__PURE__ */ new Date();
  const diffMs = date.getTime() - now.getTime();
  const diffSeconds = Math.round(diffMs / 1e3);
  const absSeconds = Math.abs(diffSeconds);
  if (absSeconds < 60) return relativeTimeFormatter.format(diffSeconds, "second");
  const diffMinutes = Math.round(diffSeconds / 60);
  if (Math.abs(diffMinutes) < 60) return relativeTimeFormatter.format(diffMinutes, "minute");
  const diffHours = Math.round(diffSeconds / 3600);
  if (Math.abs(diffHours) < 24) return relativeTimeFormatter.format(diffHours, "hour");
  const diffDays = Math.round(diffSeconds / 86400);
  if (Math.abs(diffDays) < 7) return relativeTimeFormatter.format(diffDays, "day");
  const diffWeeks = Math.round(diffSeconds / 604800);
  if (Math.abs(diffWeeks) < 5) return relativeTimeFormatter.format(diffWeeks, "week");
  const diffMonths = Math.round(diffSeconds / 2629800);
  if (Math.abs(diffMonths) < 12) return relativeTimeFormatter.format(diffMonths, "month");
  const diffYears = Math.round(diffSeconds / 31557600);
  return relativeTimeFormatter.format(diffYears, "year");
}
function slugify$2(value) {
  return String(value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
function decodeHtml(value) {
  const text2 = String(value ?? "");
  if (!text2.includes("&")) return text2;
  let decoded = text2;
  for (let index2 = 0; index2 < 3; index2 += 1) {
    decoded = decoded.replace(/&amp;/gi, "&").replace(/&(apos|#39);/gi, "'").replace(/&(acute|#180|#x00B4);/gi, "'").replace(/&(quot|#34);/gi, '"').replace(/&(nbsp|#160);/gi, " ");
    if (typeof document === "undefined") {
      break;
    }
    const textarea = document.createElement("textarea");
    textarea.innerHTML = decoded;
    const nextValue = textarea.value;
    if (nextValue === decoded) break;
    decoded = nextValue;
  }
  return decoded;
}
function normalizeContentTypeLabel(value) {
  const raw = decodeHtml(value).trim();
  if (!raw) return "";
  const normalized = raw.toLowerCase();
  const knownLabels = {
    artworks: "Artwork",
    artwork: "Artwork",
    wallpapers: "Wallpaper",
    wallpaper: "Wallpaper",
    skins: "Skin",
    skin: "Skin",
    photography: "Photography",
    photo: "Photography",
    photos: "Photography",
    other: "Other"
  };
  if (knownLabels[normalized]) {
    return knownLabels[normalized];
  }
  return raw.replace(/[-_]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
}
function getCsrfToken$b() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function swapImageToFallbackOnce(event, fallbackSrc, { clearResponsive = false } = {}) {
  const image2 = event.currentTarget;
  if (!image2 || image2.dataset.fallbackApplied === "1") {
    return;
  }
  image2.dataset.fallbackApplied = "1";
  image2.onerror = null;
  if (clearResponsive) {
    image2.removeAttribute("srcset");
    image2.removeAttribute("sizes");
  }
  image2.src = fallbackSrc;
}
function sendDiscoveryEvent$1(endpoint, payload) {
  if (!endpoint) return;
  void fetch(endpoint, {
    method: "POST",
    credentials: "same-origin",
    keepalive: true,
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$b(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: JSON.stringify(payload)
  }).catch(() => {
  });
}
async function sendFeedbackSignal(endpoint, payload) {
  if (!endpoint) {
    throw new Error("missing_feedback_endpoint");
  }
  const response = await fetch(endpoint, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$b(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: JSON.stringify(payload)
  });
  if (!response.ok) {
    throw new Error("feedback_request_failed");
  }
  return response.json().catch(() => null);
}
async function requestJson$l(endpoint, { method = "GET", body: body2 } = {}) {
  const response = await fetch(endpoint, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$b(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    const error = new Error(payload?.message || "Request failed.");
    error.payload = payload;
    throw error;
  }
  return payload;
}
function trackRecommendationFeedback(item, eventType, extraMeta = {}) {
  const endpoint = item?.discovery_endpoint;
  const artworkId = Number(item?.id ?? 0);
  if (!endpoint || artworkId <= 0) return;
  sendDiscoveryEvent$1(endpoint, {
    event_type: eventType,
    artwork_id: artworkId,
    algo_version: item?.recommendation_algo_version || item?.algo_version || void 0,
    meta: {
      gallery_type: item?.recommendation_surface || item?.gallery_type || "recommendation-surface",
      source: item?.recommendation_source || null,
      reason: item?.recommendation_reason || null,
      score: item?.recommendation_score ?? null,
      ...extraMeta
    }
  });
}
function HeartIcon(props) {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 20.25c-4.97-3.12-8.25-6.16-8.25-10.03A4.72 4.72 0 0 1 8.5 5.5c1.5 0 2.93.7 3.84 1.92A4.8 4.8 0 0 1 16.18 5.5a4.72 4.72 0 0 1 4.82 4.72c0 3.87-3.28 6.91-8.25 10.03Z" }));
}
function DownloadIcon(props) {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 3.75v10.5" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "m8.25 10.5 3.75 3.75 3.75-3.75" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 18.75h15" }));
}
function ViewIcon(props) {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M2.25 12s3.75-6.75 9.75-6.75S21.75 12 21.75 12 18 18.75 12 18.75 2.25 12 2.25 12Z" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 14.75A2.75 2.75 0 1 0 12 9.25a2.75 2.75 0 0 0 0 5.5Z" }));
}
function HideIcon(props) {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 6l12 12" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M18 6 6 18" }));
}
function TagIcon(props) {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M20.25 13.5 10.5 3.75H4.5v6l9.75 9.75a2.12 2.12 0 0 0 3 0l3-3a2.12 2.12 0 0 0 0-3Z" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M7.875 7.875h.008v.008h-.008z" }));
}
function CollectionIcon(props) {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4.5 6.75A2.25 2.25 0 0 1 6.75 4.5h10.5a2.25 2.25 0 0 1 2.25 2.25v10.5a2.25 2.25 0 0 1-2.25 2.25H6.75a2.25 2.25 0 0 1-2.25-2.25V6.75Z" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.25 12h7.5" }), /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 8.25v7.5" }));
}
function ActionLink$1({ href, label, children, onClick }) {
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: href || "#",
      "aria-label": label,
      onClick,
      className: "inline-flex h-10 w-10 items-center justify-center rounded-lg border border-white/10 bg-white/10 text-white/90 shadow-[0_14px_36px_rgba(2,6,23,0.38)] backdrop-blur-md transition duration-200 hover:bg-white/20 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80"
    },
    children
  );
}
function ActionButton({ label, children, onClick }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": label,
      onClick,
      className: "inline-flex h-10 w-10 items-center justify-center rounded-lg border border-white/10 bg-white/10 text-white/90 shadow-[0_14px_36px_rgba(2,6,23,0.38)] backdrop-blur-md transition duration-200 hover:bg-white/20 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80"
    },
    children
  );
}
function BadgePill({ className = "", iconClass = "", children }) {
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: cx$6(
        "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] backdrop-blur-sm ring-1 shadow-[0_8px_24px_rgba(2,6,23,0.28)]",
        className
      )
    },
    iconClass ? /* @__PURE__ */ React.createElement("i", { className: iconClass, "aria-hidden": "true" }) : null,
    children
  );
}
function CollectionPickerModal({
  open,
  artworkTitle,
  collections,
  loading,
  error,
  notice,
  createUrl,
  attachingCollectionId,
  onAttach,
  onClose
}) {
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose();
      }
    };
    document.addEventListener("keydown", handleKeyDown2);
    return () => document.removeEventListener("keydown", handleKeyDown2);
  }, [open, onClose]);
  if (!open) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-[140] flex items-center justify-center p-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      "aria-label": "Close add to collection dialog",
      onClick: onClose,
      className: "absolute inset-0 bg-slate-950/80 backdrop-blur-sm"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 w-full max-w-2xl overflow-hidden rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(8,15,27,0.98),rgba(6,11,20,0.98))] shadow-[0_40px_120px_rgba(2,6,23,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/10 px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-200/80" }, "Collections"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Add to collection"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Choose a showcase for ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, artworkTitle), ".")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClose,
      className: "inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })
  ))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 px-6 py-6" }, notice ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-100" }, notice) : null, error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, loading ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-10 text-center text-sm text-slate-300" }, "Loading collections...") : collections.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, collections.map((collection) => /* @__PURE__ */ React.createElement("div", { key: collection.id, className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, collection.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, collection.artworks_count, " artworks • ", collection.visibility)), collection.already_attached ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-emerald-400/20 bg-emerald-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-emerald-100" }, "Added") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onAttach(collection),
      disabled: collection.already_attached || attachingCollectionId === collection.id,
      className: `inline-flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${collection.already_attached || attachingCollectionId === collection.id ? "border-white/8 bg-white/[0.03] text-slate-500" : "border-sky-300/20 bg-sky-400/10 text-sky-100 transition hover:bg-sky-400/15"}`
    },
    /* @__PURE__ */ React.createElement(CollectionIcon, { className: "h-3.5 w-3.5" }),
    attachingCollectionId === collection.id ? "Adding..." : collection.already_attached ? "Already added" : "Add"
  ), /* @__PURE__ */ React.createElement("a", { href: collection.manage_url, className: "inline-flex items-center gap-2 rounded-xl border border-white/12 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]" }, "Manage"))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-10 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-16 w-16 items-center justify-center rounded-[20px] border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement(CollectionIcon, { className: "h-7 w-7" })), /* @__PURE__ */ React.createElement("h4", { className: "mt-4 text-lg font-semibold text-white" }, "Create your first collection"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-2 max-w-md text-sm leading-relaxed text-slate-300" }, "Start a curated showcase, then add this artwork into the sequence."), /* @__PURE__ */ React.createElement("a", { href: createUrl, className: "mt-5 inline-flex items-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "Create Collection")))));
}
function ArtworkCard$1({
  artwork,
  variant = "default",
  compact = false,
  showStats = true,
  showAuthor = true,
  className = "",
  articleClassName = "",
  frameClassName = "",
  mediaClassName = "",
  mediaStyle,
  articleStyle,
  imageClassName = "",
  imageSizes,
  imageSrcSet,
  imageWidth,
  imageHeight,
  loading = "lazy",
  decoding = "async",
  fetchPriority,
  onLike,
  onDismissed,
  showActions = true,
  metricBadge = null
}) {
  let inertiaProps = {};
  try {
    inertiaProps = X$1()?.props || {};
  } catch {
    inertiaProps = {};
  }
  const item = artwork || {};
  const rawAuthor = item.author || item.creator;
  const publisher = item.publisher && typeof item.publisher === "object" ? item.publisher : null;
  const isGroupPublisher = publisher?.type === "group" || item.published_as_type === "group";
  const title = decodeHtml(item.title || item.name || "Untitled artwork");
  const author = decodeHtml(
    (isGroupPublisher ? publisher?.name : null) || (typeof rawAuthor === "string" ? rawAuthor : rawAuthor?.name) || item.author_name || item.uname || "Skinbase Artist"
  );
  const username = isGroupPublisher ? null : rawAuthor?.username || item.author_username || item.username || null;
  const authorLevel = isGroupPublisher ? 0 : Number(rawAuthor?.level ?? item.author_level ?? item.creator?.level ?? 0);
  const authorRank = isGroupPublisher ? "" : rawAuthor?.rank || item.author_rank || item.creator?.rank || "";
  const image2 = item.image || item.thumb || item.thumb_url || item.thumbnail_url || IMAGE_FALLBACK;
  const responsiveImageSrcSet = imageSrcSet || item.thumb_srcset || item.thumbnail_srcset || void 0;
  const responsiveImageSizes = imageSizes || (variant === "embed" ? "80px" : compact ? "(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 280px" : "(max-width: 640px) 50vw, (max-width: 1024px) 33vw, (max-width: 1536px) 25vw, 320px");
  const avatar = (isGroupPublisher ? publisher?.avatar_url : null) || rawAuthor?.avatar_url || rawAuthor?.avatar || item.avatar || item.author_avatar || item.avatar_url || AVATAR_FALLBACK;
  const likes = item.likes ?? item.favourites ?? 0;
  item.views ?? item.views_count ?? item.view_count ?? 0;
  item.downloads ?? item.downloads_count ?? item.download_count ?? 0;
  const contentType = normalizeContentTypeLabel(
    item.content_type || item.content_type_name || item.contentType || item.contentTypeName || item.content_type_slug || ""
  );
  const category = decodeHtml(
    (typeof item.category === "string" ? item.category : item.category?.name) || item.category_name || ""
  );
  const width = Number(item.width ?? 0);
  const height = Number(item.height ?? 0);
  const resolution = decodeHtml(item.resolution || (width > 0 && height > 0 ? `${width}x${height}` : ""));
  const href = item.canonical_url || item.urls?.canonical || item.urls?.direct || item.url || item.href || (item.id ? `/art/${item.id}/${slugify$2(title)}` : "#");
  const downloadHref = item.download_url || item.downloadHref || (item.id ? `/download/artwork/${item.id}` : href);
  const cardLabel = `${title} by ${author}`;
  const aspectClass = compact ? "aspect-square" : "aspect-[4/5]";
  const titleClass = compact ? "text-[0.96rem]" : "text-[1rem] sm:text-[1.08rem]";
  const metadataLine = [contentType, category, resolution].filter(Boolean).join(" • ");
  const authorHref = publisher?.profile_url || rawAuthor?.profile_url || item.profile_url || item.author_url || (username ? `/@${username}` : null);
  const resolvedMetricBadge = metricBadge || item.metric_badge || null;
  const relativePublishedAt = reactExports.useMemo(
    () => formatRelativeTime(item.published_at || item.publishedAt || null),
    [item.published_at, item.publishedAt]
  );
  const maturity = item.maturity && typeof item.maturity === "object" ? item.maturity : {};
  const shouldBlurMature = Boolean(maturity.should_blur);
  const isMatureArtwork = Boolean(maturity.is_mature_effective);
  const initialLiked = Boolean(item.viewer?.is_liked);
  const [liked, setLiked] = reactExports.useState(initialLiked);
  const [likeCount, setLikeCount] = reactExports.useState(Number(likes ?? 0) || 0);
  const [likeBusy, setLikeBusy] = reactExports.useState(false);
  const [downloadBusy, setDownloadBusy] = reactExports.useState(false);
  const [hideBusy, setHideBusy] = reactExports.useState(false);
  const [dislikeBusy, setDislikeBusy] = reactExports.useState(false);
  const [dismissed, setDismissed] = reactExports.useState(false);
  const [collectionPickerOpen, setCollectionPickerOpen] = reactExports.useState(false);
  const [collectionOptionsLoading, setCollectionOptionsLoading] = reactExports.useState(false);
  const [collectionOptionsLoaded, setCollectionOptionsLoaded] = reactExports.useState(false);
  const [collectionOptions, setCollectionOptions] = reactExports.useState([]);
  const [collectionCreateUrl, setCollectionCreateUrl] = reactExports.useState("/settings/collections/create");
  const [collectionPickerError, setCollectionPickerError] = reactExports.useState("");
  const [collectionPickerNotice, setCollectionPickerNotice] = reactExports.useState("");
  const [attachingCollectionId, setAttachingCollectionId] = reactExports.useState(null);
  const openTrackedRef = reactExports.useRef(false);
  const primaryTag = reactExports.useMemo(() => {
    if (item?.primary_tag && typeof item.primary_tag === "object") {
      return item.primary_tag;
    }
    if (Array.isArray(item?.tags) && item.tags.length > 0) {
      return item.tags[0];
    }
    return null;
  }, [item.primary_tag, item.tags]);
  const hideArtworkEndpoint = item.hide_artwork_endpoint || item?.negative_feedback?.hide_artwork_endpoint || null;
  const dislikeTagEndpoint = item.dislike_tag_endpoint || item?.negative_feedback?.dislike_tag_endpoint || null;
  const canHideRecommendation = Boolean(item?.id && hideArtworkEndpoint && item?.recommendation_algo_version);
  const canDislikePrimaryTag = Boolean(dislikeTagEndpoint && item?.recommendation_algo_version && (primaryTag?.id || primaryTag?.slug));
  const authUserId = Number(inertiaProps?.auth?.user?.id ?? 0);
  const itemOwnerId = Number(item.author_id ?? rawAuthor?.id ?? item.user_id ?? item.creator?.id ?? 0);
  const canAddToCollection = Boolean(authUserId > 0 && Number(item.id ?? 0) > 0 && itemOwnerId > 0 && itemOwnerId === authUserId);
  const collectionOptionsEndpoint = canAddToCollection ? item.collection_options_endpoint || `/settings/collections/artworks/${item.id}/options` : null;
  reactExports.useEffect(() => {
    setLiked(Boolean(item.viewer?.is_liked));
    setLikeCount(Number(item.likes ?? item.favourites ?? 0) || 0);
    setDismissed(false);
    setCollectionPickerOpen(false);
    setCollectionOptionsLoading(false);
    setCollectionOptionsLoaded(false);
    setCollectionOptions([]);
    setCollectionPickerError("");
    setCollectionPickerNotice("");
    setAttachingCollectionId(null);
  }, [item.id, item.likes, item.favourites, item.viewer?.is_liked]);
  const articleData = reactExports.useMemo(() => ({
    "data-art-id": item.id ?? void 0,
    "data-art-url": href !== "#" ? href : void 0,
    "data-art-title": title,
    "data-art-img": image2
  }), [href, image2, item.id, title]);
  const handleOpen = () => {
    if (openTrackedRef.current) return;
    openTrackedRef.current = true;
    trackRecommendationFeedback(item, "click", {
      interaction_origin: "artwork-card-open",
      target_url: href
    });
  };
  const handleLike = async () => {
    if (!item.id || likeBusy) {
      onLike?.(item);
      return;
    }
    const nextState = !liked;
    setLikeBusy(true);
    setLiked(nextState);
    setLikeCount((current) => Math.max(0, current + (nextState ? 1 : -1)));
    try {
      const response = await fetch(`/api/artworks/${item.id}/like`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": getCsrfToken$b()
        },
        credentials: "same-origin",
        body: JSON.stringify({ state: nextState })
      });
      if (!response.ok) {
        throw new Error("like_request_failed");
      }
      if (nextState) {
        trackRecommendationFeedback(item, "favorite", {
          interaction_origin: "artwork-card-like"
        });
      }
      onLike?.(item);
    } catch {
      setLiked(!nextState);
      setLikeCount((current) => Math.max(0, current + (nextState ? -1 : 1)));
    } finally {
      setLikeBusy(false);
    }
  };
  const handleDownload = async (event) => {
    event.preventDefault();
    if (!item.id || downloadBusy) return;
    setDownloadBusy(true);
    try {
      trackRecommendationFeedback(item, "download", {
        interaction_origin: "artwork-card-download",
        target_url: downloadHref
      });
      const link2 = document.createElement("a");
      link2.href = downloadHref;
      link2.rel = "noopener noreferrer";
      document.body.appendChild(link2);
      link2.click();
      document.body.removeChild(link2);
    } catch {
      window.open(downloadHref, "_blank", "noopener,noreferrer");
    } finally {
      setDownloadBusy(false);
    }
  };
  const dismissArtwork = (kind) => {
    setDismissed(true);
    onDismissed?.(item, kind);
  };
  const handleHideArtwork = async (event) => {
    event.preventDefault();
    event.stopPropagation();
    if (!canHideRecommendation || hideBusy) return;
    setHideBusy(true);
    try {
      await sendFeedbackSignal(hideArtworkEndpoint, {
        artwork_id: Number(item.id),
        algo_version: item.recommendation_algo_version || item.algo_version || void 0,
        source: item.recommendation_source || "recommendation-card",
        meta: {
          gallery_type: item.recommendation_surface || item.gallery_type || "recommendation-surface",
          reason: item.recommendation_reason || null,
          primary_tag_slug: primaryTag?.slug || null,
          interaction_origin: "artwork-card-hide"
        }
      });
      dismissArtwork("hide-artwork");
    } catch {
    } finally {
      setHideBusy(false);
    }
  };
  const handleDislikePrimaryTag = async (event) => {
    event.preventDefault();
    event.stopPropagation();
    if (!canDislikePrimaryTag || dislikeBusy) return;
    setDislikeBusy(true);
    try {
      await sendFeedbackSignal(dislikeTagEndpoint, {
        tag_id: primaryTag?.id ? Number(primaryTag.id) : void 0,
        tag_slug: primaryTag?.slug || void 0,
        algo_version: item.recommendation_algo_version || item.algo_version || void 0,
        source: item.recommendation_source || "recommendation-card",
        meta: {
          artwork_id: Number(item.id),
          gallery_type: item.recommendation_surface || item.gallery_type || "recommendation-surface",
          reason: item.recommendation_reason || null,
          interaction_origin: "artwork-card-dislike-tag"
        }
      });
      dismissArtwork("dislike-tag");
    } catch {
    } finally {
      setDislikeBusy(false);
    }
  };
  const handleOpenCollectionPicker = async (event) => {
    event.preventDefault();
    event.stopPropagation();
    if (!collectionOptionsEndpoint || collectionOptionsLoading) return;
    setCollectionPickerOpen(true);
    setCollectionPickerError("");
    setCollectionPickerNotice("");
    if (collectionOptionsLoaded) {
      return;
    }
    setCollectionOptionsLoading(true);
    try {
      const payload = await requestJson$l(collectionOptionsEndpoint);
      setCollectionOptions(Array.isArray(payload?.data) ? payload.data : []);
      setCollectionCreateUrl(payload?.meta?.create_url || "/settings/collections/create");
      setCollectionOptionsLoaded(true);
    } catch (error) {
      setCollectionPickerError(error.message || "Unable to load collections.");
    } finally {
      setCollectionOptionsLoading(false);
    }
  };
  const handleAttachToCollection = async (collection) => {
    if (!collection?.attach_url || attachingCollectionId === collection.id) return;
    setAttachingCollectionId(collection.id);
    setCollectionPickerError("");
    setCollectionPickerNotice("");
    try {
      await requestJson$l(collection.attach_url, {
        method: "POST",
        body: { artwork_ids: [Number(item.id)] }
      });
      setCollectionOptions((current) => current.map((entry) => entry.id === collection.id ? { ...entry, already_attached: true, artworks_count: Number(entry.artworks_count || 0) + 1 } : entry));
      setCollectionPickerNotice(`Added to ${collection.title}.`);
    } catch (error) {
      const firstError = error?.payload?.errors ? Object.values(error.payload.errors).flat().find(Boolean) : null;
      setCollectionPickerError(firstError || error.message || "Unable to add artwork to collection.");
    } finally {
      setAttachingCollectionId(null);
    }
  };
  if (dismissed) {
    return null;
  }
  if (maturity.should_hide) {
    return null;
  }
  if (variant === "embed") {
    return /* @__PURE__ */ React.createElement(
      "article",
      {
        className: cx$6("group overflow-hidden rounded-xl border border-white/[0.08] bg-black/30 transition-colors hover:border-sky-500/30", articleClassName, className),
        style: articleStyle,
        ...articleData
      },
      /* @__PURE__ */ React.createElement(
        "a",
        {
          href,
          className: "flex gap-3 p-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80",
          "aria-label": `Open artwork: ${cardLabel}`,
          onClick: handleOpen
        },
        /* @__PURE__ */ React.createElement("div", { className: "h-16 w-20 shrink-0 overflow-hidden rounded-lg bg-white/5" }, /* @__PURE__ */ React.createElement(
          "img",
          {
            src: image2,
            srcSet: responsiveImageSrcSet,
            sizes: responsiveImageSizes,
            alt: title,
            loading,
            decoding,
            className: cx$6("h-full w-full object-cover transition-transform duration-300 group-hover:scale-105", shouldBlurMature ? "scale-[1.02] blur-xl" : ""),
            onError: (event) => {
              swapImageToFallbackOnce(event, IMAGE_FALLBACK);
            }
          }
        ), isMatureArtwork ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-2 bottom-2 rounded-lg border border-amber-300/20 bg-black/65 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Mature content") : null),
        /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-medium text-white/90" }, title), showAuthor && /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex items-center gap-2 text-xs text-slate-400" }, authorHref ? /* @__PURE__ */ React.createElement("span", null, "by ", author, " ", username ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "@", username) : null) : /* @__PURE__ */ React.createElement("span", null, "by ", author), authorLevel > 0 ? /* @__PURE__ */ React.createElement(LevelBadge, { level: authorLevel, rank: authorRank, compact: true }) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-[10px] uppercase tracking-wider text-slate-600" }, contentType || "Artwork"))
      )
    );
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "article",
    {
      className: cx$6("group relative", articleClassName, className),
      style: articleStyle,
      ...articleData
    },
    /* @__PURE__ */ React.createElement("div", { className: cx$6("relative overflow-hidden rounded-[1.6rem] border border-white/8 bg-slate-950/80 shadow-[0_18px_60px_rgba(2,6,23,0.45)] transition duration-300 ease-out group-hover:-translate-y-1 group-hover:scale-[1.02] group-hover:border-white/14 group-hover:shadow-[0_24px_80px_rgba(8,47,73,0.5)] group-focus-within:-translate-y-1 group-focus-within:scale-[1.02] group-focus-within:border-sky-200/40", frameClassName) }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href,
        "aria-label": `Open artwork: ${cardLabel}`,
        onClick: handleOpen,
        className: "absolute inset-0 z-10 rounded-[inherit] cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80"
      },
      /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, cardLabel)
    ), /* @__PURE__ */ React.createElement("div", { className: cx$6("relative overflow-hidden bg-slate-900", aspectClass, mediaClassName), style: mediaStyle }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top,_rgba(148,163,184,0.28),_transparent_52%),linear-gradient(180deg,rgba(15,23,42,0.08),rgba(15,23,42,0.42))]" }), /* @__PURE__ */ React.createElement(
      "img",
      {
        src: image2,
        srcSet: responsiveImageSrcSet,
        sizes: responsiveImageSizes,
        alt: title,
        width: imageWidth || void 0,
        height: imageHeight || void 0,
        loading,
        decoding,
        fetchPriority: fetchPriority || void 0,
        className: cx$6("h-full w-full object-cover transition duration-500 group-hover:scale-110 group-focus-within:scale-110", shouldBlurMature ? "scale-[1.02] blur-xl" : "", imageClassName),
        onError: (event) => {
          swapImageToFallbackOnce(event, IMAGE_FALLBACK, { clearResponsive: true });
        }
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-black/85 via-black/38 to-transparent opacity-90 transition duration-300 md:opacity-45 md:group-hover:opacity-100 md:group-focus-within:opacity-100" }), resolvedMetricBadge?.label || relativePublishedAt ? /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-20 flex items-start justify-between gap-3 p-3" }, /* @__PURE__ */ React.createElement("div", null, resolvedMetricBadge?.label ? /* @__PURE__ */ React.createElement(BadgePill, { className: resolvedMetricBadge.className || "bg-emerald-500/14 text-emerald-200 ring-emerald-400/30", iconClass: resolvedMetricBadge.iconClass }, resolvedMetricBadge.label) : null, isMatureArtwork ? /* @__PURE__ */ React.createElement(BadgePill, { className: "mt-2 bg-amber-500/16 text-amber-100 ring-amber-300/30", iconClass: "fa-solid fa-triangle-exclamation text-[10px]" }, "Mature content") : null), relativePublishedAt ? /* @__PURE__ */ React.createElement(BadgePill, { className: "bg-black/45 text-white/75 ring-white/12", iconClass: "fa-regular fa-clock text-[10px]" }, relativePublishedAt) : null) : null, showActions && /* @__PURE__ */ React.createElement("div", { className: cx$6(
      "absolute right-3 z-20 flex max-w-[14rem] flex-wrap justify-end translate-y-2 gap-2 opacity-100 transition duration-200 md:opacity-0 md:group-hover:translate-y-0 md:group-hover:opacity-100 md:group-focus-within:translate-y-0 md:group-focus-within:opacity-100",
      relativePublishedAt ? "top-12" : "top-3"
    ) }, /* @__PURE__ */ React.createElement(ActionButton, { label: liked ? "Unlike artwork" : "Like artwork", onClick: handleLike }, /* @__PURE__ */ React.createElement(HeartIcon, { className: cx$6("h-4 w-4 transition-transform duration-200", liked ? "fill-current text-rose-300" : "", likeBusy ? "scale-90" : "") })), /* @__PURE__ */ React.createElement(ActionLink$1, { href: downloadHref, label: downloadBusy ? "Downloading artwork" : "Download artwork", onClick: handleDownload }, /* @__PURE__ */ React.createElement(DownloadIcon, { className: cx$6("h-4 w-4", downloadBusy ? "animate-pulse text-emerald-300" : "") })), /* @__PURE__ */ React.createElement(ActionLink$1, { href, label: "View artwork" }, /* @__PURE__ */ React.createElement(ViewIcon, { className: "h-4 w-4" })), canAddToCollection ? /* @__PURE__ */ React.createElement(ActionButton, { label: "Add artwork to collection", onClick: handleOpenCollectionPicker }, /* @__PURE__ */ React.createElement(CollectionIcon, { className: "h-4 w-4" })) : null, canHideRecommendation ? /* @__PURE__ */ React.createElement(ActionButton, { label: hideBusy ? "Hiding artwork" : "Hide artwork", onClick: handleHideArtwork }, /* @__PURE__ */ React.createElement(HideIcon, { className: cx$6("h-4 w-4", hideBusy ? "animate-pulse text-amber-200" : "text-white/90") })) : null), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 backdrop-blur-[2px] opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100" }, shouldBlurMature ? /* @__PURE__ */ React.createElement("div", { className: "mb-2 inline-flex rounded-full border border-amber-300/20 bg-black/55 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your content settings") : null, /* @__PURE__ */ React.createElement("h3", { className: cx$6("truncate font-semibold text-white", titleClass) }, title), showAuthor ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-start justify-between gap-3 text-xs text-white/80" }, /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-start gap-3" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: avatar,
        alt: `Avatar of ${author}`,
        loading: "lazy",
        decoding: "async",
        className: "h-9 w-9 shrink-0 rounded-full object-cover",
        onError: (event) => {
          swapImageToFallbackOnce(event, AVATAR_FALLBACK);
        }
      }
    ), /* @__PURE__ */ React.createElement("span", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "block min-w-0 truncate text-sm font-medium text-white/90" }, author, username ? /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/60" }, " @", username) : null), authorLevel > 0 ? /* @__PURE__ */ React.createElement(LevelBadge, { level: authorLevel, rank: authorRank, compact: true, className: "shrink-0" }) : null), showStats && metadataLine && /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 block truncate text-[11px] text-white/70" }, metadataLine)))) : showStats && metadataLine ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-white/70" }, metadataLine) : null, canDislikePrimaryTag ? /* @__PURE__ */ React.createElement("div", { className: "pointer-events-auto mt-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: handleDislikePrimaryTag,
        className: "inline-flex items-center gap-1.5 rounded-full border border-white/12 bg-black/35 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/80 transition hover:border-amber-200/40 hover:bg-black/55 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80"
      },
      /* @__PURE__ */ React.createElement(TagIcon, { className: cx$6("h-3.5 w-3.5", dislikeBusy ? "animate-pulse text-amber-200" : "") }),
      dislikeBusy ? "Updating" : `Less of #${primaryTag?.slug || primaryTag?.name}`
    )) : null)))
  ), /* @__PURE__ */ React.createElement(
    CollectionPickerModal,
    {
      open: collectionPickerOpen,
      artworkTitle: title,
      collections: collectionOptions,
      loading: collectionOptionsLoading,
      error: collectionPickerError,
      notice: collectionPickerNotice,
      createUrl: collectionCreateUrl,
      attachingCollectionId,
      onAttach: handleAttachToCollection,
      onClose: () => setCollectionPickerOpen(false)
    }
  ));
}
function getCsrfToken$a() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function revokeDismissSignal(entry) {
  const item = entry?.item || null;
  const kind = entry?.kind || null;
  if (!item || !kind) {
    throw new Error("missing_dismiss_entry");
  }
  const endpoint = kind === "dislike-tag" ? item.dislike_tag_endpoint || item?.negative_feedback?.dislike_tag_endpoint : item.hide_artwork_endpoint || item?.negative_feedback?.hide_artwork_endpoint;
  if (!endpoint) {
    throw new Error("missing_revoke_endpoint");
  }
  const payload = kind === "dislike-tag" ? {
    tag_id: item?.primary_tag?.id ? Number(item.primary_tag.id) : void 0,
    tag_slug: item?.primary_tag?.slug || item?.primary_tag?.name || void 0,
    artwork_id: Number(item.id),
    algo_version: item?.recommendation_algo_version || item?.algo_version || void 0,
    meta: {
      gallery_type: item?.recommendation_surface || item?.gallery_type || "recommendation-surface",
      reason: item?.recommendation_reason || null,
      interaction_origin: "artwork-gallery-undo-dislike-tag"
    }
  } : {
    artwork_id: Number(item.id),
    algo_version: item?.recommendation_algo_version || item?.algo_version || void 0,
    meta: {
      gallery_type: item?.recommendation_surface || item?.gallery_type || "recommendation-surface",
      reason: item?.recommendation_reason || null,
      interaction_origin: "artwork-gallery-undo-hide"
    }
  };
  const response = await fetch(endpoint, {
    method: "DELETE",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$a(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: JSON.stringify(payload)
  });
  if (!response.ok) {
    throw new Error("revoke_request_failed");
  }
  return response.json().catch(() => null);
}
function cx$5(...parts) {
  return parts.filter(Boolean).join(" ");
}
function getArtworkKey(item, index2) {
  if (item?.id) return item.id;
  if (item?.title || item?.name || item?.author) {
    return `${item.title || item.name || "artwork"}-${item.author || item.author_name || item.uname || "artist"}-${index2}`;
  }
  return `artwork-${index2}`;
}
function DismissNotice({ notice, onUndo, onClose }) {
  if (!notice) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none fixed bottom-5 right-5 z-50 max-w-sm", "aria-live": "polite", "aria-atomic": "true" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-auto rounded-2xl border border-amber-300/30 bg-slate-950/92 px-4 py-3 text-amber-50 shadow-2xl shadow-black/40 backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] uppercase tracking-[0.2em] text-amber-100/70" }, "Discovery Feedback"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-medium" }, notice.message), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onUndo,
      disabled: notice.busy,
      className: "inline-flex items-center rounded-full border border-white/15 px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] text-white/85 transition hover:border-white/30 hover:text-white"
    },
    notice.busy ? "Undoing..." : "Undo"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClose,
      className: "inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] text-white/55 transition hover:text-white/85"
    },
    "Dismiss"
  ))));
}
function ArtworkGallery({
  items,
  layout = "grid",
  compact = false,
  showStats = true,
  showAuthor = true,
  className = "",
  cardClassName = "",
  limit,
  containerProps = {},
  resolveCardProps,
  children
}) {
  if (!Array.isArray(items) || items.length === 0) return null;
  const visibleItems = typeof limit === "number" ? items.slice(0, limit) : items;
  const [dismissedEntries, setDismissedEntries] = reactExports.useState([]);
  const [dismissNotice, setDismissNotice] = reactExports.useState(null);
  const visibleArtworkItems = reactExports.useMemo(
    () => visibleItems.filter((item) => !item?.maturity?.should_hide && !dismissedEntries.some((entry) => entry.item?.id === item?.id)),
    [dismissedEntries, visibleItems]
  );
  const baseClassName = layout === "masonry" ? "grid gap-6" : "grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5";
  reactExports.useEffect(() => {
    if (!dismissNotice) {
      return void 0;
    }
    const timeoutId = window.setTimeout(() => {
      setDismissNotice(null);
    }, 3200);
    return () => {
      window.clearTimeout(timeoutId);
    };
  }, [dismissNotice]);
  function handleDismissed(item, kind) {
    if (!item?.id) return;
    setDismissedEntries((current) => {
      const next = current.filter((entry) => entry.item?.id !== item.id);
      next.push({ item, kind });
      return next;
    });
    setDismissNotice({
      itemId: item.id,
      busy: false,
      message: kind === "dislike-tag" ? `We will show less content like #${item?.primary_tag?.slug || item?.primary_tag?.name || "this tag"}.` : "Artwork hidden from this recommendation view."
    });
  }
  async function handleUndoDismiss() {
    if (!dismissNotice?.itemId) {
      setDismissNotice(null);
      return;
    }
    const entry = dismissedEntries.find((current) => current.item?.id === dismissNotice.itemId);
    if (!entry) {
      setDismissNotice(null);
      return;
    }
    setDismissNotice((current) => current ? { ...current, busy: true } : current);
    try {
      await revokeDismissSignal(entry);
    } catch {
      setDismissNotice({
        itemId: entry.item.id,
        busy: false,
        message: "Undo failed. The feedback signal is still active."
      });
      return;
    }
    setDismissedEntries((current) => current.filter((entry2) => entry2.item?.id !== dismissNotice.itemId));
    setDismissNotice(null);
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: cx$5(baseClassName, className), ...containerProps }, visibleArtworkItems.map((item, index2) => {
    const cardProps = resolveCardProps?.(item, index2) || {};
    const { className: resolvedClassName = "", ...restCardProps } = cardProps;
    return /* @__PURE__ */ React.createElement(
      ArtworkCard$1,
      {
        key: getArtworkKey(item, index2),
        artwork: item,
        compact,
        showStats,
        showAuthor,
        className: cx$5(cardClassName, resolvedClassName),
        onDismissed: handleDismissed,
        ...restCardProps
      }
    );
  }), children), /* @__PURE__ */ React.createElement(DismissNotice, { notice: dismissNotice, onUndo: handleUndoDismiss, onClose: () => setDismissNotice(null) }));
}
function BoldIcon() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.5, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 4h8a4 4 0 0 1 0 8H6zM6 12h9a4 4 0 0 1 0 8H6z" }));
}
function ItalicIcon() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.5, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }));
}
function CodeIcon() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("polyline", { points: "16 18 22 12 16 6" }), /* @__PURE__ */ React.createElement("polyline", { points: "8 6 2 12 8 18" }));
}
function LinkIcon() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" }));
}
function ListIcon() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("line", { x1: "8", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "8", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "8", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "3", cy: "6", r: "1", fill: "currentColor", stroke: "none" }), /* @__PURE__ */ React.createElement("circle", { cx: "3", cy: "12", r: "1", fill: "currentColor", stroke: "none" }), /* @__PURE__ */ React.createElement("circle", { cx: "3", cy: "18", r: "1", fill: "currentColor", stroke: "none" }));
}
function QuoteIcon() {
  return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.176 11 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179zM15.583 17.321C14.553 16.227 14 15 14 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C20.591 11.68 22 13.176 22 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179z" }));
}
function ToolbarBtn({ title, onClick, children }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      title,
      onMouseDown: (event) => {
        event.preventDefault();
        onClick();
      },
      className: "flex h-7 w-7 items-center justify-center rounded-md text-white/40 transition-colors hover:bg-white/[0.08] hover:text-white/70"
    },
    children
  );
}
function CommentForm({ placeholder = "Write a comment…", submitLabel = "Post", onSubmit, onCancel, compact = false }) {
  const [content2, setContent] = reactExports.useState("");
  const [busy, setBusy] = reactExports.useState(false);
  const [error, setError] = reactExports.useState("");
  const [tab2, setTab] = reactExports.useState("write");
  const textareaRef = reactExports.useRef(null);
  const wrapSelection = reactExports.useCallback((before, after) => {
    const element2 = textareaRef.current;
    if (!element2) return;
    const start = element2.selectionStart;
    const end = element2.selectionEnd;
    const selected = content2.slice(start, end);
    const replacement = before + (selected || "text") + after;
    const next = content2.slice(0, start) + replacement + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      const cursorPos = selected ? start + replacement.length : start + before.length;
      const cursorEnd = selected ? start + replacement.length : start + before.length + 4;
      element2.selectionStart = cursorPos;
      element2.selectionEnd = cursorEnd;
      element2.focus();
    });
  }, [content2]);
  const prefixLines = reactExports.useCallback((prefix) => {
    const element2 = textareaRef.current;
    if (!element2) return;
    const start = element2.selectionStart;
    const end = element2.selectionEnd;
    const selected = content2.slice(start, end);
    const lines = selected ? selected.split("\n") : [""];
    const prefixed = lines.map((line) => prefix + line).join("\n");
    const next = content2.slice(0, start) + prefixed + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      element2.selectionStart = start;
      element2.selectionEnd = start + prefixed.length;
      element2.focus();
    });
  }, [content2]);
  const insertLink = reactExports.useCallback(() => {
    const element2 = textareaRef.current;
    if (!element2) return;
    const start = element2.selectionStart;
    const end = element2.selectionEnd;
    const selected = content2.slice(start, end);
    const isUrl2 = /^https?:\/\//.test(selected);
    const replacement = isUrl2 ? `[link](${selected})` : `[${selected || "link"}](https://)`;
    const next = content2.slice(0, start) + replacement + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      if (isUrl2) {
        element2.selectionStart = start + 1;
        element2.selectionEnd = start + 5;
      } else {
        const urlStart = start + replacement.length - 1;
        element2.selectionStart = urlStart - 8;
        element2.selectionEnd = urlStart - 1;
      }
      element2.focus();
    });
  }, [content2]);
  const insertAtCursor = reactExports.useCallback((text2) => {
    const element2 = textareaRef.current;
    if (!element2) {
      setContent((current) => current + text2);
      return;
    }
    const start = element2.selectionStart ?? content2.length;
    const end = element2.selectionEnd ?? content2.length;
    const next = content2.slice(0, start) + text2 + content2.slice(end);
    setContent(next);
    requestAnimationFrame(() => {
      element2.selectionStart = start + text2.length;
      element2.selectionEnd = start + text2.length;
      element2.focus();
    });
  }, [content2]);
  const handleKeyDown2 = reactExports.useCallback((event) => {
    const mod = event.ctrlKey || event.metaKey;
    if (!mod) return;
    switch (event.key.toLowerCase()) {
      case "b":
        event.preventDefault();
        wrapSelection("**", "**");
        break;
      case "i":
        event.preventDefault();
        wrapSelection("*", "*");
        break;
      case "k":
        event.preventDefault();
        insertLink();
        break;
      case "e":
        event.preventDefault();
        wrapSelection("`", "`");
        break;
    }
  }, [insertLink, wrapSelection]);
  const handleSubmit = async (event) => {
    event.preventDefault();
    const trimmed = content2.trim();
    if (!trimmed || busy) return;
    setBusy(true);
    setError("");
    try {
      await onSubmit?.(trimmed);
      setContent("");
      setTab("write");
    } catch (submitError) {
      setError(submitError?.message || "Unable to post comment.");
    } finally {
      setBusy(false);
    }
  };
  return /* @__PURE__ */ React.createElement("form", { className: "space-y-3", onSubmit: handleSubmit }, /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border border-white/[0.08] bg-white/[0.04] transition-all duration-200 focus-within:border-white/[0.12] focus-within:shadow-lg focus-within:shadow-black/20 ${compact ? "rounded-xl" : ""}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/[0.06] px-3 py-1.5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTab("write"),
      className: [
        "rounded-md px-3 py-1 text-xs font-medium transition-colors",
        tab2 === "write" ? "bg-white/[0.08] text-white" : "text-white/40 hover:text-white/60"
      ].join(" ")
    },
    "Write"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTab("preview"),
      className: [
        "rounded-md px-3 py-1 text-xs font-medium transition-colors",
        tab2 === "preview" ? "bg-white/[0.08] text-white" : "text-white/40 hover:text-white/60"
      ].join(" ")
    },
    "Preview"
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ React.createElement(
    "span",
    {
      className: [
        "text-[11px] tabular-nums font-medium transition-colors",
        content2.length > 9e3 ? "text-amber-400/80" : "text-white/20"
      ].join(" ")
    },
    content2.length > 0 && `${content2.length.toLocaleString()}/10,000`
  ), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: insertAtCursor, disabled: busy }))), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 border-b border-white/[0.04] px-3 py-1" }, /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, /* @__PURE__ */ React.createElement(BoldIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, /* @__PURE__ */ React.createElement(ItalicIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, /* @__PURE__ */ React.createElement(CodeIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Link (Ctrl+K)", onClick: insertLink }, /* @__PURE__ */ React.createElement(LinkIcon, null)), /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-4 w-px bg-white/[0.08]" }), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Bulleted list", onClick: () => prefixLines("- ") }, /* @__PURE__ */ React.createElement(ListIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Quote", onClick: () => prefixLines("> ") }, /* @__PURE__ */ React.createElement(QuoteIcon, null))), tab2 === "write" && /* @__PURE__ */ React.createElement(
    "textarea",
    {
      ref: textareaRef,
      value: content2,
      onChange: (event) => setContent(event.target.value),
      onKeyDown: handleKeyDown2,
      rows: compact ? 3 : 4,
      maxLength: 1e4,
      placeholder,
      disabled: busy,
      className: "w-full resize-none bg-transparent px-4 py-3 text-sm leading-relaxed text-white/90 placeholder-white/35 outline-none transition disabled:opacity-50"
    }
  ), tab2 === "preview" && /* @__PURE__ */ React.createElement("div", { className: "min-h-[7rem] px-4 py-3" }, content2.trim() ? /* @__PURE__ */ React.createElement("div", { className: "prose prose-invert prose-sm max-w-none text-[13px] leading-relaxed text-white/80 [&_a]:text-accent [&_a]:no-underline hover:[&_a]:underline [&_code]:rounded [&_code]:bg-white/[0.08] [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:text-[12px] [&_code]:text-amber-300/80 [&_blockquote]:border-l-2 [&_blockquote]:border-accent/40 [&_blockquote]:pl-3 [&_blockquote]:text-white/50 [&_ul]:list-disc [&_ul]:pl-4 [&_ol]:list-decimal [&_ol]:pl-4 [&_li]:text-white/70 [&_strong]:text-white [&_em]:text-white/70 [&_p]:mb-2 [&_p:last-child]:mb-0" }, /* @__PURE__ */ React.createElement(
    Markdown,
    {
      allowedElements: ["p", "strong", "em", "a", "code", "pre", "ul", "ol", "li", "blockquote", "br"],
      unwrapDisallowed: true,
      components: {
        a: ({ href, children }) => /* @__PURE__ */ React.createElement("a", { href, target: "_blank", rel: "noopener noreferrer nofollow" }, children)
      }
    },
    content2
  )) : /* @__PURE__ */ React.createElement("p", { className: "text-sm italic text-white/25" }, "Nothing to preview")), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "px-4 pb-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-white/15" }, "Markdown supported · ", /* @__PURE__ */ React.createElement("kbd", { className: "rounded bg-white/[0.06] px-1 py-0.5 text-[10px] text-white/25" }, "Ctrl+B"), " bold · ", /* @__PURE__ */ React.createElement("kbd", { className: "rounded bg-white/[0.06] px-1 py-0.5 text-[10px] text-white/25" }, "Ctrl+I"), " italic · ", /* @__PURE__ */ React.createElement("kbd", { className: "rounded bg-white/[0.06] px-1 py-0.5 text-[10px] text-white/25" }, "Ctrl+K"), " link"))), error ? /* @__PURE__ */ React.createElement("p", { className: "text-sm text-rose-300" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs text-white/35" }, "Use emoji and markdown to match the rest of the site."), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, onCancel ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onCancel,
      className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white"
    },
    "Cancel"
  ) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: busy || content2.trim().length === 0,
      className: "rounded-full bg-sky-500 px-4 py-2 text-sm font-semibold text-white transition hover:bg-sky-400 disabled:cursor-not-allowed disabled:opacity-60"
    },
    busy ? "Posting…" : submitLabel
  ))));
}
function CommentItem$2({ comment, canReply, onReply, onDelete, onReport }) {
  const [replying, setReplying] = reactExports.useState(false);
  return /* @__PURE__ */ React.createElement("article", { id: `story-comment-${comment.id}`, className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: comment.user?.avatar_url || "https://files.skinbase.org/default/avatar_default.webp",
      alt: comment.user?.display || "User",
      className: "h-10 w-10 rounded-full object-cover ring-1 ring-white/10"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, comment.user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: comment.user.profile_url, className: "text-sm font-semibold text-white hover:text-sky-300" }, comment.user.display) : /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, comment.user?.display || "User"), /* @__PURE__ */ React.createElement(LevelBadge, { level: comment.user?.level, rank: comment.user?.rank, compact: true }), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.16em] text-white/30" }, comment.time_ago)), /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "prose prose-invert prose-sm mt-2 max-w-none text-white/80 prose-p:my-1.5 prose-a:text-sky-300",
      dangerouslySetInnerHTML: { __html: comment.rendered_content || "" }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3 text-xs text-white/45" }, canReply ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setReplying((value) => !value), className: "transition hover:text-white" }, "Reply") : null, comment.can_delete ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onDelete?.(comment.id), className: "transition hover:text-rose-300" }, "Delete") : null, comment.can_report ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onReport?.(comment), className: "transition hover:text-amber-300" }, "Report") : null), replying ? /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement(
    CommentForm,
    {
      compact: true,
      placeholder: `Reply to ${comment.user?.display || "user"}…`,
      submitLabel: "Reply",
      onCancel: () => setReplying(false),
      onSubmit: async (content2) => {
        await onReply?.(comment.id, content2);
        setReplying(false);
      }
    }
  )) : null, Array.isArray(comment.replies) && comment.replies.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 border-l border-white/[0.08] pl-4" }, comment.replies.map((reply) => /* @__PURE__ */ React.createElement(CommentItem$2, { key: reply.id, comment: reply, canReply, onReply, onDelete, onReport }))) : null)));
}
function CommentList({ comments = [], canReply = false, onReply, onDelete, onReport, emptyMessage = "No comments yet." }) {
  if (!comments.length) {
    return /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/45" }, emptyMessage);
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, comments.map((comment) => /* @__PURE__ */ React.createElement(CommentItem$2, { key: comment.id, comment, canReply, onReply, onDelete, onReport })));
}
function getCsrfToken$9() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$k(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$9(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed.");
  }
  return payload;
}
function TypeBadge({ collection }) {
  const label = collection?.type === "editorial" ? "Editorial" : collection?.type === "community" ? "Community" : "Personal";
  return /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, label);
}
const COLLABORATOR_ROLE_COLORS = {
  owner: "border-amber-300/20 bg-amber-400/10 text-amber-200",
  moderator: "border-sky-300/20 bg-sky-400/10 text-sky-200",
  contributor: "border-emerald-300/20 bg-emerald-400/10 text-emerald-200",
  curator: "border-violet-300/20 bg-violet-400/10 text-violet-200"
};
function CollaboratorCard({ member }) {
  const roleColor = COLLABORATOR_ROLE_COLORS[String(member?.role || "").toLowerCase()] ?? "border-white/10 bg-white/[0.05] text-slate-300";
  return /* @__PURE__ */ React.createElement("a", { href: member?.user?.profile_url || "#", className: "group flex items-center gap-4 rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 transition hover:border-white/20 hover:bg-white/[0.07]" }, member?.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member?.user?.name || member?.user?.username, className: "h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10 transition group-hover:ring-sky-400/30" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white group-hover:text-sky-100" }, member?.user?.name || member?.user?.username), member?.user?.username ? /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "@", member.user.username) : null), /* @__PURE__ */ React.createElement("span", { className: `shrink-0 rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] ${roleColor}` }, member?.role, member?.status === "pending" ? " · invited" : ""));
}
function SubmissionCard({ submission, onApprove, onReject, onWithdraw, onReport }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, submission?.artwork?.thumb ? /* @__PURE__ */ React.createElement("img", { src: submission.artwork.thumb, alt: submission.artwork.title, className: "h-20 w-20 rounded-2xl object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, submission?.artwork?.title || "Artwork submission"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, submission?.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, "Submitted by @", submission?.user?.username), submission?.message ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, submission.message) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, submission?.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApprove?.(submission), className: "rounded-full border border-emerald-400/20 bg-emerald-400/10 px-3 py-2 text-xs font-semibold text-emerald-100" }, "Approve") : null, submission?.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onReject?.(submission), className: "rounded-full border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold text-rose-100" }, "Reject") : null, submission?.can_withdraw ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onWithdraw?.(submission), className: "rounded-full border border-white/12 bg-white/[0.05] px-3 py-2 text-xs font-semibold text-white" }, "Withdraw") : null, submission?.can_report ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onReport?.(submission), className: "rounded-full border border-white/12 bg-white/[0.05] px-3 py-2 text-xs font-semibold text-white" }, "Report") : null))));
}
const HERO_ACTION_TONES = {
  neutral: {
    idle: "border-white/10 bg-white/[0.05] text-white hover:border-white/20 hover:bg-white/[0.09]",
    active: "border-white/15 bg-[linear-gradient(135deg,rgba(255,255,255,0.12),rgba(255,255,255,0.04))] text-white shadow-[0_18px_40px_rgba(2,6,23,0.18)]",
    icon: "border-white/10 bg-white/[0.08] text-slate-200",
    iconActive: "border-white/15 bg-white/[0.12] text-white"
  },
  rose: {
    idle: "border-white/10 bg-white/[0.05] text-white hover:border-rose-400/30 hover:bg-rose-400/[0.12] hover:text-rose-100",
    active: "border-rose-400/30 bg-[linear-gradient(135deg,rgba(244,63,94,0.18),rgba(255,255,255,0.06))] text-rose-50 shadow-[0_18px_40px_rgba(244,63,94,0.14)]",
    icon: "border-rose-300/15 bg-rose-400/[0.08] text-rose-200",
    iconActive: "border-rose-300/30 bg-rose-400/[0.16] text-rose-50"
  },
  emerald: {
    idle: "border-white/10 bg-white/[0.05] text-white hover:border-emerald-400/30 hover:bg-emerald-400/[0.12] hover:text-emerald-100",
    active: "border-emerald-400/30 bg-[linear-gradient(135deg,rgba(52,211,153,0.18),rgba(255,255,255,0.06))] text-emerald-50 shadow-[0_18px_40px_rgba(52,211,153,0.14)]",
    icon: "border-emerald-300/15 bg-emerald-400/[0.08] text-emerald-200",
    iconActive: "border-emerald-300/30 bg-emerald-400/[0.16] text-emerald-50"
  },
  violet: {
    idle: "border-white/10 bg-white/[0.05] text-white hover:border-violet-400/30 hover:bg-violet-400/[0.12] hover:text-violet-100",
    active: "border-violet-400/30 bg-[linear-gradient(135deg,rgba(167,139,250,0.18),rgba(255,255,255,0.06))] text-violet-50 shadow-[0_18px_40px_rgba(167,139,250,0.14)]",
    icon: "border-violet-300/15 bg-violet-400/[0.08] text-violet-200",
    iconActive: "border-violet-300/30 bg-violet-400/[0.16] text-violet-50"
  },
  sky: {
    idle: "border-white/10 bg-white/[0.05] text-white hover:border-sky-400/30 hover:bg-sky-400/[0.12] hover:text-sky-100",
    active: "border-sky-400/30 bg-[linear-gradient(135deg,rgba(56,189,248,0.18),rgba(255,255,255,0.06))] text-sky-50 shadow-[0_18px_40px_rgba(56,189,248,0.14)]",
    icon: "border-sky-300/15 bg-sky-400/[0.08] text-sky-200",
    iconActive: "border-sky-300/30 bg-sky-400/[0.16] text-sky-50"
  },
  amber: {
    idle: "border-white/10 bg-white/[0.05] text-white hover:border-amber-400/30 hover:bg-amber-400/[0.12] hover:text-amber-100",
    active: "border-amber-400/30 bg-[linear-gradient(135deg,rgba(251,191,36,0.18),rgba(255,255,255,0.06))] text-amber-50 shadow-[0_18px_40px_rgba(251,191,36,0.14)]",
    icon: "border-amber-300/15 bg-amber-400/[0.08] text-amber-200",
    iconActive: "border-amber-300/30 bg-amber-400/[0.16] text-amber-50"
  }
};
function CollectionHeroAction({ href = null, onClick = null, icon, label, tone = "neutral", active = false, disabled = false, compact = false }) {
  const toneClasses2 = HERO_ACTION_TONES[tone] ?? HERO_ACTION_TONES.neutral;
  const Component = href ? "a" : "button";
  const componentProps = href ? { href } : { type: "button", onClick, disabled };
  return /* @__PURE__ */ React.createElement(
    Component,
    {
      ...componentProps,
      className: `group inline-flex items-center justify-center gap-3 rounded-[20px] border px-4 ${compact ? "py-3" : "py-3.5"} text-sm font-semibold tracking-[-0.01em] transition duration-200 ${active ? toneClasses2.active : toneClasses2.idle} ${disabled ? "cursor-not-allowed opacity-60" : ""}`
    },
    /* @__PURE__ */ React.createElement("span", { className: `flex h-9 w-9 items-center justify-center rounded-2xl border transition ${active ? toneClasses2.iconActive : toneClasses2.icon}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-sm` })),
    /* @__PURE__ */ React.createElement("span", null, label)
  );
}
const HERO_METRIC_TONES = {
  sky: {
    icon: "text-sky-200",
    chip: "border-sky-300/20 bg-sky-400/[0.12]",
    glow: "from-sky-400/35",
    orb: "bg-sky-400/20"
  },
  rose: {
    icon: "text-rose-200",
    chip: "border-rose-300/20 bg-rose-400/[0.12]",
    glow: "from-rose-400/35",
    orb: "bg-rose-400/20"
  },
  emerald: {
    icon: "text-emerald-200",
    chip: "border-emerald-300/20 bg-emerald-400/[0.12]",
    glow: "from-emerald-400/35",
    orb: "bg-emerald-400/20"
  },
  violet: {
    icon: "text-violet-200",
    chip: "border-violet-300/20 bg-violet-400/[0.12]",
    glow: "from-violet-400/35",
    orb: "bg-violet-400/20"
  },
  amber: {
    icon: "text-amber-200",
    chip: "border-amber-300/20 bg-amber-400/[0.12]",
    glow: "from-amber-400/35",
    orb: "bg-amber-400/20"
  },
  slate: {
    icon: "text-slate-200",
    chip: "border-white/10 bg-white/[0.08]",
    glow: "from-white/20",
    orb: "bg-white/[0.12]"
  }
};
function HeroMetricCard({ icon, label, value, helper = null, tone = "slate" }) {
  const style = HERO_METRIC_TONES[tone] ?? HERO_METRIC_TONES.slate;
  return /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[26px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(15,23,42,0.32))] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[2px] bg-gradient-to-r ${style.glow} via-transparent to-transparent` }), /* @__PURE__ */ React.createElement("div", { className: `absolute -right-5 top-3 h-14 w-14 rounded-full blur-2xl ${style.orb}` }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex h-11 w-11 items-center justify-center rounded-2xl border ${style.chip}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-base ${style.icon}` })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-[2rem] font-black leading-none tracking-[-0.04em] text-white" }, value), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, label), helper ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, helper) : null));
}
function HeroSignalCard({ icon, label, value, description = null, tone = "slate" }) {
  const style = HERO_METRIC_TONES[tone] ?? HERO_METRIC_TONES.slate;
  return /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[24px] border border-white/10 bg-[linear-gradient(135deg,rgba(255,255,255,0.06),rgba(15,23,42,0.32))] p-4 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[2px] bg-gradient-to-r ${style.glow} via-transparent to-transparent` }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: `mt-0.5 flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border ${style.chip}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-base ${style.icon}` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-2xl font-black tracking-[-0.04em] text-white" }, value), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-relaxed text-slate-400" }, description) : null)));
}
function getSpotlightClasses(style) {
  switch (style) {
    case "editorial":
      return "border-amber-300/20 bg-[linear-gradient(135deg,rgba(120,53,15,0.45),rgba(2,6,23,0.82))] text-amber-50";
    case "seasonal":
      return "border-emerald-300/20 bg-[linear-gradient(135deg,rgba(6,78,59,0.5),rgba(2,6,23,0.82))] text-emerald-50";
    case "challenge":
      return "border-fuchsia-300/20 bg-[linear-gradient(135deg,rgba(112,26,117,0.48),rgba(2,6,23,0.82))] text-fuchsia-50";
    case "community":
      return "border-sky-300/20 bg-[linear-gradient(135deg,rgba(3,105,161,0.45),rgba(2,6,23,0.82))] text-sky-50";
    default:
      return "border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.9),rgba(30,41,59,0.72))] text-white";
  }
}
function EmptyCollectionState({ isOwner, smart = false }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] px-6 py-14 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-20 w-20 items-center justify-center rounded-[24px] border border-white/12 bg-white/[0.06] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${smart ? "fa-wand-magic-sparkles" : "fa-images"} text-3xl` })), /* @__PURE__ */ React.createElement("h2", { className: "mt-5 text-2xl font-semibold text-white" }, "This collection is still taking shape"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-lg text-sm leading-relaxed text-slate-300" }, isOwner ? smart ? "Adjust the smart rules to broaden the match or publish more artworks that fit this set." : "Add artworks to start building the visual rhythm, cover image, and sequence for this showcase." : smart ? "This smart collection does not have visible matches right now." : "There are no visible artworks in this collection right now."));
}
function OwnerCard({ owner, collectionType }) {
  const label = owner?.is_system ? "Editorial Owner" : collectionType === "editorial" ? "Editorial Curator" : "Curator";
  const body2 = /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "relative shrink-0" }, owner?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: owner.avatar_url, alt: owner?.name || owner?.username, className: "h-14 w-14 rounded-2xl object-cover ring-2 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.06] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-astronaut text-xl" })), /* @__PURE__ */ React.createElement("div", { className: "absolute -bottom-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full border border-white/10 bg-sky-500 text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-nib text-[8px]" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-lg font-semibold text-white" }, owner?.name || owner?.username || "Skinbase Curator"), owner?.username ? /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "@", owner.username) : null), owner?.profile_url ? /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square ml-auto shrink-0 text-slate-500 text-sm" }) : null);
  if (owner?.profile_url) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-7 overflow-hidden rounded-[26px] border border-white/10 bg-[linear-gradient(135deg,rgba(255,255,255,0.06),rgba(15,23,42,0.34))] shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] transition hover:border-sky-400/25 hover:bg-[linear-gradient(135deg,rgba(255,255,255,0.08),rgba(15,23,42,0.4))]" }, /* @__PURE__ */ React.createElement("div", { className: "h-[2px] bg-gradient-to-r from-sky-400/55 via-sky-400/20 to-transparent" }), /* @__PURE__ */ React.createElement("a", { href: owner.profile_url, className: "block px-5 py-4" }, body2));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-7 overflow-hidden rounded-[26px] border border-white/10 bg-[linear-gradient(135deg,rgba(255,255,255,0.06),rgba(15,23,42,0.34))] shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("div", { className: "h-[2px] bg-gradient-to-r from-sky-400/55 via-sky-400/20 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "px-5 py-4" }, body2));
}
function PageSection({ eyebrow, title, count, icon, children }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, icon && /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.05] text-sky-300" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-sm` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, eyebrow), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, title))), count !== void 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, count) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children));
}
function EntityLinkCard({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item?.url || "#", className: "flex h-full flex-col gap-4 rounded-[24px] border border-white/10 bg-white/[0.04] p-5 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, item?.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item?.title, className: "h-16 w-16 rounded-[18px] object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center rounded-[18px] border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-diagram-project" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "truncate text-lg font-semibold text-white" }, item?.title), item?.meta ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.meta) : null), item?.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, item.subtitle) : null, item?.relationship_type ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-200/80" }, item.relationship_type) : null)), item?.description ? /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-relaxed text-slate-300" }, item.description) : null);
}
function CollectionCover({ collection }) {
  const coverImage = collection?.cover_image;
  const coverMaturity = collection?.cover_image_maturity || null;
  const shouldBlur = Boolean(coverMaturity?.should_blur);
  const isMature = Boolean(coverMaturity?.is_mature_effective);
  if (!coverImage) {
    return /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[16/10] items-center justify-center bg-[linear-gradient(135deg,#08111f,#0f172a,#08111f)] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-5xl" }));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("img", { src: coverImage, alt: collection?.title, className: `aspect-[16/10] h-full w-full object-cover ${shouldBlur ? "scale-[1.02] blur-xl" : ""}` }), isMature ? /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Mature cover") : null, shouldBlur ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-4 bottom-4 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-center text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your settings") : null);
}
function humanizeToken(value) {
  return String(value || "").replaceAll("_", " ").replaceAll("-", " ").replace(/\b\w/g, (match) => match.toUpperCase());
}
function groupEntityLinks(items) {
  return (Array.isArray(items) ? items : []).reduce((groups, item) => {
    const key = item?.linked_type || "other";
    if (!groups[key]) groups[key] = [];
    groups[key].push(item);
    return groups;
  }, {});
}
function recommendationReasons(currentCollection, candidate) {
  const reasons = [];
  if (candidate?.event_key && currentCollection?.event_key && candidate.event_key === currentCollection.event_key) {
    reasons.push("Same event context");
  }
  if (candidate?.campaign_key && currentCollection?.campaign_key && candidate.campaign_key === currentCollection.campaign_key) {
    reasons.push("Same campaign");
  }
  if (candidate?.theme_token && currentCollection?.theme_token && candidate.theme_token === currentCollection.theme_token) {
    reasons.push("Shared theme");
  }
  if (candidate?.type && currentCollection?.type && candidate.type === currentCollection.type) {
    reasons.push(`${humanizeToken(candidate.type)} collection`);
  }
  if (candidate?.owner?.id && currentCollection?.owner?.id && candidate.owner.id === currentCollection.owner.id) {
    reasons.push("Same curator");
  }
  if (candidate?.trust_tier && currentCollection?.trust_tier && candidate.trust_tier === currentCollection.trust_tier) {
    reasons.push(`${humanizeToken(candidate.trust_tier)} trust tier`);
  }
  return reasons.slice(0, 3);
}
const CONTEXT_SIGNAL_TYPES = {
  Campaign: { icon: "fa-solid fa-bullhorn", accent: "border-orange-300/20 from-orange-400/50", badge: "border-orange-300/20 bg-orange-400/10 text-orange-200", kicker: "text-orange-300/80" },
  Event: { icon: "fa-solid fa-calendar-star", accent: "border-sky-300/20 from-sky-400/50", badge: "border-sky-300/20 bg-sky-400/10 text-sky-200", kicker: "text-sky-300/80" },
  Program: { icon: "fa-solid fa-layer-group", accent: "border-violet-300/20 from-violet-400/50", badge: "border-violet-300/20 bg-violet-400/10 text-violet-200", kicker: "text-violet-300/80" },
  Theme: { icon: "fa-solid fa-palette", accent: "border-teal-300/20 from-teal-400/50", badge: "border-teal-300/20 bg-teal-400/10 text-teal-200", kicker: "text-teal-300/80" },
  "Quality Tier": { icon: "fa-solid fa-gauge-high", accent: "border-amber-300/20 from-amber-400/50", badge: "border-amber-300/20 bg-amber-400/10 text-amber-200", kicker: "text-amber-300/80" }
};
function ContextSignalCard({ item }) {
  const typeStyle = CONTEXT_SIGNAL_TYPES[item.meta] ?? { icon: "fa-solid fa-circle-info", accent: "border-white/10 from-slate-400/30", badge: "border-white/10 bg-white/[0.05] text-slate-300", kicker: "text-sky-200/80" };
  const wrapperClassName = `relative overflow-hidden flex h-full flex-col gap-3 rounded-[24px] border ${typeStyle.accent.split(" ")[0]} bg-white/[0.04] p-5 transition hover:bg-white/[0.07]`;
  const body2 = /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[2px] bg-gradient-to-r ${typeStyle.accent.split(" ")[1]} via-transparent to-transparent` }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: `flex h-8 w-8 items-center justify-center rounded-xl border ${typeStyle.badge}` }, /* @__PURE__ */ React.createElement("i", { className: `${typeStyle.icon} text-[11px]` })), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${typeStyle.badge}` }, item.meta)), item.kicker ? /* @__PURE__ */ React.createElement("span", { className: `text-[11px] font-semibold uppercase tracking-[0.16em] ${typeStyle.kicker}` }, item.kicker) : null), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, item.subtitle) : null), item.description ? /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-relaxed text-slate-300" }, item.description) : null);
  if (item.url) {
    return /* @__PURE__ */ React.createElement("a", { href: item.url, className: wrapperClassName }, body2);
  }
  return /* @__PURE__ */ React.createElement("div", { className: wrapperClassName }, body2);
}
function CollectionShow() {
  const { props } = X$1();
  const {
    collection: initialCollection,
    artworks,
    owner,
    isOwner,
    manageUrl,
    editUrl,
    analyticsUrl,
    historyUrl,
    profileCollectionsUrl,
    featuredCollectionsUrl,
    engagement,
    seo,
    members: initialMembers,
    comments: initialComments,
    submissions: initialSubmissions,
    entityLinks,
    relatedCollections,
    commentsEndpoint,
    submitEndpoint,
    submissionArtworkOptions,
    seriesContext,
    canSubmit,
    canComment,
    reportEndpoint
  } = props;
  const [collection, setCollection] = React.useState(initialCollection);
  const [comments, setComments] = React.useState(initialComments || []);
  const [submissions, setSubmissions] = React.useState(initialSubmissions || []);
  const [selectedArtworkId, setSelectedArtworkId] = React.useState(submissionArtworkOptions?.[0]?.id || "");
  const [state, setState] = React.useState({
    liked: Boolean(engagement?.liked),
    following: Boolean(engagement?.following),
    saved: Boolean(engagement?.saved),
    notice: "",
    busy: false
  });
  const artworkItems = artworks?.data ?? [];
  const creatorIds = Array.from(new Set(artworkItems.map((artwork) => artwork?.author?.id).filter(Boolean)));
  const featuringCreatorsCount = creatorIds.length;
  const showArtworkAuthors = collection?.type !== "personal" || featuringCreatorsCount > 1;
  const enabledModules = Array.isArray(collection?.layout_modules) ? collection.layout_modules.filter((module) => module?.enabled !== false) : [];
  const enabledModuleKeys = new Set(enabledModules.map((module) => module?.key).filter(Boolean));
  const showIntroBlock = enabledModuleKeys.size === 0 || enabledModuleKeys.has("intro_block");
  const metaOwnerName = owner?.name || owner?.username || collection?.owner?.name || "Skinbase Curator";
  const metaTitle = seo?.title || `${collection?.title} — Skinbase`;
  const metaDescription = seo?.description || collection?.summary || collection?.description || "";
  const collectionSchema = seo?.canonical ? {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: collection?.title,
    description: metaDescription,
    url: seo.canonical,
    image: seo?.og_image || collection?.cover_image || void 0,
    isPartOf: {
      "@type": "WebSite",
      name: "Skinbase",
      url: typeof window !== "undefined" ? window.location.origin : void 0
    },
    author: owner ? {
      "@type": "Person",
      name: metaOwnerName,
      url: owner.profile_url
    } : void 0,
    keywords: [collection?.type, collection?.mode, collection?.badge_label].filter(Boolean).join(", ") || void 0,
    mainEntity: {
      "@type": "ItemList",
      numberOfItems: collection?.artworks_count || artworkItems.length || 0,
      itemListElement: artworkItems.slice(0, 12).map((artwork, index2) => ({
        "@type": "ListItem",
        position: index2 + 1,
        url: artwork.url,
        name: artwork.title
      }))
    }
  } : null;
  const [members] = React.useState(initialMembers || []);
  const spotlightClasses = getSpotlightClasses(collection?.spotlight_style);
  const groupedEntityLinks = groupEntityLinks(entityLinks);
  const storyLinks = groupedEntityLinks.story || [];
  const taxonomyLinks = [...groupedEntityLinks.category || [], ...groupedEntityLinks.tag || []];
  const contributorLinks = [...groupedEntityLinks.creator || [], ...groupedEntityLinks.artwork || []];
  const linkedContextSignals = [
    ...(groupedEntityLinks.campaign || []).map((item) => ({
      meta: item.meta || "Campaign",
      kicker: item.relationship_type || "Linked campaign",
      title: item.title,
      subtitle: item.subtitle,
      description: item.description,
      url: item.url
    })),
    ...(groupedEntityLinks.event || []).map((item) => ({
      meta: item.meta || "Event",
      kicker: item.relationship_type || "Linked event",
      title: item.title,
      subtitle: item.subtitle,
      description: item.description,
      url: item.url
    }))
  ];
  const contextSignals = [
    collection?.campaign_key ? {
      meta: "Campaign",
      kicker: "Discover surface",
      title: collection.campaign_label || humanizeToken(collection.campaign_key),
      subtitle: collection.campaign_key,
      description: "This collection is programmed into a campaign surface and can be explored alongside other campaign-ready sets.",
      url: `/collections/campaigns/${encodeURIComponent(collection.campaign_key)}`
    } : null,
    collection?.program_key ? {
      meta: "Program",
      kicker: "Partner context",
      title: humanizeToken(collection.program_key),
      subtitle: collection.partner_label || collection.partner_key || "Collection program",
      description: "This collection is attached to a program or partner-ready surface, which affects how it is grouped and surfaced.",
      url: `/collections/program/${encodeURIComponent(collection.program_key)}`
    } : null,
    collection?.event_label || collection?.event_key ? {
      meta: "Event",
      kicker: "Seasonal context",
      title: collection.event_label || humanizeToken(collection.event_key),
      subtitle: collection.season_key ? `Season ${humanizeToken(collection.season_key)}` : "Event-linked collection",
      description: "This collection is tied to an event or seasonal programming window, so related recommendations favor matching event context.",
      url: null
    } : null,
    collection?.theme_token ? {
      meta: "Theme",
      kicker: "Visual language",
      title: humanizeToken(collection.theme_token),
      subtitle: collection.presentation_style ? `Presentation ${humanizeToken(collection.presentation_style)}` : null,
      description: "Theme and presentation signals help similar collections cluster together in discovery and recommendation surfaces.",
      url: `/collections/search?theme=${encodeURIComponent(collection.theme_token)}`
    } : null,
    collection?.trust_tier ? {
      meta: "Quality Tier",
      kicker: "Placement signal",
      title: humanizeToken(collection.trust_tier),
      subtitle: collection?.quality_score != null ? `Quality score ${Number(collection.quality_score).toFixed(1)}` : null,
      description: "Trust tier and quality score shape how aggressively this collection can be used in premium or partner-facing placements.",
      url: `/collections/search?quality_tier=${encodeURIComponent(collection.trust_tier)}`
    } : null,
    ...linkedContextSignals
  ].filter(Boolean).filter((item, index2, items) => {
    const key = `${item.meta}:${item.title}:${item.subtitle || ""}`;
    return items.findIndex((candidate) => `${candidate.meta}:${candidate.title}:${candidate.subtitle || ""}` === key) === index2;
  });
  const heroMetrics = [
    {
      icon: "fa-images",
      label: "Artworks",
      value: (collection?.artworks_count ?? 0).toLocaleString(),
      helper: showArtworkAuthors && featuringCreatorsCount > 1 ? `${featuringCreatorsCount} creators featured` : collection?.mode === "smart" ? "Matched works" : "Published pieces",
      tone: "sky"
    },
    {
      icon: "fa-heart",
      label: "Likes",
      value: (collection?.likes_count ?? 0).toLocaleString(),
      helper: "Community response",
      tone: "rose"
    },
    {
      icon: "fa-bell",
      label: "Followers",
      value: (collection?.followers_count ?? 0).toLocaleString(),
      helper: "Watching updates",
      tone: "emerald"
    },
    {
      icon: "fa-eye",
      label: "Views",
      value: (collection?.views_count ?? 0).toLocaleString(),
      helper: "Detail visits",
      tone: "violet"
    },
    {
      icon: "fa-bookmark",
      label: "Saves",
      value: (collection?.saves_count ?? 0).toLocaleString(),
      helper: "Pinned for later",
      tone: "amber"
    }
  ];
  const heroSignals = [
    collection?.quality_score != null ? {
      icon: "fa-gauge-high",
      label: "Quality",
      value: Number(collection.quality_score).toFixed(1),
      description: collection?.trust_tier ? `${humanizeToken(collection.trust_tier)} placement tier` : "Placement quality signal",
      tone: "emerald"
    } : null,
    collection?.ranking_score != null ? {
      icon: "fa-ranking-star",
      label: "Ranking",
      value: Number(collection.ranking_score).toFixed(1),
      description: "Current discovery momentum score",
      tone: "amber"
    } : null,
    collection?.presentation_style && collection.presentation_style !== "standard" ? {
      icon: "fa-panorama",
      label: "Presentation",
      value: humanizeToken(collection.presentation_style),
      description: "Visual treatment for this collection surface",
      tone: "sky"
    } : null,
    collection?.campaign_key ? {
      icon: "fa-bullhorn",
      label: "Campaign",
      value: collection.campaign_label || humanizeToken(collection.campaign_key),
      description: "Programmed into a campaign surface",
      tone: "rose"
    } : null
  ].filter(Boolean);
  const { share } = useWebShare({
    onFallback: async ({ url }) => {
      if (navigator?.clipboard?.writeText) {
        await navigator.clipboard.writeText(url);
        setState((current) => ({ ...current, notice: "Collection link copied." }));
      }
    }
  });
  async function handleLike() {
    if (!engagement?.can_interact) {
      if (engagement?.login_url) window.location.assign(engagement.login_url);
      return;
    }
    setState((current) => ({ ...current, busy: true, notice: "" }));
    try {
      const payload = await requestJson$k(state.liked ? engagement.unlike_url : engagement.like_url, {
        method: state.liked ? "DELETE" : "POST"
      });
      setState((current) => ({ ...current, liked: Boolean(payload?.liked), busy: false }));
      setCollection((current) => ({ ...current, likes_count: payload?.likes_count ?? current.likes_count }));
    } catch (error) {
      setState((current) => ({ ...current, busy: false, notice: error.message }));
    }
  }
  async function handleFollow() {
    if (!engagement?.can_interact) {
      if (engagement?.login_url) window.location.assign(engagement.login_url);
      return;
    }
    setState((current) => ({ ...current, busy: true, notice: "" }));
    try {
      const payload = await requestJson$k(state.following ? engagement.unfollow_url : engagement.follow_url, {
        method: state.following ? "DELETE" : "POST"
      });
      setState((current) => ({ ...current, following: Boolean(payload?.following), busy: false }));
      setCollection((current) => ({ ...current, followers_count: payload?.followers_count ?? current.followers_count }));
    } catch (error) {
      setState((current) => ({ ...current, busy: false, notice: error.message }));
    }
  }
  async function handleShare() {
    try {
      const payload = await requestJson$k(engagement?.share_url, { method: "POST" });
      setCollection((current) => ({ ...current, shares_count: payload?.shares_count ?? current.shares_count }));
      await share({
        title: collection?.title,
        text: collection?.summary || collection?.description || `Explore ${collection?.title} on Skinbase.`,
        url: collection?.public_url
      });
    } catch (error) {
      setState((current) => ({ ...current, notice: error.message }));
    }
  }
  async function handleSave() {
    if (!engagement?.save_url) {
      if (engagement?.login_url) window.location.assign(engagement.login_url);
      return;
    }
    setState((current) => ({ ...current, busy: true, notice: "" }));
    try {
      const payload = await requestJson$k(state.saved ? engagement.unsave_url : engagement.save_url, {
        method: state.saved ? "DELETE" : "POST",
        body: state.saved ? void 0 : {
          context: "collection_detail",
          context_meta: {
            collection_type: collection?.type || null,
            collection_mode: collection?.mode || null
          }
        }
      });
      setState((current) => ({ ...current, saved: Boolean(payload?.saved), busy: false }));
      setCollection((current) => ({ ...current, saves_count: payload?.saves_count ?? current.saves_count }));
    } catch (error) {
      setState((current) => ({ ...current, busy: false, notice: error.message }));
    }
  }
  async function handleCommentSubmit(body2) {
    const payload = await requestJson$k(commentsEndpoint, {
      method: "POST",
      body: { body: body2 }
    });
    setComments(payload?.comments || []);
    setCollection((current) => ({ ...current, comments_count: payload?.comments_count ?? current.comments_count }));
  }
  async function handleDeleteComment(commentId) {
    const payload = await requestJson$k(`${commentsEndpoint}/${commentId}`, { method: "DELETE" });
    setComments(payload?.comments || []);
    setCollection((current) => ({ ...current, comments_count: payload?.comments_count ?? current.comments_count }));
  }
  async function handleSubmitArtwork() {
    if (!submitEndpoint || !selectedArtworkId) return;
    try {
      const payload = await requestJson$k(submitEndpoint, {
        method: "POST",
        body: { artwork_id: selectedArtworkId }
      });
      setSubmissions(payload?.submissions || []);
      setState((current) => ({ ...current, notice: "Artwork submitted for review." }));
    } catch (error) {
      setState((current) => ({ ...current, notice: error.message }));
    }
  }
  async function handleSubmissionAction(submission, action) {
    const url = action === "approve" ? `/collections/submissions/${submission.id}/approve` : action === "reject" ? `/collections/submissions/${submission.id}/reject` : `/collections/submissions/${submission.id}`;
    const payload = await requestJson$k(url, {
      method: action === "withdraw" ? "DELETE" : "POST"
    });
    setSubmissions(payload?.submissions || []);
    if (action === "approve") {
      setCollection((current) => ({ ...current, artworks_count: (current?.artworks_count ?? 0) + 1 }));
    }
  }
  async function handleReport(targetType, targetId) {
    if (!reportEndpoint) {
      if (engagement?.login_url) window.location.assign(engagement.login_url);
      return;
    }
    const reason = window.prompt("Why are you reporting this? (required)");
    if (!reason || !reason.trim()) return;
    try {
      await requestJson$k(reportEndpoint, {
        method: "POST",
        body: {
          target_type: targetType,
          target_id: targetId,
          reason: reason.trim()
        }
      });
      setState((current) => ({ ...current, notice: "Report submitted. Thank you." }));
    } catch (error) {
      setState((current) => ({ ...current, notice: error.message }));
    }
  }
  function renderModule(module) {
    if (!module?.key) return null;
    if (module.key === "intro_block") {
      return null;
    }
    if (module.key === "featured_artworks") {
      if (!artworkItems.length) return null;
      return /* @__PURE__ */ React.createElement(PageSection, { icon: "fa-star", eyebrow: "Highlights", title: "Featured artworks", count: Math.min(artworkItems.length, 3) }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-relaxed text-slate-300" }, "Start with the standout pieces from this collection before diving into the full sequence."), /* @__PURE__ */ React.createElement(ArtworkGallery, { items: artworkItems.slice(0, 3), showAuthor: showArtworkAuthors, className: "grid-cols-1 gap-5 md:grid-cols-3" })));
    }
    if (module.key === "editorial_note") {
      if (collection?.type !== "editorial") return null;
      return /* @__PURE__ */ React.createElement(PageSection, { icon: "fa-pen-nib", eyebrow: "Editorial", title: "Editorial context" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-4" }, collection?.description || "A staff-curated collection prepared for premium discovery placement."), collection?.event_label || collection?.badge_label ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, collection?.event_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, collection.event_label) : null, collection?.badge_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100" }, collection.badge_label) : null) : null));
    }
    if (module.key === "artwork_grid") {
      return /* @__PURE__ */ React.createElement("section", null, artworkItems.length ? /* @__PURE__ */ React.createElement(ArtworkGallery, { items: artworkItems, showAuthor: showArtworkAuthors, className: "grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4" }) : /* @__PURE__ */ React.createElement(EmptyCollectionState, { isOwner, smart: collection?.mode === "smart" }), artworks?.links?.prev || artworks?.links?.next ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("a", { href: artworks?.links?.prev || "#", className: `inline-flex items-center gap-2 rounded-2xl border px-4 py-3 text-sm font-semibold transition ${artworks?.links?.prev ? "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.08]" : "pointer-events-none border-white/8 bg-white/[0.02] text-slate-500"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw" }), "Previous"), /* @__PURE__ */ React.createElement("a", { href: artworks?.links?.next || "#", className: `inline-flex items-center gap-2 rounded-2xl border px-4 py-3 text-sm font-semibold transition ${artworks?.links?.next ? "border-white/12 bg-white/[0.05] text-white hover:bg-white/[0.08]" : "pointer-events-none border-white/8 bg-white/[0.02] text-slate-500"}` }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right fa-fw" }))) : null);
    }
    if (module.key === "discussion") {
      if (!collection?.allow_comments) return null;
      return /* @__PURE__ */ React.createElement(PageSection, { icon: "fa-comments", eyebrow: "Discussion", title: "Collection comments", count: (collection?.comments_count ?? comments.length).toLocaleString() }, canComment ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement(CommentForm, { onSubmit: handleCommentSubmit, placeholder: "Talk about the curation, mood, or standout pieces…", submitLabel: "Post comment" })) : null, /* @__PURE__ */ React.createElement("div", { className: canComment ? "mt-5" : "" }, /* @__PURE__ */ React.createElement(CommentList, { comments, canReply: false, onDelete: handleDeleteComment, onReport: (comment) => handleReport("collection_comment", comment.id), emptyMessage: "No comments yet." })));
    }
    if (module.key === "related_collections") {
      if (!Array.isArray(relatedCollections) || !relatedCollections.length) return null;
      return /* @__PURE__ */ React.createElement(PageSection, { icon: "fa-layer-group", eyebrow: "More to Explore", title: "Related collections" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2" }, relatedCollections.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, recommendationReasons(collection, item).map((reason) => /* @__PURE__ */ React.createElement("span", { key: `${item.id}-${reason}`, className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold text-sky-100" }, reason))), /* @__PURE__ */ React.createElement(CollectionCard, { collection: item, isOwner: false })))));
    }
    if (module.key === "collaborators") {
      return /* @__PURE__ */ React.createElement(PageSection, { icon: "fa-users", eyebrow: "Contributors", title: "Curation team" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, members.length ? members.filter((member) => member?.status === "active").map((member) => /* @__PURE__ */ React.createElement(CollaboratorCard, { key: member.id, member })) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "This collection is curated by a single owner right now.")));
    }
    if (module.key === "submissions") {
      if (!collection?.allow_submissions) return null;
      return /* @__PURE__ */ React.createElement(PageSection, { icon: "fa-paper-plane", eyebrow: "Submissions", title: "Submit to this collection" }, canSubmit && submissionArtworkOptions?.length ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(selectedArtworkId || ""), onChange: (val) => setSelectedArtworkId(val), placeholder: "Select artwork", options: submissionArtworkOptions.map((a) => ({ value: String(a.id), label: a.title })) }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleSubmitArtwork, className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-paper-plane fa-fw" }), "Submit artwork")) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Sign in with at least one artwork on your account to submit here."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, submissions.length ? submissions.map((submission) => /* @__PURE__ */ React.createElement(
        SubmissionCard,
        {
          key: submission.id,
          submission,
          onApprove: (item) => handleSubmissionAction(item, "approve"),
          onReject: (item) => handleSubmissionAction(item, "reject"),
          onWithdraw: (item) => handleSubmissionAction(item, "withdraw"),
          onReport: (item) => handleReport("collection_submission", item.id)
        }
      )) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No submissions yet.")));
    }
    return null;
  }
  const renderedFullModules = enabledModules.filter((module) => module.slot === "full").map(renderModule).filter(Boolean);
  const renderedMainModules = enabledModules.filter((module) => module.slot === "main").map(renderModule).filter(Boolean);
  const renderedSidebarModules = enabledModules.filter((module) => module.slot === "sidebar").map(renderModule).filter(Boolean);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: metaTitle, description: metaDescription, jsonLd: collectionSchema }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[36rem] opacity-95", style: { background: "radial-gradient(circle at top left, rgba(56,189,248,0.18), transparent 32%), radial-gradient(circle at 82% 10%, rgba(249,115,22,0.18), transparent 26%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: profileCollectionsUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to collections"), isOwner && manageUrl ? /* @__PURE__ */ React.createElement("a", { href: manageUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip fa-fw text-[11px]" }), "Manage artworks") : null, isOwner && editUrl ? /* @__PURE__ */ React.createElement("a", { href: editUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[11px]" }), "Edit details") : null, isOwner && analyticsUrl ? /* @__PURE__ */ React.createElement("a", { href: analyticsUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column fa-fw text-[11px]" }), "Analytics") : null, isOwner && historyUrl ? /* @__PURE__ */ React.createElement("a", { href: historyUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[11px]" }), "History") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] shadow-[0_30px_90px_rgba(2,6,23,0.32)] backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: `h-[3px] bg-gradient-to-r ${collection?.type === "editorial" ? "from-amber-400/80 via-amber-400/30 to-transparent" : collection?.type === "community" ? "from-emerald-400/80 via-emerald-400/30 to-transparent" : collection?.mode === "smart" ? "from-sky-400/80 via-sky-400/30 to-transparent" : "from-violet-400/80 via-violet-400/30 to-transparent"}` }), /* @__PURE__ */ React.createElement("div", { className: "grid items-start gap-6 p-5 md:p-7 xl:grid-cols-[minmax(0,1.2fr)_420px]" }, /* @__PURE__ */ React.createElement("div", { className: "relative self-start overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/60" }, /* @__PURE__ */ React.createElement(CollectionCover, { collection }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[linear-gradient(to_top,rgba(2,6,23,0.8),rgba(2,6,23,0.08))]" })), /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.12),transparent_28%),radial-gradient(circle_at_90%_8%,rgba(251,191,36,0.14),transparent_24%),linear-gradient(180deg,rgba(15,23,42,0.94),rgba(10,18,32,0.92))] px-5 py-6 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] md:px-6 md:py-7" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute -left-14 top-10 h-36 w-36 rounded-full bg-sky-400/10 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute -right-10 bottom-8 h-32 w-32 rounded-full bg-amber-300/10 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 flex h-full flex-col justify-between" }, collection?.banner_text ? /* @__PURE__ */ React.createElement("div", { className: `mb-4 inline-flex max-w-full items-center gap-2 rounded-[22px] border px-4 py-3 text-sm font-medium shadow-[0_18px_40px_rgba(2,6,23,0.2)] ${spotlightClasses}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sparkles text-[12px]" }), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, collection.banner_text)) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, collection?.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/25 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Featured Collection") : null, collection?.mode === "smart" ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Smart Collection") : null, /* @__PURE__ */ React.createElement(TypeBadge, { collection }), collection?.event_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white" }, collection.event_label) : null, collection?.campaign_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, collection.campaign_label) : null, collection?.badge_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white" }, collection.badge_label) : null, collection?.series_key ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white" }, "Series ", collection.series_order ? `#${collection.series_order}` : "") : null, isOwner ? /* @__PURE__ */ React.createElement(CollectionVisibilityBadge, { visibility: collection?.visibility }) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 max-w-3xl text-4xl font-black tracking-[-0.06em] text-white md:text-5xl xl:text-[4rem] xl:leading-[0.92]" }, collection?.title), showIntroBlock ? /* @__PURE__ */ React.createElement(React.Fragment, null, collection?.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-lg text-slate-300 md:text-xl" }, collection.subtitle) : null, collection?.summary || collection?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, collection?.summary || collection?.description) : /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-relaxed text-slate-400 md:text-[15px]" }, "A curated selection from @", owner?.username, ", assembled as a focused gallery rather than a simple archive."), collection?.smart_summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 max-w-2xl rounded-[22px] border border-sky-300/15 bg-sky-400/[0.07] px-4 py-3 text-sm leading-relaxed text-sky-100/90" }, collection.smart_summary) : null, featuringCreatorsCount > 1 ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, "Featuring artworks by ", featuringCreatorsCount, " creators.") : null) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-7 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleLike, disabled: state.busy || !engagement?.like_url, icon: "fa-heart", label: state.liked ? "Liked" : "Like", tone: "rose", active: state.liked }), /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleFollow, disabled: state.busy || !engagement?.follow_url, icon: "fa-bell", label: state.following ? "Following" : "Follow", tone: "emerald", active: state.following }), /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleSave, disabled: state.busy || !engagement?.save_url && !engagement?.unsave_url, icon: "fa-bookmark", label: state.saved ? "Saved" : "Save", tone: "violet", active: state.saved })), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleShare, icon: "fa-share-nodes", label: "Share", tone: "neutral", compact: true }), featuredCollectionsUrl ? /* @__PURE__ */ React.createElement(CollectionHeroAction, { href: featuredCollectionsUrl, icon: "fa-compass", label: "Explore", tone: "sky", compact: true }) : null, reportEndpoint && !isOwner ? /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: () => handleReport("collection", collection?.id), icon: "fa-flag", label: "Report", tone: "amber", compact: true }) : null)), state.notice ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-sky-100" }, state.notice) : null, /* @__PURE__ */ React.createElement(OwnerCard, { owner, collectionType: collection?.type }))))), heroMetrics.length || heroSignals.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-5 shadow-[0_20px_70px_rgba(2,6,23,0.22)] backdrop-blur-xl md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Collection Snapshot"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Stats and placement signals")), /* @__PURE__ */ React.createElement("p", { className: "max-w-xl text-sm leading-relaxed text-slate-400" }, "The engagement counters and ranking signals now live outside the hero so the header can stay focused on the artwork, title, and actions.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(320px,0.95fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-5" }, heroMetrics.map((item) => /* @__PURE__ */ React.createElement(HeroMetricCard, { key: item.label, icon: item.icon, label: item.label, value: item.value, helper: item.helper, tone: item.tone }))), heroSignals.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-1" }, heroSignals.map((item) => /* @__PURE__ */ React.createElement(HeroSignalCard, { key: item.label, icon: item.icon, label: item.label, value: item.value, description: item.description, tone: item.tone }))) : null)) : null, seriesContext?.url || seriesContext?.previous || seriesContext?.next || Array.isArray(seriesContext?.siblings) && seriesContext.siblings.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Series"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, seriesContext?.title || "Connected collection sequence"), seriesContext?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, seriesContext.description) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, collection?.series_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, collection.series_key) : null, seriesContext?.url ? /* @__PURE__ */ React.createElement("a", { href: seriesContext.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-list fa-fw text-[10px]" }), "View full series") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, seriesContext?.previous ? /* @__PURE__ */ React.createElement("a", { href: seriesContext.previous.url, className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-4 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Previous"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, seriesContext.previous.title)), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-slate-500" })) : null, seriesContext?.next ? /* @__PURE__ */ React.createElement("a", { href: seriesContext.next.url, className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-4 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Next"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, seriesContext.next.title)), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-slate-500" })) : null), Array.isArray(seriesContext?.siblings) && seriesContext.siblings.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, seriesContext.siblings.slice(0, 2).map((item) => /* @__PURE__ */ React.createElement(CollectionCard, { key: item.id, collection: item, isOwner: false }))) : null)) : null, contextSignals.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-amber-300/15 bg-amber-400/10 text-amber-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-diagram-project text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Related Context"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Campaign, event, and quality context"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, contextSignals.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, contextSignals.map((item) => /* @__PURE__ */ React.createElement(ContextSignalCard, { key: `${item.meta}-${item.title}`, item })))) : null, storyLinks.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-lime-300/15 bg-lime-400/10 text-lime-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Stories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Stories and editorial references linked to this collection"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, storyLinks.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, storyLinks.map((item) => /* @__PURE__ */ React.createElement(EntityLinkCard, { key: `${item.linked_type}-${item.linked_id}-${item.id}`, item })))) : null, taxonomyLinks.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-violet-300/15 bg-violet-400/10 text-violet-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tags text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-violet-200/80" }, "Browse The Theme"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Categories and tags that anchor this collection"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, taxonomyLinks.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, taxonomyLinks.map((item) => /* @__PURE__ */ React.createElement(EntityLinkCard, { key: `${item.linked_type}-${item.linked_id}-${item.id}`, item })))) : null, contributorLinks.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-300/15 bg-sky-400/10 text-sky-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-group text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Connected Creators"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Creators and artworks that give the set its shape"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, contributorLinks.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, contributorLinks.map((item) => /* @__PURE__ */ React.createElement(EntityLinkCard, { key: `${item.linked_type}-${item.linked_id}-${item.id}`, item })))) : null, renderedFullModules.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-6" }, renderedFullModules) : null, renderedMainModules.length || renderedSidebarModules.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, renderedMainModules), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, renderedSidebarModules)) : null)));
}
const __vite_glob_0_47 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionShow
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$8() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$j(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$8(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed.");
  }
  return payload;
}
function isoToLocalInput$1(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 6e4);
  return local.toISOString().slice(0, 16);
}
function titleize(value) {
  return String(value || "").split("_").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}
function Field$2({ label, help, children }) {
  return /* @__PURE__ */ React.createElement("label", { className: "block space-y-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, label), children, help ? /* @__PURE__ */ React.createElement("span", { className: "block text-xs leading-relaxed text-slate-400" }, help) : null);
}
function StatCard$5({ label, value, tone = "sky" }) {
  const toneClasses2 = {
    sky: "border-sky-300/15 bg-sky-400/10 text-sky-100",
    amber: "border-amber-300/15 bg-amber-400/10 text-amber-100",
    emerald: "border-emerald-300/15 bg-emerald-400/10 text-emerald-100"
  };
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${toneClasses2[tone] || toneClasses2.sky}` }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, value));
}
function sortAssignments(items) {
  return [...items].sort((left, right) => {
    const keyCompare = String(left.program_key || "").localeCompare(String(right.program_key || ""));
    if (keyCompare !== 0) return keyCompare;
    return (Number(right.priority) || 0) - (Number(left.priority) || 0);
  });
}
function buildHooksForm(collection) {
  return {
    experiment_key: collection?.experiment_key || "",
    experiment_treatment: collection?.experiment_treatment || "",
    placement_variant: collection?.placement_variant || "",
    ranking_mode_variant: collection?.ranking_mode_variant || "",
    collection_pool_version: collection?.collection_pool_version || "",
    test_label: collection?.test_label || "",
    promotion_tier: collection?.promotion_tier || "",
    partner_key: collection?.partner_key || "",
    trust_tier: collection?.trust_tier || "",
    sponsorship_state: collection?.sponsorship_state || "",
    ownership_domain: collection?.ownership_domain || "",
    commercial_review_state: collection?.commercial_review_state || "",
    legal_review_state: collection?.legal_review_state || "",
    placement_eligibility: Boolean(collection?.placement_eligibility)
  };
}
function buildDiagnostics(collection) {
  if (!collection) {
    return null;
  }
  return {
    collection_id: Number(collection.id),
    workflow_state: collection.workflow_state || null,
    health_state: collection.health_state || null,
    placement_eligibility: Boolean(collection.placement_eligibility),
    experiment_key: collection.experiment_key || null,
    experiment_treatment: collection.experiment_treatment || null,
    placement_variant: collection.placement_variant || null,
    ranking_mode_variant: collection.ranking_mode_variant || null,
    collection_pool_version: collection.collection_pool_version || null,
    test_label: collection.test_label || null,
    partner_key: collection.partner_key || null,
    trust_tier: collection.trust_tier || null,
    promotion_tier: collection.promotion_tier || null,
    sponsorship_state: collection.sponsorship_state || null,
    ownership_domain: collection.ownership_domain || null,
    commercial_review_state: collection.commercial_review_state || null,
    legal_review_state: collection.legal_review_state || null,
    ranking_bucket: collection.ranking_bucket || null,
    recommendation_tier: collection.recommendation_tier || null,
    last_health_check_at: collection.last_health_check_at || null,
    last_recommendation_refresh_at: collection.last_recommendation_refresh_at || null
  };
}
function buildProgramUrl(pattern, programKey) {
  if (!pattern || !programKey) return null;
  return pattern.replace("__PROGRAM__", String(programKey));
}
function CollectionStaffProgramming() {
  const { props } = X$1();
  const initialCollectionOptions = Array.isArray(props.collectionOptions) ? props.collectionOptions : [];
  const initialAssignments = Array.isArray(props.assignments) ? props.assignments : [];
  const baseProgramKeys = Array.isArray(props.programKeyOptions) ? props.programKeyOptions : [];
  const initialMergeQueue = props.mergeQueue || { summary: {}, pending: [], recent: [] };
  const observabilitySummary = props.observabilitySummary || { counts: {}, watchlist: [], generated_at: null };
  const endpoints = props.endpoints || {};
  const historyPattern = props.historyPattern || "";
  const seo = props.seo || {};
  const viewer = props.viewer || {};
  const [assignments, setAssignments] = React.useState(sortAssignments(initialAssignments));
  const [collectionOverrides, setCollectionOverrides] = React.useState({});
  const collectionOptions = React.useMemo(() => initialCollectionOptions.map((collection) => collectionOverrides[collection.id] || collection), [collectionOverrides, initialCollectionOptions]);
  const [mergeQueue, setMergeQueue] = React.useState(initialMergeQueue);
  const [previewCollections, setPreviewCollections] = React.useState([]);
  const [diagnostics, setDiagnostics] = React.useState({
    eligibility: null,
    duplicates: null,
    recommendations: null
  });
  const [notice, setNotice] = React.useState("");
  const [toast, setToast] = React.useState({ id: 0, visible: false, message: "", variant: "success" });
  const [busy, setBusy] = React.useState("");
  const [queueBusy, setQueueBusy] = React.useState({});
  const [selectedCollectionId, setSelectedCollectionId] = React.useState(initialCollectionOptions[0]?.id || "");
  const [previewForm, setPreviewForm] = React.useState({
    program_key: baseProgramKeys[0] || "",
    limit: 8
  });
  const [assignmentForm, setAssignmentForm] = React.useState({
    id: null,
    collection_id: collectionOptions[0]?.id || "",
    program_key: baseProgramKeys[0] || "",
    campaign_key: "",
    placement_scope: "",
    starts_at: "",
    ends_at: "",
    priority: 0,
    notes: ""
  });
  const selectedCollection = React.useMemo(() => collectionOptions.find((collection) => String(collection.id) === String(selectedCollectionId)) || null, [collectionOptions, selectedCollectionId]);
  const [hooksForm, setHooksForm] = React.useState(buildHooksForm(initialCollectionOptions[0] || null));
  const [hooksDiagnostics, setHooksDiagnostics] = React.useState(buildDiagnostics(initialCollectionOptions[0] || null));
  const programKeyOptions = React.useMemo(() => {
    return Array.from(new Set([
      ...baseProgramKeys,
      ...assignments.map((assignment) => assignment.program_key).filter(Boolean),
      ...collectionOptions.map((collection) => collection.program_key).filter(Boolean),
      assignmentForm.program_key || null,
      previewForm.program_key || null
    ].filter(Boolean))).sort((left, right) => String(left).localeCompare(String(right)));
  }, [assignmentForm.program_key, assignments, baseProgramKeys, collectionOptions, previewForm.program_key]);
  React.useEffect(() => {
    if (!assignmentForm.collection_id && collectionOptions[0]?.id) {
      setAssignmentForm((current) => ({ ...current, collection_id: collectionOptions[0].id }));
    }
    if (!selectedCollectionId && collectionOptions[0]?.id) {
      setSelectedCollectionId(collectionOptions[0].id);
    }
  }, [assignmentForm.collection_id, collectionOptions, selectedCollectionId]);
  React.useEffect(() => {
    if (!assignmentForm.program_key && programKeyOptions[0]) {
      setAssignmentForm((current) => ({ ...current, program_key: programKeyOptions[0] }));
    }
    if (!previewForm.program_key && programKeyOptions[0]) {
      setPreviewForm((current) => ({ ...current, program_key: programKeyOptions[0] }));
    }
  }, [assignmentForm.program_key, previewForm.program_key, programKeyOptions]);
  React.useEffect(() => {
    setMergeQueue(initialMergeQueue);
  }, [initialMergeQueue]);
  React.useEffect(() => {
    setHooksForm(buildHooksForm(selectedCollection));
    setHooksDiagnostics(buildDiagnostics(selectedCollection));
  }, [selectedCollection]);
  function showToast(message, variant = "success") {
    setToast({
      id: Date.now() + Math.random(),
      visible: true,
      message,
      variant
    });
  }
  function resetAssignmentForm() {
    setAssignmentForm({
      id: null,
      collection_id: collectionOptions[0]?.id || "",
      program_key: programKeyOptions[0] || "",
      campaign_key: "",
      placement_scope: "",
      starts_at: "",
      ends_at: "",
      priority: 0,
      notes: ""
    });
  }
  function hydrateAssignment(assignment) {
    setAssignmentForm({
      id: assignment.id,
      collection_id: assignment.collection?.id || "",
      program_key: assignment.program_key || "",
      campaign_key: assignment.campaign_key || "",
      placement_scope: assignment.placement_scope || "",
      starts_at: isoToLocalInput$1(assignment.starts_at),
      ends_at: isoToLocalInput$1(assignment.ends_at),
      priority: assignment.priority || 0,
      notes: assignment.notes || ""
    });
  }
  async function handleAssignmentSubmit(event) {
    event.preventDefault();
    setBusy("assignment");
    setNotice("");
    try {
      const url = assignmentForm.id ? endpoints.updatePattern?.replace("__PROGRAM__", String(assignmentForm.id)) : endpoints.store;
      const payload = await requestJson$j(url, {
        method: assignmentForm.id ? "PATCH" : "POST",
        body: {
          collection_id: Number(assignmentForm.collection_id),
          program_key: assignmentForm.program_key,
          campaign_key: assignmentForm.campaign_key || null,
          placement_scope: assignmentForm.placement_scope || null,
          starts_at: assignmentForm.starts_at ? new Date(assignmentForm.starts_at).toISOString() : null,
          ends_at: assignmentForm.ends_at ? new Date(assignmentForm.ends_at).toISOString() : null,
          priority: Number(assignmentForm.priority || 0),
          notes: assignmentForm.notes || null
        }
      });
      setAssignments((current) => sortAssignments([...current.filter((item) => item.id !== payload.assignment.id), payload.assignment]));
      setNotice(assignmentForm.id ? "Programming assignment updated." : "Programming assignment created.");
      resetAssignmentForm();
    } catch (error) {
      setNotice(error.message || "Failed to save programming assignment.");
    } finally {
      setBusy("");
    }
  }
  async function handlePreview(event) {
    event.preventDefault();
    setBusy("preview");
    setNotice("");
    try {
      const payload = await requestJson$j(endpoints.preview, {
        method: "POST",
        body: {
          program_key: previewForm.program_key,
          limit: Number(previewForm.limit || 8)
        }
      });
      setPreviewCollections(Array.isArray(payload.collections) ? payload.collections : []);
      setNotice("Preview refreshed.");
    } catch (error) {
      setNotice(error.message || "Failed to preview this program key.");
    } finally {
      setBusy("");
    }
  }
  async function runDiagnostic(kind) {
    const endpointMap = {
      eligibility: endpoints.refreshEligibility,
      duplicates: endpoints.duplicateScan,
      recommendations: endpoints.refreshRecommendations
    };
    const url = endpointMap[kind];
    if (!url) {
      return;
    }
    setBusy(kind);
    setNotice("");
    try {
      const payload = await requestJson$j(url, {
        method: "POST",
        body: {
          collection_id: selectedCollectionId ? Number(selectedCollectionId) : null
        }
      });
      setDiagnostics((current) => ({ ...current, [kind]: payload.result || null }));
      setNotice(payload?.result?.message || `${titleize(kind)} queued.`);
    } catch (error) {
      setNotice(error.message || `Failed to run ${kind}.`);
    } finally {
      setBusy("");
    }
  }
  async function handleQueueAction(kind, item) {
    const sourceId = item?.source?.id;
    const targetId = item?.target?.id;
    if (!sourceId || !targetId) {
      return;
    }
    const endpointMap = {
      canonicalize: endpoints.canonicalizeCandidate,
      merge: endpoints.mergeCandidate,
      reject: endpoints.rejectCandidate
    };
    const confirmationMap = {
      canonicalize: `Designate "${item.target?.title || "this collection"}" as the canonical target for "${item.source?.title || "this collection"}"?`,
      merge: `Merge "${item.source?.title || "this collection"}" into "${item.target?.title || "this collection"}" from the staff queue?`,
      reject: `Mark "${item.target?.title || "this collection"}" as not a duplicate of "${item.source?.title || "this collection"}"?`
    };
    const url = endpointMap[kind];
    if (!url) {
      return;
    }
    if (!window.confirm(confirmationMap[kind] || "Continue?")) {
      return;
    }
    setQueueBusy((current) => ({ ...current, [item.id]: kind }));
    try {
      const payload = await requestJson$j(url, {
        method: "POST",
        body: {
          source_collection_id: Number(sourceId),
          target_collection_id: Number(targetId)
        }
      });
      if (payload?.mergeQueue) {
        setMergeQueue(payload.mergeQueue);
      }
      showToast(payload?.message || `${titleize(kind)} action completed.`, "success");
    } catch (error) {
      showToast(error.message || `Failed to ${kind} this queue item.`, "error");
    } finally {
      setQueueBusy((current) => {
        const next = { ...current };
        delete next[item.id];
        return next;
      });
    }
  }
  async function handleHooksSubmit(event) {
    event.preventDefault();
    if (!selectedCollectionId || !endpoints.metadataUpdate) {
      return;
    }
    setBusy("hooks");
    setNotice("");
    try {
      const payload = await requestJson$j(endpoints.metadataUpdate, {
        method: "POST",
        body: {
          collection_id: Number(selectedCollectionId),
          experiment_key: hooksForm.experiment_key || null,
          experiment_treatment: hooksForm.experiment_treatment || null,
          placement_variant: hooksForm.placement_variant || null,
          ranking_mode_variant: hooksForm.ranking_mode_variant || null,
          collection_pool_version: hooksForm.collection_pool_version || null,
          test_label: hooksForm.test_label || null,
          promotion_tier: hooksForm.promotion_tier || null,
          partner_key: viewer.isAdmin ? hooksForm.partner_key || null : void 0,
          trust_tier: viewer.isAdmin ? hooksForm.trust_tier || null : void 0,
          sponsorship_state: viewer.isAdmin ? hooksForm.sponsorship_state || null : void 0,
          ownership_domain: viewer.isAdmin ? hooksForm.ownership_domain || null : void 0,
          commercial_review_state: viewer.isAdmin ? hooksForm.commercial_review_state || null : void 0,
          legal_review_state: viewer.isAdmin ? hooksForm.legal_review_state || null : void 0,
          placement_eligibility: Boolean(hooksForm.placement_eligibility)
        }
      });
      if (payload?.collection?.id) {
        setCollectionOverrides((current) => ({
          ...current,
          [payload.collection.id]: payload.collection
        }));
      }
      setHooksDiagnostics(payload?.diagnostics || buildDiagnostics(payload?.collection || selectedCollection));
      setHooksForm(buildHooksForm(payload?.collection || selectedCollection));
      setNotice(payload?.message || "Experiment and program governance hooks updated.");
    } catch (error) {
      setNotice(error.message || "Failed to update experiment and program governance hooks.");
    } finally {
      setBusy("");
    }
  }
  const totalPrograms = Array.from(new Set(assignments.map((assignment) => assignment.program_key).filter(Boolean))).length;
  const eligibleAssignments = assignments.filter((assignment) => assignment.collection?.placement_eligibility === true).length;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, seo.title || "Collection Programming — Skinbase"), /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description || "Staff programming tools for collections." }), seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null, /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots || "noindex,follow" })), /* @__PURE__ */ React.createElement(
    ShareToast,
    {
      key: toast.id,
      message: toast.message,
      visible: toast.visible,
      variant: toast.variant,
      duration: toast.variant === "error" ? 3200 : 2200,
      onHide: () => setToast((current) => ({ ...current, visible: false }))
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-95", style: { background: "radial-gradient(circle at 18% 15%, rgba(56,189,248,0.18), transparent 28%), radial-gradient(circle at 85% 14%, rgba(132,204,22,0.16), transparent 26%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Staff Programming"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, "Collections programming studio"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "Manage program assignments, preview live pools, and run targeted diagnostics before collections hit discovery surfaces."), notice ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-sky-100" }, notice) : null), endpoints.surfaces ? /* @__PURE__ */ React.createElement("a", { href: endpoints.surfaces, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-thumbtack fa-fw text-[11px]" }), "Open placement studio") : null)), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-5 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$5, { label: "Assignments", value: assignments.length, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$5, { label: "Program Keys", value: totalPrograms, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$5, { label: "Eligible", value: eligibleAssignments, tone: "emerald" })), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-200/80" }, "Merge Queue"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Pending duplicates and recent decisions"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Review what still needs merge attention and what staff already resolved. Each row links back into the collection studio for full compare-and-confirm actions.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$5, { label: "Pending", value: mergeQueue?.summary?.pending || 0, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$5, { label: "Approved", value: mergeQueue?.summary?.approved || 0, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$5, { label: "Rejected", value: mergeQueue?.summary?.rejected || 0, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$5, { label: "Merged", value: mergeQueue?.summary?.completed || 0, tone: "sky" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-200/80" }, "Needs Review"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold text-white" }, "Suggested duplicate pairs")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, mergeQueue?.pending?.length || 0)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, (mergeQueue?.pending || []).length ? mergeQueue.pending.map((item) => {
    const activeQueueAction = queueBusy[item.id] || "";
    const cardBusy = Boolean(activeQueueAction);
    return /* @__PURE__ */ React.createElement("div", { key: `merge-pending-${item.id}`, className: `rounded-[24px] border border-white/10 bg-white/[0.04] p-4 transition ${cardBusy ? "ring-1 ring-sky-300/25" : ""}` }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (item.comparison?.match_reasons || []).map((reason) => /* @__PURE__ */ React.createElement("span", { key: reason, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, titleize(reason)))), cardBusy ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-notch fa-spin fa-fw text-[10px]" }), "Processing ", titleize(activeQueueAction)) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Source"), item.source ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: item.source, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Candidate"), item.target ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: item.target, isOwner: true }) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2 md:grid-cols-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Shared artworks: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.comparison?.shared_artworks_count ?? 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Source count: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.comparison?.source_artworks_count ?? 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Target count: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.comparison?.target_artworks_count ?? 0))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.source?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.source.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-code-compare fa-fw text-[10px]" }), "Review source") : null, item.target?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.target.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" }), "Open target") : null, item.source?.id && historyPattern ? /* @__PURE__ */ React.createElement("a", { href: historyPattern.replace("__COLLECTION__", String(item.source.id)), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[10px]" }), "History") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleQueueAction("canonicalize", item), disabled: cardBusy, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${activeQueueAction === "canonicalize" ? "fa-circle-notch fa-spin" : "fa-badge-check"} fa-fw text-[10px]` }), activeQueueAction === "canonicalize" ? "Canonicalizing..." : "Canonicalize"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleQueueAction("merge", item), disabled: cardBusy, className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${activeQueueAction === "merge" ? "fa-circle-notch fa-spin" : "fa-code-merge"} fa-fw text-[10px]` }), activeQueueAction === "merge" ? "Merging..." : "Merge now"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleQueueAction("reject", item), disabled: cardBusy, className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-xs font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${activeQueueAction === "reject" ? "fa-circle-notch fa-spin" : "fa-ban"} fa-fw text-[10px]` }), activeQueueAction === "reject" ? "Rejecting..." : "Reject")));
  }) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-10 text-sm text-slate-300" }, "No pending merge candidates right now."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Recent Decisions"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold text-white" }, "Canonical, reject, and merge history")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, mergeQueue?.recent?.length || 0)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, (mergeQueue?.recent || []).length ? mergeQueue.recent.map((item) => /* @__PURE__ */ React.createElement("div", { key: `merge-recent-${item.id}`, className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, titleize(item.action_type)), item.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, item.summary) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-slate-500" }, item.updated_at ? new Date(item.updated_at).toLocaleString() : "Unknown time", item.actor?.username ? ` • @${item.actor.username}` : ""))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Source"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.source?.title || "Collection")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Target"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.target?.title || "Collection"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.source?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.source.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[10px]" }), "Open source") : null, item.target?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.target.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" }), "Open target") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-10 text-sm text-slate-300" }, "No recent merge decisions yet."))))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleAssignmentSubmit, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Assignment"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Program key and scope")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$2, { label: "Collection" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(assignmentForm.collection_id || ""), onChange: (val) => setAssignmentForm((current) => ({ ...current, collection_id: val })), options: collectionOptions.map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement(Field$2, { label: "Program Key", help: "Use stable internal names like discover-spring or homepage-hero." }, /* @__PURE__ */ React.createElement("input", { list: "program-key-options", value: assignmentForm.program_key, onChange: (event) => setAssignmentForm((current) => ({ ...current, program_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Placement Scope", help: "Optional placement scope such as homepage.hero or discover.rail." }, /* @__PURE__ */ React.createElement("input", { value: assignmentForm.placement_scope, onChange: (event) => setAssignmentForm((current) => ({ ...current, placement_scope: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Campaign Key" }, /* @__PURE__ */ React.createElement("input", { value: assignmentForm.campaign_key, onChange: (event) => setAssignmentForm((current) => ({ ...current, campaign_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Priority" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "-100", max: "100", value: assignmentForm.priority, onChange: (event) => setAssignmentForm((current) => ({ ...current, priority: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field$2, { label: "Starts At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: assignmentForm.starts_at, onChange: (nextValue) => setAssignmentForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Start time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$2, { label: "Ends At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: assignmentForm.ends_at, onChange: (nextValue) => setAssignmentForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "End time", clearable: true, className: "bg-white/[0.04]" }))), /* @__PURE__ */ React.createElement(Field$2, { label: "Notes", help: "Operational note for launch timing, overrides, or review context." }, /* @__PURE__ */ React.createElement("textarea", { value: assignmentForm.notes, onChange: (event) => setAssignmentForm((current) => ({ ...current, notes: event.target.value })), className: "mt-4 min-h-[120px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 1e3 })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "assignment", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "assignment" ? "fa-circle-notch fa-spin" : "fa-sliders"} fa-fw` }), assignmentForm.id ? "Update Assignment" : "Save Assignment"), assignmentForm.id ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetAssignmentForm, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left fa-fw" }), "Cancel Edit") : null), /* @__PURE__ */ React.createElement("datalist", { id: "program-key-options" }, programKeyOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option, value: option })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handlePreview, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Preview"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Inspect a live program pool")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_140px_auto]" }, /* @__PURE__ */ React.createElement(Field$2, { label: "Program Key" }, /* @__PURE__ */ React.createElement("input", { list: "program-key-options", value: previewForm.program_key, onChange: (event) => setPreviewForm((current) => ({ ...current, program_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Limit" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "1", max: "24", value: previewForm.limit, onChange: (event) => setPreviewForm((current) => ({ ...current, limit: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "preview", className: "inline-flex h-[50px] w-full items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "preview" ? "fa-circle-notch fa-spin" : "fa-binoculars"} fa-fw` }), "Preview"))), previewCollections.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, previewCollections.map((collection) => /* @__PURE__ */ React.createElement("div", { key: collection.id, className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: true })))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-8 text-sm text-slate-300" }, "Run a preview to inspect which collections currently qualify for a given program key.")), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Diagnostics"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Eligibility, duplicate risk, and ranking refresh")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-[320px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Operations summary"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Stale health"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.stale_health || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Stale recommendations"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.stale_recommendations || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Placement blocked"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.placement_blocked || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Duplicate risk"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.duplicate_risk || 0)))), observabilitySummary?.generated_at ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs text-slate-400" }, "Generated ", new Date(observabilitySummary.generated_at).toLocaleString()) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Watchlist"), Array.isArray(observabilitySummary?.watchlist) && observabilitySummary.watchlist.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-2" }, observabilitySummary.watchlist.map((collection) => /* @__PURE__ */ React.createElement("div", { key: `watch-${collection.id}`, className: "rounded-[20px] border border-white/10 bg-white/[0.04] p-3" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: true })))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "No watchlist items are currently flagged."))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement(Field$2, { label: "Target Collection", help: "Leave a selection in place to inspect one collection. Change it any time before running a diagnostic." }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(selectedCollectionId || ""), onChange: (val) => setSelectedCollectionId(val), options: collectionOptions.map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runDiagnostic("eligibility"), disabled: busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-lime-300/20 bg-lime-400/10 px-4 py-3 text-sm font-semibold text-lime-100 transition hover:bg-lime-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "eligibility" ? "fa-circle-notch fa-spin" : "fa-shield-check"} fa-fw` }), "Eligibility"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runDiagnostic("duplicates"), disabled: busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "duplicates" ? "fa-circle-notch fa-spin" : "fa-id-card"} fa-fw` }), "Duplicates"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runDiagnostic("recommendations"), disabled: busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "recommendations" ? "fa-circle-notch fa-spin" : "fa-arrows-rotate"} fa-fw` }), "Refresh"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Eligibility"), diagnostics.eligibility ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement("p", null, diagnostics.eligibility.status === "queued" ? `${diagnostics.eligibility.count} collection(s) queued.` : `${diagnostics.eligibility.count} collection(s) evaluated.`), diagnostics.eligibility.message ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, diagnostics.eligibility.message) : null, (diagnostics.eligibility.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection_id, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, item.health_state || "unknown", " · ", item.readiness_state || "unknown", " · ", item.placement_eligibility ? "eligible" : "blocked"))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Run an eligibility refresh to verify readiness and public placement safety.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Duplicate candidates"), diagnostics.duplicates ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement("p", null, diagnostics.duplicates.status === "queued" ? `${diagnostics.duplicates.count} collection(s) queued.` : `${diagnostics.duplicates.count} collection(s) with candidates.`), diagnostics.duplicates.message ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, diagnostics.duplicates.message) : null, (diagnostics.duplicates.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection_id, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, item.candidates?.length ? item.candidates.map((candidate) => candidate.title).join(", ") : "No candidates"))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Run duplicate scan to surface overlap before programming a collection widely.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Recommendation refresh"), diagnostics.recommendations ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement("p", null, diagnostics.recommendations.status === "queued" ? `${diagnostics.recommendations.count} collection(s) queued.` : `${diagnostics.recommendations.count} collection(s) refreshed.`), diagnostics.recommendations.message ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, diagnostics.recommendations.message) : null, (diagnostics.recommendations.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection_id, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, titleize(item.recommendation_tier || "unknown"), " · ", titleize(item.ranking_bucket || "unknown"), " · ", titleize(item.search_boost_tier || "unknown")))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Run a recommendation refresh to update ranking and search tiers for this collection.")))), /* @__PURE__ */ React.createElement("form", { onSubmit: handleHooksSubmit, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-fuchsia-200/80" }, "Hooks"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Experiment and program governance"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-relaxed text-slate-300" }, "Control experiment keys, promotion tiers, and staff-only program governance hooks for the selected collection without leaving the programming studio.")), selectedCollection?.program_key && endpoints.publicProgramPattern ? /* @__PURE__ */ React.createElement("a", { href: buildProgramUrl(endpoints.publicProgramPattern, selectedCollection.program_key), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[11px]" }), "Open public program landing") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(Field$2, { label: "Experiment Key", help: "Internal test or treatment key for cross-surface collection experiments." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.experiment_key, onChange: (event) => setHooksForm((current) => ({ ...current, experiment_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Treatment", help: "Variant or treatment label tied to the experiment key." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.experiment_treatment, onChange: (event) => setHooksForm((current) => ({ ...current, experiment_treatment: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Placement Variant", help: "Surface-specific placement variant such as homepage_a or search_dense." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.placement_variant, onChange: (event) => setHooksForm((current) => ({ ...current, placement_variant: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Ranking Variant", help: "Override or annotate ranking mode experiments without changing the live pool logic." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.ranking_mode_variant, onChange: (event) => setHooksForm((current) => ({ ...current, ranking_mode_variant: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Pool Version", help: "Snapshot or rollout version for the collection pool definition." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.collection_pool_version, onChange: (event) => setHooksForm((current) => ({ ...current, collection_pool_version: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Test Label", help: "Human-readable campaign or experiment label for operations and diagnostics." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.test_label, onChange: (event) => setHooksForm((current) => ({ ...current, test_label: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Promotion Tier", help: "Optional internal tier for elevated or restrained programming treatment." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.promotion_tier, onChange: (event) => setHooksForm((current) => ({ ...current, promotion_tier: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), viewer.isAdmin ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Field$2, { label: "Partner Key", help: "Admin-only internal key for trusted partner or program ownership." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.partner_key, onChange: (event) => setHooksForm((current) => ({ ...current, partner_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Trust Tier", help: "Admin-only trust marker used for internal partner/program review logic." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.trust_tier, onChange: (event) => setHooksForm((current) => ({ ...current, trust_tier: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Sponsorship State", help: "Admin-only state for sponsored, pending, or cleared program treatment." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.sponsorship_state, onChange: (event) => setHooksForm((current) => ({ ...current, sponsorship_state: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Ownership Domain", help: "Admin-only internal ownership domain such as editorial, partner, creator_program, or events." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.ownership_domain, onChange: (event) => setHooksForm((current) => ({ ...current, ownership_domain: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Commercial Review", help: "Admin-only commercial review status for future partner and sponsor programs." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.commercial_review_state, onChange: (event) => setHooksForm((current) => ({ ...current, commercial_review_state: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$2, { label: "Legal Review", help: "Admin-only legal review status when collections need compliance approval before wider promotion." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.legal_review_state, onChange: (event) => setHooksForm((current) => ({ ...current, legal_review_state: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 }))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-4 py-4 text-sm text-slate-300 md:col-span-2 xl:col-span-3" }, "Partner, sponsorship, ownership, and review metadata remain admin-only. Moderators can still manage experiment and promotion hooks here.")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center gap-3 rounded-[20px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: hooksForm.placement_eligibility, onChange: (event) => setHooksForm((current) => ({ ...current, placement_eligibility: event.target.checked })), label: "Placement eligible override" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Experiment"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.experiment_key || selectedCollection?.experiment_key || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Treatment"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.experiment_treatment || selectedCollection?.experiment_treatment || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Placement Variant"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.placement_variant || selectedCollection?.placement_variant || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Workflow"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.workflow_state || selectedCollection?.workflow_state || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Health"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.health_state || selectedCollection?.health_state || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Recommendation Tier"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.recommendation_tier || selectedCollection?.recommendation_tier || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Ranking Bucket"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.ranking_bucket || selectedCollection?.ranking_bucket || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Ranking Variant"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.ranking_mode_variant || selectedCollection?.ranking_mode_variant || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Pool Version"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.collection_pool_version || selectedCollection?.collection_pool_version || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Test Label"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.test_label || selectedCollection?.test_label || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Promotion Tier"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.promotion_tier || selectedCollection?.promotion_tier || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Partner Key"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.partner_key || selectedCollection?.partner_key || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Trust Tier"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.trust_tier || selectedCollection?.trust_tier || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Sponsorship State"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.sponsorship_state || selectedCollection?.sponsorship_state || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Ownership Domain"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.ownership_domain || selectedCollection?.ownership_domain || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Commercial Review"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.commercial_review_state || selectedCollection?.commercial_review_state || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Legal Review"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.legal_review_state || selectedCollection?.legal_review_state || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last Health Check"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.last_health_check_at ? new Date(hooksDiagnostics.last_health_check_at).toLocaleString() : "Not yet")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last Recommendation Refresh"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.last_recommendation_refresh_at ? new Date(hooksDiagnostics.last_recommendation_refresh_at).toLocaleString() : "Not yet"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "hooks" || !selectedCollectionId, className: "inline-flex items-center gap-2 rounded-2xl border border-fuchsia-300/20 bg-fuchsia-400/10 px-5 py-3 text-sm font-semibold text-fuchsia-100 transition hover:bg-fuchsia-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "hooks" ? "fa-circle-notch fa-spin" : "fa-flask-vial"} fa-fw` }), "Save Hooks"), selectedCollection?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: selectedCollection.manage_url, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw" }), "Open collection") : null)))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Assignments"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Current programming inventory")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, assignments.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-5" }, assignments.length ? assignments.map((assignment) => /* @__PURE__ */ React.createElement("div", { key: assignment.id, className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, assignment.program_key), assignment.placement_scope ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, assignment.placement_scope) : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "priority ", assignment.priority)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => hydrateAssignment(assignment), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw text-[10px]" }), "Edit"), endpoints.managePattern ? /* @__PURE__ */ React.createElement("a", { href: endpoints.managePattern.replace("__COLLECTION__", String(assignment.collection?.id || "")), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" }), "Manage") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-5 xl:grid-cols-[minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement("div", null, assignment.collection ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: assignment.collection, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Campaign: ", assignment.campaign_key || "None"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Starts: ", assignment.starts_at ? new Date(assignment.starts_at).toLocaleString() : "Immediate"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Ends: ", assignment.ends_at ? new Date(assignment.ends_at).toLocaleString() : "Open-ended"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Placement: ", assignment.collection?.placement_eligibility ? "Eligible" : "Blocked"), assignment.notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, assignment.notes) : null)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "No programming assignments yet. Create the first one above."))))));
}
const __vite_glob_0_48 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionStaffProgramming
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$7() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$i(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$7(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed.");
  }
  return payload;
}
function isoToLocalInput(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const local = new Date(date.getTime() - date.getTimezoneOffset() * 6e4);
  return local.toISOString().slice(0, 16);
}
function rulesJsonToText(rulesJson) {
  if (!rulesJson) return '{\n  "campaign_key": "",\n  "owner_username": "",\n  "presentation_style": "hero_grid",\n  "min_quality_score": 80\n}';
  try {
    return JSON.stringify(rulesJson, null, 2);
  } catch {
    return '{\n  "campaign_key": "",\n  "owner_username": "",\n  "presentation_style": "hero_grid",\n  "min_quality_score": 80\n}';
  }
}
function Field$1({ label, help, children }) {
  return /* @__PURE__ */ React.createElement("label", { className: "block space-y-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, label), children, help ? /* @__PURE__ */ React.createElement("span", { className: "block text-xs leading-relaxed text-slate-400" }, help) : null);
}
function CollectionStaffSurfaces() {
  const { props } = X$1();
  const collectionOptions = Array.isArray(props.collectionOptions) ? props.collectionOptions : [];
  const [definitions, setDefinitions] = React.useState(Array.isArray(props.definitions) ? props.definitions : []);
  const [placements, setPlacements] = React.useState(Array.isArray(props.placements) ? props.placements : []);
  const [conflicts, setConflicts] = React.useState(Array.isArray(props.conflicts) ? props.conflicts : []);
  const [definitionForm, setDefinitionForm] = React.useState({
    id: null,
    surface_key: "",
    title: "",
    description: "",
    mode: "manual",
    ranking_mode: "ranking_score",
    max_items: 12,
    is_active: true,
    starts_at: "",
    ends_at: "",
    fallback_surface_key: "",
    rules_json: '{\n  "campaign_key": "",\n  "owner_username": "",\n  "presentation_style": "hero_grid",\n  "min_quality_score": 80\n}'
  });
  const [placementForm, setPlacementForm] = React.useState({
    id: null,
    surface_key: props.surfaceKeyOptions?.[0] || "",
    collection_id: collectionOptions[0]?.id || "",
    placement_type: "manual",
    priority: 0,
    starts_at: "",
    ends_at: "",
    is_active: true,
    campaign_key: "",
    notes: ""
  });
  const [batchForm, setBatchForm] = React.useState({
    collection_ids: [],
    campaign_key: "",
    campaign_label: "",
    event_label: "",
    season_key: "",
    editorial_notes: "",
    surface_key: props.surfaceKeyOptions?.[0] || "",
    placement_type: "campaign",
    priority: 0,
    starts_at: "",
    ends_at: "",
    is_active: true,
    notes: ""
  });
  const [batchResult, setBatchResult] = React.useState(null);
  const [notice, setNotice] = React.useState("");
  const [busy, setBusy] = React.useState("");
  const seo = props.seo || {};
  const surfaceKeyOptions = React.useMemo(() => {
    const keys2 = definitions.map((definition2) => definition2.surface_key).filter(Boolean);
    return Array.from(new Set(keys2)).sort((left, right) => String(left).localeCompare(String(right)));
  }, [definitions]);
  const conflictPlacementIds = React.useMemo(() => {
    return new Set(conflicts.flatMap((conflict) => Array.isArray(conflict.placement_ids) ? conflict.placement_ids : []));
  }, [conflicts]);
  React.useEffect(() => {
    setPlacementForm((current) => {
      if (current.surface_key && surfaceKeyOptions.includes(current.surface_key)) {
        return current;
      }
      return {
        ...current,
        surface_key: surfaceKeyOptions[0] || ""
      };
    });
    setBatchForm((current) => {
      if (!current.surface_key || surfaceKeyOptions.includes(current.surface_key)) {
        return current;
      }
      return {
        ...current,
        surface_key: surfaceKeyOptions[0] || ""
      };
    });
  }, [surfaceKeyOptions]);
  function resetDefinitionForm() {
    setDefinitionForm({
      id: null,
      surface_key: "",
      title: "",
      description: "",
      mode: "manual",
      ranking_mode: "ranking_score",
      max_items: 12,
      is_active: true,
      starts_at: "",
      ends_at: "",
      fallback_surface_key: "",
      rules_json: '{\n  "campaign_key": "",\n  "owner_username": "",\n  "presentation_style": "hero_grid",\n  "min_quality_score": 80\n}'
    });
  }
  function resetPlacementForm() {
    setPlacementForm({
      id: null,
      surface_key: surfaceKeyOptions[0] || "",
      collection_id: collectionOptions[0]?.id || "",
      placement_type: "manual",
      priority: 0,
      starts_at: "",
      ends_at: "",
      is_active: true,
      campaign_key: "",
      notes: ""
    });
  }
  function toggleBatchCollection(collectionId) {
    setBatchForm((current) => {
      const currentIds = Array.isArray(current.collection_ids) ? current.collection_ids : [];
      const nextIds = currentIds.includes(collectionId) ? currentIds.filter((id) => id !== collectionId) : [...currentIds, collectionId];
      return {
        ...current,
        collection_ids: nextIds
      };
    });
  }
  async function handleDefinitionSubmit(event) {
    event.preventDefault();
    setBusy("definition");
    setNotice("");
    try {
      const rulesJson = definitionForm.rules_json.trim() ? JSON.parse(definitionForm.rules_json) : null;
      const url = definitionForm.id ? props.endpoints?.definitionsUpdatePattern?.replace("__DEFINITION__", String(definitionForm.id)) : props.endpoints?.definitionsStore;
      const payload = await requestJson$i(url, {
        method: definitionForm.id ? "PATCH" : "POST",
        body: {
          ...definitionForm,
          max_items: Number(definitionForm.max_items || 12),
          starts_at: definitionForm.starts_at ? new Date(definitionForm.starts_at).toISOString() : null,
          ends_at: definitionForm.ends_at ? new Date(definitionForm.ends_at).toISOString() : null,
          fallback_surface_key: definitionForm.fallback_surface_key || null,
          rules_json: rulesJson
        }
      });
      setDefinitions((current) => {
        const next = current.filter((definition2) => definition2.id !== payload.definition.id);
        return [...next, payload.definition].sort((left, right) => String(left.surface_key).localeCompare(String(right.surface_key)));
      });
      setNotice(definitionForm.id ? "Surface definition updated." : "Surface definition saved.");
      resetDefinitionForm();
    } catch (error) {
      setNotice(error.message || "Failed to save definition.");
    } finally {
      setBusy("");
    }
  }
  async function handlePlacementSubmit(event) {
    event.preventDefault();
    setBusy("placement");
    setNotice("");
    try {
      const url = placementForm.id ? props.endpoints?.placementsUpdatePattern?.replace("__PLACEMENT__", String(placementForm.id)) : props.endpoints?.placementsStore;
      const payload = await requestJson$i(url, {
        method: placementForm.id ? "PATCH" : "POST",
        body: {
          ...placementForm,
          collection_id: Number(placementForm.collection_id),
          priority: Number(placementForm.priority || 0),
          starts_at: placementForm.starts_at ? new Date(placementForm.starts_at).toISOString() : null,
          ends_at: placementForm.ends_at ? new Date(placementForm.ends_at).toISOString() : null
        }
      });
      setPlacements((current) => {
        const next = current.filter((placement) => placement.id !== payload.placement.id);
        return [...next, payload.placement].sort((left, right) => {
          if (left.surface_key === right.surface_key) return (right.priority || 0) - (left.priority || 0);
          return String(left.surface_key).localeCompare(String(right.surface_key));
        });
      });
      setConflicts(Array.isArray(payload.conflicts) ? payload.conflicts : []);
      setNotice(placementForm.id ? "Surface placement updated." : "Surface placement saved.");
      resetPlacementForm();
    } catch (error) {
      setNotice(error.message || "Failed to save placement.");
    } finally {
      setBusy("");
    }
  }
  async function handleBatchEditorial(mode) {
    setBusy(`batch-${mode}`);
    setNotice("");
    try {
      const payload = await requestJson$i(props.endpoints?.batchEditorial, {
        method: "POST",
        body: {
          ...batchForm,
          starts_at: batchForm.starts_at ? new Date(batchForm.starts_at).toISOString() : null,
          ends_at: batchForm.ends_at ? new Date(batchForm.ends_at).toISOString() : null,
          collection_ids: (batchForm.collection_ids || []).map((id) => Number(id)),
          priority: Number(batchForm.priority || 0),
          surface_key: batchForm.surface_key || null,
          apply: mode === "apply"
        }
      });
      setBatchResult(payload.plan || null);
      if (mode === "apply") {
        setPlacements(Array.isArray(payload.placements) ? payload.placements : []);
        setConflicts(Array.isArray(payload.conflicts) ? payload.conflicts : []);
        setNotice("Batch editorial changes applied.");
      } else {
        setNotice("Batch editorial preview generated.");
      }
    } catch (error) {
      setNotice(error.message || "Batch editorial tools failed.");
    } finally {
      setBusy("");
    }
  }
  function hydrateDefinition(definition2) {
    setDefinitionForm({
      id: definition2.id,
      surface_key: definition2.surface_key || "",
      title: definition2.title || "",
      description: definition2.description || "",
      mode: definition2.mode || "manual",
      ranking_mode: definition2.ranking_mode || "ranking_score",
      max_items: definition2.max_items || 12,
      is_active: definition2.is_active !== false,
      starts_at: isoToLocalInput(definition2.starts_at),
      ends_at: isoToLocalInput(definition2.ends_at),
      fallback_surface_key: definition2.fallback_surface_key || "",
      rules_json: rulesJsonToText(definition2.rules_json)
    });
  }
  function hydratePlacement(placement) {
    setPlacementForm({
      id: placement.id,
      surface_key: placement.surface_key || "",
      collection_id: placement.collection?.id || "",
      placement_type: placement.placement_type || "manual",
      priority: placement.priority || 0,
      starts_at: isoToLocalInput(placement.starts_at),
      ends_at: isoToLocalInput(placement.ends_at),
      is_active: placement.is_active !== false,
      campaign_key: placement.campaign_key || "",
      notes: placement.notes || ""
    });
  }
  async function handleDeleteDefinition(definition2) {
    if (!window.confirm(`Delete surface definition "${definition2.surface_key}"?`)) return;
    setBusy(`delete-definition-${definition2.id}`);
    setNotice("");
    try {
      const url = props.endpoints?.definitionsDeletePattern?.replace("__DEFINITION__", String(definition2.id));
      await requestJson$i(url, { method: "DELETE" });
      setDefinitions((current) => current.filter((item) => item.id !== definition2.id));
      if (definitionForm.id === definition2.id) {
        resetDefinitionForm();
      }
      setNotice("Surface definition deleted.");
    } catch (error) {
      setNotice(error.message || "Failed to delete definition.");
    } finally {
      setBusy("");
    }
  }
  async function handleDeletePlacement(placement) {
    if (!window.confirm(`Delete placement for "${placement.collection?.title || "this collection"}" on ${placement.surface_key}?`)) return;
    setBusy(`delete-placement-${placement.id}`);
    setNotice("");
    try {
      const url = props.endpoints?.placementsDeletePattern?.replace("__PLACEMENT__", String(placement.id));
      const payload = await requestJson$i(url, { method: "DELETE" });
      setPlacements((current) => current.filter((item) => item.id !== placement.id));
      setConflicts(Array.isArray(payload.conflicts) ? payload.conflicts : []);
      if (placementForm.id === placement.id) {
        resetPlacementForm();
      }
      setNotice("Surface placement deleted.");
    } catch (error) {
      setNotice(error.message || "Failed to delete placement.");
    } finally {
      setBusy("");
    }
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se$1, null, /* @__PURE__ */ React.createElement("title", null, seo.title || "Collection Surfaces — Skinbase"), /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description || "Staff tools for collection surfaces." }), seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null, /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots || "noindex,follow" })), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-95", style: { background: "radial-gradient(circle at 15% 14%, rgba(245,158,11,0.16), transparent 26%), radial-gradient(circle at 82% 18%, rgba(56,189,248,0.16), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Staff Surfaces"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, "Collections placement studio"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "Define reusable discovery surfaces, then place eligible public collections into manual or campaign-specific slots with clear timing and notes."), notice ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-sky-100" }, notice) : null), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleDefinitionSubmit, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Surface Definition"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Rules and ranking")), definitionForm.id ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, "Editing ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, definitionForm.surface_key)) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Surface Key", help: definitionForm.id ? "Surface keys stay stable during edits so existing placements remain attached." : null }, /* @__PURE__ */ React.createElement("input", { value: definitionForm.surface_key, onChange: (event) => setDefinitionForm((current) => ({ ...current, surface_key: event.target.value })), disabled: Boolean(definitionForm.id), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none disabled:cursor-not-allowed disabled:opacity-60", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Title" }, /* @__PURE__ */ React.createElement("input", { value: definitionForm.title, onChange: (event) => setDefinitionForm((current) => ({ ...current, title: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 160 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Mode" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: definitionForm.mode, onChange: (val) => setDefinitionForm((current) => ({ ...current, mode: val })), searchable: false, options: [{ value: "manual", label: "Manual" }, { value: "automatic", label: "Automatic" }, { value: "hybrid", label: "Hybrid" }] })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ranking" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: definitionForm.ranking_mode, onChange: (val) => setDefinitionForm((current) => ({ ...current, ranking_mode: val })), searchable: false, options: [{ value: "ranking_score", label: "Ranking score" }, { value: "recent_activity", label: "Recent activity" }, { value: "quality_score", label: "Quality score" }] })), /* @__PURE__ */ React.createElement(Field$1, { label: "Max Items" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "1", max: "24", value: definitionForm.max_items, onChange: (event) => setDefinitionForm((current) => ({ ...current, max_items: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Starts At", help: "Optional activation window for the full surface definition." }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: definitionForm.starts_at, onChange: (nextValue) => setDefinitionForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Start time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ends At", help: "Leave blank when the surface should stay live until staff changes it." }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: definitionForm.ends_at, onChange: (nextValue) => setDefinitionForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "End time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Fallback Surface Key", help: "Optional fallback when this definition is inactive, scheduled out, or resolves no items." }, /* @__PURE__ */ React.createElement("input", { value: definitionForm.fallback_surface_key, onChange: (event) => setDefinitionForm((current) => ({ ...current, fallback_surface_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: definitionForm.is_active, onChange: (event) => setDefinitionForm((current) => ({ ...current, is_active: event.target.checked })), label: "Active" }))), /* @__PURE__ */ React.createElement(Field$1, { label: "Description", help: "Operational note for staff browsing this surface later." }, /* @__PURE__ */ React.createElement("textarea", { value: definitionForm.description, onChange: (event) => setDefinitionForm((current) => ({ ...current, description: event.target.value })), className: "mt-4 min-h-[96px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 400 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Rules JSON", help: "Supported filters include campaign, event, season, type, presentation_style, theme_token, collaboration_mode, owner_username or owner_usernames, commercial_eligible_only, analytics_enabled_only, min_quality_score, min_ranking_score, include_collection_ids, exclude_collection_ids, and featured_only." }, /* @__PURE__ */ React.createElement("textarea", { value: definitionForm.rules_json, onChange: (event) => setDefinitionForm((current) => ({ ...current, rules_json: event.target.value })), className: "mt-4 min-h-[160px] w-full rounded-2xl border border-white/10 bg-slate-950/50 px-4 py-3 font-mono text-sm text-white outline-none", spellCheck: false })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "definition", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "definition" ? "fa-circle-notch fa-spin" : "fa-layer-group"} fa-fw` }), definitionForm.id ? "Update Definition" : "Save Definition"), definitionForm.id ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetDefinitionForm, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left fa-fw" }), "Cancel Edit") : null)), /* @__PURE__ */ React.createElement("form", { onSubmit: handlePlacementSubmit, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Surface Placement"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Manual and campaign slots")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Surface" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: placementForm.surface_key, onChange: (val) => setPlacementForm((current) => ({ ...current, surface_key: val })), options: surfaceKeyOptions.map((o) => ({ value: o, label: o })) })), /* @__PURE__ */ React.createElement(Field$1, { label: "Collection" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(placementForm.collection_id || ""), onChange: (val) => setPlacementForm((current) => ({ ...current, collection_id: val })), options: collectionOptions.map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement(Field$1, { label: "Placement Type" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: placementForm.placement_type, onChange: (val) => setPlacementForm((current) => ({ ...current, placement_type: val })), searchable: false, options: [{ value: "manual", label: "Manual" }, { value: "campaign", label: "Campaign" }, { value: "scheduled_override", label: "Scheduled override" }] })), /* @__PURE__ */ React.createElement(Field$1, { label: "Priority" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "-100", max: "100", value: placementForm.priority, onChange: (event) => setPlacementForm((current) => ({ ...current, priority: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Starts At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: placementForm.starts_at, onChange: (nextValue) => setPlacementForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Start time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ends At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: placementForm.ends_at, onChange: (nextValue) => setPlacementForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "End time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Campaign Key", help: "Optional campaign label for reporting and grouped overrides." }, /* @__PURE__ */ React.createElement("input", { value: placementForm.campaign_key, onChange: (event) => setPlacementForm((current) => ({ ...current, campaign_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: placementForm.is_active, onChange: (event) => setPlacementForm((current) => ({ ...current, is_active: event.target.checked })), label: "Active placement" }))), /* @__PURE__ */ React.createElement(Field$1, { label: "Notes", help: "Internal note for why this collection owns the slot." }, /* @__PURE__ */ React.createElement("textarea", { value: placementForm.notes, onChange: (event) => setPlacementForm((current) => ({ ...current, notes: event.target.value })), className: "mt-4 min-h-[110px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 1e3 })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "placement", className: "inline-flex items-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "placement" ? "fa-circle-notch fa-spin" : "fa-thumbtack"} fa-fw` }), placementForm.id ? "Update Placement" : "Save Placement"), placementForm.id ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetPlacementForm, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left fa-fw" }), "Cancel Edit") : null))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Batch Editorial Tools"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Campaign planning in one pass")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, batchForm.collection_ids.length, " selected")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Choose collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "The selector uses current public discovery candidates so staff can quickly prepare a seasonal or editorial run."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, collectionOptions.map((option) => {
    const checked = batchForm.collection_ids.includes(option.id);
    return /* @__PURE__ */ React.createElement("label", { key: option.id, className: `flex cursor-pointer items-start gap-3 rounded-[22px] border px-4 py-3 transition ${checked ? "border-lime-300/30 bg-lime-400/10" : "border-white/10 bg-white/[0.04] hover:bg-white/[0.07]"}` }, /* @__PURE__ */ React.createElement(Checkbox, { checked, onChange: () => toggleBatchCollection(option.id) }), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block truncate text-sm font-semibold text-white" }, option.title), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs text-slate-400" }, option.type || "collection", " · ", option.visibility || "public")));
  }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Campaign metadata"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Campaign Key" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.campaign_key, onChange: (event) => setBatchForm((current) => ({ ...current, campaign_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Campaign Label" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.campaign_label, onChange: (event) => setBatchForm((current) => ({ ...current, campaign_label: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Event Label" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.event_label, onChange: (event) => setBatchForm((current) => ({ ...current, event_label: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Season Key" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.season_key, onChange: (event) => setBatchForm((current) => ({ ...current, season_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 }))), /* @__PURE__ */ React.createElement(Field$1, { label: "Editorial Notes", help: "Shared context recorded on each selected collection." }, /* @__PURE__ */ React.createElement("textarea", { value: batchForm.editorial_notes, onChange: (event) => setBatchForm((current) => ({ ...current, editorial_notes: event.target.value })), className: "mt-4 min-h-[120px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 4e3 })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Optional placement plan"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "If you set a surface, the preview shows which collections can safely be placed and which ones will be skipped."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Surface" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: batchForm.surface_key, onChange: (val) => setBatchForm((current) => ({ ...current, surface_key: val })), placeholder: "No placement", options: surfaceKeyOptions.map((o) => ({ value: o, label: o })) })), /* @__PURE__ */ React.createElement(Field$1, { label: "Placement Type" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: batchForm.placement_type, onChange: (val) => setBatchForm((current) => ({ ...current, placement_type: val })), searchable: false, options: [{ value: "campaign", label: "Campaign" }, { value: "manual", label: "Manual" }, { value: "scheduled_override", label: "Scheduled override" }] })), /* @__PURE__ */ React.createElement(Field$1, { label: "Priority" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "-100", max: "100", value: batchForm.priority, onChange: (event) => setBatchForm((current) => ({ ...current, priority: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: batchForm.is_active, onChange: (event) => setBatchForm((current) => ({ ...current, is_active: event.target.checked })), label: "Active placement" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Starts At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: batchForm.starts_at, onChange: (nextValue) => setBatchForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Start time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ends At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: batchForm.ends_at, onChange: (nextValue) => setBatchForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "End time", clearable: true, className: "bg-white/[0.04]" }))), /* @__PURE__ */ React.createElement(Field$1, { label: "Placement Notes" }, /* @__PURE__ */ React.createElement("textarea", { value: batchForm.notes, onChange: (event) => setBatchForm((current) => ({ ...current, notes: event.target.value })), className: "mt-4 min-h-[110px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 1e3 })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleBatchEditorial("preview"), disabled: busy === "batch-preview", className: "inline-flex items-center gap-2 rounded-2xl border border-lime-300/20 bg-lime-400/10 px-5 py-3 text-sm font-semibold text-lime-100 transition hover:bg-lime-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "batch-preview" ? "fa-circle-notch fa-spin" : "fa-flask"} fa-fw` }), "Preview Batch"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleBatchEditorial("apply"), disabled: busy === "batch-apply", className: "inline-flex items-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "batch-apply" ? "fa-circle-notch fa-spin" : "fa-wand-magic-sparkles"} fa-fw` }), "Apply Batch"))), batchResult ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Preview results"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, batchResult.collections_count, " collections reviewed, ", batchResult.placement_eligible_count, " placement-ready."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (batchResult.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection?.id, className: "rounded-[22px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, item.collection?.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, item.collection?.visibility, " · ", item.collection?.lifecycle_state, " · ", item.collection?.moderation_status)), item.placement ? /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${item.placement.eligible ? "border-lime-300/20 bg-lime-400/10 text-lime-100" : "border-rose-300/20 bg-rose-400/10 text-rose-100"}` }, item.placement.eligible ? `ready for ${item.placement.surface_key}` : "placement skipped") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "metadata only")), item.eligibility?.reasons?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-amber-100/80" }, "Campaign readiness: ", item.eligibility.reasons.join(" ")) : null, item.placement?.reasons?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-rose-100/80" }, "Placement: ", item.placement.reasons.join(" ")) : null)))) : null))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Definitions"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Registered surfaces")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, definitions.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, definitions.map((definition2) => /* @__PURE__ */ React.createElement("div", { key: definition2.id, className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, definition2.surface_key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, definition2.mode)), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-lg font-semibold text-white" }, definition2.title), definition2.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, definition2.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, definition2.ranking_mode), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "max ", definition2.max_items), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, definition2.is_active ? "active" : "inactive"), definition2.starts_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "starts ", new Date(definition2.starts_at).toLocaleString()) : null, definition2.ends_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "ends ", new Date(definition2.ends_at).toLocaleString()) : null, definition2.fallback_surface_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "fallback ", definition2.fallback_surface_key) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => hydrateDefinition(definition2), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw text-[10px]" }), "Edit Definition"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleDeleteDefinition(definition2), disabled: busy === `delete-definition-${definition2.id}`, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `delete-definition-${definition2.id}` ? "fa-circle-notch fa-spin" : "fa-trash"} fa-fw text-[10px]` }), "Delete"))))))), conflicts.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-rose-300/20 bg-rose-500/10 p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-100/80" }, "Conflicts"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Schedule overlaps need review")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-xs font-semibold text-rose-100" }, conflicts.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, conflicts.map((conflict, index2) => /* @__PURE__ */ React.createElement("div", { key: `${conflict.surface_key}-${index2}`, className: "rounded-[24px] border border-rose-300/20 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-100" }, conflict.surface_key)), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-rose-50" }, conflict.summary), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-rose-100/70" }, "Window: ", conflict.window?.starts_at ? new Date(conflict.window.starts_at).toLocaleString() : "Immediate", " to ", conflict.window?.ends_at ? new Date(conflict.window.ends_at).toLocaleString() : "Open-ended"))))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Placements"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Active and scheduled slots")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, placements.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-5" }, placements.map((placement) => /* @__PURE__ */ React.createElement("div", { key: placement.id, className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, placement.surface_key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, placement.placement_type), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "priority ", placement.priority), conflictPlacementIds.has(placement.id) || placement.has_conflict ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-100" }, "conflict") : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => hydratePlacement(placement), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw text-[10px]" }), "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleDeletePlacement(placement), disabled: busy === `delete-placement-${placement.id}`, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `delete-placement-${placement.id}` ? "fa-circle-notch fa-spin" : "fa-trash"} fa-fw text-[10px]` }), "Delete"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-5 xl:grid-cols-[minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement("div", null, placement.collection ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: placement.collection, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Starts: ", placement.starts_at ? new Date(placement.starts_at).toLocaleString() : "Immediate"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Ends: ", placement.ends_at ? new Date(placement.ends_at).toLocaleString() : "Open-ended"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Campaign: ", placement.campaign_key || "None"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Status: ", placement.is_active ? "Active" : "Inactive"), placement.notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3 text-slate-300" }, placement.notes) : null)))))))));
}
const __vite_glob_0_49 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CollectionStaffSurfaces
}, Symbol.toStringTag, { value: "Module" }));
const aspectRatios = {
  square: "1 / 1",
  portrait: "4 / 5",
  story: "9 / 16",
  landscape: "16 / 9"
};
const placementStyles = {
  "top-left": { top: "12%", left: "12%" },
  "top-right": { top: "12%", right: "12%" },
  "bottom-left": { bottom: "12%", left: "12%" },
  "bottom-right": { bottom: "12%", right: "12%" }
};
function DraggableElement({ elementId, canvasRef, freePos, savedWidth, onMove, style, className, children }) {
  const dragState = React.useRef(null);
  const [localPos, setLocalPos] = React.useState(null);
  const [localWidth, setLocalWidth] = React.useState(null);
  function handlePointerDown(event) {
    event.preventDefault();
    event.stopPropagation();
    const canvas = canvasRef.current;
    if (!canvas) return;
    const canvasRect = canvas.getBoundingClientRect();
    const elemRect = event.currentTarget.getBoundingClientRect();
    const offsetX = event.clientX - elemRect.left;
    const offsetY = event.clientY - elemRect.top;
    const startX = (elemRect.left - canvasRect.left) / canvasRect.width * 100;
    const startY = (elemRect.top - canvasRect.top) / canvasRect.height * 100;
    const widthPct = Math.round(elemRect.width / canvasRect.width * 1e3) / 10;
    dragState.current = { canvasRect, offsetX, offsetY, widthPct };
    event.currentTarget.setPointerCapture(event.pointerId);
    setLocalPos({ x: startX, y: startY });
    setLocalWidth(widthPct);
  }
  function calcPos(event) {
    const { canvasRect, offsetX, offsetY } = dragState.current;
    return {
      x: Math.max(0, Math.min(94, (event.clientX - canvasRect.left - offsetX) / canvasRect.width * 100)),
      y: Math.max(0, Math.min(92, (event.clientY - canvasRect.top - offsetY) / canvasRect.height * 100))
    };
  }
  function handlePointerMove(event) {
    if (!dragState.current) return;
    setLocalPos(calcPos(event));
  }
  function handlePointerUp(event) {
    if (!dragState.current) return;
    const pos = calcPos(event);
    const widthPct = dragState.current.widthPct;
    dragState.current = null;
    setLocalPos(null);
    setLocalWidth(null);
    onMove?.(elementId, Math.round(pos.x * 10) / 10, Math.round(pos.y * 10) / 10, widthPct);
  }
  const isDragging = localPos !== null;
  const absPos = localPos ?? freePos;
  const resolvedWidth = localWidth ?? savedWidth;
  const posStyle = absPos ? { position: "absolute", left: `${absPos.x}%`, top: `${absPos.y}%`, zIndex: isDragging ? 50 : 10, width: resolvedWidth != null ? `${resolvedWidth}%` : void 0 } : {};
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      style: { ...style, ...posStyle, cursor: isDragging ? "grabbing" : "grab", touchAction: "none", userSelect: "none" },
      className: `${className} rounded ${isDragging ? "ring-2 ring-sky-400/70 opacity-90" : "ring-1 ring-transparent hover:ring-white/30"} transition-[box-shadow]`,
      onPointerDown: handlePointerDown,
      onPointerMove: handlePointerMove,
      onPointerUp: handlePointerUp,
      onPointerCancel: handlePointerUp
    },
    children
  );
}
function overlayStyle(style) {
  if (style === "dark-strong") return "linear-gradient(180deg, rgba(2,6,23,0.38), rgba(2,6,23,0.68))";
  if (style === "light-soft") return "linear-gradient(180deg, rgba(255,255,255,0.08), rgba(255,255,255,0.22))";
  if (style === "dark-soft") return "linear-gradient(180deg, rgba(2,6,23,0.18), rgba(2,6,23,0.48))";
  return "none";
}
function positionStyle(position2) {
  if (position2 === "top") return { alignItems: "flex-start", paddingTop: "10%" };
  if (position2 === "upper-middle") return { alignItems: "flex-start", paddingTop: "22%" };
  if (position2 === "lower-middle") return { alignItems: "flex-end", paddingBottom: "18%" };
  if (position2 === "bottom") return { alignItems: "flex-end", paddingBottom: "10%" };
  return { alignItems: "center" };
}
function alignmentClass(alignment) {
  if (alignment === "left") return "justify-start items-start text-left";
  if (alignment === "right") return "justify-end items-end text-right";
  return "justify-center items-center text-center";
}
function focalPositionStyle(position2) {
  if (position2 === "top") return "center top";
  if (position2 === "bottom") return "center bottom";
  if (position2 === "left") return "left center";
  if (position2 === "right") return "right center";
  if (position2 === "top-left") return "left top";
  if (position2 === "top-right") return "right top";
  if (position2 === "bottom-left") return "left bottom";
  if (position2 === "bottom-right") return "right bottom";
  return "center center";
}
function shadowValue(preset) {
  if (preset === "none") return "none";
  if (preset === "strong") return "0 12px 36px rgba(2, 6, 23, 0.72)";
  return "0 8px 24px rgba(2, 6, 23, 0.5)";
}
function resolveTextBlocks(card, project) {
  const blocks = Array.isArray(project.text_blocks) ? project.text_blocks.filter((block) => block?.enabled !== false && String(block?.text || "").trim() !== "") : [];
  if (blocks.length) return blocks;
  const content2 = project.content || {};
  return [
    { key: "title", type: "title", text: card?.title || content2.title || "Untitled card", enabled: true },
    { key: "quote", type: "quote", text: card?.quote_text || content2.quote_text || "Your next quote starts here.", enabled: true },
    { key: "author", type: "author", text: card?.quote_author || content2.quote_author || "", enabled: Boolean(card?.quote_author || content2.quote_author) },
    { key: "source", type: "source", text: card?.quote_source || content2.quote_source || "", enabled: Boolean(card?.quote_source || content2.quote_source) }
  ].filter((block) => String(block.text || "").trim() !== "");
}
function blockClass(type2) {
  if (type2 === "title") return "text-[11px] font-semibold uppercase tracking-[0.28em] text-white/55";
  if (type2 === "author") return "font-medium uppercase tracking-[0.18em] text-white/80 sm:text-sm lg:text-base";
  if (type2 === "source") return "text-[11px] uppercase tracking-[0.18em] text-white/50 sm:text-xs";
  if (type2 === "caption") return "text-[10px] uppercase tracking-[0.2em] text-white/45";
  if (type2 === "body") return "text-sm leading-6 text-white/90 sm:text-base";
  return "font-semibold tracking-[-0.03em] sm:text-[1.65rem] lg:text-[2.1rem]";
}
function blockStyle(type2, typography, textColor, accentColor, fontFamily) {
  const quoteSize = Math.max(10, Math.min(typography.quote_size || 72, 120));
  const authorSize = Math.max(14, Math.min(typography.author_size || 28, 42));
  const letterSpacing = Math.max(-1, Math.min(typography.letter_spacing || 0, 10));
  const lineHeight = Math.max(0.9, Math.min(typography.line_height || 1.2, 1.8));
  const shadowPreset = typography.shadow_preset || "soft";
  const opacity = typography.text_opacity != null ? Math.max(10, Math.min(100, Number(typography.text_opacity))) / 100 : 1;
  const toCqw = (px) => `${(px / 1080 * 100).toFixed(2)}cqw`;
  const sizeMap2 = {
    title: toCqw(Math.max(16, quoteSize * 0.48)),
    quote: toCqw(quoteSize),
    author: toCqw(authorSize),
    source: toCqw(Math.max(12, authorSize * 0.82)),
    body: toCqw(Math.max(16, quoteSize * 0.54)),
    caption: toCqw(Math.max(12, authorSize * 0.74))
  };
  const fontSize = sizeMap2[type2] ?? sizeMap2.quote;
  const font = fontFamily ? { fontFamily } : {};
  if (type2 === "title") {
    return { ...font, opacity, color: accentColor, fontSize, letterSpacing: `${Math.max(letterSpacing, 0) / 10}em`, textShadow: shadowValue(shadowPreset) };
  }
  if (type2 === "author" || type2 === "source") {
    return { ...font, opacity, color: accentColor, fontSize, textShadow: shadowValue(shadowPreset) };
  }
  if (type2 === "body" || type2 === "caption") {
    return { ...font, opacity, color: textColor, fontSize, lineHeight, textShadow: shadowValue(shadowPreset) };
  }
  return { ...font, opacity, color: textColor, fontSize, lineHeight, letterSpacing: `${letterSpacing / 12}px`, textShadow: shadowValue(shadowPreset) };
}
function NovaCardCanvasPreview({ card, fonts = [], className = "", editable = false, onElementMove = null, renderMode = false }) {
  const canvasRef = React.useRef(null);
  const project = card?.project_json || {};
  const layout = project.layout || {};
  const typography = project.typography || {};
  const resolvedFont = fonts.find((f2) => f2.key === (typography.font_preset || "modern-sans"));
  const fontFamily = resolvedFont?.family || null;
  const background = project.background || {};
  const backgroundImage = card?.background_image?.processed_url;
  const colors = Array.isArray(background.gradient_colors) && background.gradient_colors.length >= 2 ? background.gradient_colors : ["#0f172a", "#1d4ed8"];
  const backgroundStyle = background.type === "upload" && backgroundImage ? `url(${backgroundImage}) ${focalPositionStyle(background.focal_position)}/cover no-repeat` : background.type === "solid" ? background.solid_color || "#111827" : `linear-gradient(180deg, ${colors[0]}, ${colors[1]})`;
  const allTextBlocks = resolveTextBlocks(card, project);
  const flowTextBlocks = allTextBlocks.filter((b2) => b2.pos_x == null || b2.pos_y == null);
  const freeTextBlocks = allTextBlocks.filter((b2) => b2.pos_x != null && b2.pos_y != null);
  const decorations = Array.isArray(project.decorations) ? project.decorations : [];
  const assetItems = Array.isArray(project.assets?.items) ? project.assets.items : [];
  const textColor = typography.text_color || "#ffffff";
  const accentColor = typography.accent_color || textColor;
  const layoutMaxWidth = layout.max_width === "compact" ? "62%" : layout.max_width === "wide" ? "88%" : "76%";
  const maxWidth = typography.quote_width != null ? `${typography.quote_width}%` : layoutMaxWidth;
  const padding = layout.padding === "tight" ? "8%" : layout.padding === "airy" ? "14%" : "11%";
  return /* @__PURE__ */ React.createElement("div", { ref: canvasRef, "data-card-canvas": true, className: `relative overflow-hidden bg-slate-950 [container-type:inline-size] ${renderMode ? "" : "rounded-[28px] border border-white/10 shadow-[0_30px_80px_rgba(2,6,23,0.35)]"} ${className}`, style: { aspectRatio: aspectRatios[card?.format || "square"] || aspectRatios.square } }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0", style: { background: backgroundStyle, filter: background.type === "upload" && Number(background.blur_level || 0) > 0 ? `blur(${Math.max(Number(background.blur_level) / 8, 0)}px)` : void 0 } }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0", style: { background: overlayStyle(background.overlay_style), opacity: Math.max(0, Math.min(Number(background.opacity || 50), 100)) / 100 } }), !renderMode && /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 rounded-full border border-white/10 bg-black/25 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white/80 backdrop-blur" }, (card?.format || "square").replace("-", " ")), assetItems.slice(0, 6).map((item, index2) => {
    if (item?.type === "frame") {
      const top = index2 % 2 === 0 ? "10%" : "88%";
      return /* @__PURE__ */ React.createElement("div", { key: `${item.asset_key || item.label || "frame"}-${index2}`, className: "absolute left-[12%] right-[12%] h-px bg-white/35", style: { top } });
    }
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: `${item.asset_key || item.label || "asset"}-${index2}`,
        className: "absolute text-white/85 drop-shadow-[0_6px_14px_rgba(2,6,23,0.3)]",
        style: {
          top: `${12 + index2 % 3 * 18}%`,
          left: `${10 + Math.floor(index2 / 3) * 72}%`,
          color: accentColor,
          fontSize: `${(Math.max(18, Math.min(item.size || 26, 56)) / 1080 * 100).toFixed(2)}cqw`
        }
      },
      item.glyph || item.label || "✦"
    );
  }), /* @__PURE__ */ React.createElement("div", { className: `relative flex h-full w-full ${alignmentClass(layout.alignment)}`, style: { padding, ...positionStyle(layout.position) } }, /* @__PURE__ */ React.createElement("div", { className: "flex w-full flex-col gap-4", style: { maxWidth } }, flowTextBlocks.map((block, index2) => {
    const type2 = block?.type || "body";
    const text2 = type2 === "author" ? `— ${block.text}` : block.text;
    const defStyle = blockStyle(type2, typography, textColor, accentColor, fontFamily);
    const blockCls = blockClass(type2);
    const blockKey = `${block.key || type2}-${index2}`;
    if (editable) {
      return /* @__PURE__ */ React.createElement(
        DraggableElement,
        {
          key: blockKey,
          elementId: `block:${block.key || type2}`,
          canvasRef,
          freePos: null,
          onMove: onElementMove,
          style: defStyle,
          className: blockCls
        },
        text2
      );
    }
    return /* @__PURE__ */ React.createElement("div", { key: blockKey, style: defStyle, className: blockCls }, text2);
  }))), freeTextBlocks.map((block, index2) => {
    const type2 = block?.type || "body";
    const text2 = type2 === "author" ? `— ${block.text}` : block.text;
    const defStyle = blockStyle(type2, typography, textColor, accentColor, fontFamily);
    const blockCls = blockClass(type2);
    const blockKey = `free-${block.key || type2}-${index2}`;
    if (editable) {
      return /* @__PURE__ */ React.createElement(
        DraggableElement,
        {
          key: blockKey,
          elementId: `block:${block.key || type2}`,
          canvasRef,
          freePos: { x: block.pos_x, y: block.pos_y },
          savedWidth: block.pos_width ?? null,
          onMove: onElementMove,
          style: defStyle,
          className: blockCls
        },
        text2
      );
    }
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: blockKey,
        style: { ...defStyle, position: "absolute", left: `${block.pos_x}%`, top: `${block.pos_y}%`, ...block.pos_width != null ? { width: `${block.pos_width}%` } : {} },
        className: blockCls
      },
      text2
    );
  }), decorations.slice(0, 6).map((decoration, index2) => {
    const hasFreePos = decoration.pos_x != null && decoration.pos_y != null;
    const placementPos = placementStyles[decoration.placement] || placementStyles["top-right"];
    const decOpacity = decoration.opacity != null ? Math.max(10, Math.min(100, Number(decoration.opacity))) / 100 : 0.85;
    const decStyle = {
      color: accentColor,
      fontSize: `${(Math.max(18, Math.min(decoration.size || 28, 64)) / 1080 * 100).toFixed(2)}cqw`,
      opacity: decOpacity,
      zIndex: 20
    };
    const decKey = `${decoration.key || decoration.glyph || "dec"}-${index2}`;
    const decContent = decoration.glyph || "✦";
    if (editable) {
      const freePos = hasFreePos ? { x: decoration.pos_x, y: decoration.pos_y } : null;
      const absStyle = hasFreePos ? { position: "absolute", left: `${decoration.pos_x}%`, top: `${decoration.pos_y}%` } : { position: "absolute", ...placementPos };
      return /* @__PURE__ */ React.createElement(
        DraggableElement,
        {
          key: decKey,
          elementId: `decoration:${index2}`,
          canvasRef,
          freePos,
          savedWidth: null,
          onMove: onElementMove,
          style: { ...absStyle, ...decStyle },
          className: "drop-shadow-[0_6px_14px_rgba(2,6,23,0.3)]"
        },
        decContent
      );
    }
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: decKey,
        className: "absolute drop-shadow-[0_6px_14px_rgba(2,6,23,0.3)]",
        style: { ...placementPos, ...decStyle }
      },
      decContent
    );
  }));
}
function requestJson$h(url, { method = "GET", body: body2 } = {}) {
  return fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(payload?.message || "Request failed");
    return payload;
  });
}
function renderOverrideHistoryItems(items, prefix) {
  return (items || []).slice(0, 3).map((entry, index2) => /* @__PURE__ */ React.createElement("div", { key: `${prefix}-${index2}-${entry.updated_at || entry.source || entry.moderation_status || "override"}`, className: "rounded-2xl border border-white/10 bg-black/10 px-3 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-sky-100/75" }, /* @__PURE__ */ React.createElement("span", null, entry.moderation_status || "unknown status"), entry.disposition_label ? /* @__PURE__ */ React.createElement("span", null, entry.disposition_label) : null, entry.actor_username ? /* @__PURE__ */ React.createElement("span", null, "@", entry.actor_username) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.14em] text-sky-100/55" }, entry.source ? /* @__PURE__ */ React.createElement("span", null, String(entry.source).replaceAll("_", " ")) : null, entry.updated_at ? /* @__PURE__ */ React.createElement("span", null, new Date(entry.updated_at).toLocaleString()) : null), entry.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-sky-50" }, entry.note) : null));
}
function NovaCardsAdminIndex() {
  const { props } = X$1();
  const [cards, setCards] = React.useState(props.cards?.data || []);
  const [featuredCreators, setFeaturedCreators] = React.useState(props.featuredCreators || []);
  const [categories, setCategories] = React.useState(props.categories || []);
  const [reportStatus, setReportStatus] = React.useState("open");
  const [reports, setReports] = React.useState([]);
  const [reportsMeta, setReportsMeta] = React.useState({ total: 0 });
  const [reportCounts, setReportCounts] = React.useState(props.reportingQueue?.statuses || { open: 0, reviewing: 0, closed: 0 });
  const [reportNotes, setReportNotes] = React.useState({});
  const [reportBusy, setReportBusy] = React.useState({});
  const [reportsLoading, setReportsLoading] = React.useState(false);
  const [reportsError, setReportsError] = React.useState("");
  const [cardDispositions, setCardDispositions] = React.useState(() => Object.fromEntries((props.cards?.data || []).map((card) => [card.id, card.moderation_override?.disposition || ""])));
  const [reportDispositions, setReportDispositions] = React.useState({});
  const [newCategory, setNewCategory] = React.useState({ slug: "", name: "", description: "", active: true, order_num: categories.length });
  const endpoints = props.endpoints || {};
  const stats = props.stats || {};
  const reportingQueue = props.reportingQueue || {};
  const moderationDispositionOptions = props.moderationDispositionOptions || {};
  function dispositionOptionsForStatus(status2) {
    return moderationDispositionOptions?.[status2] || [];
  }
  function preferredDisposition(status2, currentValue) {
    const options = dispositionOptionsForStatus(status2);
    if (currentValue && options.some((option) => option.value === currentValue)) {
      return currentValue;
    }
    return options[0]?.value || "";
  }
  React.useEffect(() => {
    let active = true;
    async function loadReports() {
      if (!endpoints.reportsQueue) {
        return;
      }
      setReportsLoading(true);
      setReportsError("");
      try {
        const separator = String(endpoints.reportsQueue).includes("?") ? "&" : "?";
        const response = await requestJson$h(`${endpoints.reportsQueue}${separator}status=${reportStatus}`);
        if (!active) return;
        setReports(response.data || []);
        setReportsMeta(response.meta || { total: 0 });
        setReportDispositions((current) => {
          const next = { ...current };
          (response.data || []).forEach((report) => {
            const target = report?.target?.moderation_target;
            if (target?.card_id && !(report.id in next)) {
              next[report.id] = preferredDisposition(target.moderation_status, target.moderation_override?.disposition);
            }
          });
          return next;
        });
        setReportNotes((current) => {
          const next = { ...current };
          (response.data || []).forEach((report) => {
            if (!(report.id in next)) {
              next[report.id] = report.moderator_note || "";
            }
          });
          return next;
        });
      } catch (error) {
        if (!active) return;
        setReportsError(error.message);
        setReports([]);
      } finally {
        if (active) {
          setReportsLoading(false);
        }
      }
    }
    loadReports();
    return () => {
      active = false;
    };
  }, [endpoints.reportsQueue, reportStatus]);
  async function updateCard(cardId, patch2) {
    const response = await requestJson$h(String(endpoints.updateCardPattern || "").replace("__CARD__", String(cardId)), {
      method: "PATCH",
      body: patch2
    });
    setCardDispositions((current) => ({
      ...current,
      [cardId]: preferredDisposition(response.card?.moderation_status, response.card?.moderation_override?.disposition)
    }));
    setCards((current) => current.map((card) => card.id === cardId ? response.card : card));
  }
  async function updateCreator(creatorId, patch2) {
    const response = await requestJson$h(String(endpoints.updateCreatorPattern || "").replace("__CREATOR__", String(creatorId)), {
      method: "PATCH",
      body: patch2
    });
    setFeaturedCreators((current) => current.map((creator) => creator.id === creatorId ? response.creator : creator));
  }
  function syncReportCounts(previousStatus, nextStatus) {
    if (!previousStatus || !nextStatus || previousStatus === nextStatus) {
      return;
    }
    setReportCounts((current) => ({
      ...current,
      [previousStatus]: Math.max(0, Number(current?.[previousStatus] || 0) - 1),
      [nextStatus]: Number(current?.[nextStatus] || 0) + 1
    }));
  }
  function mergeUpdatedReport(updatedReport, previousStatus) {
    setReportNotes((current) => ({ ...current, [updatedReport.id]: updatedReport.moderator_note || "" }));
    setReportDispositions((current) => ({
      ...current,
      [updatedReport.id]: preferredDisposition(updatedReport?.target?.moderation_target?.moderation_status, updatedReport?.target?.moderation_target?.moderation_override?.disposition)
    }));
    if (previousStatus && previousStatus !== updatedReport.status) {
      syncReportCounts(previousStatus, updatedReport.status);
    }
    setReports((current) => {
      if (previousStatus && previousStatus !== updatedReport.status) {
        return current.filter((report) => report.id !== updatedReport.id);
      }
      return current.map((report) => report.id === updatedReport.id ? updatedReport : report);
    });
  }
  async function saveCategory(category) {
    const isExisting = Boolean(category.id);
    const url = isExisting ? String(endpoints.updateCategoryPattern || "").replace("__CATEGORY__", String(category.id)) : endpoints.storeCategory;
    const response = await requestJson$h(url, {
      method: isExisting ? "PATCH" : "POST",
      body: category
    });
    setCategories((current) => {
      if (isExisting) {
        return current.map((item) => item.id === category.id ? { ...item, ...response.category } : item);
      }
      return [...current, { ...response.category, cards_count: 0 }];
    });
    if (!isExisting) {
      setNewCategory({ slug: "", name: "", description: "", active: true, order_num: categories.length + 1 });
    }
  }
  async function updateReport(reportId, patch2) {
    const currentReport = reports.find((report) => report.id === reportId);
    if (!currentReport) {
      return;
    }
    setReportBusy((current) => ({ ...current, [reportId]: true }));
    try {
      const response = await requestJson$h(String(endpoints.updateReportPattern || "").replace("__REPORT__", String(reportId)), {
        method: "PATCH",
        body: patch2
      });
      mergeUpdatedReport(response.report, currentReport.status);
    } finally {
      setReportBusy((current) => ({ ...current, [reportId]: false }));
    }
  }
  async function moderateReportTarget(reportId, action) {
    const currentReport = reports.find((report) => report.id === reportId);
    if (!currentReport) {
      return;
    }
    setReportBusy((current) => ({ ...current, [reportId]: true }));
    try {
      const response = await requestJson$h(String(endpoints.moderateReportTargetPattern || "").replace("__REPORT__", String(reportId)), {
        method: "POST",
        body: { action, disposition: reportDispositions[reportId] || null }
      });
      mergeUpdatedReport(response.report, currentReport.status);
      setCards((current) => current.map((card) => card.id === response.report?.target?.moderation_target?.card_id ? {
        ...card,
        moderation_status: response.report.target.moderation_target.moderation_status,
        moderation_override: response.report.target.moderation_target.moderation_override,
        moderation_override_history: response.report.target.moderation_target.moderation_override_history
      } : card));
    } finally {
      setReportBusy((current) => ({ ...current, [reportId]: false }));
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Nova Cards Moderation" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Moderation surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Nova Cards control panel"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Review pending cards, feature standout work, and keep the starter category taxonomy healthy as Nova Cards launches.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: endpoints.templates || "/cp/cards/templates", className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-swatchbook" }), "Manage templates"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.assetPacks || "/cp/cards/asset-packs", className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shapes" }), "Asset packs"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.challenges || "/cp/cards/challenges", className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy" }), "Challenges")))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, [
    ["Pending", stats.pending || 0, "fa-clock"],
    ["Flagged", stats.flagged || 0, "fa-flag"],
    ["Featured", stats.featured || 0, "fa-star"],
    ["Published", stats.published || 0, "fa-earth-americas"],
    ["Remixable", stats.remixable || 0, "fa-code-branch"],
    ["Challenges", stats.challenges || 0, "fa-trophy"]
  ].map(([label, value, icon]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-12 w-12 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon}` })), /* @__PURE__ */ React.createElement("span", { className: "text-3xl font-semibold tracking-[-0.04em] text-white" }, value))))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Reporting queue"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, reportingQueue.label || "Nova Cards report queue"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, reportingQueue.description || "Review reports targeting Nova Cards surfaces.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-amber-300/20 bg-amber-400/10 px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/75" }, "Pending reports"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold tracking-[-0.04em] text-amber-50" }, reportCounts.open || 0), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-amber-100/70" }, reportingQueue.enabled ? "Connected to moderation pipeline" : "Reporting disabled"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, [
    ["open", reportCounts.open || 0],
    ["reviewing", reportCounts.reviewing || 0],
    ["closed", reportCounts.closed || 0]
  ].map(([status2, count]) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: status2,
      type: "button",
      onClick: () => setReportStatus(status2),
      className: `rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition ${reportStatus === status2 ? "border-sky-300/30 bg-sky-400/12 text-sky-100" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"}`
    },
    status2,
    " • ",
    count
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-white/10 bg-[#08111f]/70 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, reportStatus.charAt(0).toUpperCase() + reportStatus.slice(1), " reports"), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, reportsMeta.total || reports.length, " total")), reportsLoading ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-slate-400" }, "Loading report queue…") : null, reportsError ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, reportsError) : null, !reportsLoading && !reportsError && !reports.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-400" }, "No reports in this state.") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, reports.map((report) => /* @__PURE__ */ React.createElement("div", { key: report.id, className: "rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, String(report.target?.type || report.target_type).replaceAll("_", " ")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, report.status)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-lg font-semibold text-white" }, report.target?.label || `Target #${report.target_id}`), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, report.target?.subtitle || "No target details available."), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm font-semibold text-slate-200" }, report.reason), report.details ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, report.details) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Reported by ", report.reporter?.username ? `@${report.reporter.username}` : "unknown", report.created_at ? ` • ${new Date(report.created_at).toLocaleString()}` : ""), report.last_moderated_by?.username || report.last_moderated_at ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Last touched ", report.last_moderated_by?.username ? `by @${report.last_moderated_by.username}` : "by staff", report.last_moderated_at ? ` • ${new Date(report.last_moderated_at).toLocaleString()}` : "") : null, report.target?.moderation_target ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-amber-300/15 bg-amber-400/10 px-4 py-3 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Card moderation target"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, report.target.moderation_target.title), report.target.moderation_target.context ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-amber-100/70" }, report.target.moderation_target.context) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs uppercase tracking-[0.14em] text-amber-100/80" }, /* @__PURE__ */ React.createElement("span", null, "Status ", report.target.moderation_target.status), /* @__PURE__ */ React.createElement("span", null, "Moderation ", report.target.moderation_target.moderation_status)), report.target.moderation_target.moderation_reason_labels?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-amber-200/15 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/75" }, "Heuristic flags"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, report.target.moderation_target.moderation_reason_labels.map((label) => /* @__PURE__ */ React.createElement("span", { key: `${report.id}-${label}`, className: "rounded-full border border-amber-200/20 bg-amber-50/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-amber-50" }, label))), report.target.moderation_target.moderation_source ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-[11px] uppercase tracking-[0.14em] text-amber-100/60" }, "Source ", String(report.target.moderation_target.moderation_source).replaceAll("_", " ")) : null) : null, report.target.moderation_target.moderation_override ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-sky-200/15 bg-sky-400/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Latest staff override"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs uppercase tracking-[0.14em] text-sky-100/80" }, /* @__PURE__ */ React.createElement("span", null, "Status ", report.target.moderation_target.moderation_override.moderation_status), report.target.moderation_target.moderation_override.disposition_label ? /* @__PURE__ */ React.createElement("span", null, report.target.moderation_target.moderation_override.disposition_label) : null, report.target.moderation_target.moderation_override.actor_username ? /* @__PURE__ */ React.createElement("span", null, "@", report.target.moderation_target.moderation_override.actor_username) : null, report.target.moderation_target.moderation_override.source ? /* @__PURE__ */ React.createElement("span", null, String(report.target.moderation_target.moderation_override.source).replaceAll("_", " ")) : null), report.target.moderation_target.moderation_override.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-sky-50" }, report.target.moderation_target.moderation_override.note) : null) : null, report.target.moderation_target.moderation_override_history?.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-sky-200/10 bg-sky-400/[0.08] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/75" }, "Recent override history"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, renderOverrideHistoryItems(report.target.moderation_target.moderation_override_history, `report-${report.id}`))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 max-w-xs" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/75" }, "Disposition"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: preferredDisposition(report.target.moderation_target.moderation_status, reportDispositions[report.id]),
      onChange: (value) => setReportDispositions((current) => ({ ...current, [report.id]: value })),
      options: dispositionOptionsForStatus(report.target.moderation_target.moderation_status).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, (report.target.moderation_target.available_actions || []).map((actionItem) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${report.id}-${actionItem.action}`,
      type: "button",
      onClick: () => moderateReportTarget(report.id, actionItem.action),
      disabled: Boolean(reportBusy[report.id]),
      className: "inline-flex items-center gap-2 rounded-full border border-amber-200/20 bg-amber-50/10 px-3 py-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-50 transition hover:bg-amber-50/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    actionItem.label
  )))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-[#08111f]/70 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Moderator note"), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: reportNotes[report.id] ?? "",
      onChange: (event) => setReportNotes((current) => ({ ...current, [report.id]: event.target.value })),
      rows: 3,
      className: "mt-3 w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-sm text-white",
      placeholder: "Capture reviewer context, outcome, or escalation notes."
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => updateReport(report.id, { moderator_note: (reportNotes[report.id] || "").trim() || null }),
      disabled: Boolean(reportBusy[report.id]),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-60"
    },
    "Save note"
  ), ["open", "reviewing", "closed"].filter((status2) => status2 !== report.status).map((status2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${report.id}-${status2}`,
      type: "button",
      onClick: () => updateReport(report.id, { status: status2, moderator_note: (reportNotes[report.id] || "").trim() || null }),
      disabled: Boolean(reportBusy[report.id]),
      className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    "Mark ",
    status2
  )))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-[#08111f]/70 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Audit trail"), !report.history?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-400" }, "No moderator actions recorded yet.") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, (report.history || []).map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, entry.summary || entry.action_type), /* @__PURE__ */ React.createElement("span", null, entry.actor?.username ? `@${entry.actor.username}` : "system"), /* @__PURE__ */ React.createElement("span", null, entry.created_at ? new Date(entry.created_at).toLocaleString() : "")), entry.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-300" }, entry.note) : null))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 lg:max-w-[260px] lg:justify-end" }, report.target?.public_url ? /* @__PURE__ */ React.createElement("a", { href: report.target.public_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]" }, "Open target") : null, report.target?.moderation_url ? /* @__PURE__ */ React.createElement("a", { href: report.target.moderation_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]" }, "Moderate") : null))))))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, cards.map((card) => /* @__PURE__ */ React.createElement("div", { key: card.id, className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-4 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[260px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement(NovaCardCanvasPreview, { card }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, card.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "@", card.creator?.username, " • ", card.category?.name || "Uncategorized")), /* @__PURE__ */ React.createElement("a", { href: card.public_url, className: "text-sm text-sky-300 transition hover:text-sky-200" }, "Open public page")), /* @__PURE__ */ React.createElement("p", { className: "mt-3 line-clamp-3 text-sm leading-7 text-slate-300" }, card.quote_text), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Status"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.status, onChange: (val) => updateCard(card.id, { status: val }), searchable: false, options: ["draft", "processing", "published", "hidden", "rejected"].map((s2) => ({ value: s2, label: s2 })) })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Moderation"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.moderation_status, onChange: (val) => updateCard(card.id, { moderation_status: val, disposition: preferredDisposition(val, cardDispositions[card.id]) }), searchable: false, options: ["pending", "approved", "flagged", "rejected"].map((s2) => ({ value: s2, label: s2 })) })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Disposition"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: preferredDisposition(card.moderation_status, cardDispositions[card.id]),
      onChange: (val) => {
        setCardDispositions((current) => ({ ...current, [card.id]: val }));
        updateCard(card.id, { moderation_status: card.moderation_status, disposition: val });
      },
      searchable: false,
      options: dispositionOptionsForStatus(card.moderation_status)
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Featured"), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(card.featured), onChange: (event) => updateCard(card.id, { featured: event.target.checked }) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Allow remix"), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(card.allow_remix), onChange: (event) => updateCard(card.id, { allow_remix: event.target.checked }) }))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-4 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.likes_count || 0, " likes"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.saves_count || 0, " saves"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.remixes_count || 0, " remixes"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.challenge_entries_count || 0, " challenge entries")), card.moderation_reason_labels?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-amber-300/15 bg-amber-400/10 px-4 py-3 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Heuristic moderation flags"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, card.moderation_reason_labels.map((label) => /* @__PURE__ */ React.createElement("span", { key: `${card.id}-${label}`, className: "rounded-full border border-amber-200/20 bg-amber-50/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-amber-50" }, label))), card.moderation_source ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-[11px] uppercase tracking-[0.14em] text-amber-100/70" }, "Source ", String(card.moderation_source).replaceAll("_", " ")) : null) : null, card.moderation_override ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/15 bg-sky-400/10 px-4 py-3 text-sm text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Latest staff override"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs uppercase tracking-[0.14em] text-sky-100/80" }, /* @__PURE__ */ React.createElement("span", null, "Status ", card.moderation_override.moderation_status), card.moderation_override.disposition_label ? /* @__PURE__ */ React.createElement("span", null, card.moderation_override.disposition_label) : null, card.moderation_override.actor_username ? /* @__PURE__ */ React.createElement("span", null, "@", card.moderation_override.actor_username) : null, card.moderation_override.source ? /* @__PURE__ */ React.createElement("span", null, String(card.moderation_override.source).replaceAll("_", " ")) : null), card.moderation_override.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-sky-50" }, card.moderation_override.note) : null) : null, card.moderation_override_history?.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/10 bg-sky-400/[0.08] px-4 py-3 text-sm text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/75" }, "Recent override history"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, renderOverrideHistoryItems(card.moderation_override_history, `card-${card.id}`))) : null))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Creator curation"), !featuredCreators.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-400" }, "No public Nova creators are available for curation yet.") : null, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, featuredCreators.map((creator) => /* @__PURE__ */ React.createElement("div", { key: creator.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, creator.display_name), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "@", creator.username)), creator.public_url ? /* @__PURE__ */ React.createElement("a", { href: creator.public_url, className: "text-xs font-semibold uppercase tracking-[0.16em] text-sky-300 transition hover:text-sky-200" }, "Open profile") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-2 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#08111f]/70 px-3 py-3" }, creator.public_cards_count || 0, " public cards"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#08111f]/70 px-3 py-3" }, creator.featured_cards_count || 0, " featured"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#08111f]/70 px-3 py-3" }, creator.total_views_count || 0, " views")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Feature on editorial page"), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(creator.nova_featured_creator), onChange: (event) => updateCreator(creator.id, { nova_featured_creator: event.target.checked }) })))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Categories"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, categories.map((category) => /* @__PURE__ */ React.createElement("div", { key: category.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, category.name), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, category.slug, " • ", category.cards_count, " cards")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveCategory(category), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.08]" }, "Save")))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Add category"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: newCategory.name, onChange: (event) => setNewCategory((current) => ({ ...current, name: event.target.value })), placeholder: "Name", className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: newCategory.slug, onChange: (event) => setNewCategory((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: newCategory.description, onChange: (event) => setNewCategory((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveCategory(newCategory), className: "w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Create category"))))));
}
const __vite_glob_0_51 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NovaCardsAdminIndex
}, Symbol.toStringTag, { value: "Module" }));
function requestJson$g(url, { method = "GET", body: body2 } = {}) {
  return fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(payload?.message || "Request failed");
    return payload;
  });
}
function NovaCardsAssetPackAdmin() {
  const { props } = X$1();
  const [packs, setPacks] = React.useState(props.packs || []);
  const [selectedId, setSelectedId] = React.useState(null);
  const [form, setForm] = React.useState({ slug: "", name: "", description: "", type: "asset", preview_image: "", manifest_json: {}, official: true, active: true, order_num: 0 });
  const endpoints = props.endpoints || {};
  function loadPack(pack) {
    setSelectedId(pack.id);
    setForm({
      slug: pack.slug,
      name: pack.name,
      description: pack.description || "",
      type: pack.type || "asset",
      preview_image: pack.preview_image || "",
      manifest_json: pack.manifest_json || {},
      official: Boolean(pack.official),
      active: Boolean(pack.active),
      order_num: pack.order_num || 0
    });
  }
  function resetForm() {
    setSelectedId(null);
    setForm({ slug: "", name: "", description: "", type: "asset", preview_image: "", manifest_json: {}, official: true, active: true, order_num: packs.length });
  }
  async function savePack() {
    const isExisting = Boolean(selectedId);
    const url = isExisting ? String(endpoints.updatePattern || "").replace("__PACK__", String(selectedId)) : endpoints.store;
    const response = await requestJson$g(url, { method: isExisting ? "PATCH" : "POST", body: form });
    if (isExisting) {
      setPacks((current) => current.map((pack) => pack.id === selectedId ? response.pack : pack));
    } else {
      setPacks((current) => [...current, response.pack]);
      setSelectedId(response.pack.id);
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Nova Cards Asset Packs" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "V2 pack system"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Official asset and template packs"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Control the official packs exposed in the v2 editor and public pack directories.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetForm, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "New pack"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.cards || "/cp/cards", className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to cards")))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Existing packs"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, packs.map((pack) => /* @__PURE__ */ React.createElement("button", { key: pack.id, type: "button", onClick: () => loadPack(pack), className: `w-full rounded-[22px] border p-4 text-left transition ${selectedId === pack.id ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tracking-[-0.03em] text-white" }, pack.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, pack.slug)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, pack.type)), pack.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, pack.description) : null)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Pack editor"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), placeholder: "Pack name", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: form.description, onChange: (event) => setForm((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 3, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" }), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.type, onChange: (val) => setForm((current) => ({ ...current, type: val })), searchable: false, options: [{ value: "asset", label: "asset" }, { value: "template", label: "template" }] })), /* @__PURE__ */ React.createElement("input", { value: form.preview_image, onChange: (event) => setForm((current) => ({ ...current, preview_image: event.target.value })), placeholder: "Preview image URL", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: JSON.stringify(form.manifest_json || {}, null, 2), onChange: (event) => {
    try {
      setForm((current) => ({ ...current, manifest_json: JSON.parse(event.target.value || "{}") }));
    } catch {
    }
  }, rows: 10, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 font-mono text-sm text-white md:col-span-2" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.active), onChange: (event) => setForm((current) => ({ ...current, active: event.target.checked })), label: "Active" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: savePack, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update pack" : "Create pack"))));
}
const __vite_glob_0_52 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NovaCardsAssetPackAdmin
}, Symbol.toStringTag, { value: "Module" }));
function requestJson$f(url, { method = "GET", body: body2 } = {}) {
  return fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(payload?.message || "Request failed");
    return payload;
  });
}
function NovaCardsChallengeAdmin() {
  const { props } = X$1();
  const [challenges, setChallenges] = React.useState(props.challenges || []);
  const [selectedId, setSelectedId] = React.useState(null);
  const [form, setForm] = React.useState({ slug: "", title: "", description: "", prompt: "", rules_json: {}, status: "draft", official: true, featured: false, winner_card_id: "", starts_at: "", ends_at: "" });
  const endpoints = props.endpoints || {};
  const cards = props.cards || [];
  function loadChallenge(challenge) {
    setSelectedId(challenge.id);
    setForm({
      slug: challenge.slug,
      title: challenge.title,
      description: challenge.description || "",
      prompt: challenge.prompt || "",
      rules_json: challenge.rules_json || {},
      status: challenge.status || "draft",
      official: Boolean(challenge.official),
      featured: Boolean(challenge.featured),
      winner_card_id: challenge.winner_card_id || "",
      starts_at: challenge.starts_at || "",
      ends_at: challenge.ends_at || ""
    });
  }
  function resetForm() {
    setSelectedId(null);
    setForm({ slug: "", title: "", description: "", prompt: "", rules_json: {}, status: "draft", official: true, featured: false, winner_card_id: "", starts_at: "", ends_at: "" });
  }
  async function saveChallenge() {
    const isExisting = Boolean(selectedId);
    const url = isExisting ? String(endpoints.updatePattern || "").replace("__CHALLENGE__", String(selectedId)) : endpoints.store;
    const response = await requestJson$f(url, { method: isExisting ? "PATCH" : "POST", body: { ...form, winner_card_id: form.winner_card_id || null } });
    if (isExisting) {
      setChallenges((current) => current.map((challenge) => challenge.id === selectedId ? response.challenge : challenge));
    } else {
      setChallenges((current) => [...current, response.challenge]);
      setSelectedId(response.challenge.id);
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Nova Cards Challenges" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Challenge system"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Nova Cards challenge programming"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Program official challenge prompts, track featured runs, and connect winner cards.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetForm, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "New challenge"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.cards || "/cp/cards", className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to cards")))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,1.2fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Existing challenges"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, challenges.map((challenge) => /* @__PURE__ */ React.createElement("button", { key: challenge.id, type: "button", onClick: () => loadChallenge(challenge), className: `w-full rounded-[22px] border p-4 text-left transition ${selectedId === challenge.id ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tracking-[-0.03em] text-white" }, challenge.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, challenge.slug)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, challenge.status)), challenge.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, challenge.description) : null)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Challenge editor"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: form.title, onChange: (event) => setForm((current) => ({ ...current, title: event.target.value })), placeholder: "Title", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: form.description, onChange: (event) => setForm((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 3, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" }), /* @__PURE__ */ React.createElement("textarea", { value: form.prompt, onChange: (event) => setForm((current) => ({ ...current, prompt: event.target.value })), placeholder: "Prompt", rows: 4, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" }), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Status"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.status, onChange: (val) => setForm((current) => ({ ...current, status: val })), searchable: false, options: ["draft", "active", "completed", "archived"].map((s2) => ({ value: s2, label: s2 })) })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Winner card"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.winner_card_id || ""), onChange: (val) => setForm((current) => ({ ...current, winner_card_id: val })), placeholder: "No winner", options: cards.map((c) => ({ value: String(c.id), label: c.title })) })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Starts at"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.starts_at, onChange: (nextValue) => setForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Starts at", clearable: true, className: "bg-[#0d1726]" })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Ends at"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.ends_at, onChange: (nextValue) => setForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "Ends at", clearable: true, className: "bg-[#0d1726]" })), /* @__PURE__ */ React.createElement("textarea", { value: JSON.stringify(form.rules_json || {}, null, 2), onChange: (event) => {
    try {
      setForm((current) => ({ ...current, rules_json: JSON.parse(event.target.value || "{}") }));
    } catch {
    }
  }, rows: 10, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 font-mono text-sm text-white md:col-span-2" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.featured), onChange: (event) => setForm((current) => ({ ...current, featured: event.target.checked })), label: "Featured" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveChallenge, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update challenge" : "Create challenge"))));
}
const __vite_glob_0_53 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NovaCardsChallengeAdmin
}, Symbol.toStringTag, { value: "Module" }));
function requestJson$e(url, { method = "GET", body: body2 } = {}) {
  return fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(payload?.message || "Request failed");
    return payload;
  });
}
function NovaCardsCollectionAdmin() {
  const { props } = X$1();
  const [collections, setCollections] = React.useState(props.collections || []);
  const [selectedId, setSelectedId] = React.useState(props.collections?.[0]?.id || null);
  const [cardId, setCardId] = React.useState("");
  const [cardNote, setCardNote] = React.useState("");
  const endpoints = props.endpoints || {};
  const admins = props.admins || [];
  const cards = props.cards || [];
  const selected = React.useMemo(() => collections.find((entry) => entry.id === selectedId) || null, [collections, selectedId]);
  const [form, setForm] = React.useState(() => ({
    user_id: admins[0]?.id || "",
    slug: "",
    name: "",
    description: "",
    visibility: "public",
    official: true,
    featured: false
  }));
  React.useEffect(() => {
    if (!selected) {
      setForm({ user_id: admins[0]?.id || "", slug: "", name: "", description: "", visibility: "public", official: true, featured: false });
      return;
    }
    setForm({
      user_id: selected.owner?.id || admins[0]?.id || "",
      slug: selected.slug || "",
      name: selected.name || "",
      description: selected.description || "",
      visibility: selected.visibility || "public",
      official: Boolean(selected.official),
      featured: Boolean(selected.featured)
    });
  }, [admins, selected]);
  async function saveCollection() {
    const isExisting = Boolean(selectedId);
    const url = isExisting ? String(endpoints.updatePattern || "").replace("__COLLECTION__", String(selectedId)) : endpoints.store;
    const response = await requestJson$e(url, { method: isExisting ? "PATCH" : "POST", body: form });
    if (isExisting) {
      setCollections((current) => current.map((entry) => entry.id === selectedId ? response.collection : entry));
    } else {
      setCollections((current) => [response.collection, ...current]);
      setSelectedId(response.collection.id);
    }
  }
  async function attachCard() {
    if (!selectedId || !cardId) return;
    const response = await requestJson$e(String(endpoints.attachCardPattern || "").replace("__COLLECTION__", String(selectedId)), {
      method: "POST",
      body: { card_id: Number(cardId), note: cardNote || null }
    });
    setCollections((current) => current.map((entry) => entry.id === selectedId ? response.collection : entry));
    setCardId("");
    setCardNote("");
  }
  async function detachCard(collectionId, currentCardId) {
    const response = await requestJson$e(
      String(endpoints.detachCardPattern || "").replace("__COLLECTION__", String(collectionId)).replace("__CARD__", String(currentCardId)),
      { method: "DELETE" }
    );
    setCollections((current) => current.map((entry) => entry.id === collectionId ? response.collection : entry));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Nova Cards Collections" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Editorial layer"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Official and public card collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Create editorial collections, assign owners, and curate the public card sets that the v2 browse surface links to.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setSelectedId(null), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "New collection"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.cards || "/cp/cards", className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to cards")))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Collections"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, collections.map((collection) => /* @__PURE__ */ React.createElement("button", { key: collection.id, type: "button", onClick: () => setSelectedId(collection.id), className: `w-full rounded-[22px] border p-4 text-left transition ${selectedId === collection.id ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tracking-[-0.03em] text-white" }, collection.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, collection.featured ? "Featured • " : "", collection.official ? "Official" : "@" + (collection.owner?.username || "creator"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, collection.cards_count, " cards")), collection.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, collection.description) : null)))), /* @__PURE__ */ React.createElement("section", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Collection editor"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Owner"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.user_id, onChange: (val) => setForm((current) => ({ ...current, user_id: Number(val) })), options: admins.map((a) => ({ value: a.id, label: a.name || a.username })) })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => setForm((current) => ({ ...current, visibility: val })), searchable: false, options: [{ value: "public", label: "public" }, { value: "private", label: "private" }] })), /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), placeholder: "Collection name", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: form.description, onChange: (event) => setForm((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 4, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-4" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official collection" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.featured), onChange: (event) => setForm((current) => ({ ...current, featured: event.target.checked })), label: "Featured collection" })), selected?.public_url ? /* @__PURE__ */ React.createElement("a", { href: selected.public_url, className: "text-sky-100 transition hover:text-white", target: "_blank", rel: "noreferrer" }, "Open public page") : null), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveCollection, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update collection" : "Create collection")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Curate cards"), !selectedId ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/12 bg-white/[0.03] px-4 py-8 text-center text-sm text-slate-400" }, "Create or select a collection first.") : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(cardId || ""), onChange: (val) => setCardId(val), placeholder: "Select a card", options: cards.map((c) => ({ value: String(c.id), label: c.title })) }), /* @__PURE__ */ React.createElement("input", { value: cardNote, onChange: (event) => setCardNote(event.target.value), placeholder: "Optional curator note", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: attachCard, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Add")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (selected?.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "flex items-start justify-between gap-4 rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, item.card?.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "#", item.sort_order, " ", item.card?.creator?.username ? `• @${item.card.creator.username}` : ""), item.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, item.note) : null), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => detachCard(selectedId, item.card.id), className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15" }, "Remove")))))))));
}
const __vite_glob_0_54 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NovaCardsCollectionAdmin
}, Symbol.toStringTag, { value: "Module" }));
function requestJson$d(url, { method = "GET", body: body2 } = {}) {
  return fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) throw new Error(payload?.message || "Request failed");
    return payload;
  });
}
function NovaCardsTemplateAdmin() {
  const { props } = X$1();
  const [templates, setTemplates] = React.useState(props.templates || []);
  const [selectedId, setSelectedId] = React.useState(null);
  const [form, setForm] = React.useState({
    slug: "",
    name: "",
    description: "",
    supported_formats: ["square"],
    active: true,
    official: true,
    order_num: templates.length,
    config_json: {
      font_preset: "modern-sans",
      gradient_preset: "midnight-nova",
      text_align: "center",
      layout: "quote_heavy",
      text_color: "#ffffff",
      overlay_style: "dark-soft"
    }
  });
  const endpoints = props.endpoints || {};
  const formats2 = props.editorOptions?.formats || [];
  const fonts = props.editorOptions?.font_presets || [];
  const gradients = props.editorOptions?.gradient_presets || [];
  function loadTemplate(template) {
    setSelectedId(template.id);
    setForm({
      slug: template.slug,
      name: template.name,
      description: template.description || "",
      preview_image: template.preview_image || null,
      supported_formats: template.supported_formats || [],
      active: Boolean(template.active),
      official: Boolean(template.official),
      order_num: template.order_num || 0,
      config_json: template.config_json || {}
    });
  }
  function resetForm() {
    setSelectedId(null);
    setForm({
      slug: "",
      name: "",
      description: "",
      supported_formats: ["square"],
      active: true,
      official: true,
      order_num: templates.length,
      config_json: {
        font_preset: "modern-sans",
        gradient_preset: "midnight-nova",
        text_align: "center",
        layout: "quote_heavy",
        text_color: "#ffffff",
        overlay_style: "dark-soft"
      }
    });
  }
  async function saveTemplate() {
    const isExisting = Boolean(selectedId);
    const url = isExisting ? String(endpoints.updatePattern || "").replace("__TEMPLATE__", String(selectedId)) : endpoints.store;
    const response = await requestJson$d(url, {
      method: isExisting ? "PATCH" : "POST",
      body: form
    });
    if (isExisting) {
      setTemplates((current) => current.map((template) => template.id === selectedId ? response.template : template));
    } else {
      setTemplates((current) => [...current, response.template]);
      setSelectedId(response.template.id);
    }
  }
  function toggleFormat(key) {
    setForm((current) => {
      const exists = current.supported_formats.includes(key);
      return {
        ...current,
        supported_formats: exists ? current.supported_formats.filter((item) => item !== key) : [...current.supported_formats, key]
      };
    });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Nova Cards Templates" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Template system"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Official Nova Cards templates"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Keep starter templates config-driven so the editor and render pipeline stay aligned as new card styles ship.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetForm, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "New template"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.cards || "/cp/cards", className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to cards")))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,1.4fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Existing templates"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, templates.map((template) => /* @__PURE__ */ React.createElement("button", { key: template.id, type: "button", onClick: () => loadTemplate(template), className: `w-full rounded-[22px] border p-4 text-left transition ${selectedId === template.id ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tracking-[-0.03em] text-white" }, template.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, template.slug)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, template.supported_formats?.join(", "))), template.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, template.description) : null)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Template editor"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), placeholder: "Template name", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: form.description, onChange: (event) => setForm((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 3, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" }), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Font preset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.font_preset || "modern-sans", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, font_preset: val } })), options: fonts.map((f2) => ({ value: f2.key, label: f2.label })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Gradient preset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.gradient_preset || "midnight-nova", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, gradient_preset: val } })), options: gradients.map((g2) => ({ value: g2.key, label: g2.label })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Layout preset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.layout || "quote_heavy", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, layout: val } })), options: ["quote_heavy", "author_emphasis", "centered", "minimal"].map((v2) => ({ value: v2, label: v2 })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Text alignment"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.text_align || "center", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, text_align: val } })), options: ["left", "center", "right"].map((v2) => ({ value: v2, label: v2 })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Overlay style"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.overlay_style || "dark-soft", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, overlay_style: val } })), options: ["none", "dark-soft", "dark-strong", "light-soft"].map((v2) => ({ value: v2, label: v2 })), searchable: false })), /* @__PURE__ */ React.createElement("label", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Text color"), /* @__PURE__ */ React.createElement("input", { type: "color", value: form.config_json?.text_color || "#ffffff", onChange: (event) => setForm((current) => ({ ...current, config_json: { ...current.config_json, text_color: event.target.value } })), className: "h-12 w-full rounded-2xl border border-white/10 bg-[#0d1726] p-2" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-sm font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Supported formats"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, formats2.map((format) => /* @__PURE__ */ React.createElement("div", { key: format.key, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.supported_formats.includes(format.key), onChange: () => toggleFormat(format.key), label: format.label }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.active), onChange: (event) => setForm((current) => ({ ...current, active: event.target.checked })), label: "Active" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveTemplate, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update template" : "Create template"))));
}
const __vite_glob_0_55 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NovaCardsTemplateAdmin
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$6() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$c(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$6(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed.");
  }
  return payload;
}
function buildFilterUrl(next, baseUrl) {
  if (typeof window === "undefined" && !baseUrl) return "#";
  const url = new URL(baseUrl || window.location.href, window.location.origin);
  Object.entries(next).forEach(([key, value]) => {
    if (value === null || value === void 0 || value === "" || value === "all") {
      url.searchParams.delete(key);
    } else {
      url.searchParams.set(key, String(value));
    }
  });
  return `${url.pathname}?${url.searchParams.toString()}`.replace(/\?$/, "");
}
function buildSearchActionUrl(baseUrl) {
  const url = new URL(baseUrl, window.location.origin);
  url.searchParams.delete("q");
  return `${url.pathname}?${url.searchParams.toString()}`.replace(/\?$/, "");
}
function reorderCollectionIds(collections, collectionId, direction) {
  const currentIndex = collections.findIndex((item) => Number(item.id) === Number(collectionId));
  if (currentIndex === -1) return null;
  const targetIndex = direction === "up" ? currentIndex - 1 : currentIndex + 1;
  if (targetIndex < 0 || targetIndex >= collections.length) return null;
  const nextCollections = [...collections];
  const [movedCollection] = nextCollections.splice(currentIndex, 1);
  nextCollections.splice(targetIndex, 0, movedCollection);
  return nextCollections.map((item) => Number(item.id));
}
function EmptyState$3({ browseUrl }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[32px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-20 w-20 items-center justify-center rounded-[24px] border border-white/12 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bookmark text-3xl" })), /* @__PURE__ */ React.createElement("h2", { className: "mt-5 text-2xl font-semibold text-white" }, "No saved collections yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm leading-relaxed text-slate-300" }, "Save collections to build a personal reference library for inspiration, campaigns, and creators you want to revisit."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex justify-center" }, /* @__PURE__ */ React.createElement("a", { href: browseUrl, className: "inline-flex items-center gap-2 rounded-2xl border border-white/12 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass fa-fw" }), "Browse collections")));
}
function FilterLink({ href, active, children, count }) {
  return /* @__PURE__ */ React.createElement("a", { href, className: `flex items-center justify-between rounded-2xl border px-4 py-3 text-sm transition ${active ? "border-sky-300/20 bg-sky-400/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-white hover:bg-white/[0.07]"}` }, /* @__PURE__ */ React.createElement("span", null, children), typeof count === "number" ? /* @__PURE__ */ React.createElement("span", { className: `text-xs ${active ? "text-sky-100/80" : "text-slate-400"}` }, count) : null);
}
function formatDateTime$1(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return date.toLocaleString();
}
function SavedCollections() {
  const { props } = X$1();
  const seo = props.seo || {};
  const initialCollections = Array.isArray(props.collections) ? props.collections : [];
  const recentlyRevisited = Array.isArray(props.recentlyRevisited) ? props.recentlyRevisited : [];
  const recommendedCollections = Array.isArray(props.recommendedCollections) ? props.recommendedCollections : [];
  const browseUrl = props.browseUrl || "/collections/featured";
  const libraryUrl = props.libraryUrl || "/me/saved/collections";
  const activeFilters = props.activeFilters || { q: "", filter: "all", sort: "saved_desc", list: null };
  const activeList = props.activeList || null;
  const filterOptions = Array.isArray(props.filterOptions) ? props.filterOptions : [];
  const sortOptions = Array.isArray(props.sortOptions) ? props.sortOptions : [];
  const searchBaseUrl = activeList?.url || libraryUrl;
  const [collections, setCollections] = React.useState(initialCollections);
  const [savedLists, setSavedLists] = React.useState(Array.isArray(props.savedLists) ? props.savedLists : []);
  const [newListTitle, setNewListTitle] = React.useState("");
  const [selectedLists, setSelectedLists] = React.useState({});
  const [notes, setNotes] = React.useState(() => Object.fromEntries(initialCollections.map((collection) => [collection.id, collection.saved_note || ""])));
  const [search2, setSearch] = React.useState(activeFilters.q || "");
  const [notice, setNotice] = React.useState("");
  const [busy, setBusy] = React.useState("");
  React.useEffect(() => {
    setCollections(initialCollections);
    setNotes(Object.fromEntries(initialCollections.map((collection) => [collection.id, collection.saved_note || ""])));
  }, [initialCollections]);
  React.useEffect(() => {
    setSearch(activeFilters.q || "");
  }, [activeFilters.q]);
  React.useEffect(() => {
    setSavedLists(Array.isArray(props.savedLists) ? props.savedLists : []);
  }, [props.savedLists]);
  const listSchema = seo?.canonical ? {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: "Saved collections",
    description: seo?.description || "Your saved collections on Skinbase.",
    url: seo.canonical,
    mainEntity: {
      "@type": "ItemList",
      numberOfItems: collections.length,
      itemListElement: collections.slice(0, 18).map((collection, index2) => ({
        "@type": "ListItem",
        position: index2 + 1,
        url: collection.url,
        name: collection.title
      }))
    }
  } : null;
  async function handleCreateList(event) {
    event.preventDefault();
    if (!newListTitle.trim() || !props.endpoints?.createList) return;
    setBusy("create-list");
    setNotice("");
    try {
      const payload = await requestJson$c(props.endpoints.createList, {
        method: "POST",
        body: { title: newListTitle.trim() }
      });
      setSavedLists((current) => [...current, payload.list].sort((left, right) => String(left.title).localeCompare(String(right.title))));
      setNewListTitle("");
      setNotice("Saved list created.");
    } catch (error) {
      setNotice(error.message || "Failed to create list.");
    } finally {
      setBusy("");
    }
  }
  async function handleAddToList(collectionId) {
    const listId = selectedLists[collectionId] || savedLists[0]?.id;
    if (!listId || !props.endpoints?.addToListPattern) return;
    setBusy(`list-${collectionId}`);
    setNotice("");
    try {
      const payload = await requestJson$c(props.endpoints.addToListPattern.replace("__COLLECTION__", String(collectionId)), {
        method: "POST",
        body: { saved_list_id: Number(listId) }
      });
      setSavedLists((current) => current.map((list2) => Number(list2.id) === Number(listId) ? { ...list2, items_count: Number(payload?.list?.items_count || list2.items_count || 0) } : list2));
      setNotice(payload?.added ? "Collection added to saved list." : "Collection already exists in that saved list.");
    } catch (error) {
      setNotice(error.message || "Failed to add collection to list.");
    } finally {
      setBusy("");
    }
  }
  async function handleUnsave(collection) {
    if (!collection?.id || !props.endpoints?.unsavePattern) return;
    setBusy(`unsave-${collection.id}`);
    setNotice("");
    try {
      await requestJson$c(props.endpoints.unsavePattern.replace("__COLLECTION__", String(collection.id)), {
        method: "DELETE"
      });
      setCollections((current) => current.filter((item) => Number(item.id) !== Number(collection.id)));
      setSavedLists((current) => current.map((list2) => {
        const isMember = Array.isArray(collection.saved_list_ids) && collection.saved_list_ids.includes(Number(list2.id));
        return isMember ? { ...list2, items_count: Math.max(0, Number(list2.items_count || 0) - 1) } : list2;
      }));
      setNotice("Collection removed from your saved library.");
    } catch (error) {
      setNotice(error.message || "Failed to remove collection from your saved library.");
    } finally {
      setBusy("");
    }
  }
  async function handleRemoveFromList(collection) {
    if (!activeList?.id || !collection?.id || !props.endpoints?.removeFromListPattern) return;
    setBusy(`remove-${collection.id}`);
    setNotice("");
    try {
      const payload = await requestJson$c(
        props.endpoints.removeFromListPattern.replace("__LIST__", String(activeList.id)).replace("__COLLECTION__", String(collection.id)),
        { method: "DELETE" }
      );
      setCollections((current) => current.filter((item) => Number(item.id) !== Number(collection.id)));
      setSavedLists((current) => current.map((list2) => Number(list2.id) === Number(payload?.list?.id) ? { ...list2, items_count: Number(payload?.list?.items_count || 0) } : list2));
      setNotice("Collection removed from this saved list.");
    } catch (error) {
      setNotice(error.message || "Failed to remove collection from this saved list.");
    } finally {
      setBusy("");
    }
  }
  async function handleReorderCollection(collectionId, direction) {
    if (!activeList?.id || !props.endpoints?.reorderItemsPattern) return;
    const reorderedCollectionIds = reorderCollectionIds(collections, collectionId, direction);
    if (!reorderedCollectionIds) return;
    setBusy(`reorder-${collectionId}`);
    setNotice("");
    try {
      await requestJson$c(
        props.endpoints.reorderItemsPattern.replace("__LIST__", String(activeList.id)),
        {
          method: "POST",
          body: { collection_ids: reorderedCollectionIds }
        }
      );
      setCollections((current) => {
        const order2 = new Map(reorderedCollectionIds.map((id, index2) => [Number(id), index2]));
        return [...current].sort((left, right) => {
          const leftOrder = order2.get(Number(left.id)) ?? Number.MAX_SAFE_INTEGER;
          const rightOrder = order2.get(Number(right.id)) ?? Number.MAX_SAFE_INTEGER;
          return leftOrder - rightOrder;
        });
      });
      setNotice("Saved list order updated.");
    } catch (error) {
      setNotice(error.message || "Failed to update saved list order.");
    } finally {
      setBusy("");
    }
  }
  async function handleSaveNote(collectionId) {
    if (!props.endpoints?.updateNotePattern) return;
    setBusy(`note-${collectionId}`);
    setNotice("");
    try {
      const payload = await requestJson$c(
        props.endpoints.updateNotePattern.replace("__COLLECTION__", String(collectionId)),
        {
          method: "PATCH",
          body: { note: notes[collectionId] || "" }
        }
      );
      setCollections((current) => current.map((collection) => Number(collection.id) === Number(collectionId) ? { ...collection, saved_note: payload?.note?.note || null } : collection));
      setNotice(payload?.note ? "Saved note updated." : "Saved note removed.");
    } catch (error) {
      setNotice(error.message || "Failed to update saved note.");
    } finally {
      setBusy("");
    }
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: seo?.title || "Saved Collections — Skinbase", description: seo?.description || "Your saved collections on Skinbase.", jsonLd: listSchema }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-95", style: { background: "radial-gradient(circle at 15% 14%, rgba(245,158,11,0.16), transparent 26%), radial-gradient(circle at 82% 18%, rgba(56,189,248,0.16), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: browseUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Browse collections")), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Library"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, "Saved collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "A personal shortlist of collections worth revisiting. Organize them into saved lists, pivot by editorial or campaign relevance, and keep a working shelf of what should influence your next publish."), activeList ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-folder-open fa-fw" }), "Viewing list: ", activeList.title) : null, activeFilters.q ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-sm font-semibold text-amber-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass fa-fw" }), "Search: ", activeFilters.q) : null, notice ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-sky-100" }, notice) : null), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[320px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("aside", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Search"), /* @__PURE__ */ React.createElement("form", { method: "GET", action: buildSearchActionUrl(searchBaseUrl), className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("input", { name: "q", value: search2, onChange: (event) => setSearch(event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35", placeholder: "Search titles, notes context, or curator", maxLength: 120 }), activeFilters.filter && activeFilters.filter !== "all" ? /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "filter", value: activeFilters.filter }) : null, activeFilters.sort && activeFilters.sort !== "saved_desc" ? /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "sort", value: activeFilters.sort }) : null, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "inline-flex flex-1 items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass fa-fw" }), "Apply"), activeFilters.q || search2 ? /* @__PURE__ */ React.createElement("a", { href: buildFilterUrl({ q: null }, searchBaseUrl), className: "inline-flex items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, "Clear") : null))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Filters"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, filterOptions.map((option) => /* @__PURE__ */ React.createElement(
    FilterLink,
    {
      key: option.key,
      href: buildFilterUrl({ q: activeFilters.q, filter: option.key, sort: activeFilters.sort }, searchBaseUrl),
      active: activeFilters.filter === option.key,
      count: option.count
    },
    option.label
  )))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Sort"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, sortOptions.map((option) => /* @__PURE__ */ React.createElement(
    FilterLink,
    {
      key: option.key,
      href: buildFilterUrl({ q: activeFilters.q, filter: activeFilters.filter, sort: option.key }, searchBaseUrl),
      active: activeFilters.sort === option.key
    },
    option.label
  )))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Saved Lists"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, savedLists.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement(FilterLink, { href: buildFilterUrl({ q: activeFilters.q, filter: activeFilters.filter, sort: activeFilters.sort }, libraryUrl), active: !activeFilters.list }, "All saved collections"), savedLists.map((list2) => /* @__PURE__ */ React.createElement(FilterLink, { key: list2.id, href: buildFilterUrl({ q: activeFilters.q, filter: activeFilters.filter, sort: activeFilters.sort }, list2.url || libraryUrl), active: Number(activeFilters.list) === Number(list2.id), count: list2.items_count }, list2.title))), /* @__PURE__ */ React.createElement("form", { onSubmit: handleCreateList, className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: newListTitle, onChange: (event) => setNewListTitle(event.target.value), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none transition focus:border-sky-300/35", placeholder: "Create a saved list", maxLength: 120 }), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "create-list", className: "inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "create-list" ? "fa-circle-notch fa-spin" : "fa-folder-plus"} fa-fw` }), "Create list")))), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, recentlyRevisited.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Recently Revisited"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Jump back into active references")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, recentlyRevisited.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid grid-cols-1 gap-5 xl:grid-cols-3" }, recentlyRevisited.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: `revisited-${collection.id}`, collection, isOwner: false })))) : null, /* @__PURE__ */ React.createElement("section", null, collections.length ? /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-5 xl:grid-cols-2" }, collections.map((collection, index2) => /* @__PURE__ */ React.createElement("div", { key: collection.id, className: "space-y-3" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: false }), collection.saved_because || collection.last_viewed_at ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, collection.saved_because ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-2 text-xs font-semibold text-amber-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-lightbulb fa-fw" }), collection.saved_because) : null, collection.last_viewed_at ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-[#0d1726] px-3 py-2 text-xs font-semibold text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-clock-rotate-left fa-fw" }), "Last revisited ", formatDateTime$1(collection.last_viewed_at)) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleUnsave(collection), disabled: busy === `unsave-${collection.id}`, className: "inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-2.5 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `unsave-${collection.id}` ? "fa-circle-notch fa-spin" : "fa-bookmark-slash"} fa-fw` }), "Remove from saved"), activeList ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleRemoveFromList(collection), disabled: busy === `remove-${collection.id}`, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.07] disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `remove-${collection.id}` ? "fa-circle-notch fa-spin" : "fa-folder-minus"} fa-fw` }), "Remove from list") : null, activeList && collections.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "ml-auto inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-[#0d1726] p-1" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleReorderCollection(collection.id, "up"),
      disabled: index2 === 0 || busy === `reorder-${collection.id}`,
      className: "inline-flex h-10 w-10 items-center justify-center rounded-xl text-sm text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40",
      "aria-label": `Move ${collection.title} up`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `reorder-${collection.id}` ? "fa-circle-notch fa-spin" : "fa-arrow-up"} fa-fw` })
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => handleReorderCollection(collection.id, "down"),
      disabled: index2 === collections.length - 1 || busy === `reorder-${collection.id}`,
      className: "inline-flex h-10 w-10 items-center justify-center rounded-xl text-sm text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40",
      "aria-label": `Move ${collection.title} down`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `reorder-${collection.id}` ? "fa-circle-notch fa-spin" : "fa-arrow-down"} fa-fw` })
  )) : null), savedLists.length ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(selectedLists[collection.id] || savedLists[0]?.id || ""), onChange: (val) => setSelectedLists((current) => ({ ...current, [collection.id]: val })), options: savedLists.map((l3) => ({ value: String(l3.id), label: l3.title })) }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleAddToList(collection.id), disabled: busy === `list-${collection.id}`, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.07] disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `list-${collection.id}` ? "fa-circle-notch fa-spin" : "fa-folder-plus"} fa-fw` }), "Add to list")) : null, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Private Note"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleSaveNote(collection.id), disabled: busy === `note-${collection.id}`, className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `note-${collection.id}` ? "fa-circle-notch fa-spin" : "fa-note-sticky"} fa-fw` }), "Save note")), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: notes[collection.id] || "",
      onChange: (event) => setNotes((current) => ({ ...current, [collection.id]: event.target.value })),
      rows: 3,
      maxLength: 1e3,
      placeholder: "Why did you save this collection? Add campaign context, inspiration notes, or follow-up ideas.",
      className: "mt-3 w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35"
    }
  ))))) : activeFilters.q || activeFilters.filter !== "all" || activeFilters.sort !== "saved_desc" || activeFilters.list ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[32px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-16 text-center text-sm text-slate-300" }, "No saved collections match the current search or filters.") : /* @__PURE__ */ React.createElement(EmptyState$3, { browseUrl })), recommendedCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Recommended Next"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Because of what you save")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, recommendedCollections.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid grid-cols-1 gap-5 xl:grid-cols-3" }, recommendedCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false })))) : null)))));
}
const __vite_glob_0_56 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: SavedCollections
}, Symbol.toStringTag, { value: "Module" }));
const FALLBACK_AVATAR = "https://files.skinbase.org/default/avatar_default.webp";
const BADGE_TONES = {
  rose: "border-rose-400/25 bg-rose-500/10 text-rose-200",
  amber: "border-amber-400/25 bg-amber-500/10 text-amber-200",
  sky: "border-sky-400/25 bg-sky-500/10 text-sky-200"
};
function ActivityAvatar({ user }) {
  if (!user) return null;
  const badgeClassName = BADGE_TONES[user.badge?.tone] || BADGE_TONES.sky;
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("a", { href: user.profile_url || "#", className: "shrink-0" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: user.avatar_url || FALLBACK_AVATAR,
      alt: user.name || user.username || "User",
      className: "h-11 w-11 rounded-2xl object-cover ring-1 ring-white/10",
      loading: "lazy",
      decoding: "async",
      onError: (event) => {
        event.currentTarget.src = FALLBACK_AVATAR;
      }
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("a", { href: user.profile_url || "#", className: "truncate text-sm font-semibold text-white hover:text-sky-200 transition-colors" }, user.name || user.username || "User"), user.username && /* @__PURE__ */ React.createElement("p", { className: "truncate text-xs text-white/35" }, "@", user.username), user.badge && /* @__PURE__ */ React.createElement("span", { className: `mt-1 inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] ${badgeClassName}` }, user.badge.label)));
}
function ActivityArtworkPreview({ artwork, story }) {
  if (artwork?.url && artwork?.thumb) {
    return /* @__PURE__ */ React.createElement(
      "a",
      {
        href: artwork.url,
        className: "group block w-full shrink-0 overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.03] sm:w-[120px]"
      },
      /* @__PURE__ */ React.createElement("div", { className: "aspect-[6/5] overflow-hidden bg-black/20" }, /* @__PURE__ */ React.createElement(
        "img",
        {
          src: artwork.thumb,
          alt: artwork.title || "Artwork",
          className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.04]",
          loading: "lazy",
          decoding: "async"
        }
      )),
      /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] px-3 py-2" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-[11px] font-medium text-white/65" }, artwork.title || "Artwork"))
    );
  }
  if (!story?.url || !story?.cover_url) return null;
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: story.url,
      className: "group block w-full shrink-0 overflow-hidden rounded-2xl border border-white/[0.08] bg-white/[0.03] sm:w-[120px]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "aspect-[6/5] overflow-hidden bg-black/20" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: story.cover_url,
        alt: story.title || "Story",
        className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.04]",
        loading: "lazy",
        decoding: "async"
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] px-3 py-2" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-[11px] font-medium text-white/65" }, story.title || "Story"))
  );
}
function ActivityReactions({ activity, isLoggedIn = false }) {
  const commentId = activity?.comment?.id || null;
  const commentUrl = activity?.comment?.url || null;
  const artworkUrl = activity?.artwork?.url || null;
  const storyUrl = activity?.story?.url || null;
  if (!commentId && !artworkUrl && !storyUrl) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 pt-2" }, commentId ? /* @__PURE__ */ React.createElement(
    ReactionBar,
    {
      entityType: "comment",
      entityId: commentId,
      initialTotals: activity?.comment?.reactions || {},
      isLoggedIn
    }
  ) : null, commentUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: commentUrl,
      className: "inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-xs font-medium text-white/55 transition hover:border-sky-400/30 hover:bg-sky-500/10 hover:text-sky-200"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-comment-dots" }),
    "Reply"
  ) : null, artworkUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artworkUrl,
      className: "inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-xs font-medium text-white/55 transition hover:border-white/15 hover:bg-white/[0.07] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-image" }),
    "View artwork"
  ) : null, storyUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: storyUrl,
      className: "inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.03] px-3 py-1.5 text-xs font-medium text-white/55 transition hover:border-white/15 hover:bg-white/[0.07] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-newspaper" }),
    "Read story"
  ) : null);
}
function ActivityHeadline({ activity }) {
  const artworkLink = activity?.artwork?.url;
  const artworkTitle = activity?.artwork?.title || "an artwork";
  const storyLink = activity?.story?.url;
  const storyTitle = activity?.story?.title || "a story";
  const mentionedUser = activity?.mentioned_user;
  const reaction = activity?.reaction;
  const commentAuthor = activity?.comment?.author;
  const targetUser = activity?.target_user;
  switch (activity?.type) {
    case "upload":
      if (storyLink) {
        return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "published "), storyLink ? /* @__PURE__ */ React.createElement("a", { href: storyLink, className: "text-sky-300 hover:text-sky-200" }, storyTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, storyTitle));
      }
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "published "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    case "favorite":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "favorited "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    case "follow":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "followed "), targetUser?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: targetUser.profile_url, className: "text-sky-300 hover:text-sky-200" }, "@", targetUser.username || targetUser.name) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, "another creator"));
    case "award":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "awarded "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    case "story_like":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "liked "), storyLink ? /* @__PURE__ */ React.createElement("a", { href: storyLink, className: "text-sky-300 hover:text-sky-200" }, storyTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, storyTitle));
    case "story_comment":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "commented on "), storyLink ? /* @__PURE__ */ React.createElement("a", { href: storyLink, className: "text-sky-300 hover:text-sky-200" }, storyTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, storyTitle));
    case "comment":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "commented on "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    case "reply":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "replied on "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    case "reaction":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "reacted ", reaction?.emoji || "👍", " ", reaction?.label || "Like", " "), /* @__PURE__ */ React.createElement("span", null, "to "), commentAuthor?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: commentAuthor.profile_url, className: "text-sky-300 hover:text-sky-200" }, commentAuthor.name || commentAuthor.username || "a creator") : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, "a creator"), /* @__PURE__ */ React.createElement("span", null, " on "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    case "mention":
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, "mentioned "), mentionedUser?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: mentionedUser.profile_url, className: "text-sky-300 hover:text-sky-200" }, "@", mentionedUser.username || mentionedUser.name) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, "someone"), /* @__PURE__ */ React.createElement("span", null, " on "), artworkLink ? /* @__PURE__ */ React.createElement("a", { href: artworkLink, className: "text-sky-300 hover:text-sky-200" }, artworkTitle) : /* @__PURE__ */ React.createElement("span", { className: "text-white" }, artworkTitle));
    default:
      return /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-white/70" }, "Shared new activity.");
  }
}
function ActivityCard$2({ activity, isLoggedIn = false }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/[0.06] bg-[linear-gradient(180deg,rgba(11,16,26,0.96),rgba(7,11,19,0.92))] p-4 shadow-[0_18px_45px_rgba(0,0,0,0.28)] backdrop-blur-xl sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "sm:w-[220px] sm:shrink-0" }, /* @__PURE__ */ React.createElement(ActivityAvatar, { user: activity.user })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(ActivityHeadline, { activity }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] uppercase tracking-[0.18em] text-white/25" }, activity.time_ago || "")), activity.comment?.body ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/[0.06] bg-white/[0.025] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "whitespace-pre-line break-words text-sm leading-6 text-white/80" }, activity.comment.body)) : null, activity.type === "mention" && activity.mentioned_user ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 inline-flex items-center gap-2 rounded-full border border-sky-400/20 bg-sky-500/10 px-3 py-1 text-xs text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-at" }), "Mentioned @", activity.mentioned_user.username || activity.mentioned_user.name) : null, /* @__PURE__ */ React.createElement(ActivityReactions, { activity, isLoggedIn })), /* @__PURE__ */ React.createElement("div", { className: "sm:ml-auto" }, /* @__PURE__ */ React.createElement(ActivityArtworkPreview, { artwork: activity.artwork, story: activity.story }))));
}
function ActivitySkeleton() {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4 animate-pulse" }, Array.from({ length: 5 }).map((_2, index2) => /* @__PURE__ */ React.createElement("div", { key: index2, className: "rounded-[28px] border border-white/[0.06] bg-white/[0.025] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3 sm:w-[220px]" }, /* @__PURE__ */ React.createElement("div", { className: "h-11 w-11 rounded-2xl bg-white/[0.08]" }), /* @__PURE__ */ React.createElement("div", { className: "flex-1 space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 w-24 rounded bg-white/[0.08]" }), /* @__PURE__ */ React.createElement("div", { className: "h-2.5 w-16 rounded bg-white/[0.06]" }))), /* @__PURE__ */ React.createElement("div", { className: "flex-1 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 w-4/5 rounded bg-white/[0.08]" }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.04] bg-white/[0.02] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 w-full rounded bg-white/[0.06]" }), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-3 w-3/4 rounded bg-white/[0.05]" })), /* @__PURE__ */ React.createElement("div", { className: "h-8 w-48 rounded-full bg-white/[0.05]" })), /* @__PURE__ */ React.createElement("div", { className: "h-[132px] w-full rounded-2xl bg-white/[0.05] sm:w-[120px]" })))));
}
function EmptyState$2({ isFiltered }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.06] bg-white/[0.025] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl border border-white/[0.06] bg-white/[0.03] text-white/35" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wave-square text-xl" })), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white/80" }, "No activity yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-2 max-w-md text-sm leading-6 text-white/45" }, isFiltered ? "This filter has no recent activity right now." : "When creators and members interact around artworks, their activity will appear here."));
}
function ActivityFeed$2({
  activities = [],
  isLoggedIn = false,
  loading = false,
  loadingMore = false,
  error = null,
  sentinelRef
}) {
  if (loading && activities.length === 0) {
    return /* @__PURE__ */ React.createElement(ActivitySkeleton, null);
  }
  if (!loading && activities.length === 0) {
    return /* @__PURE__ */ React.createElement(EmptyState$2, { isFiltered: Boolean(error) === false });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-500/20 bg-rose-500/10 px-4 py-3 text-sm text-rose-200" }, error) : null, activities.map((activity) => /* @__PURE__ */ React.createElement(ActivityCard$2, { key: activity.id, activity, isLoggedIn })), loadingMore ? /* @__PURE__ */ React.createElement(ActivitySkeleton, null) : null, /* @__PURE__ */ React.createElement("div", { ref: sentinelRef, className: "h-6", "aria-hidden": "true" }));
}
const FILTER_TABS$1 = [
  { key: "all", label: "All Activity" },
  { key: "comments", label: "Comments" },
  { key: "replies", label: "Replies" },
  { key: "following", label: "Following", authRequired: true },
  { key: "my", label: "My Activity", authRequired: true }
];
function FilterPills({ activeFilter, isAuthenticated, onChange }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, FILTER_TABS$1.map((tab2) => {
    const disabled = tab2.authRequired && !isAuthenticated;
    const active = activeFilter === tab2.key;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.key,
        type: "button",
        disabled,
        onClick: () => !disabled && onChange(tab2.key),
        className: [
          "rounded-full border px-4 py-2 text-sm font-medium transition-all",
          active ? "border-sky-400/30 bg-sky-500/14 text-sky-200 shadow-[0_0_0_1px_rgba(56,189,248,0.08)]" : "border-white/[0.06] bg-white/[0.03] text-white/55 hover:border-white/15 hover:bg-white/[0.05] hover:text-white/85",
          disabled ? "cursor-not-allowed opacity-35" : ""
        ].join(" "),
        title: disabled ? "Log in to use this filter" : void 0
      },
      tab2.label
    );
  }));
}
function updateUrl(filter2, userId) {
  const url = new URL(window.location.href);
  if (filter2 && filter2 !== "all") url.searchParams.set("filter", filter2);
  else url.searchParams.delete("filter");
  if (userId) url.searchParams.set("user_id", String(userId));
  else url.searchParams.delete("user_id");
  window.history.replaceState({}, "", url.toString());
}
function updateHeaderSummary(filter2, userId) {
  const filterLabels = {
    all: "All Activity",
    comments: "Comments",
    replies: "Replies",
    following: "Following",
    my: "My Activity"
  };
  const filterNode = document.getElementById("community-activity-filter-summary");
  const scopeNode = document.getElementById("community-activity-scope-summary");
  if (filterNode) {
    filterNode.innerHTML = `<i class="fa-solid fa-filter"></i> ${filterLabels[filter2] || filterLabels.all}`;
  }
  if (scopeNode) {
    if (userId) {
      scopeNode.className = "inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-white/65";
      scopeNode.innerHTML = `<i class="fa-solid fa-user"></i> User #${userId}`;
    } else {
      scopeNode.className = "hidden";
      scopeNode.innerHTML = "";
    }
  }
}
function CommunityActivityPage({
  initialActivities = [],
  initialMeta = {},
  initialFilter = "all",
  initialUserId = null,
  isAuthenticated = false
}) {
  const [activeFilter, setActiveFilter] = reactExports.useState(initialFilter);
  const [activities, setActivities] = reactExports.useState(initialActivities);
  const [meta, setMeta] = reactExports.useState(initialMeta);
  const [loading, setLoading] = reactExports.useState(false);
  const [loadingMore, setLoadingMore] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const sentinelRef = reactExports.useRef(null);
  const requestIdRef = reactExports.useRef(0);
  const hasMore = Boolean(meta?.has_more);
  const nextPage = Number(meta?.current_page || 1) + 1;
  const fetchFeed = reactExports.useCallback(async ({ filter: filter2, page, append: append2 }) => {
    const requestId = ++requestIdRef.current;
    setError(null);
    if (append2) setLoadingMore(true);
    else setLoading(true);
    try {
      const params = new URLSearchParams({ filter: filter2, page: String(page) });
      if (initialUserId) params.set("user_id", String(initialUserId));
      const response = await fetch(`/api/activity?${params.toString()}`, {
        headers: { Accept: "application/json", "X-Requested-With": "XMLHttpRequest" },
        credentials: "same-origin"
      });
      if (requestId !== requestIdRef.current) return;
      if (response.status === 401) {
        setError("Please log in to view this activity filter.");
        if (!append2) {
          setActivities([]);
          setMeta({ current_page: 1, last_page: 1, has_more: false, total: 0 });
        }
        return;
      }
      if (!response.ok) {
        throw new Error("Failed to load community activity.");
      }
      const payload = await response.json();
      setActivities((prev) => append2 ? [...prev, ...payload.data || []] : payload.data || []);
      setMeta(payload.meta || {});
    } catch {
      if (requestId === requestIdRef.current) {
        setError("Failed to load community activity. Please try again.");
      }
    } finally {
      if (requestId === requestIdRef.current) {
        setLoading(false);
        setLoadingMore(false);
      }
    }
  }, [initialUserId]);
  const handleFilterChange = reactExports.useCallback((nextFilter) => {
    if (nextFilter === activeFilter) return;
    setActiveFilter(nextFilter);
    updateUrl(nextFilter, initialUserId);
    fetchFeed({ filter: nextFilter, page: 1, append: false });
  }, [activeFilter, fetchFeed, initialUserId]);
  reactExports.useEffect(() => {
    updateHeaderSummary(activeFilter, initialUserId);
  }, [activeFilter, initialUserId]);
  reactExports.useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || loading || loadingMore || !hasMore) return void 0;
    const observer = new IntersectionObserver((entries) => {
      const [entry] = entries;
      if (entry?.isIntersecting) {
        fetchFeed({ filter: activeFilter, page: nextPage, append: true });
      }
    }, { rootMargin: "220px 0px" });
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [activeFilter, fetchFeed, hasMore, loading, loadingMore, nextPage]);
  const resultsLabel = reactExports.useMemo(() => {
    const total = Number(meta?.total || activities.length || 0);
    if (!total) return "No recent activity";
    return `${total.toLocaleString()} events`;
  }, [activities.length, meta?.total]);
  return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl px-6 pt-8 pb-20 md:px-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex flex-col gap-4 rounded-[28px] border border-white/[0.06] bg-[linear-gradient(180deg,rgba(10,16,26,0.92),rgba(6,10,18,0.88))] p-5 shadow-[0_20px_60px_rgba(0,0,0,0.25)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.22em] text-white/35" }, "Live community pulse"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-white/55" }, "Comments, replies, reactions, and mentions from across Skinbase in one scrolling Nova feed.")), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-medium text-white/45" }, resultsLabel)), /* @__PURE__ */ React.createElement(FilterPills, { activeFilter, isAuthenticated, onChange: handleFilterChange })), /* @__PURE__ */ React.createElement(
    ActivityFeed$2,
    {
      activities,
      isLoggedIn: isAuthenticated,
      loading,
      loadingMore,
      error,
      sentinelRef
    }
  ));
}
if (typeof document !== "undefined") {
  const mountEl = document.getElementById("community-activity-root");
  if (mountEl) {
    let props = {};
    try {
      const propsEl = document.getElementById("community-activity-props");
      props = propsEl ? JSON.parse(propsEl.textContent || "{}") : {};
    } catch {
      props = {};
    }
    clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(CommunityActivityPage, { ...props }));
  }
}
const __vite_glob_0_57 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CommunityActivityPage
}, Symbol.toStringTag, { value: "Module" }));
function Pagination({ meta, onPageChange }) {
  if (!meta) return null;
  const currentPage = Number(meta.current_page || 1);
  const lastPage = meta.last_page != null ? Number(meta.last_page) : null;
  const hasMore = Boolean(meta.has_more);
  if (lastPage !== null && lastPage <= 1) return null;
  if (lastPage === null && currentPage <= 1 && !hasMore) return null;
  const pages2 = [];
  if (lastPage !== null && lastPage <= 7) {
    for (let i = 1; i <= lastPage; i++) pages2.push(i);
  } else if (lastPage !== null) {
    const around = new Set(
      [1, lastPage, currentPage, currentPage - 1, currentPage + 1].filter(
        (p) => p >= 1 && p <= lastPage
      )
    );
    const sorted = [...around].sort((a, b2) => a - b2);
    for (let i = 0; i < sorted.length; i++) {
      if (i > 0 && sorted[i] - sorted[i - 1] > 1) pages2.push("…");
      pages2.push(sorted[i]);
    }
  }
  return /* @__PURE__ */ React.createElement(
    "nav",
    {
      "aria-label": "Pagination",
      className: "mt-10 flex items-center justify-center gap-1 flex-wrap"
    },
    /* @__PURE__ */ React.createElement(
      "button",
      {
        disabled: currentPage <= 1,
        onClick: () => onPageChange(currentPage - 1),
        className: "px-3 py-1.5 rounded-md text-sm text-white/50 hover:text-white hover:bg-white/[0.06] disabled:opacity-25 disabled:pointer-events-none transition-colors",
        "aria-label": "Previous page"
      },
      "‹ Prev"
    ),
    lastPage !== null ? pages2.map(
      (p, i) => p === "…" ? /* @__PURE__ */ React.createElement("span", { key: `sep-${i}`, className: "px-2 text-white/25 text-sm select-none" }, "…") : /* @__PURE__ */ React.createElement(
        "button",
        {
          key: p,
          onClick: () => p !== currentPage && onPageChange(p),
          "aria-current": p === currentPage ? "page" : void 0,
          className: [
            "min-w-[2rem] px-3 py-1.5 rounded-md text-sm font-medium transition-colors",
            p === currentPage ? "bg-sky-600/30 text-sky-300 ring-1 ring-sky-500/40" : "text-white/50 hover:text-white hover:bg-white/[0.06]"
          ].join(" ")
        },
        p
      )
    ) : /* @__PURE__ */ React.createElement("span", { className: "px-2 text-sm text-white/35" }, "Page ", currentPage),
    /* @__PURE__ */ React.createElement(
      "button",
      {
        disabled: lastPage !== null ? currentPage >= lastPage : !hasMore,
        onClick: () => onPageChange(currentPage + 1),
        className: "px-3 py-1.5 rounded-md text-sm text-white/50 hover:text-white hover:bg-white/[0.06] disabled:opacity-25 disabled:pointer-events-none transition-colors",
        "aria-label": "Next page"
      },
      "Next ›"
    )
  );
}
function PinIcon() {
  return /* @__PURE__ */ React.createElement(
    "svg",
    {
      className: "w-3.5 h-3.5 shrink-0 text-white/30",
      fill: "none",
      viewBox: "0 0 24 24",
      stroke: "currentColor",
      strokeWidth: 2
    },
    /* @__PURE__ */ React.createElement(
      "path",
      {
        strokeLinecap: "round",
        strokeLinejoin: "round",
        d: "M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
      }
    ),
    /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 11a3 3 0 11-6 0 3 3 0 016 0z" })
  );
}
function ImageIcon() {
  return /* @__PURE__ */ React.createElement(
    "svg",
    {
      className: "w-3 h-3 shrink-0 text-white/25",
      fill: "none",
      viewBox: "0 0 24 24",
      stroke: "currentColor",
      strokeWidth: 2
    },
    /* @__PURE__ */ React.createElement(
      "path",
      {
        strokeLinecap: "round",
        strokeLinejoin: "round",
        d: "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
      }
    )
  );
}
function CommentItem$1({ comment }) {
  const { commenter, artwork, comment_text, time_ago, created_at } = comment;
  return /* @__PURE__ */ React.createElement("article", { className: "flex gap-4 p-4 sm:p-5 rounded-xl border border-white/[0.065] bg-white/[0.025] hover:bg-white/[0.04] transition-colors" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: commenter.profile_url,
      className: "shrink-0 mt-0.5",
      "aria-label": `View ${commenter.display}'s profile`
    },
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: commenter.avatar_url,
        alt: commenter.display,
        width: 48,
        height: 48,
        className: "w-12 h-12 rounded-full object-cover ring-1 ring-white/[0.1]",
        loading: "lazy",
        onError: (e) => {
          e.currentTarget.onerror = null;
          e.currentTarget.src = commenter.avatar_fallback || "https://files.skinbase.org/default/avatar_default.webp";
        }
      }
    )
  ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-baseline gap-2 flex-wrap mb-1" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: commenter.profile_url,
      className: "text-sm font-bold text-white hover:text-white/80 transition-colors"
    },
    commenter.display
  ), /* @__PURE__ */ React.createElement(
    "time",
    {
      dateTime: created_at,
      title: created_at ? new Date(created_at).toLocaleString() : "",
      className: "text-xs text-white/40"
    },
    time_ago
  )), /* @__PURE__ */ React.createElement("p", { className: "text-base text-white leading-relaxed whitespace-pre-line break-words mb-3" }, comment_text), artwork && /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artwork.url,
      className: "inline-flex items-center gap-1.5 text-xs text-sky-400 hover:text-sky-300 transition-colors group"
    },
    /* @__PURE__ */ React.createElement(PinIcon, null),
    /* @__PURE__ */ React.createElement("span", { className: "font-medium" }, artwork.title)
  )), artwork?.thumb && /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artwork.url,
      className: "shrink-0 self-start group",
      tabIndex: -1,
      "aria-hidden": "true"
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-[220px] overflow-hidden rounded-lg ring-1 ring-white/[0.07] group-hover:ring-white/20 transition-all" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: artwork.thumb,
        alt: artwork.title ?? "Artwork",
        width: 220,
        height: 96,
        className: "w-full h-24 object-cover",
        loading: "lazy",
        onError: (e) => {
          e.currentTarget.closest("a").style.display = "none";
        }
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1.5 px-0.5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 mb-0.5" }, /* @__PURE__ */ React.createElement(ImageIcon, null), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/45 truncate max-w-[200px]" }, artwork.title)))
  ));
}
function FeedSkeleton() {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3 animate-pulse" }, Array.from({ length: 6 }).map((_2, i) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: i,
      className: "flex gap-4 p-5 rounded-xl border border-white/[0.06] bg-white/[0.02]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-12 h-12 rounded-full bg-white/[0.07] shrink-0" }),
    /* @__PURE__ */ React.createElement("div", { className: "flex-1 space-y-2 pt-1" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.07] rounded w-32" }), /* @__PURE__ */ React.createElement("div", { className: "h-4 bg-white/[0.06] rounded w-full" }), /* @__PURE__ */ React.createElement("div", { className: "h-4 bg-white/[0.05] rounded w-3/4" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.04] rounded w-24 mt-2" })),
    /* @__PURE__ */ React.createElement("div", { className: "w-[220px] h-24 rounded-lg bg-white/[0.05] shrink-0" })
  )));
}
function EmptyState$1() {
  return /* @__PURE__ */ React.createElement("div", { className: "py-16 text-center" }, /* @__PURE__ */ React.createElement(
    "svg",
    {
      className: "mx-auto w-10 h-10 text-white/15 mb-4",
      fill: "none",
      viewBox: "0 0 24 24",
      stroke: "currentColor",
      strokeWidth: 1.5
    },
    /* @__PURE__ */ React.createElement(
      "path",
      {
        strokeLinecap: "round",
        strokeLinejoin: "round",
        d: "M8.625 9.75a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375m-13.5 3.01c0 1.6 1.123 2.994 2.707 3.227 1.087.16 2.185.283 3.293.369V21l4.184-4.183a1.14 1.14 0 01.778-.332 48.294 48.294 0 005.83-.498c1.585-.233 2.708-1.626 2.708-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"
      }
    )
  ), /* @__PURE__ */ React.createElement("p", { className: "text-white/30 text-sm" }, "No comments found."));
}
function CommentsFeed({
  comments = [],
  meta = {},
  loading = false,
  error = null,
  onPageChange
}) {
  if (loading) return /* @__PURE__ */ React.createElement(FeedSkeleton, null);
  if (error) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-red-500/20 bg-red-900/10 px-6 py-5 text-sm text-red-400" }, error);
  }
  if (!comments || comments.length === 0) return /* @__PURE__ */ React.createElement(EmptyState$1, null);
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { role: "feed", "aria-live": "polite", "aria-busy": loading, className: "space-y-3" }, comments.map((comment) => /* @__PURE__ */ React.createElement(CommentItem$1, { key: comment.comment_id, comment }))), /* @__PURE__ */ React.createElement(Pagination, { meta, onPageChange }));
}
const FILTER_TABS = [
  { key: "all", label: "All" },
  { key: "following", label: "Following", authRequired: true },
  { key: "mine", label: "My Comments", authRequired: true }
];
function LatestCommentsPage({ initialComments = [], initialMeta = {}, isAuthenticated = false }) {
  const [activeFilter, setActiveFilter] = reactExports.useState("all");
  const [comments, setComments] = reactExports.useState(initialComments);
  const [meta, setMeta] = reactExports.useState(initialMeta);
  const [loading, setLoading] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const initialized = reactExports.useRef(false);
  const fetchComments = reactExports.useCallback(async (filter2, page = 1) => {
    setLoading(true);
    setError(null);
    try {
      const url = `/api/comments/latest?type=${encodeURIComponent(filter2)}&page=${page}`;
      const res = await fetch(url, {
        headers: { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest" },
        credentials: "same-origin"
      });
      if (res.status === 401) {
        setError("Please log in to view this feed.");
        setComments([]);
        setMeta({});
        return;
      }
      if (!res.ok) {
        setError("Failed to load comments. Please try again.");
        return;
      }
      const json = await res.json();
      setComments(json.data ?? []);
      setMeta(json.meta ?? {});
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  }, []);
  const handleFilterChange = (key) => {
    if (key === activeFilter) return;
    setActiveFilter(key);
    initialized.current = true;
    fetchComments(key, 1);
  };
  const handlePageChange = (page) => {
    initialized.current = true;
    fetchComments(activeFilter, page);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-5xl mx-auto" }, /* @__PURE__ */ React.createElement("div", { className: "mb-7" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-widest text-white/30 mb-1" }, "Community"), /* @__PURE__ */ React.createElement("h1", { className: "text-3xl font-bold text-white leading-tight" }, "Latest Comments"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white/50" }, "Most recent artwork comments from the community.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-6" }, FILTER_TABS.map((tab2) => {
    const disabled = tab2.authRequired && !isAuthenticated;
    const active = activeFilter === tab2.key;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.key,
        onClick: () => !disabled && handleFilterChange(tab2.key),
        disabled,
        "aria-current": active ? "page" : void 0,
        title: disabled ? "Log in to use this filter" : void 0,
        className: [
          "px-4 py-1.5 rounded-full text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-500",
          active ? "bg-sky-600/25 text-sky-300 ring-1 ring-sky-500/40" : "text-white/50 hover:text-white/80 hover:bg-white/[0.06]",
          disabled && "opacity-30 cursor-not-allowed"
        ].filter(Boolean).join(" ")
      },
      tab2.label
    );
  })), /* @__PURE__ */ React.createElement(
    CommentsFeed,
    {
      comments,
      meta,
      loading,
      error,
      onPageChange: handlePageChange
    }
  ));
}
if (typeof document !== "undefined") {
  const mountEl = document.getElementById("latest-comments-root");
  if (mountEl) {
    let props = {};
    try {
      const propsEl = document.getElementById("latest-comments-props");
      props = propsEl ? JSON.parse(propsEl.textContent || "{}") : {};
    } catch {
      props = {};
    }
    clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(LatestCommentsPage, { ...props }));
  }
}
const __vite_glob_0_58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: LatestCommentsPage
}, Symbol.toStringTag, { value: "Module" }));
function EnhanceStubWarning({ config, moderation = false, className = "" }) {
  if (!config?.showStubWarning) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-50 ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", null, "Skinbase Enhance is currently running in preview mode. The generated result is a workflow placeholder until the real upscaling worker is enabled."), moderation ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs uppercase tracking-[0.14em] text-amber-100/80" }, "Engine: ", config.engine, ". This is not a real AI upscale result.") : null);
}
function EnhanceCreate() {
  const { props } = X$1();
  const form = G$1({ image: null, scale: props.options?.scales?.[0]?.value || 2, mode: props.options?.modes?.[0]?.value || "standard" });
  const [previewUrl, setPreviewUrl] = React.useState(null);
  const [sourceType, setSourceType] = React.useState(props.selectedArtwork ? "artwork" : "upload");
  React.useEffect(() => () => {
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
    }
  }, [previewUrl]);
  function handleFileChange(event) {
    const file = event.target.files?.[0] || null;
    form.setData("image", file);
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
    }
    setPreviewUrl(file ? URL.createObjectURL(file) : null);
  }
  function submit(event) {
    event.preventDefault();
    const action = sourceType === "artwork" && props.selectedArtwork?.store_url ? props.selectedArtwork.store_url : props.storeUrl;
    form.post(action, {
      forceFormData: sourceType !== "artwork",
      preserveScroll: true
    });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Skinbase Enhance" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.18),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Skinbase Enhance"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Create an upscaled image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Large images may take longer to process. The original image will stay unchanged.")), /* @__PURE__ */ React.createElement(xe, { href: props.indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Back to jobs"))), /* @__PURE__ */ React.createElement(EnhanceStubWarning, { config: props.enhanceConfig, className: "mt-6" }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.05fr)_380px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Enhance source"), props.selectedArtwork ? /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-white/10 bg-white/[0.04] p-1 text-xs font-semibold text-slate-300" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setSourceType("artwork"),
      className: `rounded-full px-4 py-2 transition ${sourceType === "artwork" ? "bg-sky-400/15 text-sky-50" : "hover:bg-white/[0.06]"}`
    },
    "Existing artwork"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setSourceType("upload"),
      className: `rounded-full px-4 py-2 transition ${sourceType === "upload" ? "bg-sky-400/15 text-sky-50" : "hover:bg-white/[0.06]"}`
    },
    "Upload image"
  )) : null), sourceType === "artwork" && props.selectedArtwork ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[28px] border border-sky-300/20 bg-[linear-gradient(180deg,rgba(14,165,233,0.1),rgba(8,17,29,0.9))] p-6 text-left" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Existing artwork source"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, props.selectedArtwork.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-6 text-slate-300" }, "Use the current artwork source without re-uploading a file. The original artwork remains untouched and the enhanced result will be stored as a separate job output."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: props.selectedArtwork.show_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-[10px]" }), "View artwork"), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-lock text-[10px]" }), "Original stays unchanged")), form.errors.source ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, form.errors.source) : null) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("label", { className: "mt-4 flex min-h-[420px] cursor-pointer flex-col items-center justify-center rounded-[28px] border border-dashed border-white/15 bg-black/20 px-6 py-8 text-center transition hover:border-sky-300/30 hover:bg-sky-400/[0.03]" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "Selected for enhance", className: "max-h-[420px] w-full rounded-[20px] object-contain" }) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center rounded-full border border-white/10 bg-white/[0.05] text-white/70" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-cloud-arrow-up text-2xl" })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-lg font-semibold text-white" }, "Choose a JPEG, PNG, or WebP image"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 max-w-md text-sm text-slate-400" }, "Upload an image up to ", props.maxUploadMb, " MB. SVG, GIF, and unsupported file types are rejected.")), /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/jpeg,image/png,image/webp", onChange: handleFileChange, className: "hidden" })), form.errors.image ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-rose-300" }, form.errors.image) : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Enhance settings"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, "Scale"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-2 gap-3" }, (props.options?.scales || []).map((option) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: option.value,
      type: "button",
      onClick: () => form.setData("scale", option.value),
      className: `rounded-2xl border px-4 py-4 text-left transition ${Number(form.data.scale) === Number(option.value) ? "border-sky-300/30 bg-sky-400/12 text-sky-50" : "border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, option.label),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-current/70" }, "Upscale size")
  ))), form.errors.scale ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-rose-300" }, form.errors.scale) : null), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, "Mode"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, (props.options?.modes || []).map((option) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: option.value,
      type: "button",
      onClick: () => form.setData("mode", option.value),
      className: `w-full rounded-2xl border px-4 py-4 text-left transition ${String(form.data.mode) === String(option.value) ? "border-sky-300/30 bg-sky-400/12 text-sky-50" : "border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.08]"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, option.label),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-current/70" }, "Optimized preset")
  ))), form.errors.mode ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-rose-300" }, form.errors.mode) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm leading-6 text-amber-50" }, "The original file is preserved separately. Completed outputs can be reviewed and downloaded before you decide how to use them."), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "mt-6 inline-flex w-full items-center justify-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-5 py-3 text-sm font-semibold text-sky-50 transition hover:bg-sky-400/20 disabled:cursor-not-allowed disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles text-xs" }), form.processing ? "Starting enhance…" : sourceType === "artwork" ? "Enhance artwork image" : "Start enhance"))));
}
const __vite_glob_0_59 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: EnhanceCreate
}, Symbol.toStringTag, { value: "Module" }));
const TONES$3 = {
  pending: "border-white/10 bg-white/[0.05] text-slate-200",
  queued: "border-sky-300/20 bg-sky-400/12 text-sky-100",
  processing: "border-violet-300/20 bg-violet-400/12 text-violet-100",
  completed: "border-emerald-300/20 bg-emerald-400/12 text-emerald-100",
  failed: "border-rose-300/20 bg-rose-400/12 text-rose-100",
  cancelled: "border-amber-300/20 bg-amber-400/12 text-amber-100",
  expired: "border-white/10 bg-white/[0.05] text-slate-300",
  unknown: "border-white/10 bg-white/[0.04] text-slate-300"
};
const LABELS = {
  pending: "Pending",
  queued: "Queued",
  processing: "Processing",
  completed: "Completed",
  failed: "Failed",
  cancelled: "Cancelled",
  expired: "Expired"
};
function EnhanceStatusBadge({ status: status2, className = "" }) {
  const key = String(status2 || "").toLowerCase();
  const tone = TONES$3[key] || TONES$3.unknown;
  const label = LABELS[key] || "Unknown";
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tone} ${className}`.trim() }, label);
}
const dateFormatter = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "2-digit",
  hour: "2-digit",
  minute: "2-digit",
  hour12: false,
  timeZone: "UTC"
});
const numberFormatter = new Intl.NumberFormat("en-US");
function formatEnhanceDate(value) {
  if (!value) return "—";
  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return "—";
  }
  return `${dateFormatter.format(parsed)} UTC`;
}
function formatEnhanceInteger(value) {
  const parsed = Number(value);
  if (!Number.isFinite(parsed)) {
    return "0";
  }
  return numberFormatter.format(parsed);
}
function formatDate$h(value) {
  return formatEnhanceDate(value);
}
function JobCard({ job }) {
  return /* @__PURE__ */ React.createElement("article", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-[#08111d] shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[220px_1fr]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square bg-black/30" }, job.preview_url || job.source_url ? /* @__PURE__ */ React.createElement("img", { src: job.preview_url || job.source_url, alt: "Enhance preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-white/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-4xl" }))), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(EnhanceStatusBadge, { status: job.status }), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.scale, "x"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.mode), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.engine)), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-2xl font-semibold tracking-[-0.03em] text-white" }, job.artwork?.title ? `Artwork enhance: ${job.artwork.title}` : `Enhance job #${job.id}`), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Created ", formatDate$h(job.created_at), " ", job.processing_seconds ? `• ${job.processing_seconds}s processing` : ""), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, job.input_width, " × ", job.input_height, job.output_width && job.output_height ? ` → ${job.output_width} × ${job.output_height}` : ""), job.error_message ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, job.error_message) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: job.show_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Open job"), job.artwork?.url ? /* @__PURE__ */ React.createElement("a", { href: job.artwork.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Open artwork") : null))));
}
function EnhanceIndex() {
  const { props } = X$1();
  const jobs = props.jobs?.data || [];
  const latestCompleted = props.latestCompleted || [];
  const flash = props.flash || {};
  const enhanceConfig = props.enhanceConfig || {};
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Skinbase Enhance" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Skinbase Enhance"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Image Upscaler"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Improve older wallpapers, digital art, and photos with a clean upscaled version. Your original file is never replaced automatically.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: props.createUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sparkles text-[10px]" }), "Start enhance"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Daily limit"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, formatEnhanceInteger(props.dailyLimit || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Total jobs"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, formatEnhanceInteger(props.jobs?.total || jobs.length))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Completed outputs"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, formatEnhanceInteger(latestCompleted.length))))), /* @__PURE__ */ React.createElement(EnhanceStubWarning, { config: enhanceConfig, className: "mt-6" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, latestCompleted.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Latest completed"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Recent enhanced outputs"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, latestCompleted.map((job) => /* @__PURE__ */ React.createElement(xe, { key: job.id, href: job.show_url, className: "overflow-hidden rounded-[28px] border border-white/10 bg-[#08111d] transition hover:border-sky-300/30 hover:bg-[#0b1524]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square bg-black/20" }, job.output_url ? /* @__PURE__ */ React.createElement("img", { src: job.output_url, alt: `Enhance job ${job.id}`, className: "h-full w-full object-cover" }) : null), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement(EnhanceStatusBadge, { status: job.status }), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm font-semibold text-white" }, "Job #", job.id), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, job.scale, "x • ", job.mode)))))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "History"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Your enhance jobs")), jobs.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-300" }, "No enhance jobs yet. Upload an image to start your first upscale.") : /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, jobs.map((job) => /* @__PURE__ */ React.createElement(JobCard, { key: job.id, job })))));
}
const __vite_glob_0_60 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: EnhanceIndex
}, Symbol.toStringTag, { value: "Module" }));
function BeforeAfterSlider({ beforeUrl, afterUrl, beforeAlt = "Original image", afterAlt = "Enhanced image" }) {
  const [position2, setPosition] = React.useState(50);
  if (!beforeUrl || !afterUrl) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-[#08111d] p-5 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Before / after"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, "Compare the original with the enhanced result")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-200" }, position2, "%")), /* @__PURE__ */ React.createElement("div", { className: "relative mt-5 overflow-hidden rounded-[24px] border border-white/10 bg-black/40" }, /* @__PURE__ */ React.createElement("img", { src: beforeUrl, alt: beforeAlt, className: "block w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-y-0 left-0 overflow-hidden border-r border-white/80", style: { width: `${position2}%` } }, /* @__PURE__ */ React.createElement("img", { src: afterUrl, alt: afterAlt, className: "block h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-y-0 left-0", style: { left: `calc(${position2}% - 1px)` } }, /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 -translate-x-1/2 items-center justify-center rounded-full border border-white/80 bg-black/60 text-white shadow-[0_0_30px_rgba(15,23,42,0.5)]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-left-right text-xs" })))), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute left-3 top-3 rounded-full border border-white/10 bg-[#08111dd8] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-100" }, "Original"), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute right-3 top-3 rounded-full border border-emerald-300/20 bg-emerald-400/12 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Enhanced")), /* @__PURE__ */ React.createElement("label", { className: "mt-5 block" }, /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, "Adjust before and after comparison slider"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "range",
      min: "0",
      max: "100",
      step: "1",
      value: position2,
      onChange: (event) => setPosition(Number(event.target.value || 50)),
      className: "h-2 w-full cursor-pointer appearance-none rounded-full bg-white/10 accent-sky-300",
      "aria-label": "Adjust before and after comparison slider"
    }
  )));
}
function formatDate$g(value) {
  return formatEnhanceDate(value);
}
function DetailRow$1({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4 border-b border-white/[0.06] py-3 last:border-b-0 last:pb-0" }, /* @__PURE__ */ React.createElement("dt", { className: "text-sm text-slate-400" }, label), /* @__PURE__ */ React.createElement("dd", { className: "text-right text-sm text-white" }, value));
}
function EnhanceShow() {
  const { props } = X$1();
  const job = props.job || {};
  const flash = props.flash || {};
  const errors = props.errors || {};
  const statusKey = String(job.status || "").toLowerCase();
  const statusCopy = {
    pending: "Waiting to be queued.",
    queued: "Waiting for processor.",
    processing: "Enhancing image.",
    completed: "Enhanced image ready.",
    failed: "Enhancement failed.",
    cancelled: "Cancelled.",
    expired: "Enhanced output expired and cleaned files were removed."
  }[statusKey] || "Unknown status.";
  React.useEffect(() => {
    if (!["pending", "queued", "processing"].includes(statusKey)) {
      return void 0;
    }
    const timer = window.setTimeout(() => {
      At.reload({ only: ["job", "flash"], preserveScroll: true });
    }, 8e3);
    return () => window.clearTimeout(timer);
  }, [statusKey]);
  const canCompare = Boolean(job.source_url && job.output_url && job.status === "completed");
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: `Enhance Job #${job.id || ""}` }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.18),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(EnhanceStatusBadge, { status: job.status }), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.scale, "x"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.mode), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.engine)), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Enhance job #", job.id), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, statusCopy)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: props.indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Back to jobs"), /* @__PURE__ */ React.createElement(xe, { href: props.createUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-[10px]" }), "New enhance"), job.download_url ? /* @__PURE__ */ React.createElement("a", { href: job.download_url, className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-50 transition hover:bg-emerald-400/20" }, "Download enhanced") : null, job.can_retry ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(job.retry_url, {}, { preserveScroll: true }), className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-amber-50 transition hover:bg-amber-400/20" }, "Retry") : null, job.can_delete ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this enhance job and its generated files?")) return;
    At.delete(job.delete_url);
  }, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 transition hover:bg-rose-400/20" }, "Delete") : null))), /* @__PURE__ */ React.createElement(EnhanceStubWarning, { config: props.enhanceConfig, className: "mt-6" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, errors.job ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, errors.job) : null, job.error_message ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, job.error_message) : null, canCompare ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement(BeforeAfterSlider, { beforeUrl: job.source_url, afterUrl: job.output_url })) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_380px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Original source"), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, job.source_url ? /* @__PURE__ */ React.createElement("img", { src: job.source_url, alt: "Original source", className: "w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex min-h-[280px] items-center justify-center text-white/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-4xl" })))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Enhanced result"), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, job.output_url ? /* @__PURE__ */ React.createElement("img", { src: job.output_url, alt: "Enhanced output", className: "w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex min-h-[280px] items-center justify-center text-white/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-hourglass-half text-4xl" })))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Metadata"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("pre", { className: "overflow-x-auto whitespace-pre-wrap break-words" }, JSON.stringify(job.metadata || {}, null, 2))))), /* @__PURE__ */ React.createElement("aside", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Job details"), /* @__PURE__ */ React.createElement("dl", { className: "mt-4" }, /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Created", value: formatDate$g(job.created_at) }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Queued", value: formatDate$g(job.queued_at) }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Started", value: formatDate$g(job.started_at) }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Finished", value: formatDate$g(job.finished_at) }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Expires", value: formatDate$g(job.expires_at) }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Input size", value: job.input_filesize ? `${(job.input_filesize / 1024 / 1024).toFixed(2)} MB` : "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Input mime", value: job.input_mime || "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Input dimensions", value: job.input_width && job.input_height ? `${job.input_width} × ${job.input_height}` : "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Output size", value: job.output_filesize ? `${(job.output_filesize / 1024 / 1024).toFixed(2)} MB` : "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Output mime", value: job.output_mime || "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Output dimensions", value: job.output_width && job.output_height ? `${job.output_width} × ${job.output_height}` : "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Processing seconds", value: job.processing_seconds ?? "—" }), /* @__PURE__ */ React.createElement(DetailRow$1, { label: "Artwork", value: job.artwork?.title ? /* @__PURE__ */ React.createElement("a", { href: job.artwork.url, className: "text-sky-300 hover:text-sky-200" }, job.artwork.title) : "Standalone upload" })))));
}
const __vite_glob_0_61 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: EnhanceShow
}, Symbol.toStringTag, { value: "Module" }));
function PostActions({
  post: post2,
  isLoggedIn,
  onCommentToggle,
  onReactionChange
}) {
  const [liked, setLiked] = reactExports.useState(post2.viewer_liked ?? false);
  const [likeCount, setLikeCount] = reactExports.useState(post2.reactions_count ?? 0);
  const [busy, setBusy] = reactExports.useState(false);
  const [menuOpen, setMenuOpen] = reactExports.useState(false);
  const [shareMsg, setShareMsg] = reactExports.useState(null);
  const handleLike = async () => {
    if (!isLoggedIn) {
      window.location.href = "/login";
      return;
    }
    if (busy) return;
    setBusy(true);
    try {
      if (liked) {
        await axios.delete(`/api/posts/${post2.id}/reactions/like`);
        setLiked(false);
        setLikeCount((c) => Math.max(0, c - 1));
        onReactionChange?.({ liked: false, count: Math.max(0, likeCount - 1) });
      } else {
        await axios.post(`/api/posts/${post2.id}/reactions`, { reaction: "like" });
        setLiked(true);
        setLikeCount((c) => c + 1);
        onReactionChange?.({ liked: true, count: likeCount + 1 });
      }
    } catch {
    } finally {
      setBusy(false);
    }
  };
  const handleCopyLink = () => {
    const url = `${window.location.origin}/@${post2.author.username}/posts?post=${post2.id}`;
    navigator.clipboard?.writeText(url);
    setShareMsg("Link copied!");
    setTimeout(() => setShareMsg(null), 2e3);
    setMenuOpen(false);
  };
  const handleReport = async () => {
    setMenuOpen(false);
    const reason = window.prompt("Why are you reporting this post? (required)");
    if (!reason?.trim()) return;
    try {
      await axios.post(`/api/posts/${post2.id}/report`, { reason: reason.trim() });
      alert("Report submitted. Thank you!");
    } catch (err) {
      if (err.response?.data?.message) {
        alert(err.response.data.message);
      }
    }
  };
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 text-slate-400 relative" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: handleLike,
      disabled: busy,
      className: `flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-colors ${liked ? "text-sky-400 bg-sky-500/10 hover:bg-sky-500/20" : "hover:bg-white/5 hover:text-slate-200"}`,
      title: liked ? "Unlike" : "Like",
      "aria-label": liked ? "Unlike this post" : "Like this post"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-${liked ? "solid" : "regular"} fa-heart fa-fw text-xs` }),
    /* @__PURE__ */ React.createElement("span", { className: "tabular-nums" }, likeCount > 0 && likeCount)
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: onCommentToggle,
      className: "flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm hover:bg-white/5 hover:text-slate-200 transition-colors",
      title: "Comment",
      "aria-label": "Show comments"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-comment fa-fw text-xs" }),
    /* @__PURE__ */ React.createElement("span", { className: "tabular-nums" }, post2.comments_count > 0 && post2.comments_count)
  ), /* @__PURE__ */ React.createElement("div", { className: "relative ml-auto" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setMenuOpen((v2) => !v2),
      className: "flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:bg-white/5 hover:text-slate-200 transition-colors",
      "aria-label": "More options"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-ellipsis-h fa-fw text-xs" })
  ), menuOpen && /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "absolute right-0 bottom-full mb-1 w-44 rounded-xl border border-white/10 bg-[#10192e] shadow-2xl z-50 overflow-hidden",
      onBlur: () => setMenuOpen(false)
    },
    /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: handleCopyLink,
        className: "w-full text-left px-4 py-2.5 text-sm text-slate-300 hover:bg-white/5 flex items-center gap-2"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link fa-fw opacity-60" }),
      "Copy link"
    ),
    isLoggedIn && /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: handleReport,
        className: "w-full text-left px-4 py-2.5 text-sm text-rose-400 hover:bg-white/5 flex items-center gap-2"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag fa-fw opacity-60" }),
      "Report post"
    )
  )), shareMsg && /* @__PURE__ */ React.createElement("span", { className: "absolute -top-8 right-0 text-xs bg-slate-800 text-white px-2 py-1 rounded shadow" }, shareMsg));
}
function formatRelative$1(isoString) {
  const diff = Date.now() - new Date(isoString).getTime();
  const s2 = Math.floor(diff / 1e3);
  if (s2 < 60) return "just now";
  const m2 = Math.floor(s2 / 60);
  if (m2 < 60) return `${m2}m ago`;
  const h = Math.floor(m2 / 60);
  if (h < 24) return `${h}h ago`;
  const d2 = Math.floor(h / 24);
  return `${d2}d ago`;
}
function PostComments({ postId, isLoggedIn, isOwn = false, initialCount = 0 }) {
  const [comments, setComments] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [submitting, setSubmitting] = reactExports.useState(false);
  const [body2, setBody] = reactExports.useState("");
  const [error, setError] = reactExports.useState(null);
  const [page, setPage] = reactExports.useState(1);
  const [hasMore, setHasMore] = reactExports.useState(false);
  const [loaded, setLoaded] = reactExports.useState(false);
  const textareaRef = reactExports.useRef(null);
  const fetchComments = async (p = 1) => {
    setLoading(true);
    try {
      const { data } = await axios.get(`/api/posts/${postId}/comments`, { params: { page: p } });
      setComments((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setHasMore(data.meta.current_page < data.meta.last_page);
      setPage(p);
    } catch {
    } finally {
      setLoading(false);
      setLoaded(true);
    }
  };
  reactExports.useEffect(() => {
    fetchComments(1);
  }, [postId]);
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!body2.trim()) return;
    setSubmitting(true);
    setError(null);
    try {
      const { data } = await axios.post(`/api/posts/${postId}/comments`, { body: body2 });
      setComments((prev) => [...prev, data.comment]);
      setBody("");
    } catch (err) {
      setError(err.response?.data?.message ?? "Failed to post comment.");
    } finally {
      setSubmitting(false);
    }
  };
  const handleDelete = async (commentId) => {
    if (!window.confirm("Delete this comment?")) return;
    try {
      await axios.delete(`/api/posts/${postId}/comments/${commentId}`);
      setComments((prev) => prev.filter((c) => c.id !== commentId));
    } catch {
    }
  };
  const handleHighlight = async (comment) => {
    try {
      if (comment.is_highlighted) {
        await axios.delete(`/api/posts/${postId}/comments/${comment.id}/highlight`);
        setComments(
          (prev) => prev.map((c) => c.id === comment.id ? { ...c, is_highlighted: false } : c)
        );
      } else {
        await axios.post(`/api/posts/${postId}/comments/${comment.id}/highlight`);
        setComments(
          (prev) => prev.map((c) => ({ ...c, is_highlighted: c.id === comment.id }))
        );
      }
    } catch {
    }
  };
  const sorted = [...comments].sort(
    (a, b2) => (b2.is_highlighted ? 1 : 0) - (a.is_highlighted ? 1 : 0)
  );
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, !loaded && loading && /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, [1, 2].map((i) => /* @__PURE__ */ React.createElement("div", { key: i, className: "flex gap-2 animate-pulse" }, /* @__PURE__ */ React.createElement("div", { className: "w-7 h-7 rounded-full bg-white/10 shrink-0" }), /* @__PURE__ */ React.createElement("div", { className: "flex-1 space-y-1" }, /* @__PURE__ */ React.createElement("div", { className: "h-2.5 bg-white/10 rounded w-24" }), /* @__PURE__ */ React.createElement("div", { className: "h-2 bg-white/6 rounded w-3/4" }))))), loaded && sorted.map((c) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: c.id,
      className: `flex gap-2 group ${c.is_highlighted ? "rounded-xl bg-sky-500/5 border border-sky-500/15 px-3 py-2 -mx-3" : ""}`
    },
    /* @__PURE__ */ React.createElement("a", { href: `/@${c.author.username}`, className: "shrink-0" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: c.author.avatar ?? "/images/avatar_default.webp",
        alt: c.author.name,
        className: "w-7 h-7 rounded-full object-cover ring-1 ring-white/10",
        loading: "lazy"
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-baseline gap-2 flex-wrap" }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: `/@${c.author.username}`,
        className: "text-xs font-semibold text-white/80 hover:text-sky-400 transition-colors"
      },
      c.author.name || `@${c.author.username}`
    ), /* @__PURE__ */ React.createElement(LevelBadge, { level: c.author.level, rank: c.author.rank, compact: true }), /* @__PURE__ */ React.createElement("span", { className: "text-[10px] text-slate-600" }, formatRelative$1(c.created_at)), c.is_highlighted && /* @__PURE__ */ React.createElement("span", { className: "text-[10px] text-sky-400 font-medium flex items-center gap-1" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-star fa-xs" }), "Highlighted by author")), /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "text-sm text-slate-300 mt-0.5 [&_a]:text-sky-400 [&_a]:hover:underline",
        dangerouslySetInnerHTML: { __html: c.body }
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-1 opacity-0 group-hover:opacity-100 transition-all ml-1" }, isOwn && /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: () => handleHighlight(c),
        title: c.is_highlighted ? "Remove highlight" : "Highlight comment",
        className: `text-xs transition-colors px-1 py-0.5 rounded ${c.is_highlighted ? "text-sky-400 hover:text-slate-400" : "text-slate-600 hover:text-sky-400"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: `${c.is_highlighted ? "fa-solid" : "fa-regular"} fa-star` })
    ), isLoggedIn && /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: () => handleDelete(c.id),
        className: "text-slate-600 hover:text-rose-400 transition-all text-xs",
        title: "Delete comment"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can" })
    ))
  )), loaded && hasMore && /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchComments(page + 1),
      disabled: loading,
      className: "text-xs text-sky-400 hover:text-sky-300 transition-colors"
    },
    loading ? "Loading…" : "Load more comments"
  ), isLoggedIn ? /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit, className: "flex gap-2 mt-2" }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      ref: textareaRef,
      value: body2,
      onChange: (e) => setBody(e.target.value),
      placeholder: "Write a comment…",
      maxLength: 1e3,
      rows: 1,
      className: "flex-1 bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white resize-none placeholder-slate-600 focus:outline-none focus:border-sky-500/50 transition-colors",
      onKeyDown: (e) => {
        if (e.key === "Enter" && !e.shiftKey) {
          e.preventDefault();
          handleSubmit(e);
        }
      }
    }
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: submitting || !body2.trim(),
      className: "px-3 py-2 rounded-xl bg-sky-600 hover:bg-sky-500 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm transition-colors"
    },
    submitting ? /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-paper-plane" })
  )) : /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mt-2" }, /* @__PURE__ */ React.createElement("a", { href: "/login", className: "text-sky-400 hover:underline" }, "Sign in"), " to comment."), error && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-400" }, error));
}
const ICONS = {
  public: { icon: "fa-globe", label: "Public", cls: "text-slate-500" },
  followers: { icon: "fa-user-friends", label: "Followers", cls: "text-sky-500/70" },
  private: { icon: "fa-lock", label: "Private", cls: "text-amber-500/70" }
};
function VisibilityPill({ visibility, showLabel = false }) {
  const v2 = ICONS[visibility] ?? ICONS.public;
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: `inline-flex items-center gap-1 text-xs ${v2.cls}`,
      title: v2.label,
      "aria-label": `Visibility: ${v2.label}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${v2.icon} fa-fw` }),
    showLabel && /* @__PURE__ */ React.createElement("span", null, v2.label)
  );
}
function LinkPreviewCard({ preview, onDismiss, loading = false }) {
  if (loading) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/[0.08] bg-white/[0.03] overflow-hidden flex gap-3 p-3 animate-pulse" }, /* @__PURE__ */ React.createElement("div", { className: "w-20 h-20 rounded-lg bg-white/10 shrink-0" }), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 flex flex-col gap-2 justify-center" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/10 rounded w-2/3" }), /* @__PURE__ */ React.createElement("div", { className: "h-2.5 bg-white/10 rounded w-full" }), /* @__PURE__ */ React.createElement("div", { className: "h-2.5 bg-white/10 rounded w-4/5" }), /* @__PURE__ */ React.createElement("div", { className: "h-2 bg-white/[0.06] rounded w-1/3 mt-1" })));
  }
  if (!preview?.url) return null;
  const domain = (() => {
    try {
      return new URL(preview.url).hostname.replace(/^www\./, "");
    } catch {
      return preview.site_name ?? "";
    }
  })();
  return /* @__PURE__ */ React.createElement("div", { className: "relative rounded-xl border border-white/[0.08] bg-white/[0.03] overflow-hidden hover:border-white/[0.14] transition-colors group" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: preview.url,
      target: "_blank",
      rel: "noopener noreferrer nofollow",
      className: "flex gap-0 items-stretch",
      onClick: (e) => e.stopPropagation()
    },
    preview.image ? /* @__PURE__ */ React.createElement("div", { className: "w-24 shrink-0 bg-white/5" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: preview.image,
        alt: "",
        className: "w-full h-full object-cover",
        loading: "lazy",
        onError: (e) => {
          e.currentTarget.parentElement.style.display = "none";
        }
      }
    )) : /* @__PURE__ */ React.createElement("div", { className: "w-24 shrink-0 bg-white/[0.04] flex items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link text-xl" })),
    /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 px-3 py-2.5 flex flex-col justify-center gap-0.5" }, preview.site_name && /* @__PURE__ */ React.createElement("p", { className: "text-[10px] uppercase tracking-wide text-sky-500/80 font-medium truncate" }, preview.site_name), preview.title && /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white/90 line-clamp-2 leading-snug" }, preview.title), preview.description && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 line-clamp-2 leading-relaxed mt-0.5" }, preview.description), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1 truncate" }, domain))
  ), onDismiss && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: (e) => {
        e.stopPropagation();
        onDismiss();
      },
      className: "absolute top-1.5 right-1.5 w-5 h-5 rounded-full bg-black/60 hover:bg-black/80 text-slate-400 hover:text-white flex items-center justify-center transition-colors text-[10px]",
      "aria-label": "Remove link preview"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })
  ));
}
function formatRelative(isoString) {
  const diff = Date.now() - new Date(isoString).getTime();
  const s2 = Math.floor(diff / 1e3);
  if (s2 < 60) return "just now";
  const m2 = Math.floor(s2 / 60);
  if (m2 < 60) return `${m2}m ago`;
  const h = Math.floor(m2 / 60);
  if (h < 24) return `${h}h ago`;
  const d2 = Math.floor(h / 24);
  return `${d2}d ago`;
}
function formatScheduledDate$1(isoString) {
  const d2 = new Date(isoString);
  return d2.toLocaleString(void 0, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  });
}
function BodyWithHashtags({ html: html2 }) {
  const processed = html2.replace(
    new RegExp('(?<!["\\w])#([A-Za-z][A-Za-z0-9_]{1,63})', "g"),
    (_2, tag) => `<a href="/tags/${tag.toLowerCase()}" class="text-sky-400 hover:underline">#${tag}</a>`
  );
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "text-sm text-slate-300 leading-relaxed [&_a]:text-sky-400 [&_a]:hover:underline [&_strong]:text-white/90 [&_em]:text-slate-200",
      dangerouslySetInnerHTML: { __html: processed }
    }
  );
}
function PostCard$1({ post: post2, isLoggedIn = false, viewerUsername = null, onDelete, onUnsaved }) {
  const [showComments, setShowComments] = reactExports.useState(false);
  const [postData, setPostData] = reactExports.useState(post2);
  const [editMode, setEditMode] = reactExports.useState(false);
  const [editBody, setEditBody] = reactExports.useState(post2.body ?? "");
  const [saving, setSaving] = reactExports.useState(false);
  const [menuOpen, setMenuOpen] = reactExports.useState(false);
  const [saveLoading, setSaveLoading] = reactExports.useState(false);
  const [analyticsOpen, setAnalyticsOpen] = reactExports.useState(false);
  const [analytics, setAnalytics] = reactExports.useState(null);
  const isOwn = viewerUsername && post2.author.username === viewerUsername;
  const handleSaveEdit = async () => {
    setSaving(true);
    try {
      const { data } = await axios.patch(`/api/posts/${post2.id}`, { body: editBody });
      setPostData(data.post);
      setEditMode(false);
    } catch {
    } finally {
      setSaving(false);
    }
  };
  const handleDelete = async () => {
    if (!window.confirm("Delete this post?")) return;
    try {
      await axios.delete(`/api/posts/${post2.id}`);
      onDelete?.(post2.id);
    } catch {
    }
  };
  const handlePin = async () => {
    try {
      if (postData.is_pinned) {
        await axios.delete(`/api/posts/${post2.id}/pin`);
        setPostData((p) => ({ ...p, is_pinned: false, pinned_order: null }));
      } else {
        const { data } = await axios.post(`/api/posts/${post2.id}/pin`);
        setPostData((p) => ({ ...p, is_pinned: true, pinned_order: data.pinned_order ?? 1 }));
      }
    } catch {
    }
    setMenuOpen(false);
  };
  const handleSaveToggle = async () => {
    if (!isLoggedIn || saveLoading) return;
    setSaveLoading(true);
    try {
      if (postData.viewer_saved) {
        await axios.delete(`/api/posts/${post2.id}/save`);
        setPostData((p) => ({ ...p, viewer_saved: false, saves_count: Math.max(0, (p.saves_count ?? 1) - 1) }));
        onUnsaved?.(post2.id);
      } else {
        await axios.post(`/api/posts/${post2.id}/save`);
        setPostData((p) => ({ ...p, viewer_saved: true, saves_count: (p.saves_count ?? 0) + 1 }));
      }
    } catch {
    } finally {
      setSaveLoading(false);
    }
  };
  const handleOpenAnalytics = async () => {
    if (!isOwn) return;
    setAnalyticsOpen(true);
    if (!analytics) {
      try {
        const { data } = await axios.get(`/api/posts/${post2.id}/analytics`);
        setAnalytics(data);
      } catch {
        setAnalytics(null);
      }
    }
  };
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.025] hover:border-white/10 transition-colors" }, postData.is_pinned && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5 px-5 pt-3 pb-0 text-[11px] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-thumbtack fa-fw text-sky-500/60" }), /* @__PURE__ */ React.createElement("span", null, "Pinned post")), isOwn && postData.status === "scheduled" && postData.publish_at && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5 px-5 pt-3 pb-0 text-[11px] text-amber-500/80" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-clock fa-fw" }), /* @__PURE__ */ React.createElement("span", null, "Scheduled for ", formatScheduledDate$1(postData.publish_at))), postData.type === "achievement" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5 px-5 pt-3 pb-0 text-[11px] text-amber-400/90" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy fa-fw text-amber-400" }), /* @__PURE__ */ React.createElement("span", { className: "font-medium tracking-wide uppercase" }, "Achievement unlocked")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 px-5 pt-4 pb-3" }, /* @__PURE__ */ React.createElement("a", { href: `/@${post2.author.username}`, className: "shrink-0" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: post2.author.avatar ?? "/images/avatar_default.webp",
      alt: post2.author.name,
      className: "w-9 h-9 rounded-full object-cover ring-1 ring-white/10 hover:ring-sky-500/40 transition-all",
      loading: "lazy"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 flex-wrap" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/@${post2.author.username}`,
      className: "text-sm font-semibold text-white/90 hover:text-sky-400 transition-colors"
    },
    post2.author.name || `@${post2.author.username}`
  ), /* @__PURE__ */ React.createElement("span", { className: "text-slate-600 text-xs" }, "@", post2.author.username), post2.meta?.tagged_users?.length > 0 && /* @__PURE__ */ React.createElement("span", { className: "text-slate-600 text-xs flex items-center gap-1 flex-wrap" }, /* @__PURE__ */ React.createElement("span", { className: "text-slate-700" }, "with"), post2.meta.tagged_users.map((u2, i) => /* @__PURE__ */ React.createElement(React.Fragment, { key: u2.id }, i > 0 && /* @__PURE__ */ React.createElement("span", { className: "text-slate-700" }, ","), /* @__PURE__ */ React.createElement("a", { href: `/@${u2.username}`, className: "text-sky-500/80 hover:text-sky-400 transition-colors" }, "@", u2.username))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5 text-[11px] text-slate-500 mt-0.5" }, /* @__PURE__ */ React.createElement("span", null, formatRelative(post2.created_at)), /* @__PURE__ */ React.createElement("span", { "aria-hidden": true }, "·"), /* @__PURE__ */ React.createElement(VisibilityPill, { visibility: post2.visibility }))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1" }, isLoggedIn && !isOwn && /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: handleSaveToggle,
      disabled: saveLoading,
      title: postData.viewer_saved ? "Remove bookmark" : "Save post",
      className: `flex items-center justify-center w-8 h-8 rounded-lg transition-colors ${postData.viewer_saved ? "text-amber-400 hover:bg-amber-500/10" : "text-slate-600 hover:text-slate-300 hover:bg-white/5"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `${postData.viewer_saved ? "fa-solid" : "fa-regular"} fa-bookmark fa-fw text-sm` })
  ), isOwn && /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: handleOpenAnalytics,
      title: "Post analytics",
      className: "flex items-center justify-center w-8 h-8 rounded-lg text-slate-600 hover:text-sky-400 hover:bg-sky-500/10 transition-colors"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-simple fa-fw text-sm" })
  ), isOwn && /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setMenuOpen((v2) => !v2),
      className: "text-slate-500 hover:text-slate-300 px-2 py-1 rounded-lg hover:bg-white/5 transition-colors",
      "aria-label": "Post options"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-ellipsis-v fa-fw text-xs" })
  ), menuOpen && /* @__PURE__ */ React.createElement("div", { className: "absolute right-0 top-full mt-1 w-40 rounded-xl border border-white/10 bg-[#10192e] shadow-2xl z-50 overflow-hidden" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => {
        setEditMode(true);
        setMenuOpen(false);
      },
      className: "w-full text-left px-4 py-2.5 text-sm text-slate-300 hover:bg-white/5 flex items-center gap-2"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw opacity-60" }),
    "Edit"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: handlePin,
      className: "w-full text-left px-4 py-2.5 text-sm text-slate-300 hover:bg-white/5 flex items-center gap-2"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid fa-thumbtack fa-fw opacity-60 ${postData.is_pinned ? "text-sky-400" : ""}` }),
    postData.is_pinned ? "Unpin post" : "Pin post"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => {
        handleDelete();
        setMenuOpen(false);
      },
      className: "w-full text-left px-4 py-2.5 text-sm text-rose-400 hover:bg-white/5 flex items-center gap-2"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can fa-fw opacity-60" }),
    "Delete"
  ))))), /* @__PURE__ */ React.createElement("div", { className: "px-5 pb-3 space-y-3" }, editMode ? /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: editBody,
      onChange: (e) => setEditBody(e.target.value),
      maxLength: 2e3,
      rows: 4,
      className: "w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white resize-none focus:outline-none focus:border-sky-500/50 transition-colors"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: handleSaveEdit,
      disabled: saving,
      className: "px-4 py-1.5 rounded-lg bg-sky-600 hover:bg-sky-500 text-white text-xs transition-colors disabled:opacity-40"
    },
    saving ? "Saving…" : "Save"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setEditMode(false),
      className: "px-4 py-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/5 text-xs transition-colors"
    },
    "Cancel"
  ))) : postData.body && /* @__PURE__ */ React.createElement(BodyWithHashtags, { html: postData.body }), !editMode && postData.hashtags && postData.hashtags.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-1.5 pt-0.5" }, postData.hashtags.map((tag) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: tag,
      href: `/tags/${tag}`,
      className: "text-[11px] text-sky-500/80 hover:text-sky-400 hover:bg-sky-500/10 px-2 py-0.5 rounded-full border border-sky-500/20 hover:border-sky-500/40 transition-all"
    },
    "#",
    tag
  ))), !editMode && postData.meta?.link_preview?.url && /* @__PURE__ */ React.createElement(LinkPreviewCard, { preview: postData.meta.link_preview }), postData.type === "artwork_share" && postData.artwork && /* @__PURE__ */ React.createElement(ArtworkCard$1, { artwork: postData.artwork, variant: "embed", showActions: false, showStats: false })), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.04] px-5 py-2" }, /* @__PURE__ */ React.createElement(
    PostActions,
    {
      post: postData,
      isLoggedIn,
      onCommentToggle: () => setShowComments((v2) => !v2),
      onReactionChange: ({ liked, count }) => setPostData((p) => ({ ...p, viewer_liked: liked, reactions_count: count }))
    }
  )), showComments && /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.04] px-5 py-4" }, /* @__PURE__ */ React.createElement(
    PostComments,
    {
      postId: post2.id,
      isLoggedIn,
      isOwn,
      initialCount: postData.comments_count
    }
  )), analyticsOpen && /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "fixed inset-0 z-50 flex items-center justify-center bg-black/70 px-4",
      onClick: (e) => {
        if (e.target === e.currentTarget) setAnalyticsOpen(false);
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-sm rounded-2xl border border-white/10 bg-[#0d1628] p-6 shadow-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between mb-4" }, /* @__PURE__ */ React.createElement("h3", { className: "font-semibold text-white" }, "Post Analytics"), /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: () => setAnalyticsOpen(false),
        className: "text-slate-500 hover:text-white w-7 h-7 flex items-center justify-center rounded-lg hover:bg-white/5 transition-colors"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })
    )), !analytics ? /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-8" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin text-slate-500 text-xl" })) : /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3" }, [
      { label: "Impressions", value: analytics.impressions?.toLocaleString() ?? "—", icon: "fa-eye", color: "text-sky-400" },
      { label: "Saves", value: analytics.saves?.toLocaleString() ?? "—", icon: "fa-bookmark", color: "text-amber-400" },
      { label: "Reactions", value: analytics.reactions?.toLocaleString() ?? "—", icon: "fa-heart", color: "text-rose-400" },
      { label: "Engagement", value: analytics.engagement_rate ? `${analytics.engagement_rate}%` : "—", icon: "fa-chart-simple", color: "text-emerald-400" }
    ].map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-xl bg-white/[0.04] border border-white/[0.06] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: `${item.color} text-sm mb-1` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} fa-fw` })), /* @__PURE__ */ React.createElement("p", { className: "text-xl font-bold text-white/90 tabular-nums leading-tight" }, item.value), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-500 mt-0.5" }, item.label)))))
  ));
}
function PostCardSkeleton() {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.03] p-5 animate-pulse space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "w-9 h-9 rounded-full bg-white/10 shrink-0" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-1.5 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/10 rounded w-28" }), /* @__PURE__ */ React.createElement("div", { className: "h-2 bg-white/6 rounded w-20" }))), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/10 rounded w-full" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/8 rounded w-4/5" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/6 rounded w-2/3" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl bg-white/5 aspect-[16/9]" }), /* @__PURE__ */ React.createElement("div", { className: "flex gap-4 pt-1" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/8 rounded w-12" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/6 rounded w-16" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/6 rounded w-10" })));
}
const FILTER_OPTIONS = [
  { value: "all", label: "All" },
  { value: "shares", label: "Artwork Shares" },
  { value: "uploads", label: "New Uploads" },
  { value: "text", label: "Text Posts" }
];
function EmptyFollowingState() {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-24 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-20 h-20 rounded-2xl bg-white/5 flex items-center justify-center mb-5 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-users text-3xl" })), /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white/80 mb-2" }, "Nothing here yet"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-500 text-sm max-w-sm leading-relaxed" }, "Follow some creators to see their posts here. Discover amazing artwork on", " ", /* @__PURE__ */ React.createElement("a", { href: "/discover/trending", className: "text-sky-400 hover:underline" }, "Trending"), "."));
}
function FollowingFeed() {
  const { props } = X$1();
  const { auth, seo } = props;
  const authUser = auth?.user ?? null;
  const [posts, setPosts] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [page, setPage] = reactExports.useState(1);
  const [hasMore, setHasMore] = reactExports.useState(false);
  const [loaded, setLoaded] = reactExports.useState(false);
  const [filter2, setFilter] = reactExports.useState("all");
  const fetchFeed = reactExports.useCallback(async (p = 1, f2 = filter2) => {
    setLoading(true);
    try {
      const { data } = await axios.get("/api/posts/following", {
        params: { page: p, filter: f2 }
      });
      setPosts((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setHasMore(data.meta.current_page < data.meta.last_page);
      setPage(p);
    } catch {
    } finally {
      setLoading(false);
      setLoaded(true);
    }
  }, [filter2]);
  reactExports.useEffect(() => {
    fetchFeed(1, filter2);
  }, [filter2]);
  const handleFilterChange = (f2) => {
    if (f2 === filter2) return;
    setFilter(f2);
    setPosts([]);
    setLoaded(false);
    setPage(1);
  };
  const handleDeleted = reactExports.useCallback((postId) => {
    setPosts((prev) => prev.filter((p) => p.id !== postId));
  }, []);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[#080f1e]" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl mx-auto px-4 pt-8 pb-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between mb-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h1", { className: "text-xl font-bold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-users-rays mr-2 text-sky-400 opacity-80" }), "Following Feed"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 mt-0.5" }, "Posts from creators you follow")), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/discover/trending",
      className: "text-xs text-sky-400 hover:text-sky-300 transition-colors"
    },
    "Discover creators →"
  )), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2 overflow-x-auto pb-1 scrollbar-hide" }, FILTER_OPTIONS.map((f2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: f2.value,
      onClick: () => handleFilterChange(f2.value),
      className: `px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all border ${filter2 === f2.value ? "bg-sky-600/20 border-sky-500/40 text-sky-300" : "bg-white/[0.03] border-white/[0.06] text-slate-400 hover:text-white hover:border-white/10"}`
    },
    f2.label
  )))), /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl mx-auto px-4 pb-16 space-y-4" }, !loaded && loading && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(PostCardSkeleton, null), /* @__PURE__ */ React.createElement(PostCardSkeleton, null), /* @__PURE__ */ React.createElement(PostCardSkeleton, null)), loaded && !loading && posts.length === 0 && /* @__PURE__ */ React.createElement(EmptyFollowingState, null), posts.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard$1,
    {
      key: post2.id,
      post: post2,
      isLoggedIn: !!authUser,
      viewerUsername: authUser?.username ?? null,
      onDelete: handleDeleted
    }
  )), loaded && hasMore && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchFeed(page + 1),
      disabled: loading,
      className: "px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm transition-colors disabled:opacity-50"
    },
    loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more"
  )))));
}
const __vite_glob_0_62 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: FollowingFeed
}, Symbol.toStringTag, { value: "Module" }));
function HashtagFeed() {
  const { props } = X$1();
  const { auth, tag, seo } = props;
  const authUser = auth?.user ?? null;
  const [posts, setPosts] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [page, setPage] = reactExports.useState(1);
  const [hasMore, setHasMore] = reactExports.useState(false);
  const [loaded, setLoaded] = reactExports.useState(false);
  const [totalPosts, setTotalPosts] = reactExports.useState(null);
  const fetchFeed = reactExports.useCallback(async (p = 1) => {
    setLoading(true);
    try {
      const { data } = await axios.get(`/api/feed/hashtag/${encodeURIComponent(tag)}`, {
        params: { page: p }
      });
      setPosts((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setHasMore(data.meta.current_page < data.meta.last_page);
      setTotalPosts(data.meta.total ?? null);
      setPage(p);
    } catch {
    } finally {
      setLoading(false);
      setLoaded(true);
    }
  }, [tag]);
  reactExports.useEffect(() => {
    fetchFeed(1);
  }, [tag]);
  const handleDeleted = reactExports.useCallback((id) => setPosts((prev) => prev.filter((p) => p.id !== id)), []);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[#080f1e]" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl mx-auto px-4 pt-8 pb-16" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 mb-1" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center justify-center w-10 h-10 rounded-xl bg-sky-500/15 text-sky-400 text-lg font-bold" }, "#"), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h1", { className: "text-xl font-bold text-white" }, "#", tag), totalPosts !== null && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 mt-0.5" }, totalPosts.toLocaleString(), " post", totalPosts !== 1 ? "s" : ""))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex gap-2" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/feed/trending",
      className: "text-xs text-slate-500 hover:text-sky-400 transition-colors"
    },
    "← Trending"
  ))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, !loaded && loading && /* @__PURE__ */ React.createElement(React.Fragment, null, Array.from({ length: 3 }).map((_2, i) => /* @__PURE__ */ React.createElement(PostCardSkeleton, { key: i }))), loaded && !loading && posts.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-24 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-hashtag text-2xl" })), /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white/80 mb-2" }, "No posts yet"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-500 text-sm max-w-xs" }, "No posts tagged ", /* @__PURE__ */ React.createElement("span", { className: "text-sky-400" }, "#", tag), " yet. Be the first!")), posts.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard$1,
    {
      key: post2.id,
      post: post2,
      isLoggedIn: !!authUser,
      viewerUsername: authUser?.username ?? null,
      onDelete: handleDeleted
    }
  )), loaded && hasMore && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchFeed(page + 1),
      disabled: loading,
      className: "px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm transition-colors disabled:opacity-50"
    },
    loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more"
  ))))));
}
const __vite_glob_0_63 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: HashtagFeed
}, Symbol.toStringTag, { value: "Module" }));
function SavedFeed() {
  const { props } = X$1();
  const { auth, seo } = props;
  const authUser = auth?.user ?? null;
  const [posts, setPosts] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [page, setPage] = reactExports.useState(1);
  const [hasMore, setHasMore] = reactExports.useState(false);
  const [loaded, setLoaded] = reactExports.useState(false);
  const fetchFeed = reactExports.useCallback(async (p = 1) => {
    setLoading(true);
    try {
      const { data } = await axios.get("/api/posts/saved", { params: { page: p } });
      setPosts((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setHasMore(data.meta.current_page < data.meta.last_page);
      setPage(p);
    } catch {
    } finally {
      setLoading(false);
      setLoaded(true);
    }
  }, []);
  reactExports.useEffect(() => {
    fetchFeed(1);
  }, []);
  const handleDeleted = reactExports.useCallback((id) => setPosts((prev) => prev.filter((p) => p.id !== id)), []);
  const handleUnsaved = reactExports.useCallback((id) => setPosts((prev) => prev.filter((p) => p.id !== id)), []);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[#080f1e]" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl mx-auto px-4 pt-8 pb-16" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6" }, /* @__PURE__ */ React.createElement("h1", { className: "text-xl font-bold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bookmark mr-2 text-amber-400 opacity-80" }), "Saved Posts"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 mt-0.5" }, "Posts you've bookmarked")), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, !loaded && loading && /* @__PURE__ */ React.createElement(React.Fragment, null, Array.from({ length: 3 }).map((_2, i) => /* @__PURE__ */ React.createElement(PostCardSkeleton, { key: i }))), loaded && !loading && posts.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-24 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bookmark text-2xl" })), /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white/80 mb-2" }, "Nothing saved yet"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-500 text-sm max-w-xs leading-relaxed" }, "Bookmark posts to read later. Look for the", " ", /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-bookmark text-amber-400" }), " icon on any post."), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/feed/trending",
      className: "mt-4 text-sm text-sky-400 hover:text-sky-300 transition-colors"
    },
    "Browse trending posts →"
  )), posts.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard$1,
    {
      key: post2.id,
      post: post2,
      isLoggedIn: !!authUser,
      viewerUsername: authUser?.username ?? null,
      onDelete: handleDeleted,
      onUnsaved: handleUnsaved
    }
  )), loaded && hasMore && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchFeed(page + 1),
      disabled: loading,
      className: "px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm transition-colors disabled:opacity-50"
    },
    loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more"
  ))))));
}
const __vite_glob_0_64 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: SavedFeed
}, Symbol.toStringTag, { value: "Module" }));
function TrendingHashtagsSidebar$1({ hashtags }) {
  if (!hashtags || hashtags.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 px-4 py-3 border-b border-white/[0.05]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-hashtag text-slate-500 fa-fw text-[13px]" }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-widest text-slate-500" }, "Trending Tags")), /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 space-y-1" }, hashtags.map((h) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: h.tag,
      href: `/feed/search?q=%23${h.tag}`,
      className: "flex items-center justify-between group px-2 py-1.5 rounded-lg transition-colors hover:bg-white/5 text-slate-400 hover:text-white"
    },
    /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium" }, "#", h.tag),
    /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-slate-600 group-hover:text-slate-500 tabular-nums" }, h.post_count)
  ))));
}
function SearchFeed() {
  const { props } = X$1();
  const { auth, initialQuery, trendingHashtags, seo } = props;
  const authUser = auth?.user ?? null;
  const [query, setQuery] = reactExports.useState(initialQuery ?? "");
  const [results, setResults] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [searched, setSearched] = reactExports.useState(false);
  const [meta, setMeta] = reactExports.useState(null);
  const [page, setPage] = reactExports.useState(1);
  const debounceRef = reactExports.useRef(null);
  const inputRef = reactExports.useRef(null);
  const pushUrl = reactExports.useCallback((q2) => {
    const url = q2.trim() ? `/feed/search?q=${encodeURIComponent(q2.trim())}` : "/feed/search";
    window.history.replaceState({}, "", url);
  }, []);
  const fetchResults = reactExports.useCallback(async (q2, p = 1) => {
    if (!q2.trim() || q2.trim().length < 2) {
      setResults([]);
      setMeta(null);
      setSearched(false);
      return;
    }
    setLoading(true);
    try {
      const { data } = await axios.get("/api/feed/search", {
        params: { q: q2.trim(), page: p }
      });
      setResults((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setMeta(data.meta);
      setPage(p);
      setSearched(true);
    } catch {
    } finally {
      setLoading(false);
    }
  }, []);
  const handleChange = reactExports.useCallback((e) => {
    const q2 = e.target.value;
    setQuery(q2);
    pushUrl(q2);
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => {
      fetchResults(q2, 1);
    }, 350);
  }, [fetchResults, pushUrl]);
  const handleSubmit = reactExports.useCallback((e) => {
    e.preventDefault();
    clearTimeout(debounceRef.current);
    fetchResults(query, 1);
  }, [fetchResults, query]);
  const handleClear = reactExports.useCallback(() => {
    setQuery("");
    setResults([]);
    setMeta(null);
    setSearched(false);
    pushUrl("");
    inputRef.current?.focus();
  }, [pushUrl]);
  reactExports.useEffect(() => {
    if (initialQuery?.trim().length >= 2) {
      fetchResults(initialQuery.trim(), 1);
    }
  }, []);
  const handleDeleted = reactExports.useCallback((id) => {
    setResults((prev) => prev.filter((p) => p.id !== id));
  }, []);
  const hasMore = meta ? meta.current_page < meta.last_page : false;
  const noResults = searched && !loading && results.length === 0;
  const hasResults = results.length > 0;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[#080f1e]" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-5xl mx-auto px-4 pt-8 pb-16" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h1", { className: "text-xl font-bold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass mr-2 text-slate-400/80" }), "Search Posts"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 mt-0.5" }, "Search by keywords, hashtags, or phrases")), /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 text-sm pointer-events-none" }), /* @__PURE__ */ React.createElement(
    "input",
    {
      ref: inputRef,
      type: "text",
      autoFocus: true,
      value: query,
      onChange: handleChange,
      placeholder: "Search posts…",
      className: "w-full bg-white/[0.05] border border-white/[0.08] rounded-xl pl-10 pr-10 py-3 text-sm text-white placeholder-slate-500 focus:outline-none focus:border-sky-500/40 focus:ring-1 focus:ring-sky-500/30 transition-colors"
    }
  ), query && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleClear,
      className: "absolute right-3 top-1/2 -translate-y-1/2 p-1 text-slate-500 hover:text-white transition-colors",
      "aria-label": "Clear search"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark text-sm" })
  ))), loading && !hasResults && /* @__PURE__ */ React.createElement(React.Fragment, null, Array.from({ length: 3 }).map((_2, i) => /* @__PURE__ */ React.createElement(PostCardSkeleton, { key: i }))), !searched && !loading && /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-20 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass text-2xl" })), /* @__PURE__ */ React.createElement("p", { className: "text-slate-500 text-sm" }, "Type at least 2 characters to search posts")), noResults && /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-20 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-face-rolling-eyes text-2xl" })), /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white/80 mb-1" }, "No results"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-500 text-sm" }, "Nothing matched ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "“", query, "”"), ". Try different keywords or a hashtag.")), hasResults && meta && /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-600 px-1" }, meta.total.toLocaleString(), " result", meta.total !== 1 ? "s" : "", " for", " ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-400" }, "“", query, "”")), results.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard$1,
    {
      key: post2.id,
      post: post2,
      isLoggedIn: !!authUser,
      viewerUsername: authUser?.username ?? null,
      onDelete: handleDeleted
    }
  )), loading && hasResults && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin text-slate-500" })), !loading && hasMore && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchResults(query, page + 1),
      className: "px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm transition-colors"
    },
    "Load more"
  ))), /* @__PURE__ */ React.createElement("aside", { className: "hidden lg:block w-64 shrink-0 space-y-4 pt-14" }, /* @__PURE__ */ React.createElement(TrendingHashtagsSidebar$1, { hashtags: trendingHashtags }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] px-4 py-4 text-center" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 leading-relaxed" }, "Tip: search ", /* @__PURE__ */ React.createElement("span", { className: "text-sky-400/80" }, "#hashtag"), " to find posts by topic.")))))));
}
const __vite_glob_0_65 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: SearchFeed
}, Symbol.toStringTag, { value: "Module" }));
function TrendingHashtagsSidebar({ hashtags, activeTag = null }) {
  if (!hashtags || hashtags.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 px-4 py-3 border-b border-white/[0.05]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-hashtag text-slate-500 fa-fw text-[13px]" }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-widest text-slate-500" }, "Trending Tags")), /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 space-y-1.5" }, hashtags.map((h) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: h.tag,
      href: `/tags/${h.tag}`,
      className: `flex items-center justify-between group px-2 py-1.5 rounded-lg transition-colors ${activeTag === h.tag ? "bg-sky-500/15 text-sky-400" : "hover:bg-white/5 text-slate-400 hover:text-white"}`
    },
    /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium" }, "#", h.tag),
    /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-slate-600 group-hover:text-slate-500 tabular-nums" }, h.post_count, " posts")
  ))));
}
function TrendingFeed() {
  const { props } = X$1();
  const { auth, trendingHashtags, seo } = props;
  const authUser = auth?.user ?? null;
  const [posts, setPosts] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [page, setPage] = reactExports.useState(1);
  const [hasMore, setHasMore] = reactExports.useState(false);
  const [loaded, setLoaded] = reactExports.useState(false);
  const fetchFeed = reactExports.useCallback(async (p = 1) => {
    setLoading(true);
    try {
      const { data } = await axios.get("/api/feed/trending", { params: { page: p } });
      setPosts((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setHasMore(data.meta.current_page < data.meta.last_page);
      setPage(p);
    } catch {
    } finally {
      setLoading(false);
      setLoaded(true);
    }
  }, []);
  reactExports.useEffect(() => {
    fetchFeed(1);
  }, []);
  const handleDeleted = reactExports.useCallback((id) => setPosts((prev) => prev.filter((p) => p.id !== id)), []);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[#080f1e]" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-5xl mx-auto px-4 pt-8 pb-16" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6" }, /* @__PURE__ */ React.createElement("h1", { className: "text-xl font-bold text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-fire mr-2 text-orange-400 opacity-80" }), "Trending"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 mt-0.5" }, "Most engaging posts right now")), !loaded && loading && /* @__PURE__ */ React.createElement(React.Fragment, null, Array.from({ length: 3 }).map((_2, i) => /* @__PURE__ */ React.createElement(PostCardSkeleton, { key: i }))), loaded && !loading && posts.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-24 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-16 h-16 rounded-2xl bg-white/5 flex items-center justify-center mb-4 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-fire text-2xl" })), /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white/80 mb-2" }, "Nothing trending yet"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-500 text-sm" }, "Check back soon — posts are ranked by engagement.")), posts.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard$1,
    {
      key: post2.id,
      post: post2,
      isLoggedIn: !!authUser,
      viewerUsername: authUser?.username ?? null,
      onDelete: handleDeleted
    }
  )), loaded && hasMore && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchFeed(page + 1),
      disabled: loading,
      className: "px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm transition-colors disabled:opacity-50"
    },
    loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more"
  ))), /* @__PURE__ */ React.createElement("aside", { className: "hidden lg:block w-64 shrink-0 space-y-4 pt-14" }, /* @__PURE__ */ React.createElement(TrendingHashtagsSidebar, { hashtags: trendingHashtags }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] px-4 py-4 text-center" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 leading-relaxed" }, "Posts are ranked by likes, comments & engagement over the last 7 days.")))))));
}
const __vite_glob_0_66 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: TrendingFeed
}, Symbol.toStringTag, { value: "Module" }));
function Breadcrumbs({ items = [] }) {
  return /* @__PURE__ */ React.createElement("nav", { className: "text-sm text-zinc-400", "aria-label": "Breadcrumb" }, /* @__PURE__ */ React.createElement("ol", { className: "flex flex-wrap items-center gap-1.5" }, items.map((item, i) => /* @__PURE__ */ React.createElement(React.Fragment, { key: i }, i > 0 && /* @__PURE__ */ React.createElement("li", { "aria-hidden": "true", className: "text-zinc-600" }, /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", className: "inline-block" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4l4 4-4 4", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }))), /* @__PURE__ */ React.createElement("li", null, item.href ? /* @__PURE__ */ React.createElement("a", { href: item.href, className: "hover:text-zinc-200 transition-colors" }, item.label) : /* @__PURE__ */ React.createElement("span", { className: "text-zinc-200" }, item.label))))));
}
function ThreadRow({ thread, isFirst = false }) {
  thread?.topic_id ?? thread?.id ?? 0;
  const title = thread?.topic ?? thread?.title ?? "Untitled";
  const slug = thread?.slug ?? slugify$1(title);
  const excerpt = thread?.discuss ?? "";
  const posts = thread?.num_posts ?? 0;
  const author = thread?.uname ?? "Unknown";
  const lastUpdate = thread?.last_update ?? thread?.post_date;
  const isPinned = thread?.is_pinned ?? false;
  const href = `/forum/topic/${slug}`;
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href,
      className: [
        "group flex items-start gap-4 px-5 py-4 transition-colors hover:bg-white/[0.03]",
        !isFirst && "border-t border-white/[0.06]"
      ].filter(Boolean).join(" ")
    },
    /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-sky-500/10 text-sky-400 group-hover:bg-sky-500/15 transition-colors" }, isPinned ? /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2z" })) : /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" }))),
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "m-0 truncate text-sm font-semibold leading-tight text-white transition-colors group-hover:text-sky-300" }, title), isPinned && /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-300" }, "Pinned")), excerpt && /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-xs text-white/40" }, stripHtml$3(excerpt).slice(0, 180)), /* @__PURE__ */ React.createElement("div", { className: "mt-1.5 flex flex-wrap items-center gap-3 text-xs text-white/35" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" }), /* @__PURE__ */ React.createElement("circle", { cx: "12", cy: "7", r: "4" })), author), /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), posts, " ", posts === 1 ? "reply" : "replies"), lastUpdate && /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("circle", { cx: "12", cy: "12", r: "10" }), /* @__PURE__ */ React.createElement("polyline", { points: "12 6 12 12 16 14" })), formatDate$f(lastUpdate)))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1 shrink-0" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex min-w-[2rem] items-center justify-center rounded-full bg-white/[0.06] px-2.5 py-1 text-xs font-medium text-white/60" }, posts))
  );
}
function slugify$1(text2) {
  return (text2 ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 80);
}
function stripHtml$3(html2) {
  const decodeEntities = (value) => {
    let decoded = String(value ?? "");
    for (let index2 = 0; index2 < 4; index2 += 1) {
      if (!decoded.includes("&")) break;
      if (typeof document !== "undefined") {
        const textarea = document.createElement("textarea");
        textarea.innerHTML = decoded;
        const next = textarea.value;
        if (next === decoded) break;
        decoded = next;
      } else {
        break;
      }
    }
    return decoded;
  };
  if (typeof document !== "undefined") {
    const div = document.createElement("div");
    div.innerHTML = decodeEntities(html2);
    return div.textContent || div.innerText || "";
  }
  return decodeEntities(html2).replace(/<[^>]*>/g, "");
}
function formatDate$f(dateStr) {
  try {
    const d2 = new Date(dateStr);
    return d2.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" }) + " " + d2.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
  } catch {
    return "-";
  }
}
function ForumCategory({ category, parentCategory = null, threads = [], pagination = {}, isAuthenticated = false, seo = {} }) {
  const name2 = category?.name ?? "Category";
  const slug = category?.slug;
  const breadcrumbs = [
    { label: "Home", href: "/" },
    { label: "Forum", href: "/forum" },
    ...parentCategory ? [{ label: parentCategory.name, href: `/forum/category/${parentCategory.slug}` }] : [],
    { label: name2 }
  ];
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-5xl mx-auto" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("div", { className: "mt-5 mb-6 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-widest text-white/30 mb-1" }, "Forum"), /* @__PURE__ */ React.createElement("h1", { className: "text-3xl font-bold text-white leading-tight" }, name2), category?.description && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/50" }, category.description)), isAuthenticated && slug && /* @__PURE__ */ React.createElement("a", { href: `/forum/${slug}/new` }, /* @__PURE__ */ React.createElement(
    Button$1,
    {
      variant: "primary",
      size: "sm",
      leftIcon: /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("line", { x1: "12", y1: "5", x2: "12", y2: "19" }), /* @__PURE__ */ React.createElement("line", { x1: "5", y1: "12", x2: "19", y2: "12" }))
    },
    "New topic"
  ))), /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-2xl border border-white/[0.06] bg-nova-800/50 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 border-b border-white/[0.06] px-5 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex-1 text-xs font-semibold uppercase tracking-widest text-white/30" }, "Topics"), /* @__PURE__ */ React.createElement("span", { className: "w-16 text-center text-xs font-semibold uppercase tracking-widest text-white/30" }, "Replies")), threads.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "px-5 py-12 text-center" }, /* @__PURE__ */ React.createElement("svg", { className: "mx-auto mb-4 text-zinc-600", width: "40", height: "40", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-zinc-500" }, "No topics in this board yet."), isAuthenticated && slug && /* @__PURE__ */ React.createElement("a", { href: `/forum/${slug}/new`, className: "mt-3 inline-block text-sm text-sky-300 hover:text-sky-200" }, "Be the first to start a discussion →")) : /* @__PURE__ */ React.createElement("div", null, threads.map((thread, i) => /* @__PURE__ */ React.createElement(ThreadRow, { key: thread.topic_id ?? thread.id ?? i, thread, isFirst: i === 0 })))), pagination?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(Pagination$1, { meta: pagination }))));
}
const __vite_glob_0_67 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ForumCategory
}, Symbol.toStringTag, { value: "Module" }));
const providerAdapters = {
  turnstile: {
    globalName: "turnstile",
    render(api, container, { siteKey, theme, onToken }) {
      return api.render(container, {
        sitekey: siteKey,
        theme,
        callback: (token) => onToken?.(token || ""),
        "expired-callback": () => onToken?.(""),
        "error-callback": () => onToken?.("")
      });
    },
    cleanup(api, widgetId, container, onToken) {
      if (widgetId !== null && api?.remove) {
        api.remove(widgetId);
      }
      if (container) {
        container.innerHTML = "";
      }
      onToken?.("");
    }
  },
  recaptcha: {
    globalName: "grecaptcha",
    render(api, container, { siteKey, theme, onToken }) {
      return api.render(container, {
        sitekey: siteKey,
        theme,
        callback: (token) => onToken?.(token || ""),
        "expired-callback": () => onToken?.(""),
        "error-callback": () => onToken?.("")
      });
    },
    cleanup(api, widgetId, container, onToken) {
      if (widgetId !== null && api?.reset) {
        api.reset(widgetId);
      }
      if (container) {
        container.innerHTML = "";
      }
      onToken?.("");
    }
  },
  hcaptcha: {
    globalName: "hcaptcha",
    render(api, container, { siteKey, theme, onToken }) {
      return api.render(container, {
        sitekey: siteKey,
        theme,
        callback: (token) => onToken?.(token || ""),
        "expired-callback": () => onToken?.(""),
        "error-callback": () => onToken?.("")
      });
    },
    cleanup(api, widgetId, container, onToken) {
      if (widgetId !== null && api?.remove) {
        api.remove(widgetId);
      }
      if (container) {
        container.innerHTML = "";
      }
      onToken?.("");
    }
  }
};
function loadCaptchaScript(src2) {
  if (!src2) {
    return Promise.resolve();
  }
  if (!window.__skinbaseCaptchaScripts) {
    window.__skinbaseCaptchaScripts = {};
  }
  if (!window.__skinbaseCaptchaScripts[src2]) {
    window.__skinbaseCaptchaScripts[src2] = new Promise((resolve, reject) => {
      const existing = document.querySelector(`script[src="${src2}"]`);
      if (existing) {
        if (existing.dataset.loaded === "true") {
          resolve();
          return;
        }
        existing.addEventListener("load", () => resolve(), { once: true });
        existing.addEventListener("error", () => reject(new Error(`Failed to load captcha script: ${src2}`)), { once: true });
        return;
      }
      const script = document.createElement("script");
      script.src = src2;
      script.async = true;
      script.defer = true;
      script.addEventListener("load", () => {
        script.dataset.loaded = "true";
        resolve();
      }, { once: true });
      script.addEventListener("error", () => reject(new Error(`Failed to load captcha script: ${src2}`)), { once: true });
      document.head.appendChild(script);
    });
  }
  return window.__skinbaseCaptchaScripts[src2];
}
function TurnstileField({ provider = "turnstile", siteKey, scriptUrl = "", onToken, theme = "dark", className = "" }) {
  const containerRef = reactExports.useRef(null);
  const widgetIdRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    const adapter = providerAdapters[provider] || providerAdapters.turnstile;
    if (!siteKey || !containerRef.current) {
      return void 0;
    }
    let cancelled = false;
    let intervalId = null;
    const mountWidget = () => {
      const api = window[adapter.globalName];
      if (cancelled || !api?.render || widgetIdRef.current !== null) {
        return;
      }
      widgetIdRef.current = adapter.render(api, containerRef.current, {
        siteKey,
        theme,
        onToken
      });
    };
    loadCaptchaScript(scriptUrl).catch(() => onToken?.("")).finally(() => {
      const api = window[adapter.globalName];
      if (typeof api?.ready === "function") {
        api.ready(mountWidget);
      } else {
        mountWidget();
      }
      if (widgetIdRef.current === null) {
        intervalId = window.setInterval(mountWidget, 250);
      }
    });
    return () => {
      cancelled = true;
      if (intervalId) {
        window.clearInterval(intervalId);
      }
      adapter.cleanup(window[adapter.globalName], widgetIdRef.current, containerRef.current, onToken);
      widgetIdRef.current = null;
    };
  }, [className, onToken, provider, scriptUrl, siteKey, theme]);
  if (!siteKey) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { ref: containerRef, className });
}
async function sha256Hex(value) {
  if (!window.crypto?.subtle) {
    return "";
  }
  const encoded = new TextEncoder().encode(value);
  const digest = await window.crypto.subtle.digest("SHA-256", encoded);
  return Array.from(new Uint8Array(digest)).map((part) => part.toString(16).padStart(2, "0")).join("");
}
function readWebglVendor() {
  try {
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    if (!gl) {
      return "no-webgl";
    }
    const extension2 = gl.getExtension("WEBGL_debug_renderer_info");
    if (!extension2) {
      return "webgl-hidden";
    }
    return [
      gl.getParameter(extension2.UNMASKED_VENDOR_WEBGL),
      gl.getParameter(extension2.UNMASKED_RENDERER_WEBGL)
    ].join(":");
  } catch {
    return "webgl-error";
  }
}
async function buildBotFingerprint() {
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "unknown";
  const screenSize = typeof window.screen !== "undefined" ? `${window.screen.width}x${window.screen.height}x${window.devicePixelRatio || 1}` : "no-screen";
  const payload = [
    navigator.userAgent || "unknown-ua",
    navigator.language || "unknown-language",
    navigator.platform || "unknown-platform",
    timezone,
    screenSize,
    readWebglVendor()
  ].join("|");
  return sha256Hex(payload);
}
async function populateBotFingerprint(form) {
  if (!form) {
    return "";
  }
  const fingerprint = await buildBotFingerprint();
  const field = form.querySelector('input[name="_bot_fingerprint"]');
  if (field && fingerprint !== "") {
    field.value = fingerprint;
  }
  return fingerprint;
}
function ForumEditPost({ post: post2, thread, csrfToken: csrfToken2, errors = {}, captcha = {}, seo = {} }) {
  const [content2, setContent] = reactExports.useState(post2?.content ?? "");
  const [captchaToken, setCaptchaToken] = reactExports.useState("");
  const [submitting, setSubmitting] = reactExports.useState(false);
  const breadcrumbs = [
    { label: "Home", href: "/" },
    { label: "Forum", href: "/forum" },
    { label: thread?.title ?? "Topic", href: thread?.slug ? `/forum/topic/${thread.slug}` : "/forum" },
    { label: "Edit post" }
  ];
  const handleSubmit = reactExports.useCallback((e) => {
    if (submitting) return;
    e.preventDefault();
    setSubmitting(true);
    const form = e.currentTarget;
    populateBotFingerprint(form).finally(() => {
      form?.submit();
    });
  }, [submitting]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-3xl mx-auto" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("div", { className: "mt-5 mb-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-widest text-white/30 mb-1" }, "Edit"), /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white leading-tight" }, "Edit post")), /* @__PURE__ */ React.createElement(
    "form",
    {
      method: "POST",
      action: `/forum/post/${post2?.id}`,
      onSubmit: handleSubmit,
      className: "space-y-5 rounded-2xl border border-white/[0.06] bg-nova-800/50 p-6 backdrop-blur"
    },
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "_token", value: csrfToken2 }),
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "_method", value: "PUT" }),
    /* @__PURE__ */ React.createElement("input", { type: "text", name: "homepage_url", defaultValue: "", autoComplete: "off", className: "hidden", "aria-hidden": "true", tabIndex: -1 }),
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "_bot_fingerprint", value: "" }),
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: captcha.inputName || "cf-turnstile-response", value: captchaToken }),
    errors.bot ? /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-300" }, Array.isArray(errors.bot) ? errors.bot[0] : errors.bot) : null,
    errors.captcha ? /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-200" }, Array.isArray(errors.captcha) ? errors.captcha[0] : errors.captcha) : null,
    /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-1.5 block text-sm font-medium text-white/85" }, "Content"), /* @__PURE__ */ React.createElement(
      RichTextEditor,
      {
        content: content2,
        onChange: setContent,
        placeholder: "Edit your post…",
        error: errors.content,
        minHeight: 14,
        autofocus: false
      }
    ), /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "content", value: content2 })),
    captcha.siteKey ? /* @__PURE__ */ React.createElement(
      TurnstileField,
      {
        provider: captcha.provider,
        siteKey: captcha.siteKey,
        scriptUrl: captcha.scriptUrl,
        onToken: setCaptchaToken,
        className: "rounded-lg border border-white/10 bg-black/20 p-3"
      }
    ) : null,
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between pt-2" }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: thread?.slug ? `/forum/topic/${thread.slug}` : "/forum",
        className: "text-sm text-zinc-500 hover:text-zinc-300 transition-colors"
      },
      "← Cancel"
    ), /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "primary", size: "md", loading: submitting }, "Save changes"))
  )));
}
const __vite_glob_0_68 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ForumEditPost
}, Symbol.toStringTag, { value: "Module" }));
function CategoryCard({ category }) {
  const name2 = category?.name ?? "Untitled";
  const slug = category?.slug;
  const categoryHref = slug ? `/forum/category/${slug}` : null;
  const threads = category?.thread_count ?? 0;
  const posts = category?.post_count ?? 0;
  const lastActivity = category?.last_activity_at;
  const preview = category?.preview_image ?? "/images/forum-default.jpg";
  const boards = category?.boards ?? [];
  const boardCount = boards.length;
  const activeBoards = boards.filter((board) => Number(board?.topics_count ?? 0) > 0).length;
  const latestBoard = boards.filter((board) => board?.latest_topic?.last_post_at).sort((a, b2) => new Date(b2.latest_topic.last_post_at) - new Date(a.latest_topic.last_post_at))[0];
  const timeAgo = lastActivity ? formatTimeAgo$1(lastActivity) : null;
  return /* @__PURE__ */ React.createElement("div", { className: "group relative block overflow-hidden rounded-2xl border border-white/[0.06] bg-nova-800/50 shadow-xl backdrop-blur transition-all duration-300 hover:border-cyan-400/20 hover:shadow-cyan-500/10 focus-within:ring-2 focus-within:ring-cyan-400" }, /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/9]" }, categoryHref ? /* @__PURE__ */ React.createElement("a", { href: categoryHref, className: "block h-full" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: preview,
      alt: `${name2} preview`,
      loading: "lazy",
      decoding: "async",
      className: "h-full w-full object-cover object-center transition-transform duration-500 group-hover:scale-[1.03]"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 inline-flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-400/15 text-cyan-300" }, /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" }))), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-bold leading-snug text-white transition group-hover:text-cyan-200" }, name2), category?.description && /* @__PURE__ */ React.createElement("p", { className: "mt-1 line-clamp-2 text-xs text-white/60" }, category.description), timeAgo && /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/50" }, "Last activity: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/70" }, timeAgo)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-4 text-sm" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1.5 text-cyan-300" }, /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), number$2(posts), " posts"), /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1.5 text-cyan-300/70" }, /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" }), /* @__PURE__ */ React.createElement("polyline", { points: "14 2 14 8 20 8" })), number$2(threads), " topics")), /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-cyan-200 transition group-hover:text-cyan-100" }, "View section")))) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: preview,
      alt: `${name2} preview`,
      loading: "lazy",
      decoding: "async",
      className: "h-full w-full object-cover object-center transition-transform duration-500 group-hover:scale-[1.03]"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 inline-flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-400/15 text-cyan-300" }, /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" }))), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-bold leading-snug text-white" }, name2), category?.description && /* @__PURE__ */ React.createElement("p", { className: "mt-1 line-clamp-2 text-xs text-white/60" }, category.description), timeAgo && /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/50" }, "Last activity: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/70" }, timeAgo)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-4 text-sm" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1.5 text-cyan-300" }, /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), number$2(posts), " posts"), /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1.5 text-cyan-300/70" }, /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" }), /* @__PURE__ */ React.createElement("polyline", { points: "14 2 14 8 20 8" })), number$2(threads), " topics"))))), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/8 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-white/8 bg-white/[0.02] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.12em] text-white/40" }, "Boards"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, number$2(boardCount))), /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-white/8 bg-white/[0.02] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.12em] text-white/40" }, "Topics"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, number$2(threads))), /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-white/8 bg-white/[0.02] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.12em] text-white/40" }, "Posts"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, number$2(posts)))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-between text-xs text-white/50" }, /* @__PURE__ */ React.createElement("span", null, number$2(activeBoards), " active boards"), latestBoard?.title ? /* @__PURE__ */ React.createElement("span", null, "Latest: ", latestBoard.title) : /* @__PURE__ */ React.createElement("span", null, "No recent board activity"))));
}
function number$2(n) {
  return (n ?? 0).toLocaleString();
}
function formatTimeAgo$1(dateStr) {
  try {
    const date = new Date(dateStr);
    const now = /* @__PURE__ */ new Date();
    const diff = Math.floor((now - date) / 1e3);
    if (diff < 60) return "just now";
    if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
    if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
    return date.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" });
  } catch {
    return null;
  }
}
function ForumIndex({ categories = [], trendingTopics = [], latestTopics = [], seo = {} }) {
  const totalThreads = categories.reduce((sum, cat) => sum + (Number(cat?.thread_count) || 0), 0);
  const totalPosts = categories.reduce((sum, cat) => sum + (Number(cat?.post_count) || 0), 0);
  const sortedByActivity = [...categories].sort((a, b2) => {
    const aTime = a?.last_activity_at ? new Date(a.last_activity_at).getTime() : 0;
    const bTime = b2?.last_activity_at ? new Date(b2.last_activity_at).getTime() : 0;
    return bTime - aTime;
  });
  const latestActive = sortedByActivity[0] ?? null;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "pb-20" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden border-b border-white/10 bg-[radial-gradient(circle_at_15%_20%,rgba(34,211,238,0.24),transparent_40%),radial-gradient(circle_at_80%_0%,rgba(56,189,248,0.16),transparent_42%),linear-gradient(180deg,rgba(10,14,26,0.96),rgba(8,12,22,0.92))]" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 opacity-40 [background-image:linear-gradient(rgba(255,255,255,0.06)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] [background-size:40px_40px]" }), /* @__PURE__ */ React.createElement("div", { className: "relative mx-auto w-full max-w-[1400px] px-4 py-10 sm:px-6 lg:px-10 lg:py-14" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 lg:grid-cols-[1.2fr_0.8fr] lg:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 inline-flex items-center gap-2 rounded-full border border-cyan-300/30 bg-cyan-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-cyan-100" }, "Community Hub"), /* @__PURE__ */ React.createElement("h1", { className: "text-4xl font-black leading-[0.95] tracking-[-0.02em] text-white sm:text-5xl lg:text-6xl" }, "Skinbase Forum"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-relaxed text-slate-200/80 sm:text-base" }, "Ask questions, share progress, and join focused conversations across every part of Skinbase. This page is your launch point to active topics and community knowledge."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/forum", className: "inline-flex items-center gap-2 rounded-xl bg-cyan-400 px-4 py-2.5 text-sm font-semibold text-slate-950 transition hover:bg-cyan-300" }, "Explore Categories", /* @__PURE__ */ React.createElement("span", { "aria-hidden": "true" }, "→")))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 lg:grid-cols-1" }, /* @__PURE__ */ React.createElement(StatCard$4, { label: "Sections", value: number$1(categories.length) }), /* @__PURE__ */ React.createElement(StatCard$4, { label: "Topics", value: number$1(totalThreads) }), /* @__PURE__ */ React.createElement(StatCard$4, { label: "Posts", value: number$1(totalPosts) }))), latestActive && /* @__PURE__ */ React.createElement("div", { className: "mt-7 rounded-2xl border border-white/15 bg-white/[0.04] p-4 backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-white/50" }, "Latest Activity"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap items-center gap-x-3 gap-y-1" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/forum/${latestActive.board_slug ?? latestActive.slug}`,
      className: "text-base font-semibold text-cyan-200 transition hover:text-cyan-100"
    },
    latestActive.name
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-white/45" }, formatLastActivity(latestActive.last_activity_at)))))), /* @__PURE__ */ React.createElement("section", { className: "mx-auto w-full max-w-[1400px] px-4 pt-8 sm:px-6 lg:px-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-white/40" }, "Browse"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-bold text-white sm:text-3xl" }, "Forum Sections")), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/50 sm:text-sm" }, "Choose a section to view threads or start a discussion.")), categories.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-nova-800/50 p-12 text-center" }, /* @__PURE__ */ React.createElement("svg", { className: "mx-auto mb-4 text-zinc-600", width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-zinc-400" }, "No forum categories available yet.")) : /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-3" }, categories.map((cat) => /* @__PURE__ */ React.createElement(CategoryCard, { key: cat.id ?? cat.slug, category: cat })))), /* @__PURE__ */ React.createElement("section", { className: "mx-auto grid w-full max-w-[1400px] gap-5 px-4 pt-8 sm:px-6 lg:grid-cols-2 lg:px-10" }, /* @__PURE__ */ React.createElement(Panel, { title: "Trending Topics", items: trendingTopics, emptyLabel: "Trending topics will appear once boards become active." }), /* @__PURE__ */ React.createElement(Panel, { title: "Latest Topics", items: latestTopics, emptyLabel: "Latest topics will appear here." }))));
}
function Panel({ title, items, emptyLabel }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-nova-800/50 p-5 backdrop-blur" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), items.length === 0 ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-white/45" }, emptyLabel) : /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.slug, href: `/forum/topic/${item.slug}`, className: "block rounded-xl border border-white/6 px-4 py-3 transition hover:border-cyan-400/20 hover:bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-3 text-xs text-white/45" }, item.board && /* @__PURE__ */ React.createElement("span", null, item.board), item.author && /* @__PURE__ */ React.createElement("span", null, "by ", item.author), typeof item.replies_count === "number" && /* @__PURE__ */ React.createElement("span", null, item.replies_count, " replies"), item.score !== void 0 && /* @__PURE__ */ React.createElement("span", null, "score ", item.score), item.last_post_at && /* @__PURE__ */ React.createElement("span", null, formatLastActivity(item.last_post_at)))))));
}
function StatCard$4({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/15 bg-white/[0.04] px-4 py-3 backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] uppercase tracking-[0.14em] text-white/50" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-2xl font-bold text-white" }, value));
}
function number$1(n) {
  return (n ?? 0).toLocaleString();
}
function formatLastActivity(value) {
  if (!value) {
    return "No recent activity";
  }
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return "No recent activity";
  }
  return `Updated ${date.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}`;
}
const __vite_glob_0_69 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ForumIndex
}, Symbol.toStringTag, { value: "Module" }));
const TextInput = reactExports.forwardRef(function TextInput2({
  label,
  error,
  hint,
  leftIcon,
  rightIcon,
  required,
  size = "md",
  id,
  className = "",
  ...rest
}, ref2) {
  const generatedId = reactExports.useId();
  const labelSlug = typeof label === "string" ? label.toLowerCase().replace(/\s+/g, "-") : null;
  const inputId = id ?? labelSlug ?? `text-input-${generatedId.replace(/[:]/g, "")}`;
  const sizeClass2 = {
    sm: "py-1.5 text-xs",
    md: "py-2.5 text-sm",
    lg: "py-3   text-base"
  }[size] ?? "py-2.5 text-sm";
  const paddingLeft = leftIcon ? "pl-10" : "pl-3.5";
  const paddingRight = rightIcon ? "pr-10" : "pr-3.5";
  const inputClass = [
    "block w-full rounded-xl border bg-white/[0.06] text-white",
    "placeholder:text-slate-500",
    "transition-all duration-150",
    "focus:outline-none focus:ring-2 focus:ring-offset-0",
    error ? "border-red-500/60 focus:border-red-500/70 focus:ring-red-500/40" : "border-white/12 hover:border-white/20 focus:border-accent/50 focus:ring-accent/40",
    "disabled:opacity-50 disabled:cursor-not-allowed",
    sizeClass2,
    paddingLeft,
    paddingRight,
    className
  ].join(" ");
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1.5" }, label && /* @__PURE__ */ React.createElement("label", { htmlFor: inputId, className: "text-sm font-medium text-white/85" }, label, required && /* @__PURE__ */ React.createElement("span", { className: "text-red-400 ml-1" }, "*")), /* @__PURE__ */ React.createElement("div", { className: "relative" }, leftIcon && /* @__PURE__ */ React.createElement("span", { className: "absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500 pointer-events-none" }, leftIcon), /* @__PURE__ */ React.createElement(
    "input",
    {
      id: inputId,
      ref: ref2,
      className: inputClass,
      "aria-invalid": !!error,
      "aria-describedby": error ? `${inputId}-error` : hint ? `${inputId}-hint` : void 0,
      ...rest
    }
  ), rightIcon && /* @__PURE__ */ React.createElement("span", { className: "absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-500" }, rightIcon)), error && /* @__PURE__ */ React.createElement("p", { id: `${inputId}-error`, role: "alert", className: "text-xs text-red-400" }, error), !error && hint && /* @__PURE__ */ React.createElement("p", { id: `${inputId}-hint`, className: "text-xs text-slate-500" }, hint));
});
function ForumNewThread({ category, csrfToken: csrfToken2, errors = {}, oldValues = {}, captcha = {}, seo = {} }) {
  const [title, setTitle] = reactExports.useState(oldValues.title ?? "");
  const [content2, setContent] = reactExports.useState(oldValues.content ?? "");
  const [captchaToken, setCaptchaToken] = reactExports.useState("");
  const [submitting, setSubmitting] = reactExports.useState(false);
  const slug = category?.slug;
  const categoryName = category?.name ?? "Category";
  const breadcrumbs = [
    { label: "Home", href: "/" },
    { label: "Forum", href: "/forum" },
    { label: categoryName, href: slug ? `/forum/${slug}` : "/forum" },
    { label: "New topic" }
  ];
  const handleSubmit = reactExports.useCallback(async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    await populateBotFingerprint(e.currentTarget);
    e.target.submit();
  }, [submitting]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-3xl mx-auto" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("div", { className: "mt-5 mb-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-widest text-white/30 mb-1" }, "New topic"), /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white leading-tight" }, "Create topic in ", categoryName)), /* @__PURE__ */ React.createElement(
    "form",
    {
      method: "POST",
      action: `/forum/${slug}/new`,
      onSubmit: handleSubmit,
      className: "space-y-5 rounded-2xl border border-white/[0.06] bg-nova-800/50 p-6 backdrop-blur"
    },
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "_token", value: csrfToken2 }),
    /* @__PURE__ */ React.createElement("input", { type: "text", name: "homepage_url", defaultValue: "", autoComplete: "off", className: "hidden", "aria-hidden": "true", tabIndex: -1 }),
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "_bot_fingerprint", value: "" }),
    /* @__PURE__ */ React.createElement("input", { type: "hidden", name: captcha.inputName || "cf-turnstile-response", value: captchaToken }),
    errors.bot ? /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-300" }, Array.isArray(errors.bot) ? errors.bot[0] : errors.bot) : null,
    errors.captcha ? /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-sm text-amber-200" }, Array.isArray(errors.captcha) ? errors.captcha[0] : errors.captcha) : null,
    /* @__PURE__ */ React.createElement(
      TextInput,
      {
        label: "Title",
        name: "title",
        value: title,
        onChange: (e) => setTitle(e.target.value),
        required: true,
        maxLength: 255,
        placeholder: "Thread title…",
        error: errors.title
      }
    ),
    /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-1.5 block text-sm font-medium text-white/85" }, "Content ", /* @__PURE__ */ React.createElement("span", { className: "text-red-400 ml-1" }, "*")), /* @__PURE__ */ React.createElement(
      RichTextEditor,
      {
        content: content2,
        onChange: setContent,
        placeholder: "Write your post…",
        error: errors.content,
        minHeight: 14,
        autofocus: false
      }
    ), /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "content", value: content2 })),
    captcha.siteKey ? /* @__PURE__ */ React.createElement(
      TurnstileField,
      {
        provider: captcha.provider,
        siteKey: captcha.siteKey,
        scriptUrl: captcha.scriptUrl,
        onToken: setCaptchaToken,
        className: "rounded-lg border border-white/10 bg-black/20 p-3"
      }
    ) : null,
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between pt-2" }, /* @__PURE__ */ React.createElement("a", { href: `/forum/${slug}`, className: "text-sm text-zinc-500 hover:text-zinc-300 transition-colors" }, "← Cancel"), /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "primary", size: "md", loading: submitting }, "Publish topic"))
  )));
}
const __vite_glob_0_70 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ForumNewThread
}, Symbol.toStringTag, { value: "Module" }));
function ForumSection({ category, boards = [], seo = {} }) {
  const name2 = category?.name ?? "Forum Section";
  const description = category?.description;
  const preview = category?.preview_image ?? "/images/forum/default.jpg";
  const breadcrumbs = [
    { label: "Home", href: "/" },
    { label: "Forum", href: "/forum" },
    { label: name2 }
  ];
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl px-4 pb-20 pt-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("section", { className: "mt-5 overflow-hidden rounded-3xl border border-white/10 bg-nova-800/55 shadow-xl backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-56 overflow-hidden sm:h-64" }, /* @__PURE__ */ React.createElement("img", { src: preview, alt: `${name2} preview`, className: "h-full w-full object-cover object-center" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-black/85 via-black/35 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-6 sm:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-cyan-200/85" }, "Forum Section"), /* @__PURE__ */ React.createElement("h1", { className: "mt-2 text-3xl font-black text-white sm:text-4xl" }, name2), description && /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm text-white/70 sm:text-base" }, description)))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-2xl border border-white/8 bg-nova-800/45 p-5 backdrop-blur sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-white/40" }, "Subcategories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-bold text-white" }, "Browse boards")), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/45 sm:text-sm" }, "Select a board to open its thread list.")), boards.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "py-12 text-center text-sm text-white/45" }, "No boards are available in this section yet.") : /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, boards.map((board) => /* @__PURE__ */ React.createElement("a", { key: board.id ?? board.slug, href: `/forum/${board.slug}`, className: "rounded-2xl border border-white/8 bg-white/[0.02] p-5 transition hover:border-cyan-400/25 hover:bg-white/[0.04] block" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, board.title), board.description && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/55" }, board.description)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-cyan-300/20 bg-cyan-300/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-cyan-200" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 text-xs text-white/50" }, /* @__PURE__ */ React.createElement("span", null, board.topics_count ?? 0, " topics"), /* @__PURE__ */ React.createElement("span", null, board.posts_count ?? 0, " posts"), board.latest_topic?.title && /* @__PURE__ */ React.createElement("span", null, "Latest: ", board.latest_topic.title))))))));
}
const __vite_glob_0_71 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ForumSection
}, Symbol.toStringTag, { value: "Module" }));
const ROLE_STYLES = {
  admin: "bg-red-500/15 text-red-300",
  moderator: "bg-amber-500/15 text-amber-300",
  member: "bg-sky-500/15 text-sky-300"
};
const ROLE_LABELS = {
  admin: "Admin",
  moderator: "Moderator",
  member: "Member"
};
function AuthorBadge({ user, size = "md" }) {
  const name2 = user?.name ?? "Anonymous";
  const avatar = user?.avatar_url ?? "/default/avatar_default.webp";
  const role = (user?.role ?? "member").toLowerCase();
  const cls = ROLE_STYLES[role] ?? ROLE_STYLES.member;
  const label = ROLE_LABELS[role] ?? "Member";
  const level = Number(user?.level ?? 0);
  const rank = user?.rank ?? null;
  const imgSize = size === "sm" ? "h-8 w-8" : "h-10 w-10";
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: avatar,
      alt: `${name2} avatar`,
      loading: "lazy",
      decoding: "async",
      className: `${imgSize} rounded-full border border-white/10 object-cover`
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-zinc-100" }, name2), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-1.5" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full px-2 py-0.5 text-[11px] font-medium ${cls}` }, label), rank && level > 0 ? /* @__PURE__ */ React.createElement(LevelBadge, { level, rank, compact: true }) : null)));
}
const REACTIONS = [
  { key: "like", label: "Like", emoji: "👍" },
  { key: "love", label: "Love", emoji: "❤️" },
  { key: "fire", label: "Amazing", emoji: "🔥" },
  { key: "laugh", label: "Funny", emoji: "😂" },
  { key: "disagree", label: "Disagree", emoji: "👎" }
];
function PostCard({ post: post2, thread, isOp = false, isAuthenticated = false, canModerate = false }) {
  const [reactionState, setReactionState] = reactExports.useState(post2?.reactions ?? { summary: {}, active: null });
  const [reacting, setReacting] = reactExports.useState(false);
  const author = post2?.user;
  const content2 = post2?.rendered_content ?? post2?.content ?? "";
  const postedAt = post2?.created_at;
  const editedAt = post2?.edited_at;
  const isEdited = post2?.is_edited;
  const postId = post2?.id;
  thread?.slug;
  const handleReaction = async (reaction) => {
    if (reacting || !isAuthenticated) return;
    setReacting(true);
    try {
      const res = await fetch(`/forum/post/${postId}/react`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": getCsrf$1(),
          "Accept": "application/json"
        },
        credentials: "same-origin",
        body: JSON.stringify({ reaction })
      });
      if (res.ok) {
        const json = await res.json();
        setReactionState(json);
      }
    } catch {
    }
    setReacting(false);
  };
  return /* @__PURE__ */ React.createElement(
    "article",
    {
      id: `post-${postId}`,
      className: "overflow-hidden rounded-2xl border border-white/[0.06] bg-nova-800/50 backdrop-blur transition-all hover:border-white/10"
    },
    /* @__PURE__ */ React.createElement("header", { className: "flex flex-col gap-3 border-b border-white/[0.06] px-5 py-4 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement(AuthorBadge, { user: author }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-xs text-zinc-500" }, postedAt && /* @__PURE__ */ React.createElement("time", { dateTime: postedAt }, formatDate$e(postedAt)), isOp && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-cyan-500/15 px-2.5 py-0.5 text-[11px] font-medium text-cyan-300" }, "OP"))),
    /* @__PURE__ */ React.createElement("div", { className: "px-5 py-5" }, /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "prose prose-invert max-w-none text-sm leading-relaxed prose-pre:overflow-x-auto prose-a:text-sky-300 prose-a:hover:text-sky-200",
        dangerouslySetInnerHTML: { __html: content2 }
      }
    ), isEdited && editedAt && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-zinc-600" }, "Edited ", formatTimeAgo(editedAt)), post2?.attachments?.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3 border-t border-white/[0.06] pt-4" }, /* @__PURE__ */ React.createElement("h4", { className: "text-xs font-semibold uppercase tracking-widest text-white/30" }, "Attachments"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2" }, post2.attachments.map((att) => /* @__PURE__ */ React.createElement(AttachmentItem, { key: att.id, attachment: att }))))),
    /* @__PURE__ */ React.createElement("footer", { className: "flex flex-wrap items-center gap-3 border-t border-white/[0.06] px-5 py-3 text-xs" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, REACTIONS.map((reaction) => {
      const count = reactionState?.summary?.[reaction.key] ?? 0;
      const isActive = reactionState?.active === reaction.key;
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          key: reaction.key,
          type: "button",
          disabled: !isAuthenticated || reacting,
          onClick: () => handleReaction(reaction.key),
          className: [
            "inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1 transition-colors",
            isActive ? "border-cyan-400/30 bg-cyan-400/10 text-cyan-200" : "border-white/10 text-zinc-400 hover:border-white/20 hover:text-zinc-200"
          ].join(" "),
          title: reaction.label
        },
        /* @__PURE__ */ React.createElement("span", null, reaction.emoji),
        /* @__PURE__ */ React.createElement("span", null, count)
      );
    })), post2?.can_edit && /* @__PURE__ */ React.createElement(
      "a",
      {
        href: `/forum/post/${postId}/edit`,
        className: "rounded-lg border border-white/10 px-2.5 py-1 text-zinc-400 transition-colors hover:border-white/20 hover:text-zinc-200"
      },
      "Edit"
    ), canModerate && /* @__PURE__ */ React.createElement("span", { className: "ml-auto text-[11px] text-amber-400/60" }, "Mod"))
  );
}
function AttachmentItem({ attachment }) {
  const mime = attachment?.mime_type ?? "";
  const isImage = mime.startsWith("image/");
  const url = attachment?.url ?? "#";
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-xl border border-white/[0.06] bg-slate-900/60" }, isImage ? /* @__PURE__ */ React.createElement("a", { href: url, target: "_blank", rel: "noopener noreferrer", className: "block" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: url,
      alt: "Attachment",
      loading: "lazy",
      decoding: "async",
      className: "h-40 w-full object-cover transition-transform hover:scale-[1.02]"
    }
  )) : /* @__PURE__ */ React.createElement(
    "a",
    {
      href: url,
      target: "_blank",
      rel: "noopener noreferrer",
      className: "flex items-center gap-3 p-3 text-sm text-sky-300 hover:text-sky-200"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" }), /* @__PURE__ */ React.createElement("polyline", { points: "14 2 14 8 20 8" })),
    "Download attachment"
  ));
}
function getCsrf$1() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") ?? "";
}
function formatDate$e(dateStr) {
  try {
    const d2 = new Date(dateStr);
    return d2.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" }) + " " + d2.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
  } catch {
    return "";
  }
}
function formatTimeAgo(dateStr) {
  try {
    const now = /* @__PURE__ */ new Date();
    const date = new Date(dateStr);
    const diff = Math.floor((now - date) / 1e3);
    if (diff < 60) return "just now";
    if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
    if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
    return formatDate$e(dateStr);
  } catch {
    return "";
  }
}
function ReplyForm({ topicKey, prefill = "", quotedAuthor = null, csrfToken: csrfToken2, captcha = {} }) {
  const [content2, setContent] = reactExports.useState(prefill);
  const [captchaToken, setCaptchaToken] = reactExports.useState("");
  const [submitting, setSubmitting] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const formRef = reactExports.useRef(null);
  const handleSubmit = reactExports.useCallback(async (e) => {
    e.preventDefault();
    if (submitting || content2.trim().length < 2) return;
    setSubmitting(true);
    setError(null);
    try {
      const fingerprint = await buildBotFingerprint();
      const res = await fetch(`/forum/topic/${topicKey}/reply`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": csrfToken2,
          "X-Bot-Fingerprint": fingerprint,
          "X-Captcha-Token": captchaToken,
          "Accept": "application/json",
          "X-Requested-With": "XMLHttpRequest"
        },
        credentials: "same-origin",
        body: JSON.stringify({
          content: content2.trim(),
          homepage_url: "",
          _bot_fingerprint: fingerprint,
          [captcha.inputName || "cf-turnstile-response"]: captchaToken
        })
      });
      if (res.ok) {
        window.location.reload();
      } else if (res.status === 422) {
        const json = await res.json();
        setError(json.errors?.content?.[0] ?? json.errors?.bot?.[0] ?? json.message ?? "Validation error.");
      } else {
        const json = await res.json().catch(() => ({}));
        setError(json?.errors?.bot?.[0] ?? json?.message ?? "Failed to post reply. Please try again.");
      }
    } catch {
      setError("Network error. Please try again.");
    }
    setSubmitting(false);
  }, [content2, topicKey, csrfToken2, submitting]);
  return /* @__PURE__ */ React.createElement(
    "form",
    {
      ref: formRef,
      onSubmit: handleSubmit,
      className: "space-y-4 rounded-2xl border border-white/[0.06] bg-nova-800/50 p-5 backdrop-blur"
    },
    quotedAuthor && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-cyan-400/70" }, "Replying with quote from ", /* @__PURE__ */ React.createElement("strong", { className: "text-cyan-300" }, quotedAuthor)),
    /* @__PURE__ */ React.createElement(
      RichTextEditor,
      {
        content: content2,
        onChange: setContent,
        placeholder: "Write your reply…",
        error,
        minHeight: 10
      }
    ),
    captcha.siteKey ? /* @__PURE__ */ React.createElement(
      TurnstileField,
      {
        provider: captcha.provider,
        siteKey: captcha.siteKey,
        scriptUrl: captcha.scriptUrl,
        onToken: setCaptchaToken,
        className: "rounded-lg border border-white/10 bg-black/20 p-3"
      }
    ) : null,
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end" }, /* @__PURE__ */ React.createElement(
      Button$1,
      {
        type: "submit",
        variant: "primary",
        size: "md",
        loading: submitting,
        disabled: content2.trim().length < 2
      },
      "Post reply"
    ))
  );
}
function ForumThread({
  thread,
  category,
  forumCategory,
  author,
  opPost,
  posts = [],
  pagination = {},
  replyCount = 0,
  sort = "asc",
  quotedPost = null,
  replyPrefill = "",
  isAuthenticated = false,
  canModerate = false,
  csrfToken: csrfToken2 = "",
  status: status2 = null,
  captcha = {},
  seo = {}
}) {
  const [currentSort, setCurrentSort] = reactExports.useState(sort);
  const breadcrumbs = [
    { label: "Home", href: "/" },
    { label: "Forum", href: "/forum" },
    ...forumCategory?.name ? [{ label: forumCategory.name }] : [],
    { label: category?.name ?? "Board", href: category?.slug ? `/forum/${category.slug}` : "/forum" },
    { label: thread?.title ?? "Thread" }
  ];
  const handleSortToggle = reactExports.useCallback(() => {
    const newSort = currentSort === "asc" ? "desc" : "asc";
    setCurrentSort(newSort);
    const url = new URL(window.location.href);
    url.searchParams.set("sort", newSort);
    window.location.href = url.toString();
  }, [currentSort]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-5xl mx-auto space-y-5" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), status2 && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-300" }, status2), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/[0.06] bg-nova-800/50 p-5 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white leading-snug" }, thread?.title), thread?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-zinc-300 sm:text-[15px]" }, thread.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2 text-xs text-zinc-500" }, /* @__PURE__ */ React.createElement("span", null, "By ", author?.name ?? "Unknown"), /* @__PURE__ */ React.createElement("span", { className: "text-zinc-700" }, "•"), thread?.created_at && /* @__PURE__ */ React.createElement("time", { dateTime: thread.created_at }, formatDate$d(thread.created_at)))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-500/15 px-2.5 py-1 text-sky-300" }, number(thread?.views ?? 0), " views"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-cyan-500/15 px-2.5 py-1 text-cyan-300" }, number(replyCount), " replies"), thread?.is_pinned && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-amber-500/15 px-2.5 py-1 text-amber-300" }, "Pinned"), thread?.is_locked && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-red-500/15 px-2.5 py-1 text-red-300" }, "Locked"))), canModerate && /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2 border-t border-white/[0.06] pt-3" }, thread?.is_locked ? /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/unlock`, csrf: csrfToken2, label: "Unlock", variant: "danger" }) : /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/lock`, csrf: csrfToken2, label: "Lock", variant: "danger" }), thread?.is_pinned ? /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/unpin`, csrf: csrfToken2, label: "Unpin", variant: "warning" }) : /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/pin`, csrf: csrfToken2, label: "Pin", variant: "warning" }))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-zinc-500" }, number(replyCount), " ", replyCount === 1 ? "reply" : "replies"), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: handleSortToggle,
      className: "flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-1.5 text-xs text-zinc-400 transition-colors hover:border-white/20 hover:text-zinc-200"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: currentSort === "asc" ? "18 15 12 21 6 15" : "18 9 12 3 6 9" }), /* @__PURE__ */ React.createElement("line", { x1: "12", y1: "3", x2: "12", y2: "21" })),
    currentSort === "asc" ? "Oldest first" : "Newest first"
  )), opPost && /* @__PURE__ */ React.createElement(
    PostCard,
    {
      post: opPost,
      thread,
      isOp: true,
      isAuthenticated,
      canModerate
    }
  ), /* @__PURE__ */ React.createElement("section", { className: "space-y-4", "aria-label": "Replies" }, posts.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.06] bg-nova-800/40 px-5 py-8 text-center text-zinc-500 text-sm" }, "No replies yet. Be the first to respond!") : posts.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard,
    {
      key: post2.id,
      post: post2,
      thread,
      isAuthenticated,
      canModerate
    }
  ))), pagination?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "sticky bottom-3 z-10 rounded-xl border border-white/[0.06] bg-nova-800/80 p-2 backdrop-blur" }, /* @__PURE__ */ React.createElement(Pagination$1, { meta: pagination })), isAuthenticated ? thread?.is_locked ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-red-500/20 bg-red-500/5 px-5 py-4 text-sm text-red-300" }, "This thread is locked. Replies are disabled.") : /* @__PURE__ */ React.createElement(
    ReplyForm,
    {
      topicKey: thread?.slug ?? thread?.id,
      prefill: replyPrefill,
      quotedAuthor: quotedPost?.user?.name,
      csrfToken: csrfToken2,
      captcha
    }
  ) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.06] bg-nova-800/40 px-5 py-5 text-sm text-zinc-400" }, /* @__PURE__ */ React.createElement("a", { href: "/login", className: "text-sky-300 hover:text-sky-200 font-medium" }, "Sign in"), " to post a reply.")));
}
function ModForm({ action, csrf, label, variant }) {
  const colors = variant === "danger" ? "bg-red-500/15 text-red-300 hover:bg-red-500/25 border-red-500/20" : "bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 border-amber-500/20";
  return /* @__PURE__ */ React.createElement("form", { method: "POST", action }, /* @__PURE__ */ React.createElement("input", { type: "hidden", name: "_token", value: csrf }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: `rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${colors}` }, label));
}
function number(n) {
  return (n ?? 0).toLocaleString();
}
function formatDate$d(dateStr) {
  try {
    const d2 = new Date(dateStr);
    return d2.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" }) + " " + d2.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
  } catch {
    return "";
  }
}
const __vite_glob_0_72 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ForumThread
}, Symbol.toStringTag, { value: "Module" }));
const TONE_CLASSNAMES$1 = {
  slate: "border-white/12 bg-white/[0.06] text-slate-100",
  sky: "border-sky-300/25 bg-sky-400/12 text-sky-100",
  emerald: "border-emerald-300/25 bg-emerald-400/12 text-emerald-100",
  amber: "border-amber-300/25 bg-amber-400/12 text-amber-100",
  rose: "border-rose-300/25 bg-rose-400/12 text-rose-100"
};
function WorldStatusBadge({ badge, className = "" }) {
  if (!badge?.label) {
    return null;
  }
  const tone = TONE_CLASSNAMES$1[badge.tone] || TONE_CLASSNAMES$1.slate;
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tone} ${className}`.trim() }, badge.label);
}
const WORLD_ANALYTICS_ENDPOINT = "/api/worlds/analytics/events";
const VISITOR_STORAGE_KEY = "skinbase:world-analytics-visitor";
const SOURCE_PARAM = "world_source";
const SOURCE_DETAIL_PARAM = "world_source_detail";
const IMPRESSION_KEYS = /* @__PURE__ */ new Set();
const ALLOWED_SOURCES = /* @__PURE__ */ new Set([
  "homepage_spotlight",
  "homepage_worlds_rail",
  "worlds_index",
  "navigation",
  "upload_flow",
  "challenge_page",
  "news_article",
  "profile",
  "direct",
  "unknown"
]);
function csrfToken$4() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function randomToken() {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID();
  }
  return `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
}
function normalizeSourceSurface(value) {
  const normalized = String(value || "").trim();
  return ALLOWED_SOURCES.has(normalized) ? normalized : "";
}
function sanitizeDetail(value) {
  return String(value || "").trim().slice(0, 80);
}
function impressionKey({ worldId, sourceSurface, sourceDetail = "", sectionKey = "" }) {
  return [worldId, sourceSurface, sanitizeDetail(sourceDetail), String(sectionKey || "").trim()].join(":");
}
function worldAnalyticsVisitorToken() {
  try {
    const existing = window.localStorage?.getItem(VISITOR_STORAGE_KEY);
    if (existing) {
      return existing;
    }
    const next = randomToken();
    window.localStorage?.setItem(VISITOR_STORAGE_KEY, next);
    return next;
  } catch {
    return randomToken();
  }
}
function withWorldSource(url, sourceSurface, sourceDetail = "") {
  if (!url) {
    return url;
  }
  try {
    const parsed = new URL(url, window.location.origin);
    if (parsed.origin !== window.location.origin) {
      return url;
    }
    const normalizedSource = normalizeSourceSurface(sourceSurface);
    if (normalizedSource) {
      parsed.searchParams.set(SOURCE_PARAM, normalizedSource);
    }
    const normalizedDetail = sanitizeDetail(sourceDetail);
    if (normalizedDetail) {
      parsed.searchParams.set(SOURCE_DETAIL_PARAM, normalizedDetail);
    }
    return `${parsed.pathname}${parsed.search}${parsed.hash}`;
  } catch {
    return url;
  }
}
function resolveWorldLandingSource() {
  try {
    const locationUrl = new URL(window.location.href);
    const explicitSource = normalizeSourceSurface(locationUrl.searchParams.get(SOURCE_PARAM));
    const explicitDetail = sanitizeDetail(locationUrl.searchParams.get(SOURCE_DETAIL_PARAM));
    if (explicitSource) {
      return {
        sourceSurface: explicitSource,
        sourceDetail: explicitDetail
      };
    }
    if (!document.referrer) {
      return { sourceSurface: "direct", sourceDetail: "" };
    }
    const referrer = new URL(document.referrer);
    if (referrer.origin !== window.location.origin) {
      return { sourceSurface: "unknown", sourceDetail: "external_referrer" };
    }
    const path = referrer.pathname || "/";
    if (path === "/") {
      return { sourceSurface: "homepage_spotlight", sourceDetail: "referrer" };
    }
    if (path === "/worlds") {
      return { sourceSurface: "worlds_index", sourceDetail: "referrer" };
    }
    if (/^\/groups\/[^/]+\/challenges\//.test(path)) {
      return { sourceSurface: "challenge_page", sourceDetail: "referrer" };
    }
    if (path.startsWith("/upload") || path.startsWith("/studio/artworks")) {
      return { sourceSurface: "upload_flow", sourceDetail: "referrer" };
    }
    if (path.startsWith("/news") || path.startsWith("/stories")) {
      return { sourceSurface: "news_article", sourceDetail: "referrer" };
    }
    if (path.startsWith("/@") || path.startsWith("/profile")) {
      return { sourceSurface: "profile", sourceDetail: "referrer" };
    }
  } catch {
    return { sourceSurface: "unknown", sourceDetail: "" };
  }
  return { sourceSurface: "unknown", sourceDetail: "" };
}
async function trackWorldAnalytics(eventType, payload = {}) {
  try {
    if (!eventType || !payload.world_id) {
      return;
    }
    await fetch(WORLD_ANALYTICS_ENDPOINT, {
      method: "POST",
      credentials: "same-origin",
      keepalive: true,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken$4(),
        "X-Requested-With": "XMLHttpRequest"
      },
      body: JSON.stringify({
        event_type: eventType,
        visitor_token: worldAnalyticsVisitorToken(),
        ...payload
      })
    });
  } catch {
  }
}
function trackWorldSourceClick({ worldId, worldTitle = "", sourceSurface = "", sourceDetail = "" }) {
  const normalizedSource = normalizeSourceSurface(sourceSurface);
  if (!worldId || !normalizedSource) {
    return;
  }
  trackWorldAnalytics("world_source_clicked", {
    world_id: worldId,
    source_surface: normalizedSource,
    source_detail: sanitizeDetail(sourceDetail),
    entity_type: "world",
    entity_id: worldId,
    entity_title: worldTitle
  });
}
function trackWorldSourceImpression({
  worldId,
  worldTitle = "",
  sourceSurface = "",
  sourceDetail = "",
  sectionKey = ""
}) {
  const normalizedSource = normalizeSourceSurface(sourceSurface);
  if (!worldId || !normalizedSource) {
    return;
  }
  const key = impressionKey({ worldId, sourceSurface: normalizedSource, sourceDetail, sectionKey });
  if (IMPRESSION_KEYS.has(key)) {
    return;
  }
  IMPRESSION_KEYS.add(key);
  trackWorldAnalytics("world_source_impression", {
    world_id: worldId,
    source_surface: normalizedSource,
    source_detail: sanitizeDetail(sourceDetail),
    section_key: String(sectionKey || "").trim().slice(0, 80),
    entity_type: "world",
    entity_id: worldId,
    entity_title: worldTitle
  });
}
function ChallengeWorldLinkBadge({ world, className = "" }) {
  if (!world?.public_url || !world?.title) {
    return null;
  }
  const badges = Array.isArray(world.status_badges) ? world.status_badges.filter((badge) => badge?.label).slice(0, 3) : [];
  const metaItems2 = [
    world.campaign_label,
    world.timeframe_label,
    Number(world.live_submission_count || 0) > 0 ? `${world.live_submission_count} live submissions` : null
  ].filter(Boolean);
  const worldHref = withWorldSource(world.public_url, "challenge_page", "linked_world");
  return /* @__PURE__ */ React.createElement("section", { className: `rounded-[26px] border border-sky-300/20 bg-[linear-gradient(135deg,_rgba(56,189,248,0.14),_rgba(15,23,42,0.92))] p-5 text-white ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Linked world"), badges.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, badges.map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: `${badge.label}-${badge.tone || "slate"}`, badge }))) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Continue in ", world.title), world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-7 text-slate-200" }, world.summary) : null, metaItems2.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, metaItems2.map((item) => /* @__PURE__ */ React.createElement("span", { key: item }, item))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: worldHref, onClick: () => trackWorldSourceClick({ worldId: world.id, worldTitle: world.title, sourceSurface: "challenge_page", sourceDetail: "linked_world" }), className: "inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-slate-950 transition hover:bg-sky-100" }, "Open world", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })), world.challenge_cta_url ? /* @__PURE__ */ React.createElement("a", { href: world.challenge_cta_url, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, world.challenge_cta_label || "Challenge update") : null));
}
const TONE_CLASSNAMES = {
  slate: "border-white/12 bg-white/[0.06] text-slate-100",
  sky: "border-sky-300/25 bg-sky-400/12 text-sky-100",
  emerald: "border-emerald-300/25 bg-emerald-400/12 text-emerald-100",
  amber: "border-amber-300/25 bg-amber-400/12 text-amber-100",
  rose: "border-rose-300/25 bg-rose-400/12 text-rose-100",
  violet: "border-violet-300/25 bg-violet-400/12 text-violet-100"
};
function WorldChallengeStatusBadge({ label, tone = "slate", className = "" }) {
  if (!label) {
    return null;
  }
  const toneClassName = TONE_CLASSNAMES[tone] || TONE_CLASSNAMES.slate;
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${toneClassName} ${className}`.trim() }, label);
}
function WorldChallengeArtworkCard({ item, featured = false, sectionKey = "challenge_entries", challengeId = null }) {
  if (!item) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("a", { href: item.url || "#", "data-world-event": "world_entity_clicked", "data-world-section-key": sectionKey, "data-world-entity-type": "artwork", "data-world-entity-id": item.id, "data-world-entity-title": item.title || "", "data-world-challenge-id": challengeId || "", className: `overflow-hidden rounded-[24px] border transition ${featured ? "border-amber-300/20 bg-amber-400/10 hover:border-amber-200/35" : "border-white/10 bg-black/20 hover:border-white/15 hover:bg-white/[0.06]"}` }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-950/80" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" }))), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, item.status_label ? /* @__PURE__ */ React.createElement(WorldChallengeStatusBadge, { label: item.status_label, tone: featured ? "amber" : "slate", className: "px-2.5 py-1 text-[10px]" }) : null, item.context_label ? /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, item.context_label) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-base font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-xs text-slate-500" }, item.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry }, entry))) : null));
}
function OutcomeSection({ section }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, section.label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-1" }, items.map((item) => /* @__PURE__ */ React.createElement(WorldChallengeArtworkCard, { key: item.id, item, featured: item.outcome_type === "winner" }))));
}
function GroupChallengeShow() {
  const { props } = X$1();
  const group = props.group || {};
  const challenge = props.challenge || {};
  const linkedWorld = props.linkedWorld || null;
  const outcomeSections = challenge.outcome_sections || {};
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(234,179,8,0.15),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${challenge.title || group.name} - Skinbase`, description: challenge.summary || challenge.description || "Group challenge" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, challenge.cover_url ? /* @__PURE__ */ React.createElement("img", { src: challenge.cover_url, alt: challenge.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-40 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-amber-200" }, group.name), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, challenge.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, challenge.summary || challenge.description || "Group challenge"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-xs uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, challenge.status), /* @__PURE__ */ React.createElement("span", null, challenge.visibility), /* @__PURE__ */ React.createElement("span", null, String(challenge.participation_scope || "").replace("_", " ")), challenge.start_at ? /* @__PURE__ */ React.createElement("span", null, "Starts ", new Date(challenge.start_at).toLocaleDateString()) : null, challenge.end_at ? /* @__PURE__ */ React.createElement("span", null, "Ends ", new Date(challenge.end_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement(ChallengeWorldLinkBadge, { world: linkedWorld, className: "mt-5" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Challenge brief"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, challenge.description || "No extended challenge brief yet."), challenge.rules_text ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Rules"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, challenge.rules_text)) : null, challenge.submission_instructions ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Submission instructions"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, challenge.submission_instructions)) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.winner }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.finalist }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.runner_up }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.honorable_mention }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.featured }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Entries"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-1" }, Array.isArray(challenge.artworks) && challenge.artworks.length > 0 ? challenge.artworks.map((artwork) => /* @__PURE__ */ React.createElement("a", { key: artwork.id, href: artwork.url, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "aspect-[4/3] w-full object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "p-4 text-white" }, artwork.title))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No entries linked yet.")))))));
}
const __vite_glob_0_73 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupChallengeShow
}, Symbol.toStringTag, { value: "Module" }));
function GroupEventShow() {
  const { props } = X$1();
  const group = props.group || {};
  const event = props.event || {};
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.15),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${event.title || group.name} - Skinbase`, description: event.summary || event.description || "Group event" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-5xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, event.cover_url ? /* @__PURE__ */ React.createElement("img", { src: event.cover_url, alt: event.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-40 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-emerald-200" }, group.name), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, event.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, event.summary || event.description || "Group event"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Starts"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-white" }, event.start_at ? new Date(event.start_at).toLocaleString() : "Not scheduled")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Details"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-white" }, event.event_type, " • ", event.visibility), event.location ? /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, event.location) : null)), event.external_url ? /* @__PURE__ */ React.createElement("a", { href: event.external_url, className: "mt-5 inline-flex rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Open external link") : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "About this event"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, event.description || "No extended event details yet."))));
}
const __vite_glob_0_74 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupEventShow
}, Symbol.toStringTag, { value: "Module" }));
const TONES$2 = {
  tip: {
    shell: "border-sky-300/25 bg-sky-400/10 text-sky-50",
    icon: "fa-solid fa-lightbulb text-sky-200",
    label: "Tip"
  },
  note: {
    shell: "border-white/15 bg-white/[0.05] text-white",
    icon: "fa-solid fa-circle-info text-slate-200",
    label: "Note"
  },
  warning: {
    shell: "border-amber-300/25 bg-amber-400/10 text-amber-50",
    icon: "fa-solid fa-triangle-exclamation text-amber-200",
    label: "Warning"
  },
  practice: {
    shell: "border-emerald-300/25 bg-emerald-400/10 text-emerald-50",
    icon: "fa-solid fa-badge-check text-emerald-200",
    label: "Best Practice"
  }
};
function DocsCallout({ tone = "note", title, children }) {
  const styles2 = TONES$2[tone] || TONES$2.note;
  return /* @__PURE__ */ React.createElement("aside", { className: `rounded-[24px] border px-4 py-4 md:px-5 ${styles2.shell}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("i", { className: styles2.icon })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] opacity-80" }, styles2.label), title ? /* @__PURE__ */ React.createElement("h3", { className: "mt-1 text-base font-semibold" }, title) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 opacity-90" }, children))));
}
function DocsFaqAccordion({ items, initialOpenIndex = 0, renderAnswer }) {
  const [openIndex, setOpenIndex] = reactExports.useState(items.length > 0 ? initialOpenIndex : -1);
  const baseId = reactExports.useId();
  reactExports.useEffect(() => {
    setOpenIndex(items.length > 0 ? Math.min(initialOpenIndex, items.length - 1) : -1);
  }, [items.length, initialOpenIndex]);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, items.map((item, index2) => {
    const buttonId = `${baseId}-button-${index2}`;
    const panelId = `${baseId}-panel-${index2}`;
    const isOpen = openIndex === index2;
    const answerContent = renderAnswer ? renderAnswer(item) : item.answer;
    return /* @__PURE__ */ React.createElement("div", { key: item.question, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("h3", null, /* @__PURE__ */ React.createElement(
      "button",
      {
        id: buttonId,
        type: "button",
        className: "flex w-full items-center justify-between gap-4 px-4 py-4 text-left md:px-5",
        "aria-expanded": isOpen,
        "aria-controls": panelId,
        onClick: () => setOpenIndex(isOpen ? -1 : index2)
      },
      /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold text-white" }, item.question),
      /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${isOpen ? "fa-minus" : "fa-plus"} text-xs` }))
    )), /* @__PURE__ */ React.createElement(
      "div",
      {
        id: panelId,
        role: "region",
        "aria-labelledby": buttonId,
        className: isOpen ? "block border-t border-white/10 px-4 py-4 md:px-5" : "hidden"
      },
      typeof answerContent === "string" ? /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-7 text-slate-300" }, answerContent) : /* @__PURE__ */ React.createElement("div", { className: "space-y-4 text-sm leading-7 text-slate-300" }, answerContent)
    ));
  }));
}
function DocsSection({ id, eyebrow, title, summary, children, className = "" }) {
  return /* @__PURE__ */ React.createElement("section", { id, "aria-labelledby": `${id}-title`, className: `scroll-mt-24 rounded-[32px] border border-white/10 bg-white/[0.03] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.22)] md:p-7 ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { id: `${id}-title`, className: "mt-2 text-3xl font-semibold tracking-[-0.03em] text-white md:text-[2rem]" }, title), summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300 md:text-[15px]" }, summary) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, children));
}
function jumpToSection(targetId) {
  if (!targetId || typeof window === "undefined") return;
  const element2 = document.getElementById(targetId);
  if (!element2) return;
  element2.scrollIntoView({ behavior: "smooth", block: "start" });
  window.history.replaceState(null, "", `#${targetId}`);
}
function DocsSidebarNav({ sections, ariaLabel = "Sections on this page", selectLabel = "Jump to section", navTitle = "On this page" }) {
  const [selectedSection, setSelectedSection] = reactExports.useState(null);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "lg:hidden" }, /* @__PURE__ */ React.createElement("label", { htmlFor: "groups-help-nav", className: "sr-only" }, selectLabel), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      id: "groups-help-nav",
      className: "w-full",
      value: selectedSection,
      placeholder: "Jump to a section",
      options: sections.map((section) => ({ value: section.id, label: section.label })),
      onChange: (value) => {
        jumpToSection(value);
        setSelectedSection(null);
      },
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("nav", { "aria-label": ariaLabel, className: "hidden lg:block lg:sticky lg:top-24" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-4 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, navTitle), /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-1.5" }, sections.map((section) => /* @__PURE__ */ React.createElement("li", { key: section.id }, /* @__PURE__ */ React.createElement("a", { href: `#${section.id}`, className: "block rounded-2xl px-3 py-2 text-sm text-slate-300 transition hover:bg-white/[0.05] hover:text-white" }, section.label)))))));
}
function FaqSearchInput({ value, onChange, onClear, resultCount }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-black/20 p-4 md:p-5" }, /* @__PURE__ */ React.createElement("label", { htmlFor: "groups-faq-search", className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search questions"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "relative flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "pointer-events-none absolute inset-y-0 left-4 flex items-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass" })), /* @__PURE__ */ React.createElement(
    "input",
    {
      id: "groups-faq-search",
      value,
      onChange: (event) => onChange(event.target.value),
      placeholder: "Search roles, invites, contributor credit, review, troubleshooting...",
      className: "w-full rounded-[20px] border border-white/10 bg-white/[0.04] py-3 pl-11 pr-4 text-sm text-white outline-none placeholder:text-slate-500"
    }
  )), value ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClear,
      className: "rounded-[20px] border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.06]"
    },
    "Clear"
  ) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-400" }, resultCount, " question", resultCount === 1 ? "" : "s", " visible"));
}
const TONES$1 = {
  sky: "border-sky-300/20 bg-sky-300/10 text-sky-100",
  amber: "border-amber-300/20 bg-amber-400/10 text-amber-100",
  white: "border-white/10 bg-black/20 text-white"
};
function QuickstartNextSteps({ items }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, items.map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.title,
      href: item.href,
      className: `rounded-[28px] border p-5 transition hover:-translate-y-0.5 hover:border-white/20 ${TONES$1[item.tone] || TONES$1.white}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] opacity-80" }, item.eyebrow),
    /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, item.title),
    /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 opacity-90" }, item.body)
  )));
}
const FAQ_CATEGORIES = [
  {
    id: "basics",
    label: "Basics",
    title: "Basics",
    summary: "Start here if you need the fastest explanation of what Groups are and when they make sense.",
    items: [
      {
        question: "What is a Group?",
        paragraphs: [
          "A Group is a shared creative identity for teams, collectives, projects, and recurring collaboration. It gives multiple creators one public home for work, updates, and shared activity.",
          "It is meant for collaboration, not as a replacement for your personal profile."
        ]
      },
      {
        question: "What is the difference between a personal profile and a Group?",
        paragraphs: [
          "A personal profile is your individual identity, portfolio, and reputation. A Group is the team or shared identity layer.",
          "Both can exist side by side. You can keep publishing personally while also publishing collaborative work under a Group."
        ]
      },
      {
        question: "Should I create a Group?",
        paragraphs: [
          "Create one if you collaborate regularly, want a shared public brand, or need shared roles and publishing workflows.",
          "If you only publish solo work and do not need a team identity yet, you can stay on your personal profile for now."
        ]
      },
      {
        question: "Can I still publish personally if I also use a Group?",
        paragraphs: [
          "Yes. Many creators use both. Personal publishing is for individual work, while Group publishing is for collaborative work or a shared brand."
        ]
      },
      {
        question: "Can a Group exist with only one member?",
        paragraphs: [
          "Yes, if the product allows it, but it is most useful when there is a real shared identity or collaboration reason behind it.",
          "If it is only being used to rename personal work, a personal profile may still be the simpler choice."
        ]
      }
    ]
  },
  {
    id: "roles-and-permissions",
    label: "Roles & Permissions",
    title: "Roles & permissions",
    summary: "These answers explain who can do what and why role differences exist inside a Group.",
    items: [
      {
        question: "What does the Owner role do?",
        paragraphs: [
          "Owner is the highest-trust role. Owners control sensitive settings, membership structure, and the overall direction of the Group."
        ]
      },
      {
        question: "What does the Admin role do?",
        paragraphs: [
          "Admins usually help manage day-to-day Group operations, member access, and important content workflows.",
          "This role should stay limited to people the Group deeply trusts."
        ]
      },
      {
        question: "What does the Editor role do?",
        paragraphs: [
          "Editors are usually the best fit for people who help manage content, publishing, reviews, releases, or coordination without needing full Group control."
        ]
      },
      {
        question: "What does the Contributor role do?",
        paragraphs: [
          "Contributors participate in the creative side of the Group without needing broad access to settings or member management.",
          "For many teams, this is the right starting role for most collaborators."
        ]
      },
      {
        question: "Who can invite members?",
        paragraphs: [
          "Usually Owners and Admins, depending on the Group setup. If you do not see invite controls, your role probably does not include member management."
        ]
      },
      {
        question: "Who can change member roles?",
        paragraphs: [
          "Usually Owners and sometimes Admins. This depends on the Group’s trust model and any role restrictions already in place."
        ]
      },
      {
        question: "Who can publish as the Group?",
        paragraphs: [
          "That depends on the Group role and workflow. Owners and Admins often can. Editors often can. Contributors may submit drafts without publishing directly if the team uses approvals."
        ]
      },
      {
        question: "Why can’t I do something another member can do?",
        paragraphs: [
          "Roles are not identical. One person may have a higher role or a permission override that gives access you do not have.",
          "If you are unsure, ask an Owner or Admin what your role is meant to cover."
        ]
      },
      {
        question: "Should I give lots of people Admin access?",
        paragraphs: [
          "Usually no. Keep high-level roles limited. It is easier to add trust later than clean up a Group where too many people can change everything."
        ]
      },
      {
        question: "Can permissions be customized?",
        paragraphs: [
          "In some cases, yes. Some Groups may use permission overrides on top of the main role system.",
          "If your team is new, it is usually better to keep the role model simple first and only customize later when there is a clear need."
        ]
      }
    ]
  },
  {
    id: "publishing-and-credit",
    label: "Publishing & Credit",
    title: "Publishing & contributor credit",
    summary: "This section covers the biggest source of user confusion: how shared identity and individual attribution work together.",
    items: [
      {
        question: "What does “publish as Group” mean?",
        paragraphs: [
          "It means the work appears publicly under the Group identity rather than under a personal profile.",
          "That does not erase individual authorship or responsibility for the work."
        ]
      },
      {
        question: "Will my name still appear if I publish under a Group?",
        paragraphs: [
          "Yes. Group publishing is designed to preserve individual credit and accountability, not hide it."
        ]
      },
      {
        question: "What is the difference between Published by, Uploaded by, Primary author, and Contributors?",
        paragraphs: [
          "Published by is the public identity the work appears under. Uploaded by is the person who handled the upload or final publish step. Primary author is the main author of the work. Contributors are additional people who made meaningful creative contributions."
        ],
        example: [
          { label: "Published by", value: "Warlock" },
          { label: "Uploaded by", value: "Gregor" },
          { label: "Primary author", value: "Gregor" },
          { label: "Contributors", value: "Denis, Paula" }
        ]
      },
      {
        question: "Who should be listed as Primary author?",
        paragraphs: [
          "The primary author should be the person who should clearly be understood as the main author of the work.",
          "Do not choose this field based only on who clicked Publish."
        ]
      },
      {
        question: "Should all contributors be credited?",
        paragraphs: [
          "Yes, if they made meaningful creative contributions. Clear credit keeps the Group trustworthy and helps avoid internal confusion later."
        ]
      },
      {
        question: "Can a Group publish an artwork while still showing who made it?",
        paragraphs: [
          "Yes. That is one of the main points of Group publishing: shared identity on the public surface, clear attribution for the humans behind the work."
        ]
      },
      {
        question: "Can I publish both personal and Group artworks?",
        paragraphs: [
          "Yes. Many creators do both. The important thing is choosing the correct context before the final publish step."
        ]
      },
      {
        question: "Why does the platform keep individual credit visible?",
        paragraphs: [
          "Because collaboration should not erase accountability or authorship. The Group represents the shared identity, but people still deserve clear credit for the work they did."
        ]
      },
      {
        question: "What should we do if contributor credit is wrong?",
        paragraphs: [
          "Fix it quickly. Review who uploaded the work, who authored it, and who contributed before making changes publicly.",
          "If there is disagreement inside the team, resolve that first so the public record reflects a clear shared decision."
        ]
      },
      {
        question: "Can contributor credit be changed later?",
        paragraphs: [
          "In many cases, yes, depending on your Group permissions and workflow. The best habit is to get it right before publishing so you do not have to correct it afterward."
        ]
      }
    ]
  },
  {
    id: "members-and-invites",
    label: "Members & Invites",
    title: "Members, invites, and join requests",
    summary: "Use these answers when you need to manage who gets access, what role they should have, and what happens when the team changes.",
    items: [
      {
        question: "How do I invite someone to a Group?",
        paragraphs: [
          "Open Group Studio, go to the member or invitation controls, choose the right role, and send the invite once you know what access that person actually needs."
        ]
      },
      {
        question: "Can I remove a member later?",
        paragraphs: [
          "Yes, if your role allows member management. Owners and authorized admins can usually update access, revoke invites, or remove active members."
        ]
      },
      {
        question: "What happens if a member leaves the Group?",
        paragraphs: [
          "Their active access can be removed, but that does not usually erase the history of work they already contributed to."
        ]
      },
      {
        question: "Can a former member still appear on older artworks they contributed to?",
        paragraphs: [
          "Yes. Older work may still show their contribution because that is part of the record of who helped make it."
        ]
      },
      {
        question: "Can people request to join a Group?",
        paragraphs: [
          "If the Group allows join requests or recruiting, yes. Otherwise access usually depends on direct invites from the team."
        ]
      },
      {
        question: "What is recruitment mode?",
        paragraphs: [
          "Recruitment mode is the public-facing signal that a Group is looking for new collaborators. It helps teams describe what roles or skills they want and how people should reach out."
        ]
      },
      {
        question: "How do I choose the right role for a new member?",
        paragraphs: [
          "Start from what they actually need to do right now. If you are unsure, start lower and promote later instead of giving broad access too early."
        ]
      },
      {
        question: "Can I change someone’s role later?",
        paragraphs: [
          "Yes, if your role allows it. Many teams adjust roles over time as trust, responsibility, or activity changes."
        ]
      },
      {
        question: "Why can’t I manage members?",
        paragraphs: [
          "Your role probably does not include member management. That level of access is usually kept to Owners and selected Admins."
        ]
      },
      {
        question: "Why can’t I see invite controls?",
        paragraphs: [
          "Invite controls are normally hidden if your role does not include them or if you are not operating inside the correct Group context."
        ]
      }
    ]
  },
  {
    id: "review-workflow",
    label: "Workflow & Review",
    title: "Review workflow and approvals",
    summary: "These answers explain why some Groups use review queues and how that affects contributors and trusted publishers.",
    items: [
      {
        question: "Why is my artwork in review?",
        paragraphs: [
          "Your Group may use a review-first workflow so contributors can submit work without publishing directly. That helps the team catch quality, context, or credit issues before something goes public."
        ]
      },
      {
        question: "Who can approve Group submissions?",
        paragraphs: [
          "Usually the people whose roles include review access, such as Owners, Admins, or selected Editors."
        ]
      },
      {
        question: "What does “needs changes” mean?",
        paragraphs: [
          "It means the submission is not ready yet but may become ready after updates. It is a request to revise, not an automatic rejection."
        ]
      },
      {
        question: "Can contributors submit drafts without publishing directly?",
        paragraphs: [
          "Yes. That is a common Group workflow. Contributors hand work off for review while a trusted reviewer or publisher handles the final public step."
        ]
      },
      {
        question: "Why would a Group use a review queue?",
        paragraphs: [
          "Review queues help larger or more structured teams keep public quality high, coordinate releases, and catch mistakes before launch."
        ]
      },
      {
        question: "Do all Groups need approval workflow?",
        paragraphs: [
          "No. Small, trusted teams may prefer direct publishing. Review is useful when it solves a real quality or coordination problem."
        ]
      },
      {
        question: "Can trusted members publish directly?",
        paragraphs: [
          "Yes, if their role allows it. Many teams reserve direct publishing for trusted operators and use review for everyone else."
        ]
      },
      {
        question: "What should I do if my submission was rejected?",
        paragraphs: [
          "Check the feedback first, then ask for clarification if needed. Treat rejection as workflow feedback, not as punishment."
        ]
      }
    ]
  },
  {
    id: "features-and-content-types",
    label: "Features & Content Types",
    title: "Group features and content types",
    summary: "This section explains how the wider Group ecosystem fits together so users know what to start with and what to add later.",
    items: [
      {
        question: "Can a Group create posts or announcements?",
        paragraphs: [
          "Yes. Posts are useful for release notes, updates, announcements, recruitment, or milestone communication."
        ]
      },
      {
        question: "What are Group projects used for?",
        paragraphs: [
          "Projects are for structured collaboration. They give the team a shared place to organize work, milestones, linked content, and progress."
        ]
      },
      {
        question: "What are Group challenges used for?",
        paragraphs: [
          "Challenges help run themed prompts, community events, or internal creative pushes that keep the Group active and focused."
        ]
      },
      {
        question: "What are Group events used for?",
        paragraphs: [
          "Events are for launches, streams, showcases, meetups, release windows, or any time-based public moment the Group wants to anchor clearly."
        ]
      },
      {
        question: "What is the shared asset library for?",
        paragraphs: [
          "The asset library stores shared resources, references, files, and internal materials so they do not get lost in scattered chat or personal storage."
        ]
      },
      {
        question: "What are releases?",
        paragraphs: [
          "Releases package a major publication moment with a title, summary, contributors, milestones, notes, and linked work in one public surface."
        ]
      },
      {
        question: "Do all Groups need to use projects, challenges, events, or releases?",
        paragraphs: [
          "No. Start with the smallest set of tools that makes your workflow clearer. Not every Group needs every feature from day one."
        ]
      },
      {
        question: "What should a simple Group use first?",
        paragraphs: [
          "Most simple Groups should begin with a clear profile, member roles, artworks, and occasional posts. Add more structure only when it solves a real problem."
        ]
      },
      {
        question: "What should a more advanced Group use later?",
        paragraphs: [
          "As the Group grows, projects, releases, review queues, recruitment, challenges, events, and shared assets become more useful."
        ]
      }
    ]
  },
  {
    id: "troubleshooting",
    label: "Troubleshooting",
    title: "Troubleshooting",
    summary: "Use these answers when something feels wrong, missing, or inconsistent. Most Group issues come down to context, role, or visibility.",
    items: [
      {
        question: "I can’t publish as the Group. Why?",
        paragraphs: [
          "The usual reasons are the wrong context, insufficient permissions, inactive membership, or a Group state or policy restriction. Start by confirming you are inside Group Studio and that your role allows publishing."
        ]
      },
      {
        question: "I don’t see Group Studio.",
        paragraphs: [
          "You may not be in the Group, may still have a pending invite, or may not be signed in. Accept the invitation first if one is waiting."
        ]
      },
      {
        question: "I was invited, but I still can’t access what I expected.",
        paragraphs: [
          "Check whether the invitation was fully accepted and whether the content you expect is internal, role-limited, or review-limited."
        ]
      },
      {
        question: "My role does not let me do what I need.",
        paragraphs: [
          "Your Group may be intentionally limiting that action to a higher-trust role. Ask an Owner or Admin whether your current role matches the work you are actually doing."
        ]
      },
      {
        question: "I published under the wrong context. What should I do?",
        paragraphs: [
          "Review the affected content immediately. Confirm whether it should live under the personal profile or the Group, then correct it before more linked content builds around the mistake."
        ]
      },
      {
        question: "Contributor credit is incorrect. What should I do?",
        paragraphs: [
          "Check the publish record and confirm who was published under, who uploaded the work, who authored it, and who contributed. Fix the incorrect part instead of replacing everything blindly."
        ]
      },
      {
        question: "I can’t manage members.",
        paragraphs: [
          "Member management is usually restricted to Owners and selected Admins. If you do not see those controls, your role probably does not include them."
        ]
      },
      {
        question: "I can’t see internal Group assets or projects.",
        paragraphs: [
          "Those areas may be internal-only, visibility-limited, or restricted by role. Confirm that you are an active member and that your role is supposed to see that content."
        ]
      },
      {
        question: "I don’t understand why I can’t approve submissions.",
        paragraphs: [
          "Approval access is usually reserved for trusted operators. If your role is Contributor or a limited Editor role, approvals may be intentionally hidden from you."
        ]
      },
      {
        question: "Our Group page looks empty. What should we do first?",
        paragraphs: [
          "Start with the basics: complete the profile, upload branding, publish one strong piece, and add one meaningful update. A small amount of clear activity is better than a big empty shell."
        ]
      },
      {
        question: "We are not sure which role to assign someone. What should we do?",
        paragraphs: [
          "Base the role on what they need to do this month, not on what title sounds impressive. If you are unsure, start lower and adjust later."
        ]
      }
    ]
  }
];
const RELATED_HELP_ITEMS$8 = [
  {
    eyebrow: "Deep dive",
    title: "Read the full Groups guide",
    body: "Use the full documentation for broader reference, advanced workflows, FAQ overlap, and deeper best practices.",
    linkKey: "full_documentation",
    tone: "white"
  },
  {
    eyebrow: "Start here",
    title: "Open the Groups Quickstart",
    body: "Use the shorter onboarding path if you want the fastest route to create a Group and publish correctly.",
    linkKey: "quickstart",
    tone: "amber"
  },
  {
    eyebrow: "Operate",
    title: "Open Group Studio",
    body: "Jump into Studio if your next step is inviting members, reviewing content, or working inside the Group context.",
    linkKey: "group_studio",
    tone: "sky"
  },
  {
    eyebrow: "Create",
    title: "Create a Group",
    body: "If the FAQ answered the basics and you are ready to move, start the creation flow directly.",
    linkKey: "create_group",
    tone: "white"
  }
];
function HeroStat$1({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function FaqAnswer({ item, links }) {
  return /* @__PURE__ */ React.createElement(React.Fragment, null, Array.isArray(item.paragraphs) ? item.paragraphs.map((paragraph2) => /* @__PURE__ */ React.createElement("p", { key: paragraph2 }, paragraph2)) : null, Array.isArray(item.bullets) && item.bullets.length > 0 ? /* @__PURE__ */ React.createElement("ul", { className: "space-y-2" }, item.bullets.map((bullet) => /* @__PURE__ */ React.createElement("li", { key: bullet, className: "flex gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-2 h-2 w-2 shrink-0 rounded-full bg-sky-300" }), /* @__PURE__ */ React.createElement("span", null, bullet)))) : null, Array.isArray(item.example) && item.example.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, item.example.map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.label, className: "rounded-[20px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, entry.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, entry.value)))) : null, Array.isArray(item.links) && item.links.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 pt-1" }, item.links.map((link2) => /* @__PURE__ */ React.createElement("a", { key: link2.label, href: links[link2.linkKey] || "#", className: "text-sm font-semibold text-sky-200 underline underline-offset-4" }, link2.label))) : null);
}
function GroupFaqPage() {
  const { props } = X$1();
  const links = props.links || {};
  const [query, setQuery] = reactExports.useState("");
  const normalizedQuery = query.trim().toLowerCase();
  const visibleCategories = FAQ_CATEGORIES.map((category) => {
    const items = category.items.filter((item) => {
      if (!normalizedQuery) return true;
      const haystack = [
        item.question,
        ...item.paragraphs || [],
        ...item.bullets || [],
        ...(item.example || []).flatMap((entry) => [entry.label, entry.value])
      ].join(" ").toLowerCase();
      return haystack.includes(normalizedQuery);
    });
    return {
      ...category,
      items
    };
  }).filter((category) => category.items.length > 0);
  const visibleQuestionCount = visibleCategories.reduce((total, category) => total + category.items.length, 0);
  const relatedHelpItems = RELATED_HELP_ITEMS$8.map((item) => ({
    ...item,
    href: links[item.linkKey] || "#"
  }));
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_CATEGORIES.flatMap((category) => category.items).map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: (item.paragraphs || []).join(" ")
        }
      }))
    }
  ];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(14,165,233,0.18),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1450px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Groups FAQ"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Find quick answers about Groups without digging through the full guide."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This page answers the most common practical questions about Groups, roles, publishing, contributor credit, invites, workflows, and troubleshooting. Use it when you want fast answers first, then go deeper only if you need to."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.full_documentation, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Read full Groups documentation"), /* @__PURE__ */ React.createElement("a", { href: links.quickstart, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open Groups Quickstart"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(HeroStat$1, { label: "Best for", value: "Fast practical questions", note: "Use the FAQ when you need answers quickly instead of reading the longer guide front to back." }), /* @__PURE__ */ React.createElement(HeroStat$1, { label: "Core idea", value: "Shared identity, preserved credit", note: "Groups publish together under one identity, but the people behind the work still matter and stay visible." }), /* @__PURE__ */ React.createElement(HeroStat$1, { label: "If you need more", value: "Jump deeper anytime", note: "This page links back to the quickstart, the full guide, Group Studio, and the creation flow." }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 max-w-3xl" }, /* @__PURE__ */ React.createElement(
    FaqSearchInput,
    {
      value: query,
      onChange: setQuery,
      onClear: () => setQuery(""),
      resultCount: visibleQuestionCount
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: visibleCategories.map((category) => ({ id: category.id, label: category.label })) }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "How to use this page" }, "Start with the category closest to your problem. If you only need the fastest route to first success, use the quickstart. If you need broader reference or advanced workflows, open the full Groups guide."), visibleCategories.length === 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.03] p-6 shadow-[0_22px_70px_rgba(2,6,23,0.22)] md:p-7" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "No matching questions"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Try a broader search term like roles, invite, publish, contributor, review, or Studio.")) : null, visibleCategories.map((category) => /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      key: category.id,
      id: category.id,
      eyebrow: "FAQ category",
      title: category.title,
      summary: category.summary
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: category.items, renderAnswer: (item) => /* @__PURE__ */ React.createElement(FaqAnswer, { item, links }) })
  )), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Related help",
      title: "Need the next step, not just the answer?",
      summary: "Use these links when the FAQ has answered the question and you are ready to act, learn more, or get support."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("a", { href: links.contact_support, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Contact"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Contact support"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use this if your question is not answered here or if you need help with an account or workflow issue.")), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Report"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Report a problem"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use this if a route, role, contributor record, or Group workflow appears broken rather than just unclear.")))
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Support flow"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.quickstart, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Quickstart"), /* @__PURE__ */ React.createElement("a", { href: links.full_documentation, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read full documentation"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("a", { href: links.create_group, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create a Group"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Quick troubleshooting rule"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If something feels wrong, check three things first: are you in the right Group context, do you have the right role, and is the content public or internal?")))))));
}
const __vite_glob_0_75 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupFaqPage
}, Symbol.toStringTag, { value: "Module" }));
function DocsComparisonTable({ columns, rows, caption }) {
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full border-collapse text-left" }, caption ? /* @__PURE__ */ React.createElement("caption", { className: "sr-only" }, caption) : null, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/10 bg-white/[0.04]" }, columns.map((column) => /* @__PURE__ */ React.createElement("th", { key: column.key, scope: "col", className: "px-4 py-3 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300 first:min-w-[180px]" }, column.label)))), /* @__PURE__ */ React.createElement("tbody", null, rows.map((row) => /* @__PURE__ */ React.createElement("tr", { key: row.id, className: "border-b border-white/5 last:border-b-0" }, columns.map((column, index2) => /* @__PURE__ */ React.createElement("td", { key: `${row.id}-${column.key}`, className: `px-4 py-4 align-top text-sm leading-6 ${index2 === 0 ? "font-semibold text-white" : "text-slate-300"}` }, row[column.key]))))))));
}
function DocsStepList({ items }) {
  return /* @__PURE__ */ React.createElement("ol", { className: "space-y-3" }, items.map((item, index2) => /* @__PURE__ */ React.createElement("li", { key: item.title, className: "flex gap-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-300/10 text-sm font-semibold text-sky-100" }, index2 + 1), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-300" }, item.description)))));
}
const SECTION_ITEMS$9 = [
  { id: "introduction", label: "Introduction" },
  { id: "what-are-groups", label: "What are Groups?" },
  { id: "why-use-a-group", label: "Why use a Group?" },
  { id: "when-to-create-a-group", label: "When should you create one?" },
  { id: "how-groups-work", label: "How Groups work" },
  { id: "roles-and-permissions", label: "Roles and permissions" },
  { id: "creating-a-group", label: "Creating a Group" },
  { id: "public-group-page", label: "Public Group page" },
  { id: "group-studio", label: "Group Studio" },
  { id: "publishing-as-a-group", label: "Publishing as a Group" },
  { id: "contributor-credit", label: "Contributor credit" },
  { id: "member-management", label: "Invites and team management" },
  { id: "review-workflow", label: "Review workflow" },
  { id: "group-features", label: "Projects, posts, events, releases" },
  { id: "tips-and-best-practices", label: "Tips and best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "suggested-workflows", label: "Suggested workflows" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "need-help", label: "Need help?" }
];
const BENEFITS = [
  "Publish under a shared name without hiding the people behind the work.",
  "Separate team identity from personal portfolios when a project needs its own public home.",
  "Manage roles, approvals, and release workflows in one place.",
  "Run projects, posts, challenges, events, assets, and releases under the same umbrella.",
  "Recruit collaborators through a Group page instead of repeating the same pitch in DMs.",
  "Keep contributor credit visible even when the final publish surface is the Group."
];
const GOOD_FIT$1 = [
  "You collaborate with two or more people regularly.",
  "You want a shared public brand for a studio, crew, or collective.",
  "You publish themed drops, packs, showcases, or release-driven work.",
  "You need shared collections, posts, assets, or release notes.",
  "You want role-based access instead of everyone sharing one account."
];
const NOT_YET = [
  "You only publish solo work and do not need a separate identity.",
  "You are still testing ideas and not ready to manage members.",
  "You want a Group only to rename personal work without collaboration value.",
  "You do not want shared workflow, shared publishing context, or shared moderation responsibility."
];
const ROLE_TABLE = {
  columns: [
    { key: "role", label: "Role" },
    { key: "settings", label: "Manage settings" },
    { key: "members", label: "Invite and change roles" },
    { key: "publishing", label: "Publish content" },
    { key: "review", label: "Review submissions" },
    { key: "workflow", label: "Manage posts, projects, events, releases" },
    { key: "assets", label: "Manage assets and shared resources" }
  ],
  rows: [
    {
      id: "owner",
      role: "Owner",
      settings: "Full control over branding, settings, membership policy, and archive actions.",
      members: "Can invite, remove, promote, transfer ownership, and approve the overall structure.",
      publishing: "Can publish directly and define the team workflow.",
      review: "Can always review, approve, request changes, or reject.",
      workflow: "Full access to posts, projects, challenges, events, releases, and reputation.",
      assets: "Full access."
    },
    {
      id: "admin",
      role: "Admin",
      settings: "Can usually manage day-to-day settings and operations.",
      members: "Can invite and manage most members, but should not be handed out casually.",
      publishing: "Usually yes.",
      review: "Usually yes.",
      workflow: "Usually full operational access across content areas.",
      assets: "Usually full access."
    },
    {
      id: "editor",
      role: "Editor",
      settings: "Usually limited or no access to sensitive settings.",
      members: "Usually cannot change member roles unless explicitly allowed.",
      publishing: "Often yes, depending on your workflow.",
      review: "Often yes when the team uses review queues.",
      workflow: "Good fit for content managers, release coordinators, and project leads.",
      assets: "Often yes."
    },
    {
      id: "contributor",
      role: "Contributor",
      settings: "No sensitive settings access.",
      members: "Cannot manage team structure.",
      publishing: "Usually submits drafts instead of publishing directly.",
      review: "Usually no.",
      workflow: "Best for creative collaborators who need to contribute without running the Group.",
      assets: "Limited to what the Group makes available."
    }
  ]
};
const CREATE_STEPS$1 = [
  { title: "Open Groups in Studio", description: "Go to Group Studio from your main Studio area, then choose Create Group." },
  { title: "Choose a clear name and slug", description: "Pick a name people can remember and a slug that still makes sense a year from now." },
  { title: "Add branding", description: "Upload a recognizable avatar or logo and a cover image that gives the Group a clear visual identity." },
  { title: "Write a short headline and description", description: "Tell visitors what the Group makes, who it is for, and what kind of collaboration to expect." },
  { title: "Set visibility", description: "Choose whether the Group should be public, unlisted, or private based on how ready you are." },
  { title: "Create the Group", description: "Finish setup, then review the public page so the branding and copy feel intentional." },
  { title: "Invite your first members", description: "Bring in owners, admins, editors, or contributors based on the work each person will actually do." },
  { title: "Decide on your workflow", description: "Choose whether the team should use direct publishing, review-first publishing, projects, releases, or lightweight milestones." },
  { title: "Publish with care", description: "Before the first public post or artwork, confirm that contributor credit and publishing context are correct." }
];
const STUDIO_AREAS$1 = [
  "Dashboard for a quick read on releases, review items, events, and activity.",
  "Artworks for group-owned publishing and shared presentation.",
  "Review Queue for approval workflows, changes requested, and moderation hygiene.",
  "Posts for announcements, release notes, recruitment, and milestones.",
  "Projects for structured collaboration and shared progress.",
  "Challenges and Events for community activity and time-based launches.",
  "Assets for internal shared files and reusable resources.",
  "Collections and Releases for public packaging, curation, and major launch moments.",
  "Members, Recruitment, Invitations, and Reputation for team health and trust signals."
];
const FEATURE_CARDS = [
  {
    title: "Projects",
    body: "Use projects when a collaboration needs a shared home, milestones, attachments, and team ownership before it becomes a public release."
  },
  {
    title: "Challenges",
    body: "Challenges work well for themed prompts, community events, and structured contribution windows that keep the Group active."
  },
  {
    title: "Events",
    body: "Events are for launches, showcases, meetups, timed drops, or public moments that need a calendar-style anchor."
  },
  {
    title: "Assets",
    body: "The asset library keeps shared files, references, and working materials organized instead of buried in chat history."
  },
  {
    title: "Releases",
    body: "Releases package a major publication moment with summary, contributors, milestones, notes, and linked work in one polished surface."
  },
  {
    title: "Posts",
    body: "Posts keep the Group human. Use them for updates, recruitment, changelogs, launch notes, and curated public communication."
  }
];
const BEST_PRACTICES$5 = [
  "Keep the Group identity focused. Visitors should understand who you are in seconds.",
  "Define Owner, Admin, Editor, and Contributor responsibilities early.",
  "Use the simplest permissions setup that supports the team today.",
  "Check publishing context before every public action.",
  "Credit real people accurately, even when the Group is the publish surface.",
  "Use projects and releases for bigger work instead of burying everything in posts.",
  "Keep assets tidy so new members are not onboarding into chaos.",
  "Pin only the most important public update, not every update.",
  "Review inactive memberships and old roles periodically.",
  "Use recruitment only when the Group can actually onboard people well.",
  "Write release notes that explain what changed and why it matters.",
  "Treat the Group page like a living portfolio, not a one-time setup screen."
];
const COMMON_MISTAKES$7 = [
  "Giving too many people admin power before the team knows how it wants to work.",
  "Publishing under the wrong context because no one checked whether Personal Studio or Group Studio was active.",
  "Forgetting contributor credit or using vague labels that do not explain the work.",
  "Creating a Group with no clear purpose, rhythm, or public identity.",
  "Letting the public page go stale after the initial setup.",
  "Using the Group identity to hide who actually made the work.",
  "Inviting members without setting expectations around ownership, publishing, and approval flow.",
  "Treating posts as noise instead of meaningful updates.",
  "Keeping an asset library that nobody can search or trust.",
  "Adding projects, challenges, events, and releases before the team has a simple baseline workflow."
];
const WORKFLOWS = [
  {
    title: "Workflow A: Small trusted team",
    summary: "Owner plus one editor and one or two contributors. Simple permissions, direct publishing when the team already trusts the process.",
    bullets: ["Use lightweight posts for updates.", "Keep contributor labels accurate.", "Only add milestones when a release needs coordination."]
  },
  {
    title: "Workflow B: Growing art collective",
    summary: "Owner, admins, editors, and contributors with a review queue and recruitment enabled.",
    bullets: ["Use projects for medium-term work.", "Review submissions before public publishing.", "Keep the member list and public page curated."]
  },
  {
    title: "Workflow C: Release-driven group",
    summary: "A team built around themed drops, packs, or showcase moments.",
    bullets: ["Use releases as the main public storytelling surface.", "Attach artworks, release notes, and milestones.", "Pair launches with a post and pinned update."]
  },
  {
    title: "Workflow D: Community challenge group",
    summary: "A Group centered on challenges, events, and recurring prompts.",
    bullets: ["Use join requests or recruiting to control growth.", "Publish clear challenge briefs and event dates.", "Keep moderation and review communication constructive."]
  }
];
const FAQ_ITEMS$8 = [
  {
    question: "What is the difference between a personal profile and a Group?",
    answer: "A personal profile is your individual identity. A Group is a shared identity for collaboration and publishing. The Group can publish the work publicly, but contributor credit should still show the people behind it."
  },
  {
    question: "Can I publish both personally and as a Group?",
    answer: "Yes. Many creators keep their personal portfolio active while also publishing collaborative work under a Group. The key is to choose the right context before you publish."
  },
  {
    question: "Will my name still appear if I publish under a Group?",
    answer: "Yes. Group publishing is meant to preserve authorship, not erase it. Uploaded by, primary author, and contributor credit should still reflect the humans involved."
  },
  {
    question: "Who can publish as a Group?",
    answer: "That depends on role and workflow. Owners and admins usually can. Editors often can. Contributors may submit drafts without publishing directly if the Group uses review-first workflows."
  },
  {
    question: "Can contributors submit drafts without publishing directly?",
    answer: "Yes. That is one of the most useful Group workflows. Contributors can hand work off for review while editors or admins handle final approval and public publishing."
  },
  {
    question: "How do I invite members?",
    answer: "Open Group Studio, go to members or invitations, choose the right role, and send an invite only after you know what that person needs access to."
  },
  {
    question: "Can I remove a member later?",
    answer: "Yes. Owners and people with the right member-management permissions can update roles, revoke invitations, or remove active members when needed."
  },
  {
    question: "What happens to old artworks if someone leaves the Group?",
    answer: "Existing publishing history and contributor credit should remain as part of the public record unless the content itself changes or is removed through normal moderation or management flows."
  },
  {
    question: "Should every team create a Group?",
    answer: "No. Create a Group when you need shared identity, shared workflows, or recurring collaboration. If you only publish solo work, a personal profile may be enough."
  },
  {
    question: "How should we use roles?",
    answer: "Start simple. Keep Owner count small, reserve Admin for deeply trusted operators, use Editor for day-to-day management, and keep Contributor focused on creative participation."
  },
  {
    question: "Can we recruit new members through the Group page?",
    answer: "Yes, if recruitment is enabled. Use it when the Group is actually ready to onboard people, not just to look active."
  },
  {
    question: "What are releases, projects, and challenges used for?",
    answer: "Projects help teams organize work. Releases package major publication moments. Challenges create themed participation and energy. Together they make the Group feel structured and alive."
  },
  {
    question: "Can a Group have posts and announcements?",
    answer: "Yes. Posts are useful for release notes, milestone updates, recruitment, public announcements, and pinned context on the Group page."
  },
  {
    question: "How should we organize our assets?",
    answer: "Keep them categorized, named clearly, and cleaned up over time. Shared assets should help the team work faster, not become a second mystery archive."
  },
  {
    question: "What should we do if contributor credit is wrong?",
    answer: "Fix it quickly. Attribution errors create confusion, trust issues, and sometimes conflict. Confirm who uploaded the work, who authored it, and who contributed before changing anything publicly."
  }
];
const TROUBLESHOOTING_ITEMS$7 = [
  {
    title: "I cannot publish as the Group",
    body: "Check that you are in Group Studio, not Personal Studio. Then confirm your role allows publishing and that the Group is active and not archived or suspended."
  },
  {
    title: "I do not see Group Studio",
    body: "You may not be signed in, may not belong to the Group, or may only have a pending invitation. Accept the invite first, then reload Studio."
  },
  {
    title: "My role does not let me do what I expected",
    body: "Ask the Owner or Admin which permissions are meant for your role. In many teams, Editors manage content while Contributors only submit drafts."
  },
  {
    title: "Contributor credit is wrong",
    body: "Review the publish record carefully: published by, uploaded by, primary author, and contributors each mean different things. Correct the one that is inaccurate rather than replacing all of them."
  },
  {
    title: "I was invited but cannot access content",
    body: "Some areas may still be internal, role-limited, or pending approval. First confirm that the invitation was accepted and the membership is active."
  },
  {
    title: "I published under the wrong context",
    body: "Stop and review the affected content immediately. Confirm whether it should live under the personal profile or the Group, then correct the publish context before more linked items are built around it."
  },
  {
    title: "I do not understand why my draft is in review",
    body: "Your Group may use a review-first workflow so contributors can submit work without publishing directly. Check the review queue feedback or ask the assigned reviewer what needs to change."
  },
  {
    title: "I do not know which role to assign someone",
    body: "Ask what they need to do this month, not what title sounds impressive. If you are unsure, start lower and promote later."
  }
];
function HeroMetric$8({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function TwoColumnChecklist({ title, eyebrow, items, tone = "sky" }) {
  const toneClass = tone === "emerald" ? "border-emerald-300/15 bg-emerald-400/10 text-emerald-100" : "border-sky-300/15 bg-sky-400/10 text-sky-100";
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, eyebrow), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "flex gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border ${toneClass}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check text-[10px]" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-300" }, item)))));
}
function InfoCard({ title, body: body2, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: icon })), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-lg font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, body2));
}
function BulletGrid$8({ items }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-6 text-slate-300" }, item)));
}
function WorkflowCard({ workflow }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, workflow.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, workflow.summary), /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-2" }, workflow.bullets.map((bullet) => /* @__PURE__ */ React.createElement("li", { key: bullet, className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mt-1.5 h-2 w-2 shrink-0 rounded-full bg-sky-300" }), /* @__PURE__ */ React.createElement("span", null, bullet)))));
}
function TroubleCard$6({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function GroupHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const heroJsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Groups Help & Guide",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Groups", "Collaborative publishing", "Contributor credit", "Group Studio", "Releases"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$8.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(14,165,233,0.18),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd: heroJsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Groups documentation"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Build, manage, and publish through Groups without losing personal credit."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "Groups on Skinbase are shared creative identities for studios, collectives, release teams, and long-term collaborations. This guide explains when to use them, how to structure roles, how publishing works, and how to keep the public page clear, trustworthy, and easy to maintain."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.create_group, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Create a Group"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("a", { href: "#roles-and-permissions", className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Jump to roles and permissions")), links.quickstart ? /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("a", { href: links.quickstart, className: "text-sm font-semibold text-sky-200 underline underline-offset-4" }, "Prefer the shorter onboarding version? Open the Groups Quickstart.")) : null, links.faq ? /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement("a", { href: links.faq, className: "text-sm font-semibold text-slate-300 underline underline-offset-4 hover:text-white" }, "Need faster answers instead? Open the Groups FAQ.")) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(HeroMetric$8, { label: "Shared identity", value: "One public home for team work", note: "Use a Group when a studio, crew, or release team needs its own visible brand." }), /* @__PURE__ */ React.createElement(HeroMetric$8, { label: "Preserved credit", value: "Authorship stays visible", note: "Published by, uploaded by, primary author, and contributors can still reflect the real humans behind the work." }), /* @__PURE__ */ React.createElement(HeroMetric$8, { label: "Studio workflow", value: "Roles, reviews, projects, releases", note: "Groups work best when the team needs structure, not just a different display name." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$9 }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-are-groups",
      eyebrow: "Foundations",
      title: "What are Groups?",
      summary: "A Group is a shared creative identity for collaboration and publishing. It is not a replacement for personal profiles. It is the public home for work that belongs to a team, studio, collective, or release-focused collaboration."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(InfoCard, { title: "Personal profile", icon: "fa-solid fa-user", body: "Your personal profile is your own portfolio, reputation, and identity. It is where your individual voice, uploads, followers, and personal presence live." }), /* @__PURE__ */ React.createElement(InfoCard, { title: "Group", icon: "fa-solid fa-people-group", body: "A Group is the shared layer. It gives a team one public identity for publishing together, managing members, and presenting collaborative work without flattening individual credit." })),
    /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "The most important rule" }, "A Group is a shared publishing identity, not a way to erase authorship. If real people made the work, their authorship and contribution history should still be represented clearly."),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, "Groups are a good fit for"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, ["Design studios", "Pixel art crews", "Wallpaper teams", "Photography collectives", "Event-based collaborations", "Release teams"].map((label) => /* @__PURE__ */ React.createElement("span", { key: label, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-slate-200" }, label))))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "why-use-a-group",
      eyebrow: "Decision guide",
      title: "Why use a Group?",
      summary: "Use a Group when the work is bigger than one person, or when a shared identity helps the team stay organized, trustworthy, and easy to understand publicly."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$8, { items: BENEFITS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "when-to-create-a-group",
      eyebrow: "Decision guide",
      title: "When should you create a Group?",
      summary: "Create a Group when it solves a real workflow or identity problem. If it is just adding overhead, you probably do not need it yet."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(TwoColumnChecklist, { title: "Create one when...", eyebrow: "Good fit", items: GOOD_FIT$1, tone: "emerald" }), /* @__PURE__ */ React.createElement(TwoColumnChecklist, { title: "Hold off when...", eyebrow: "Not yet", items: NOT_YET, tone: "sky" })),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "A simple rule of thumb" }, "If the team needs shared publishing, shared coordination, or a shared public identity more than it needs absolute simplicity, a Group is probably worth it."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "how-groups-work",
      eyebrow: "Model",
      title: "How Groups work",
      summary: "Think of a Group as two connected surfaces: a public identity page and an internal Studio workspace. One is for visibility. The other is for coordination."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(InfoCard, { title: "Group page", icon: "fa-solid fa-earth-americas", body: "The public face of the Group with branding, releases, posts, projects, challenges, events, members, and activity." }), /* @__PURE__ */ React.createElement(InfoCard, { title: "Group Studio", icon: "fa-solid fa-sliders", body: "The internal workspace for permissions, publishing, review flows, releases, assets, invites, and day-to-day operations." }), /* @__PURE__ */ React.createElement(InfoCard, { title: "Shared content", icon: "fa-solid fa-layer-group", body: "Groups can own artworks, collections, posts, projects, challenges, events, assets, and releases depending on the team workflow." }), /* @__PURE__ */ React.createElement(InfoCard, { title: "Public vs internal", icon: "fa-solid fa-lock-open", body: "Not everything is public. Some areas are internal, role-based, or review-gated. The public page should be curated. Studio should stay operational." }))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "roles-and-permissions",
      eyebrow: "Team structure",
      title: "Roles and permissions",
      summary: "Keep roles understandable. Most Groups do best when only a small number of people can change settings or manage members, while everyone else gets exactly the access they need and nothing more."
    },
    /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Start simpler than you think" }, "Most new Groups should begin with one Owner, a very small Admin circle, Editors for day-to-day managers, and Contributors for creative participation. Complexity is easier to add later than remove."),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsComparisonTable, { columns: ROLE_TABLE.columns, rows: ROLE_TABLE.rows, caption: "Group role comparison" }))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "creating-a-group",
      eyebrow: "Setup",
      title: "Creating a Group",
      summary: "A strong first setup prevents confusion later. Good names, clean branding, and clear role assignments make every other workflow easier."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: CREATE_STEPS$1 }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Setup tips" }, "Choose a name that will still make sense when the Group grows. Add a short description that says what the Group makes, not just what it likes."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not skip ownership decisions" }, "Decide early who should be Owner and who truly needs Admin. Teams create a lot of avoidable friction when this stays vague."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "public-group-page",
      eyebrow: "Public identity",
      title: "Group profile and public page",
      summary: "The public Group page is the identity page for the team. It should feel active, coherent, and curated instead of looking like a random collection of leftovers."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, ["Cover and avatar", "Description and About", "Members and leadership", "Artworks and collections", "Posts and announcements", "Projects, challenges, events, releases"].map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm font-medium text-slate-200" }, item))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Keep the page feeling alive" }, "Use a consistent visual identity, keep the About copy current, feature the best work, and pin only the update that gives new visitors the best context."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "group-studio",
      eyebrow: "Operations",
      title: "Group Studio",
      summary: "Group Studio is where you switch from being an individual creator to operating inside a shared team context. That context matters every time you publish, review, or manage content."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(InfoCard, { title: "Personal Studio", icon: "fa-solid fa-user-gear", body: "Use Personal Studio when you are managing your own portfolio, drafts, uploads, and audience as an individual creator." }), /* @__PURE__ */ React.createElement(InfoCard, { title: "Group Studio", icon: "fa-solid fa-people-roof", body: "Use Group Studio when the work belongs to the shared identity, or when roles, reviews, projects, releases, and member access need to be respected." })),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(BulletGrid$8, { items: STUDIO_AREAS$1 })),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Check context before publishing" }, "The easiest way to create confusing attribution is to publish from the wrong context. If the work belongs to the Group, confirm that Group Studio is active before you submit or publish."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "publishing-as-a-group",
      eyebrow: "Publishing",
      title: "Publishing as a Group",
      summary: "Publishing as a Group means the shared identity is the public publish surface. It does not mean the Group replaces every human role in the record."
    },
    /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, "How to read the publishing record"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Published by"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, "Warlock"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "The shared identity the work appears under publicly.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Uploaded by"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, "Gregor"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "The person who performed the upload or publishing action.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Primary author"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, "Gregor"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "The person who should be understood as the main author of the work.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, "Denis, Paula"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Additional people who made meaningful creative contributions.")))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Why this matters" }, "Group publishing creates a shared public identity for the work, but personal authorship, accountability, and contribution history should still be easy to understand."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not use Group publishing to hide authorship" }, "If the work is mainly one person\\'s piece, make sure the primary author and contributors reflect that reality clearly."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "contributor-credit",
      eyebrow: "Attribution",
      title: "Contributor credit and authorship",
      summary: "Correct attribution keeps the Group healthy. It builds trust inside the team, makes the public record clearer, and reduces avoidable disputes later."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$8, { items: [
      "Always credit real contributors, even when the Group brand is stronger than any single member.",
      "Use role labels when they add clarity, such as packaging lead, curator, reviewer, or art director.",
      "Do not swap uploader and author just because one person clicked Publish.",
      "Discuss credits early for bigger releases so nobody is negotiating attribution after launch day."
    ] }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Incorrect credit causes real friction" }, "Attribution problems are rarely just metadata problems. They affect trust, morale, and how future collaborators feel about the Group."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "member-management",
      eyebrow: "Team health",
      title: "Inviting members and managing the team",
      summary: "Healthy Groups are clear about who has access, why they have it, and how that access changes as the team grows."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(InfoCard, { title: "Invites and onboarding", icon: "fa-solid fa-user-plus", body: "Invite people with the smallest role that still lets them do the work. Explain expectations before they accept so there is no ambiguity about ownership or workflow." }), /* @__PURE__ */ React.createElement(InfoCard, { title: "Role reviews", icon: "fa-solid fa-user-check", body: "Review roles periodically. People change, projects end, and old permissions should not stay permanent by accident." })),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Role assignment guidance" }, "Keep Owner count very limited, give Admin only to trusted operators, use Editor for content managers, and keep Contributor focused on creation."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Join requests and recruiting" }, "If your Group supports join requests or recruiting, use them with a real onboarding process. Recruiting without follow-through makes the Group feel abandoned."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "review-workflow",
      eyebrow: "Quality control",
      title: "Review queue and approval workflow",
      summary: "Review flows help larger or more structured Groups keep public quality high without forcing every trusted team to work the same way."
    },
    /* @__PURE__ */ React.createElement(
      DocsStepList,
      {
        items: [
          { title: "Contributor submits a draft", description: "The work enters the Group pipeline without immediately going public." },
          { title: "Reviewer checks the work", description: "Editors, admins, or designated reviewers confirm quality, context, and credit." },
          { title: "Approve, request changes, or reject", description: "Feedback should be specific enough that the creator knows what to do next." },
          { title: "Publish when ready", description: "Once the draft is approved, the right person can publish it under the correct Group context." }
        ]
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "When direct publishing makes sense" }, "Small, trusted teams often move faster with direct publishing. Use review only when it protects quality or reduces confusion."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "When review-first helps" }, "Larger teams, new contributors, and release-heavy groups usually benefit from a review queue because it catches context, permission, and attribution mistakes before they go public."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "group-features",
      eyebrow: "Feature ecosystem",
      title: "Posts, projects, challenges, events, assets, and releases",
      summary: "These features are most useful when they connect. A healthy Group does not use them all at once. It chooses the smallest set that makes the public story and internal workflow clearer."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, FEATURE_CARDS.map((card, index2) => /* @__PURE__ */ React.createElement(InfoCard, { key: card.title, title: card.title, body: card.body, icon: ["fa-solid fa-diagram-project", "fa-solid fa-bullseye", "fa-solid fa-calendar-day", "fa-solid fa-box-open", "fa-solid fa-rocket", "fa-solid fa-bullhorn"][index2] }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "A practical progression" }, "Many teams start with artworks and posts, then add projects when collaboration gets busier, and use releases when the Group is ready for stronger public storytelling around major drops."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "tips-and-best-practices",
      eyebrow: "Operating well",
      title: "Tips and best practices",
      summary: "Most support questions come from a small set of preventable mistakes. These habits keep Groups easier to manage and easier to trust."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$8, { items: BEST_PRACTICES$5 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid these",
      title: "Common mistakes to avoid",
      summary: "Groups become confusing when identity, permissions, and attribution drift out of sync."
    },
    /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "The fastest way to make a Group feel unreliable" }, "Mix unclear roles with vague attribution and inconsistent publishing context. Users will stop trusting what they are looking at."),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3 md:grid-cols-2" }, COMMON_MISTAKES$7.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-6 text-slate-300" }, item)))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "suggested-workflows",
      eyebrow: "Patterns",
      title: "Suggested workflows",
      summary: "You do not need one perfect workflow. You need the right amount of structure for the team you actually have."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, WORKFLOWS.map((workflow) => /* @__PURE__ */ React.createElement(WorkflowCard, { key: workflow.title, workflow })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Frequently asked questions",
      summary: "Short answers to the questions people most often ask before creating, joining, or managing a Group."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$8 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Common problems and how to think through them",
      summary: "If something feels confusing, start with context, role, and visibility. Most Group issues live in one of those three buckets."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, TROUBLESHOOTING_ITEMS$7.map((item) => /* @__PURE__ */ React.createElement(TroubleCard$6, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "need-help",
      eyebrow: "Support",
      title: "Still need help?",
      summary: "Use these next steps if you are ready to create a Group, need to check your current setup, or want to contact Skinbase support."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("a", { href: links.create_group, className: "rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Create"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Create your first Group"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-sky-50/80" }, "Start with branding, visibility, and your first member invites.")), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Manage"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Check members, workflow, releases, recruitment, and review status.")), /* @__PURE__ */ React.createElement("a", { href: links.contact_support, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Contact"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Contact support"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use the general support flow if you need help untangling an account or workflow issue.")), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Report"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Report a problem"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use this if a route, permission, credit record, or workflow appears broken.")))
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.groups_directory, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Groups"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"), links.faq ? /* @__PURE__ */ React.createElement("a", { href: links.faq, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Groups FAQ") : null, /* @__PURE__ */ React.createElement("a", { href: "#publishing-as-a-group", className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Review publishing guidance"), /* @__PURE__ */ React.createElement("a", { href: "#contributor-credit", className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Check contributor credit rules"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Read this before launch day"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "Before the first public release or artwork, confirm the Group context, contributor credit, and review expectations. Those three checks prevent most avoidable confusion.")))))));
}
const __vite_glob_0_76 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupHelpPage
}, Symbol.toStringTag, { value: "Module" }));
function GroupPromoCard({ group, eyebrow = "Groups spotlight", title, description, ctaLabel = "Open group" }) {
  if (!group) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[34px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.18),transparent_28%),radial-gradient(circle_at_80%_20%,rgba(16,185,129,0.12),transparent_26%),linear-gradient(180deg,rgba(7,16,29,0.98),rgba(2,6,23,0.94))] shadow-[0_30px_90px_rgba(2,6,23,0.45)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 p-6 lg:grid-cols-[minmax(0,1.3fr)_320px] lg:p-8" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, eyebrow), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.03em] text-white sm:text-4xl" }, title || group.name), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-7 text-slate-300" }, description || group.headline || group.bio_excerpt || "Collective publishing for shared releases, artwork credits, and collaborative identity."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, (Array.isArray(group.trust_signals) ? group.trust_signals : []).slice(0, 3).map((signal) => /* @__PURE__ */ React.createElement(GroupBadgePill, { key: signal.key, label: signal.label, tone: signal.tone })), group.is_recruiting ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Actively recruiting", tone: "emerald" }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public || "/groups", className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/15" }, ctaLabel, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-xs" })), /* @__PURE__ */ React.createElement("a", { href: "/groups", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Browse all groups"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/25 p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-white/[0.04]" }, group.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: group.avatar_url, alt: "", className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-slate-300" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-lg font-semibold text-white" }, group.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, group.owner?.username || group.owner?.name ? `Led by ${group.owner.username || group.owner.name}` : "Shared publishing identity"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-2xl font-semibold text-white" }, Number(group.counts?.artworks || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-500" }, "Published artworks")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-2xl font-semibold text-white" }, Number(group.counts?.followers || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-500" }, "Followers")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-2xl font-semibold text-white" }, Number(group.counts?.members || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-500" }, "Members")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-2xl font-semibold text-white" }, Number(group.counts?.collections || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-500" }, "Collections"))))));
}
function GroupDiscoveryCard({ group, className = "", compact = false }) {
  if (!group) return null;
  const primarySummary = group.headline || group.bio_excerpt || "Collaborative publishing identity on Skinbase.";
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: group.urls?.public || "/groups",
      className: cx$7(
        "group block overflow-hidden rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-5 shadow-[0_24px_70px_rgba(2,6,23,0.34)] transition duration-200 hover:-translate-y-1 hover:border-white/20",
        className
      )
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-white/[0.04]" }, group.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: group.avatar_url, alt: "", className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-slate-300" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "truncate text-lg font-semibold text-white" }, group.name), group.is_recruiting ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Recruiting", tone: "emerald" }) : null, group.is_verified ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Verified", tone: "sky" }) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, primarySummary), group.owner?.username || group.owner?.name ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Led by ", group.owner?.username || group.owner?.name) : null)),
    /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, (Array.isArray(group.trust_signals) ? group.trust_signals : []).slice(0, compact ? 2 : 3).map((signal) => /* @__PURE__ */ React.createElement(GroupBadgePill, { key: signal.key, label: signal.label, tone: signal.tone })), (Array.isArray(group.badges) ? group.badges : []).slice(0, compact ? 1 : 2).map((badge) => /* @__PURE__ */ React.createElement(GroupBadgePill, { key: badge.key, label: badge.label, tone: "amber" }))),
    group.recruitment_headline && !compact ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-200/80" }, "Open call"), /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, group.recruitment_headline)) : null,
    group.featured_release?.title && !compact ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Featured release"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, group.featured_release.title), group.featured_release.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, group.featured_release.summary) : null) : null,
    /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-3 gap-2 rounded-2xl border border-white/10 bg-white/[0.03] p-3 text-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, formatCompactNumber$3(group.counts?.artworks)), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, "Artworks")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, formatCompactNumber$3(group.counts?.members)), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, "Members")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, formatCompactNumber$3(group.counts?.followers)), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, "Followers")))
  );
}
function GroupTrendingSection({ title, description, items = [], href = "/groups", actionLabel = "See more" }) {
  if (!Array.isArray(items) || items.length === 0) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.02em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, description) : null), /* @__PURE__ */ React.createElement("a", { href, className: "inline-flex items-center gap-2 text-sm font-semibold text-sky-200 transition hover:text-white" }, actionLabel, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-xs" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, items.map((group) => /* @__PURE__ */ React.createElement(GroupDiscoveryCard, { key: group.slug || group.id, group, compact: true }))));
}
function GroupBrowseFilters({ surfaces = [], currentSurface = "featured" }) {
  if (!Array.isArray(surfaces) || surfaces.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-2" }, surfaces.map((surface) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: surface.value,
      href: `/groups?surface=${encodeURIComponent(surface.value)}`,
      className: `rounded-full border px-4 py-2 text-sm font-semibold transition ${currentSurface === surface.value ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 bg-white/[0.03] text-white hover:border-white/20 hover:bg-white/[0.06]"}`
    },
    surface.label
  )));
}
function GroupLeaderboardCard({ item }) {
  if (!item?.entity) return null;
  const entity = item.entity;
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-4 shadow-[0_18px_50px_rgba(2,6,23,0.3)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-slate-950/70 text-lg font-black text-white" }, "#", item.rank), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("a", { href: entity.url || "/groups", className: "block truncate text-lg font-semibold text-white transition hover:text-sky-300" }, entity.name), entity.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, entity.headline) : null), /* @__PURE__ */ React.createElement("div", { className: "text-right" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-500" }, "Score"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xl font-black text-white" }, Number(item.score || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, (Array.isArray(entity.trust_signals) ? entity.trust_signals : []).slice(0, 2).map((signal) => /* @__PURE__ */ React.createElement(GroupBadgePill, { key: signal.key, label: signal.label, tone: signal.tone })), entity.is_recruiting ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Recruiting", tone: "emerald" }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, Number(entity.artworks_count || 0).toLocaleString(), " artworks"), /* @__PURE__ */ React.createElement("span", null, Number(entity.members_count || 0).toLocaleString(), " members"), /* @__PURE__ */ React.createElement("span", null, Number(entity.followers_count || 0).toLocaleString(), " followers")))));
}
function GroupIndex() {
  const { props } = X$1();
  const groups = props.groups?.data || [];
  const surfaces = Array.isArray(props.surfaces) ? props.surfaces : [];
  const currentSurface = props.currentSurface || "featured";
  const highlightSections = Array.isArray(props.highlightSections) ? props.highlightSections : [];
  const leaderboardItems = Array.isArray(props.leaderboard?.items) ? props.leaderboard.items : [];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { title: "Groups - Skinbase", description: props.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Groups"), /* @__PURE__ */ React.createElement("h1", { className: "mt-2 text-4xl font-semibold text-white" }, "Collective publishing identities"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-6 text-slate-300" }, "Discover collaborative studios, follow shared creative brands, and browse the artworks, releases, and collections published under each group identity."), /* @__PURE__ */ React.createElement(GroupBrowseFilters, { surfaces, currentSurface })), /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement(
    GroupPromoCard,
    {
      group: props.spotlightGroup,
      eyebrow: "Public groups",
      title: "Find collaborative identities with real momentum",
      description: "Groups now sit alongside creators and artworks across Nova, making shared publishing, team recruitment, and release-driven collaboration easier to discover.",
      ctaLabel: "Open spotlight"
    }
  )), highlightSections.map((section) => /* @__PURE__ */ React.createElement(
    GroupTrendingSection,
    {
      key: section.key,
      title: section.title,
      description: section.description,
      items: section.items || [],
      href: `/groups?surface=${encodeURIComponent(section.key)}`
    }
  )), leaderboardItems.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.02em] text-white" }, "Monthly group leaderboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "A fast view of the collaborative teams moving the most attention and publishing energy right now.")), /* @__PURE__ */ React.createElement("a", { href: "/leaderboard?type=groups&period=monthly", className: "text-sm font-semibold text-sky-200 transition hover:text-white" }, "View leaderboard")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, leaderboardItems.slice(0, 3).map((item) => /* @__PURE__ */ React.createElement(GroupLeaderboardCard, { key: item.entity?.id || item.rank, item })))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.02em] text-white" }, "Browse groups"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Filter the directory by discovery surface, then jump into each group’s public page for artworks, releases, projects, events, and activity.")), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-500" }, Number(props.groups?.meta?.total || 0).toLocaleString(), " public groups")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, groups.map((group) => /* @__PURE__ */ React.createElement(GroupDiscoveryCard, { key: group.slug || group.id, group }))))));
}
const __vite_glob_0_77 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupIndex
}, Symbol.toStringTag, { value: "Module" }));
function csrfToken$3() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function GroupPostShow() {
  const { props } = X$1();
  const group = props.group || {};
  const post2 = props.post || {};
  const recentPosts = Array.isArray(props.recentPosts) ? props.recentPosts : [];
  const submitReport = async () => {
    if (!props.reportEndpoint || !post2.id) return;
    const reason = window.prompt("Reason for reporting this post?");
    if (!reason) return;
    await fetch(props.reportEndpoint, {
      method: "POST",
      credentials: "same-origin",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRF-TOKEN": csrfToken$3()
      },
      body: JSON.stringify({ target_type: "group_post", target_id: post2.id, reason })
    });
  };
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${post2.title || group.name} - Skinbase`, description: post2.excerpt || group.headline || group.bio || "Group post" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-5xl" }, /* @__PURE__ */ React.createElement("article", { className: "rounded-[32px] border border-white/10 bg-white/[0.03] p-6 sm:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-sky-200" }, "← Back to ", group.name), props.reportEndpoint ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: submitReport, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Report") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs uppercase tracking-[0.16em] text-slate-400" }, post2.type ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, post2.type) : null, post2.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-amber-100" }, "Pinned") : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 text-4xl font-semibold text-white" }, post2.title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-400" }, post2.author?.name || post2.author?.username || group.name, " • ", post2.published_at ? new Date(post2.published_at).toLocaleString() : "Recently"), post2.excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-6 text-lg leading-8 text-slate-200" }, post2.excerpt) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, post2.content || "")), recentPosts.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "More from ", group.name), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, recentPosts.filter((item) => item.id !== post2.id).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.type), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, item.excerpt || "Read the full post."))))) : null));
}
const __vite_glob_0_78 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupPostShow
}, Symbol.toStringTag, { value: "Module" }));
function ArtworkGrid$2({ artworks }) {
  if (!Array.isArray(artworks) || artworks.length === 0) {
    return /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-slate-400" }, "No linked artworks yet.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, artworks.map((artwork) => /* @__PURE__ */ React.createElement("a", { key: artwork.id, href: artwork.url, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "aspect-[4/3] w-full object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, artwork.author || "Artwork")))));
}
function GroupProjectShow() {
  const { props } = X$1();
  const group = props.group || {};
  const project = props.project || {};
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${project.title || group.name} - Skinbase`, description: project.summary || project.description || group.headline || "Group project" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, project.cover_url ? /* @__PURE__ */ React.createElement("img", { src: project.cover_url, alt: project.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-40 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-sky-200" }, group.name), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, project.status), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, project.visibility)), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, project.title), project.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, project.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 text-xs text-slate-400" }, project.start_date ? /* @__PURE__ */ React.createElement("span", null, "Started ", new Date(project.start_date).toLocaleDateString()) : null, project.target_date ? /* @__PURE__ */ React.createElement("span", null, "Target ", new Date(project.target_date).toLocaleDateString()) : null, project.released_at ? /* @__PURE__ */ React.createElement("span", null, "Released ", new Date(project.released_at).toLocaleDateString()) : null, project.lead?.name || project.lead?.username ? /* @__PURE__ */ React.createElement("span", null, "Lead: ", project.lead?.name || project.lead?.username) : null))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Overview"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, project.description || "No long-form description yet."), Array.isArray(project.milestones) && project.milestones.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, project.milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, milestone.status)), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null, milestone.owner?.name || milestone.owner?.username ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, "Owner: ", milestone.owner?.name || milestone.owner?.username) : null))) : null, /* @__PURE__ */ React.createElement(ArtworkGrid$2, { artworks: project.artworks })), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Pipeline"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm leading-7 text-slate-300" }, "This project currently has ", project.counts?.milestones || 0, " milestones and is linked to ", project.release_count || project.counts?.releases || 0, " releases.")), Array.isArray(project.assets) && project.assets.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Assets"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, project.assets.map((asset) => /* @__PURE__ */ React.createElement("a", { key: asset.id, href: asset.download_url, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, asset.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, asset.category, " • ", asset.visibility))))) : null, Array.isArray(project.team) && project.team.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Team"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, project.team.map((member) => /* @__PURE__ */ React.createElement("div", { key: member.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, member.name || member.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, member.role_label || (member.is_lead ? "Lead" : "Contributor")))))) : null, project.pinned_post ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Pinned update"), /* @__PURE__ */ React.createElement("a", { href: project.pinned_post.url, className: "mt-4 inline-block text-sm font-semibold text-sky-200" }, project.pinned_post.title)) : null))));
}
const __vite_glob_0_79 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupProjectShow
}, Symbol.toStringTag, { value: "Module" }));
function QuickstartChecklist({ title, summary, items }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-emerald-300/20 bg-emerald-400/10 p-5 shadow-[0_22px_70px_rgba(2,6,23,0.2)] md:p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-100/80" }, "Checklist"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold text-white" }, title), summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-emerald-50/90" }, summary) : null, /* @__PURE__ */ React.createElement("ul", { className: "mt-5 grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("li", { key: item, className: "flex gap-3 rounded-[22px] border border-white/10 bg-black/20 px-4 py-4 text-sm leading-6 text-white" }, /* @__PURE__ */ React.createElement("span", { className: "mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-emerald-300/20 bg-emerald-300/10 text-emerald-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check text-[10px]" })), /* @__PURE__ */ React.createElement("span", null, item)))));
}
const SECTION_ITEMS$8 = [
  { id: "introduction", label: "Welcome" },
  { id: "what-is-a-group", label: "What is a Group?" },
  { id: "when-to-use", label: "When to use a Group" },
  { id: "create-first-group", label: "Create your first Group" },
  { id: "setup-properly", label: "Set it up properly" },
  { id: "invite-and-roles", label: "Invite members and roles" },
  { id: "publish-first-artwork", label: "Publish your first artwork" },
  { id: "contributor-credit", label: "Contributor credit" },
  { id: "first-week-best-practices", label: "First-week best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "quick-checklist", label: "Quick checklist" },
  { id: "next-steps", label: "Next steps" }
];
const COMPARISON_CARDS = [
  {
    title: "Personal profile",
    icon: "fa-solid fa-user",
    bullets: ["Individual identity", "Solo publishing", "Personal portfolio and reputation"]
  },
  {
    title: "Group",
    icon: "fa-solid fa-people-group",
    bullets: ["Team identity", "Collaborative publishing", "Shared brand, shared activity, shared workflow"]
  }
];
const GOOD_FIT = [
  "You work with other creators regularly.",
  "You want a shared public brand for a studio, team, or collective.",
  "You want one home for member roles, publishing, and shared activity.",
  "You release projects, themed drops, or collaborative packs together."
];
const NOT_NEEDED_YET = [
  "You only publish solo work right now.",
  "You do not need shared identity or member management yet.",
  "You are not collaborating enough to justify shared workflow overhead."
];
const CREATE_STEPS = [
  { title: "Open Groups or Creator Studio", description: "Start from the Groups area in Studio and choose Create Group." },
  { title: "Choose your name and slug", description: "Pick something clear, memorable, and easy for other creators to recognize." },
  { title: "Add your visuals", description: "Upload a logo or avatar and a cover image so the Group feels real immediately." },
  { title: "Write a short description", description: "Explain what the Group makes and who it is for in one strong paragraph." },
  { title: "Choose visibility", description: "Decide whether the Group should be public, unlisted, or private while you set it up." },
  { title: "Create the Group", description: "Finish creation, then review the public page before you invite the rest of the team." }
];
const SETUP_TASKS = [
  "Upload a clean avatar or logo.",
  "Add a cover image that matches the Group identity.",
  "Write a short description instead of leaving the page blank.",
  "Decide who should be Owner and who really needs Admin access.",
  "Choose public or private visibility intentionally.",
  "Make the page feel alive before you ask people to join it."
];
const ROLE_CARDS = [
  {
    role: "Owner",
    summary: "Full control over branding, membership, settings, and the overall workflow.",
    note: "Keep this count very small."
  },
  {
    role: "Admin",
    summary: "Helps run the Group day to day, manage members, and keep operations moving.",
    note: "Only give this to deeply trusted people."
  },
  {
    role: "Editor",
    summary: "A strong fit for content managers, release coordinators, and people who help publish work.",
    note: "Usually the best default for trusted operators."
  },
  {
    role: "Contributor",
    summary: "Contributes work without needing full control over the Group structure.",
    note: "Best starting role for most collaborators."
  }
];
const PUBLISH_STEPS = [
  { title: "Open Group Studio", description: "Make sure you are working inside the Group, not your personal publishing context." },
  { title: "Start the upload or open the draft", description: "Prepare the artwork that should appear under the Group identity publicly." },
  { title: "Confirm Group context before publish", description: "Double-check that you are publishing as the Group, not as your personal profile." },
  { title: "Review credit before final publish", description: "Check primary author and contributor fields before the artwork goes public." }
];
const CREDIT_TERMS = [
  { label: "Published by", value: "Warlock", note: "The shared identity the artwork appears under publicly." },
  { label: "Uploaded by", value: "Gregor", note: "The person who performed the upload or final publish action." },
  { label: "Primary author", value: "Gregor", note: "The main author of the work." },
  { label: "Contributors", value: "Denis, Paula", note: "Additional people who made meaningful creative contributions." }
];
const FIRST_WEEK_BEST_PRACTICES = [
  "Publish one strong piece before publishing a lot of weak or unfinished work.",
  "Fill out the Group profile early so the public page does not feel abandoned.",
  "Agree internally on how contributor credit should be assigned before launch day.",
  "Keep roles simple until the team actually needs more complexity.",
  "Use posts and updates for meaningful announcements, not noise.",
  "Feature the best work so the Group makes a strong first impression."
];
const COMMON_MISTAKES$6 = [
  "Giving too many people admin access too early.",
  "Publishing under the wrong context because no one checked whether the Group was selected.",
  "Forgetting contributor credit or leaving it vague.",
  "Creating a Group with no real purpose or activity plan.",
  "Leaving the profile blank and expecting the page to feel trustworthy.",
  "Overcomplicating permissions on day one.",
  "Letting inactive members keep strong permissions forever.",
  "Using the Group identity without clear authorship inside the team."
];
const QUICK_CHECKLIST = [
  "Group created",
  "Name and slug chosen",
  "Avatar or logo uploaded",
  "Cover added",
  "Description written",
  "First members invited",
  "Roles assigned",
  "Group context selected in Studio",
  "First artwork prepared",
  "Contributor credit reviewed",
  "First Group publish completed"
];
const NEXT_STEPS = [
  {
    eyebrow: "Create",
    title: "Create a Group",
    body: "Start the shared identity now if you are ready to move from solo work to team publishing.",
    linkKey: "create_group",
    tone: "sky"
  },
  {
    eyebrow: "Manage",
    title: "Open Group Studio",
    body: "Go straight into Studio if your Group already exists and you want to invite members or publish.",
    linkKey: "group_studio",
    tone: "white"
  },
  {
    eyebrow: "Learn more",
    title: "Read the full Groups guide",
    body: "Open the deeper documentation for releases, challenges, review workflows, troubleshooting, and advanced usage.",
    linkKey: "full_documentation",
    tone: "amber"
  },
  {
    eyebrow: "Explore",
    title: "Browse public Groups",
    body: "See how other teams present themselves, structure their identity, and publish together.",
    linkKey: "groups_directory",
    tone: "white"
  }
];
function HeroStat({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function ComparisonCard({ card }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: card.icon })), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-xl font-semibold text-white" }, card.title), /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-2" }, card.bullets.map((item) => /* @__PURE__ */ React.createElement("li", { key: item, className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mt-1.5 h-2 w-2 shrink-0 rounded-full bg-sky-300" }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function SimpleListCard({ title, eyebrow, items, tone = "sky" }) {
  const toneClass = tone === "emerald" ? "border-emerald-300/15 bg-emerald-400/10 text-emerald-50" : "border-white/10 bg-black/20 text-white";
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[28px] border p-5 ${toneClass}` }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] opacity-80" }, eyebrow), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold" }, title), /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("li", { key: item, className: "flex gap-3 text-sm leading-6 opacity-95" }, /* @__PURE__ */ React.createElement("span", { className: "mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-[10px]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check" })), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function RoleCard({ role }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[26px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, role.role), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, role.summary), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm font-medium text-slate-200" }, role.note));
}
function CompactGrid({ items }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[22px] border border-white/10 bg-black/20 p-4 text-sm leading-6 text-slate-300" }, item)));
}
function CreditCard({ item }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, item.value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, item.note));
}
function GroupQuickstartPage() {
  const { props } = X$1();
  const links = props.links || {};
  const nextSteps = NEXT_STEPS.map((item) => ({
    ...item,
    href: links[item.linkKey] || "#"
  }));
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: props.title,
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Groups", "Quickstart", "Collaborative publishing", "Contributor credit"]
    }
  ];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(14,165,233,0.18),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1380px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.74)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.18),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Groups quickstart"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Get started with Groups fast and publish together without losing individual credit."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This quickstart is the fast path from curiosity to first success. It shows what a Group is, when to use one, how to invite the right people, and how to publish your first Group artwork with contributor credit handled properly."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.create_group, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Create a Group"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("a", { href: links.full_documentation, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read full Groups documentation")), links.faq ? /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("a", { href: links.faq, className: "text-sm font-semibold text-sky-200 underline underline-offset-4" }, "Need quick answers instead of the full guide? Open the Groups FAQ.")) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(HeroStat, { label: "What a Group is", value: "A shared team identity", note: "Use it when a studio, crew, or project needs one public home instead of scattered personal uploads." }), /* @__PURE__ */ React.createElement(HeroStat, { label: "What stays visible", value: "Real contributor credit", note: "Published by, uploaded by, primary author, and contributor roles can still reflect the real people behind the work." }), /* @__PURE__ */ React.createElement(HeroStat, { label: "First win", value: "Create, invite, publish", note: "The goal of this page is simple: get you to a clean first Group publish without confusion." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$8 }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-is-a-group",
      eyebrow: "Start here",
      title: "What is a Group?",
      summary: "A Group is a shared creative identity for multiple people. It lets a team publish together under one name while still showing who uploaded, authored, and contributed to the work."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, COMPARISON_CARDS.map((card) => /* @__PURE__ */ React.createElement(ComparisonCard, { key: card.title, card }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "The key idea to keep in your head" }, "Group and personal publishing can coexist. A Group gives the team a shared identity, but it should not erase the people behind the work."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "when-to-use",
      eyebrow: "Decision",
      title: "When should you use a Group?",
      summary: "Use a Group when collaboration is real enough to need shared identity, shared workflow, or shared publishing. Skip it for now if it only adds overhead."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(SimpleListCard, { title: "Use a Group when...", eyebrow: "Good fit", items: GOOD_FIT, tone: "emerald" }), /* @__PURE__ */ React.createElement(SimpleListCard, { title: "You can wait when...", eyebrow: "Not necessary yet", items: NOT_NEEDED_YET }))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "create-first-group",
      eyebrow: "Build the foundation",
      title: "Create your first Group",
      summary: "The fastest clean start is a simple start. Get the identity created first, then improve it as the Group becomes active."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: CREATE_STEPS }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Start simple" }, "You do not need perfect branding or a complex team structure on day one. You need a clear name, a usable page, and the right first members."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "setup-properly",
      eyebrow: "Right after creation",
      title: "Set up your Group properly",
      summary: "The first few setup moves decide whether the Group feels trustworthy and active or unfinished and confusing."
    },
    /* @__PURE__ */ React.createElement(CompactGrid, { items: SETUP_TASKS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "invite-and-roles",
      eyebrow: "Team setup",
      title: "Invite members and choose roles",
      summary: "Keep the role model clear. Most teams should stay simple at first: very few Owners, very few Admins, Editors for trusted content operators, and Contributors for most collaborators."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, ROLE_CARDS.map((role) => /* @__PURE__ */ React.createElement(RoleCard, { key: role.role, role }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Recommended first move" }, "Invite your first members, assign only the roles they need right now, and avoid advanced permission tuning until the team has real workflow pressure."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Advanced overrides can wait" }, "If you need permission overrides later, you can add them later. The quickstart path is deliberately simpler than the full feature set."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "publish-first-artwork",
      eyebrow: "First success",
      title: "Publish your first artwork as a Group",
      summary: "This is where new teams get tripped up most often. The artwork should appear under the Group publicly, but the people behind it should still be represented correctly."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: PUBLISH_STEPS }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Always check publishing context before the final click" }, "Confirm whether you are publishing as your personal profile or as the Group. That one check prevents a lot of cleanup later."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "contributor-credit",
      eyebrow: "Credit",
      title: "Understand contributor credit",
      summary: "Groups are for shared identity, not for hiding who did the actual work. Before the first public publish, make sure the credit record reflects reality."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, CREDIT_TERMS.map((item) => /* @__PURE__ */ React.createElement(CreditCard, { key: item.label, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Best practice" }, "Review contributor credit before every first release, first Group artwork, or first major collaborative drop. Do not leave attribution as an afterthought."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "first-week-best-practices",
      eyebrow: "First week",
      title: "First-week best practices",
      summary: "The first week should make the Group feel intentional, active, and easy to understand."
    },
    /* @__PURE__ */ React.createElement(CompactGrid, { items: FIRST_WEEK_BEST_PRACTICES })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid these",
      title: "Common mistakes to avoid",
      summary: "These are the fastest ways to make a new Group feel confusing or unreliable."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, COMMON_MISTAKES$6.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-amber-300/15 bg-amber-400/10 p-4 text-sm leading-6 text-amber-50/95" }, item)))
  ), /* @__PURE__ */ React.createElement("section", { id: "quick-checklist", className: "scroll-mt-24" }, /* @__PURE__ */ React.createElement(
    QuickstartChecklist,
    {
      title: "Use this before your first Group publish",
      summary: "This is the lightweight completion list you want to be able to say yes to before the Group starts publishing publicly.",
      items: QUICK_CHECKLIST
    }
  )), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "next-steps",
      eyebrow: "Keep going",
      title: "Next steps",
      summary: "Once the first Group exists and the first publish is clear, move into the next surface that helps your team actually operate."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: nextSteps })
  )))));
}
const __vite_glob_0_80 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupQuickstartPage
}, Symbol.toStringTag, { value: "Module" }));
function ArtworkGrid$1({ artworks }) {
  if (!Array.isArray(artworks) || artworks.length === 0) {
    return /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-slate-400" }, "No linked artworks yet.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, artworks.map((artwork) => /* @__PURE__ */ React.createElement("a", { key: artwork.id, href: artwork.url, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 transition hover:border-white/20" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "aspect-[4/3] w-full object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, artwork.author || "Artwork")))));
}
function GroupReleaseShow() {
  const { props } = X$1();
  const group = props.group || {};
  const release = props.release || {};
  const contributors = Array.isArray(release.contributors) ? release.contributors : [];
  const milestones = Array.isArray(release.milestones) ? release.milestones : [];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${release.title || group.name} - Skinbase`, description: release.summary || release.description || group.headline || "Group release" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, release.cover_url ? /* @__PURE__ */ React.createElement("img", { src: release.cover_url, alt: release.title, className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-44 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-sky-200" }, group.name), release.status ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.status) : null, release.current_stage ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.current_stage) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, release.title), release.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, release.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 text-xs text-slate-400" }, release.released_at ? /* @__PURE__ */ React.createElement("span", null, "Released ", new Date(release.released_at).toLocaleDateString()) : null, release.planned_release_at ? /* @__PURE__ */ React.createElement("span", null, "Planned ", new Date(release.planned_release_at).toLocaleDateString()) : null, release.lead?.name || release.lead?.username ? /* @__PURE__ */ React.createElement("span", null, "Lead: ", release.lead?.name || release.lead?.username) : null, /* @__PURE__ */ React.createElement("span", null, release.counts?.artworks || 0, " artworks"), /* @__PURE__ */ React.createElement("span", null, release.counts?.contributors || 0, " contributors"), /* @__PURE__ */ React.createElement("span", null, release.counts?.milestones || 0, " milestones")))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Overview"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, release.description || "No long-form release description yet."), release.release_notes ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Release notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, release.release_notes)) : null, /* @__PURE__ */ React.createElement(ArtworkGrid$1, { artworks: release.artworks })), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Links"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, release.linked_project?.url ? /* @__PURE__ */ React.createElement("a", { href: release.linked_project.url, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, release.linked_project.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Linked project")) : null, release.linked_collection?.url ? /* @__PURE__ */ React.createElement("a", { href: release.linked_collection.url, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, release.linked_collection.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Linked collection")) : null, release.featured_artwork ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, release.featured_artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Featured artwork")) : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, contributors.length > 0 ? contributors.map((contributor) => /* @__PURE__ */ React.createElement("div", { key: contributor.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, contributor.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: contributor.avatar_url, alt: contributor.name || contributor.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, contributor.name || contributor.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, contributor.role_label || "Contributor")))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No contributor credits yet."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, milestones.length > 0 ? milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, milestone.status)), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, milestone.owner?.name || milestone.owner?.username || "No owner", milestone.due_date ? ` • due ${milestone.due_date}` : ""))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No milestones defined yet.")))))));
}
const __vite_glob_0_81 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupReleaseShow
}, Symbol.toStringTag, { value: "Module" }));
function normalizeText(value) {
  return String(value || "").trim().toLowerCase();
}
const MEMBER_ROLE_COLORS = {
  owner: { badge: "border-amber-300/25 bg-amber-400/10 text-amber-100", icon: "fa-crown", iconColor: "text-amber-300" },
  admin: { badge: "border-sky-300/25 bg-sky-400/10 text-sky-100", icon: "fa-shield-halved", iconColor: "text-sky-300" },
  editor: { badge: "border-violet-300/25 bg-violet-400/10 text-violet-100", icon: "fa-pen-nib", iconColor: "text-violet-300" },
  contributor: { badge: "border-emerald-300/25 bg-emerald-400/10 text-emerald-100", icon: "fa-star", iconColor: "text-emerald-300" }
};
const POST_TYPE_ICONS = {
  announcement: { icon: "fa-bullhorn", bar: "from-sky-400/80 to-sky-300/30", bg: "bg-sky-400/10", border: "border-sky-300/20", text: "text-sky-200" },
  update: { icon: "fa-rotate", bar: "from-emerald-400/80 to-emerald-300/30", bg: "bg-emerald-400/10", border: "border-emerald-300/20", text: "text-emerald-200" },
  event: { icon: "fa-calendar-days", bar: "from-violet-400/80 to-violet-300/30", bg: "bg-violet-400/10", border: "border-violet-300/20", text: "text-violet-200" },
  news: { icon: "fa-newspaper", bar: "from-amber-400/80 to-amber-300/30", bg: "bg-amber-400/10", border: "border-amber-300/20", text: "text-amber-200" },
  discussion: { icon: "fa-comments", bar: "from-rose-400/80 to-rose-300/30", bg: "bg-rose-400/10", border: "border-rose-300/20", text: "text-rose-200" },
  tutorial: { icon: "fa-graduation-cap", bar: "from-teal-400/80 to-teal-300/30", bg: "bg-teal-400/10", border: "border-teal-300/20", text: "text-teal-200" }
};
function formatCompactNumber$2(value) {
  return Number(value ?? 0).toLocaleString();
}
function formatDateLabel(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;
  return date.toLocaleDateString("en-US", { month: "long", year: "numeric" });
}
function websiteLabel(url) {
  if (!url) return null;
  try {
    const parsed = new URL(url.startsWith("http") ? url : `https://${url}`);
    return parsed.hostname;
  } catch {
    return String(url).replace(/^https?:\/\//, "");
  }
}
const SECTION_TABS = [
  { id: "overview", label: "Overview", icon: "fa-compass" },
  { id: "artworks", label: "Artworks", icon: "fa-images" },
  { id: "collections", label: "Collections", icon: "fa-layer-group" },
  { id: "posts", label: "Posts", icon: "fa-newspaper" },
  { id: "projects", label: "Projects", icon: "fa-diagram-project" },
  { id: "releases", label: "Releases", icon: "fa-rocket" },
  { id: "challenges", label: "Challenges", icon: "fa-trophy" },
  { id: "events", label: "Events", icon: "fa-calendar-days" },
  { id: "activity", label: "Activity", icon: "fa-bolt" },
  { id: "members", label: "Members", icon: "fa-users" },
  { id: "about", label: "About", icon: "fa-id-card" }
];
function sectionHref(baseUrl, tab2) {
  return tab2 === "overview" ? baseUrl : `${baseUrl}/${tab2}`;
}
function GroupTabs({ baseUrl, activeSection }) {
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-0 z-30 border-b border-white/10 bg-[#08111f]/80 backdrop-blur-2xl" }, /* @__PURE__ */ React.createElement("nav", { className: "overflow-x-auto scrollbar-hide", "aria-label": "Group sections" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex w-max min-w-full gap-2 px-3 py-3 justify-center xl:items-stretch" }, SECTION_TABS.map((tab2) => {
    const isActive = activeSection === tab2.id;
    return /* @__PURE__ */ React.createElement(
      "a",
      {
        key: tab2.id,
        href: sectionHref(baseUrl, tab2.id),
        className: `group relative flex items-center gap-2.5 rounded-2xl border px-3.5 py-3 text-sm font-medium whitespace-nowrap outline-none transition-all duration-150 ${isActive ? "border-sky-300/25 bg-gradient-to-br from-sky-400/18 via-white/[0.06] to-cyan-400/10 text-white shadow-[0_16px_32px_rgba(14,165,233,0.12)]" : "border-white/8 bg-white/[0.03] text-slate-400 hover:border-white/15 hover:bg-white/[0.05] hover:text-slate-100"}`
      },
      /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-9 w-9 items-center justify-center rounded-xl border text-sm ${isActive ? "border-sky-300/20 bg-sky-400/10 text-sky-200" : "border-white/10 bg-white/[0.04] text-slate-500 group-hover:text-slate-300"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} fa-fw` })),
      tab2.label,
      isActive ? /* @__PURE__ */ React.createElement("span", { className: "absolute inset-x-4 bottom-0 h-0.5 rounded-full bg-sky-300 shadow-[0_0_10px_rgba(125,211,252,0.8)]", "aria-hidden": "true" }) : null
    );
  }))));
}
function GroupHero({
  group,
  recruitment,
  trustSignals,
  following,
  followersCount,
  currentJoinRequest,
  shareLabel,
  onToggleFollow,
  onJoinRequest,
  onWithdrawJoinRequest,
  onShare,
  onReport,
  reportEndpoint
}) {
  const activeSignals = Array.isArray(trustSignals) ? trustSignals.slice(0, 3) : [];
  const joinDate = formatDateLabel(group.founded_at || group.created_at);
  const heroStats = [
    { label: "Followers", value: formatCompactNumber$2(followersCount) },
    { label: "Members", value: formatCompactNumber$2(group.counts?.members) },
    { label: "Artworks", value: formatCompactNumber$2(group.counts?.artworks) },
    { label: "Collections", value: formatCompactNumber$2(group.counts?.collections) }
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "relative mx-auto max-w-7xl px-4 pt-4 md:pt-6" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-x-10 top-8 -z-10 h-44 rounded-full blur-3xl",
      style: {
        background: "linear-gradient(90deg, rgba(56,189,248,0.18), rgba(16,185,129,0.14), rgba(59,130,246,0.12))"
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[32px] border border-white/10 bg-[#09111f]/80 shadow-[0_24px_80px_rgba(2,6,23,0.55)]" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "w-full h-[208px] md:h-[248px] xl:h-[288px]",
      style: {
        background: group.banner_url ? `url('${group.banner_url}') center center / cover no-repeat` : "linear-gradient(140deg, #07101d 0%, #0b1726 42%, #07111e 100%)",
        position: "relative"
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 z-20 flex flex-wrap items-center gap-2 md:left-6 md:top-6" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-black/30 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-200 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("span", { className: "h-2 w-2 rounded-full bg-sky-400 shadow-[0_0_12px_rgba(56,189,248,0.9)]" }), "Group profile"), group.is_verified ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-badge-check text-[10px]" }), "Verified") : null, recruitment?.is_recruiting ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-300/10 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-100 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-plus text-[10px]" }), "Recruiting") : null),
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "absolute inset-0",
        style: {
          background: group.banner_url ? "linear-gradient(180deg, rgba(2,6,23,0.16) 0%, rgba(2,6,23,0.28) 38%, rgba(2,6,23,0.9) 100%)" : "radial-gradient(ellipse at 16% 40%, rgba(77,163,255,.18) 0%, transparent 60%), radial-gradient(ellipse at 84% 22%, rgba(16,185,129,.14) 0%, transparent 54%)"
        }
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 opacity-[0.06] pointer-events-none", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "32px" } })
  ), /* @__PURE__ */ React.createElement("div", { className: "relative px-4 pb-6 md:px-7 md:pb-7" }, /* @__PURE__ */ React.createElement("div", { className: "relative -mt-16 flex flex-col gap-5 md:-mt-20 md:flex-row md:items-start md:gap-6" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto z-10 shrink-0 md:mx-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-[112px] w-[112px] items-center justify-center overflow-hidden rounded-[28px] border border-white/15 bg-[#0b1320] shadow-[0_0_0_8px_rgba(9,17,31,0.92),0_22px_44px_rgba(2,6,23,0.5)] md:h-[132px] md:w-[132px]" }, group.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: group.avatar_url, alt: group.name, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-4xl text-slate-300" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 text-center md:text-left" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_430px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-center gap-2 md:justify-start" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-stars text-[10px] text-sky-300" }), "Publishing collective"), group.owner?.username || group.owner?.name ? /* @__PURE__ */ React.createElement("a", { href: group.owner?.profile_url || "#", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300 transition hover:bg-white/[0.08] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-gear text-[10px] text-slate-400" }), "Led by ", group.owner?.username || group.owner?.name) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-[30px] font-semibold leading-tight tracking-[-0.03em] text-white md:text-[42px]" }, group.name), /* @__PURE__ */ React.createElement("p", { className: "mt-1 font-mono text-sm text-slate-400 md:text-[15px]" }, "@", group.slug), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center justify-center gap-2 md:justify-start" }, group.visibility ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300" }, group.visibility) : null, group.status ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300" }, group.status) : null, group.type ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300" }, group.type) : null, joinDate ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days fa-fw text-slate-500" }), "Since ", joinDate) : null, group.website_url ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: group.website_url.startsWith("http") ? group.website_url : `https://${group.website_url}`,
      target: "_blank",
      rel: "nofollow noopener noreferrer",
      className: "inline-flex items-center gap-1.5 rounded-full border border-sky-400/20 bg-sky-400/10 px-3 py-1.5 text-xs text-sky-200 transition-colors hover:border-sky-300/35 hover:bg-sky-400/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link fa-fw" }),
    websiteLabel(group.website_url)
  ) : null), group.headline ? /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-4 max-w-2xl text-sm leading-relaxed text-slate-300/90 md:mx-0 md:text-[15px]" }, group.headline) : null, group.bio ? /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-3xl text-sm leading-relaxed text-slate-400 md:mx-0 line-clamp-3" }, group.bio) : null, activeSignals.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center justify-center gap-2 md:justify-start" }, activeSignals.map((signal) => /* @__PURE__ */ React.createElement("span", { key: signal.key, className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-cyan-300" }), signal.label))) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 xl:pt-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-center gap-2 xl:flex-nowrap xl:justify-end" }, group.urls?.studio ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: group.urls.studio,
      className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl bg-gradient-to-r from-sky-500 to-cyan-400 px-4 py-2.5 text-sm font-semibold text-slate-950 shadow-[0_18px_36px_rgba(14,165,233,0.28)] transition-transform hover:-translate-y-0.5"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles fa-fw" }),
    "Open Studio"
  ) : null, group.urls?.follow ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onToggleFollow,
      className: `inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl border px-4 py-2.5 text-sm font-medium transition-all ${following ? "border-emerald-400/40 bg-emerald-500/12 text-emerald-300 hover:bg-emerald-500/18" : "border-sky-400/40 bg-sky-500/12 text-sky-200 hover:bg-sky-500/20"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${following ? "fa-circle-check" : "fa-user-plus"} fa-fw` }),
    following ? "Following" : "Follow group"
  ) : null, group.permissions?.can_request_join ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onJoinRequest,
      className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl border border-emerald-300/25 bg-emerald-300/10 px-4 py-2.5 text-sm font-medium text-emerald-100 transition hover:bg-emerald-300/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-door-open fa-fw" }),
    "Request to join"
  ) : null, currentJoinRequest?.status === "pending" ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onWithdrawJoinRequest,
      className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark fa-fw" }),
    "Withdraw request"
  ) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onShare,
      className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes fa-fw" }),
    shareLabel
  ), reportEndpoint ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onReport,
      className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag fa-fw" }),
    "Report"
  ) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.72),rgba(9,17,31,0.92))] p-3 text-left shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-2" }, heroStats.map((fact) => /* @__PURE__ */ React.createElement("div", { key: fact.label, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, fact.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold tracking-tight text-white md:text-[15px]" }, fact.value)))), /* @__PURE__ */ React.createElement("div", { className: "mt-2.5 flex flex-wrap items-center gap-2" }, group.owner?.username || group.owner?.name ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-crown text-[10px] text-amber-300" }), "Owner ", group.owner?.username || group.owner?.name) : null, recruitment?.headline ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bullhorn text-[10px] text-sky-300" }), recruitment.headline) : null)))))))));
}
function ArtworkGrid({ artworks, emptyLabel = "No artworks yet." }) {
  if (!Array.isArray(artworks) || artworks.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-col items-center gap-3 rounded-[24px] border border-white/8 bg-white/[0.02] py-10 text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-14 w-14 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images text-2xl" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, emptyLabel));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, artworks.map((artwork) => /* @__PURE__ */ React.createElement("a", { key: artwork.id, href: artwork.url, className: "group relative overflow-hidden rounded-[24px] border border-white/10 bg-black/20 transition hover:border-sky-300/30 hover:shadow-[0_8px_32px_rgba(56,189,248,0.08)]" }, artwork.thumb ? /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden aspect-[4/3]" }, /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-black/50 to-transparent opacity-0 transition group-hover:opacity-100" })) : /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[4/3] items-center justify-center bg-white/[0.03] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-3xl" })), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, artwork.title), artwork.author ? /* @__PURE__ */ React.createElement("span", { className: "mt-2 inline-flex items-center gap-1.5 rounded-full border border-white/8 bg-white/[0.04] px-2.5 py-1 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-pen fa-fw text-slate-500" }), artwork.author) : null))));
}
function CollectionGrid({ collections, emptyLabel = "No collections yet." }) {
  if (!Array.isArray(collections) || collections.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-col items-center gap-3 rounded-[24px] border border-white/8 bg-white/[0.02] py-10 text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-14 w-14 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-2xl" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, emptyLabel));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, collections.map((collection) => /* @__PURE__ */ React.createElement("a", { key: collection.id, href: collection.url, className: "group relative overflow-hidden rounded-[24px] border border-white/10 bg-black/20 p-5 transition hover:border-sky-300/25 hover:shadow-[0_6px_24px_rgba(56,189,248,0.07)]" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[24px] bg-gradient-to-r from-sky-400/70 via-cyan-300/50 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group fa-fw text-sm" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, collection.title), collection.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-sm leading-6 text-slate-300" }, collection.summary || collection.description_excerpt || "Open to explore this collection."))), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex justify-end" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold text-sky-300 opacity-0 transition group-hover:opacity-100" }, "Browse ", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right ml-0.5" }))))));
}
function CompactCardGrid({ items, emptyLabel, badgeKey = "status" }) {
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-col items-center gap-3 rounded-[24px] border border-white/8 bg-white/[0.02] py-10 text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-14 w-14 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-folder-open text-2xl" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, emptyLabel));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, className: "group relative overflow-hidden rounded-[24px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:shadow-[0_6px_24px_rgba(2,6,23,0.4)]" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[24px] bg-gradient-to-r from-violet-400/60 via-sky-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.title), item[badgeKey] ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-white/10 bg-white/[0.06] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item[badgeKey]) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, item.summary || "Open for more details."), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex justify-end" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold text-sky-300 opacity-0 transition group-hover:opacity-100" }, "Open ", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right ml-0.5" }))))));
}
function ReleaseGrid({ releases, emptyLabel = "No public releases yet." }) {
  if (!Array.isArray(releases) || releases.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-col items-center gap-3 rounded-[24px] border border-white/8 bg-white/[0.02] py-10 text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-14 w-14 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket text-2xl" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, emptyLabel));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-5 md:grid-cols-2 xl:grid-cols-3" }, releases.map((release) => /* @__PURE__ */ React.createElement("a", { key: release.id, href: release.url, className: "group relative overflow-hidden rounded-[24px] border border-white/10 bg-black/20 transition hover:border-sky-300/25 hover:shadow-[0_8px_32px_rgba(56,189,248,0.08)]" }, release.cover_url ? /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden aspect-[4/3]" }, /* @__PURE__ */ React.createElement("img", { src: release.cover_url, alt: release.title, className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-3 left-3 flex flex-wrap gap-1.5" }, release.status ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-white backdrop-blur-sm" }, release.status) : null, release.current_stage ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/25 bg-sky-400/20 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100 backdrop-blur-sm" }, release.current_stage) : null)) : /* @__PURE__ */ React.createElement("div", { className: "relative flex aspect-[4/3] items-center justify-center bg-gradient-to-br from-sky-900/30 to-slate-900/40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket text-3xl text-slate-400" }), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-3 left-3 flex flex-wrap gap-1.5" }, release.status ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/50 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-white backdrop-blur-sm" }, release.status) : null, release.current_stage ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/25 bg-sky-400/20 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100 backdrop-blur-sm" }, release.current_stage) : null)), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, release.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-sm leading-6 text-slate-300" }, release.summary || "Release overview and linked artworks."), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-4 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images mr-1.5" }), release.counts?.artworks || 0), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-users mr-1.5" }), release.counts?.contributors || 0), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag-checkered mr-1.5" }), release.counts?.milestones || 0))))));
}
function AssetGrid({ assets, emptyLabel = "No public resources yet." }) {
  if (!Array.isArray(assets) || assets.length === 0) {
    return /* @__PURE__ */ React.createElement("p", { className: "mt-5 text-sm text-slate-400" }, emptyLabel);
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, assets.map((asset) => /* @__PURE__ */ React.createElement("a", { key: asset.id, href: asset.download_url, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, asset.category), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, asset.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, asset.description || "Download this shared group asset."))));
}
function ActivityFeed$1({ items, emptyLabel = "No public activity yet." }) {
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("p", { className: "mt-5 text-sm text-slate-400" }, emptyLabel);
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.headline), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Pinned") : null), item.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, item.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, item.actor?.name || item.actor?.username || "System", " • ", item.occurred_at ? new Date(item.occurred_at).toLocaleString() : "Recently"), item.subject?.url ? /* @__PURE__ */ React.createElement("a", { href: item.subject.url, className: "mt-3 inline-flex text-sm font-semibold text-sky-200" }, "Open") : null)));
}
function LeadershipPreview({ leadership }) {
  if (!Array.isArray(leadership) || leadership.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-amber-400/70 via-yellow-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-amber-300/20 bg-amber-400/10 text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-crown fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/70" }, "Leadership"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Owner and admins"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2" }, leadership.map((member) => {
    const roleKey = String(member.role || "").toLowerCase();
    const roleStyle = MEMBER_ROLE_COLORS[roleKey] || MEMBER_ROLE_COLORS.contributor;
    return /* @__PURE__ */ React.createElement("a", { key: member.id, href: member.profile_url || "#", className: "group flex items-center gap-3 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4 transition hover:border-white/20 hover:bg-white/[0.04]" }, member.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.avatar_url, alt: member.name || member.username, className: "h-12 w-12 shrink-0 rounded-2xl object-cover ring-1 ring-white/10 transition group-hover:ring-white/20" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.name || member.username), /* @__PURE__ */ React.createElement("div", { className: `mt-1 inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${roleStyle.badge}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${roleStyle.icon} fa-fw text-[9px]` }), member.role_label || member.role)));
  })));
}
function FocusCard({ eyebrow, item, badgeKey = "status", ctaLabel }) {
  if (!item?.title) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, eyebrow), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, item.title), item[badgeKey] ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item[badgeKey]) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, item.summary || "Open for more details."), /* @__PURE__ */ React.createElement("a", { href: item.url, className: "mt-4 inline-flex rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, ctaLabel));
}
function TrustSignalPanel({ signals }) {
  if (!Array.isArray(signals) || signals.length === 0) {
    return null;
  }
  const TONE_STYLES2 = {
    sky: { badge: "border-sky-300/20 bg-sky-300/10 text-sky-100", dot: "bg-sky-400", bar: "from-sky-400/70 to-transparent" },
    emerald: { badge: "border-emerald-300/20 bg-emerald-300/10 text-emerald-100", dot: "bg-emerald-400", bar: "from-emerald-400/70 to-transparent" },
    amber: { badge: "border-amber-300/20 bg-amber-300/10 text-amber-100", dot: "bg-amber-400", bar: "from-amber-400/70 to-transparent" },
    violet: { badge: "border-violet-300/20 bg-violet-300/10 text-violet-100", dot: "bg-violet-400", bar: "from-violet-400/70 to-transparent" }
  };
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-check fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Trust signals"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "How this group shows up"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, signals.map((signal) => {
    const ts = TONE_STYLES2[signal.tone] || { badge: "border-white/10 bg-white/[0.04] text-white", dot: "bg-slate-400" };
    return /* @__PURE__ */ React.createElement("span", { key: signal.key, className: `inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[11px] font-semibold ${ts.badge}` }, /* @__PURE__ */ React.createElement("span", { className: `h-1.5 w-1.5 rounded-full ${ts.dot}` }), signal.label);
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, signals.map((signal) => {
    const ts = TONE_STYLES2[signal.tone] || { badge: "border-white/10 bg-white/[0.02] text-white", bar: "from-slate-400/40 to-transparent" };
    return /* @__PURE__ */ React.createElement("div", { key: `${signal.key}-reason`, className: "relative overflow-hidden rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[2px] rounded-t-2xl bg-gradient-to-r ${ts.bar}` }), /* @__PURE__ */ React.createElement("div", { className: `text-sm font-semibold ${ts.badge.includes("text-") ? ts.badge.split(" ").find((c) => c.startsWith("text-")) : "text-white"}` }, signal.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-sm leading-6 text-slate-400" }, signal.reason));
  })));
}
function BadgeShowcase({ badges }) {
  if (!Array.isArray(badges) || badges.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-amber-400/70 via-yellow-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-amber-300/20 bg-amber-400/10 text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-medal fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, "Badges"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Earned group signals"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3" }, badges.map((badge) => /* @__PURE__ */ React.createElement("div", { key: badge.key, className: "relative overflow-hidden rounded-2xl border border-amber-300/10 bg-amber-400/5 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-y-0 left-0 w-[3px] rounded-l-2xl bg-gradient-to-b from-amber-400/70 to-amber-300/20" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-certificate text-amber-300/70" }), /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, badge.label)), badge.awarded_at ? /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, new Date(badge.awarded_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-sm leading-6 text-slate-400" }, badge.reason)))));
}
function ContributorHighlights({ contributors }) {
  if (!Array.isArray(contributors) || contributors.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-emerald-400/70 via-teal-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-emerald-300/20 bg-emerald-400/10 text-emerald-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-star fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-emerald-200/70" }, "Contributors"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Trusted collaborators"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, contributors.map((entry) => /* @__PURE__ */ React.createElement("a", { key: entry.user?.id, href: entry.user?.profile_url || "#", className: "group flex gap-3 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4 transition hover:border-emerald-300/20 hover:bg-white/[0.04]" }, entry.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: entry.user.avatar_url, alt: entry.user?.name || entry.user?.username, className: "h-12 w-12 shrink-0 rounded-2xl object-cover ring-1 ring-white/10 transition group-hover:ring-emerald-300/20" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, entry.user?.name || entry.user?.username), entry.trusted_indicator ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1 rounded-full border border-emerald-300/20 bg-emerald-300/10 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-check text-[9px]" }), "Trusted") : null), entry.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, entry.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center gap-3 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket mr-1" }), entry.counts?.releases || 0), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images mr-1" }), entry.counts?.credited_artworks || 0), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-diagram-project mr-1" }), entry.counts?.projects || 0)), Array.isArray(entry.badges) && entry.badges.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-1.5" }, entry.badges.slice(0, 3).map((badge) => /* @__PURE__ */ React.createElement("span", { key: `${entry.user?.id}-${badge.key}`, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, badge.label))) : null)))));
}
function csrfToken$2() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function GroupShow() {
  const { props } = X$1();
  const group = props.group || {};
  const section = props.section || "overview";
  const featuredArtworks = Array.isArray(props.featuredArtworks) ? props.featuredArtworks : [];
  const artworks = Array.isArray(props.artworks) ? props.artworks : [];
  const featuredCollections = Array.isArray(props.featuredCollections) ? props.featuredCollections : [];
  const collections = Array.isArray(props.collections) ? props.collections : [];
  const posts = Array.isArray(props.posts) ? props.posts : [];
  const projects = Array.isArray(props.projects) ? props.projects : [];
  const releases = Array.isArray(props.releases) ? props.releases : [];
  const challenges = Array.isArray(props.challenges) ? props.challenges : [];
  const events = Array.isArray(props.events) ? props.events : [];
  const assets = Array.isArray(props.assets) ? props.assets : [];
  const activity = Array.isArray(props.activity) ? props.activity : [];
  const recruitment = props.recruitment || null;
  const currentJoinRequest = group.current_join_request || null;
  const leadership = Array.isArray(props.leadership) ? props.leadership : [];
  const members = Array.isArray(props.members) ? props.members : [];
  const topContributors = Array.isArray(props.topContributors) ? props.topContributors : [];
  const trustSignals = Array.isArray(props.trustSignals) ? props.trustSignals : [];
  const badgeShowcase = Array.isArray(props.badgeShowcase) ? props.badgeShowcase : [];
  const [following, setFollowing] = reactExports.useState(Boolean(group.viewer?.is_following));
  const [followersCount, setFollowersCount] = reactExports.useState(Number(group.counts?.followers || 0));
  const [shareLabel, setShareLabel] = reactExports.useState("Share");
  const [artworkQuery, setArtworkQuery] = reactExports.useState("");
  const [artworkSort, setArtworkSort] = reactExports.useState("latest");
  const contentShellClassName = section === "artworks" ? "mx-auto max-w-7xl px-4 md:px-6" : section === "overview" || section === "posts" ? "mx-auto max-w-7xl px-4 md:px-6" : "mx-auto max-w-6xl px-4";
  const filteredArtworks = artworks.filter((artwork) => {
    const q2 = normalizeText(artworkQuery);
    if (!q2) return true;
    return normalizeText(artwork.title).includes(q2) || normalizeText(artwork.author).includes(q2);
  }).sort((left, right) => {
    if (artworkSort === "oldest") {
      return new Date(left.published_at || 0).getTime() - new Date(right.published_at || 0).getTime();
    }
    if (artworkSort === "title") {
      return String(left.title || "").localeCompare(String(right.title || ""));
    }
    return new Date(right.published_at || 0).getTime() - new Date(left.published_at || 0).getTime();
  });
  const groupedMembers = {
    owner: members.filter((member) => member.role === "owner"),
    admins: members.filter((member) => member.role === "admin"),
    editors: members.filter((member) => member.role === "editor"),
    contributors: members.filter((member) => member.role !== "owner" && member.role !== "admin" && member.role !== "editor")
  };
  const { share } = useWebShare({
    onFallback: async ({ url }) => {
      if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
        await navigator.clipboard.writeText(url);
        setShareLabel("Link copied");
        window.setTimeout(() => setShareLabel("Share"), 2e3);
        return;
      }
      window.prompt("Copy this link", url);
    }
  });
  const submitReport = async () => {
    if (!props.reportEndpoint) return;
    const reason = window.prompt("Reason for reporting this group?");
    if (!reason) return;
    await fetch(props.reportEndpoint, {
      method: "POST",
      credentials: "same-origin",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRF-TOKEN": csrfToken$2()
      },
      body: JSON.stringify({ target_type: "group", target_id: group.id, reason })
    });
  };
  const toggleFollow = async () => {
    const response = await fetch(following ? group.urls?.unfollow : group.urls?.follow, {
      method: following ? "DELETE" : "POST",
      credentials: "same-origin",
      headers: {
        Accept: "application/json",
        "X-Requested-With": "XMLHttpRequest",
        "X-CSRF-TOKEN": csrfToken$2()
      }
    });
    const payload = await response.json().catch(() => ({}));
    if (response.ok) {
      setFollowing(Boolean(payload?.following));
      setFollowersCount(Number(payload?.followers_count || 0));
    }
  };
  const handleShare = async () => {
    const url = group.urls?.public || (typeof window !== "undefined" ? window.location.href : "");
    await share({
      title: `${group.name} on Skinbase`,
      text: group.headline || group.bio || "Check out this Skinbase group.",
      url
    });
  };
  const submitJoinRequest = async () => {
    const message = window.prompt("Why do you want to join this group?") || "";
    const desiredRole = window.prompt("Desired role: contributor, editor, or admin", "contributor") || "contributor";
    At.post(group.urls?.join_request_store, { message, desired_role: desiredRole });
  };
  const withdrawJoinRequest = async () => {
    if (!currentJoinRequest?.id || !group.urls?.join_request_withdraw_pattern) return;
    At.delete(group.urls.join_request_withdraw_pattern.replace("__JOIN_REQUEST__", String(currentJoinRequest.id)));
  };
  return /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${group.name} - Skinbase`, description: group.headline || group.bio || "Skinbase group" }), /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-90",
      style: {
        background: "radial-gradient(circle at top left, rgba(56,189,248,0.18), transparent 32%), radial-gradient(circle at 82% 10%, rgba(16,185,129,0.16), transparent 28%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #0a1220 100%)"
      }
    }
  ), /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.06]",
      style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" }
    }
  ), /* @__PURE__ */ React.createElement(
    GroupHero,
    {
      group,
      recruitment,
      trustSignals,
      following,
      followersCount,
      currentJoinRequest,
      shareLabel,
      onToggleFollow: toggleFollow,
      onJoinRequest: submitJoinRequest,
      onWithdrawJoinRequest: withdrawJoinRequest,
      onShare: handleShare,
      onReport: submitReport,
      reportEndpoint: props.reportEndpoint
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(GroupTabs, { baseUrl: group.urls?.public || "/groups", activeSection: section })), /* @__PURE__ */ React.createElement("div", { className: `${contentShellClassName} pt-6` }, section === "overview" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-8" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-amber-400/70 via-yellow-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-amber-300/20 bg-amber-400/10 text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-star fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/70" }, "Highlights"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Featured artworks"))), /* @__PURE__ */ React.createElement("a", { href: `${group.urls?.public}/artworks`, className: "text-sm font-semibold text-sky-200 transition hover:text-sky-100" }, "Browse all")), /* @__PURE__ */ React.createElement(ArtworkGrid, { artworks: featuredArtworks, emptyLabel: "No featured artworks yet." })), /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Latest work"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Latest artworks"))), /* @__PURE__ */ React.createElement("a", { href: `${group.urls?.public}/artworks`, className: "text-sm font-semibold text-sky-200 transition hover:text-sky-100" }, "View archive")), /* @__PURE__ */ React.createElement(ArtworkGrid, { artworks: artworks.slice(0, 6), emptyLabel: "No published artworks yet." })), /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-violet-400/70 via-sky-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-violet-300/20 bg-violet-400/10 text-violet-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-violet-200/70" }, "Pipeline"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent releases"))), /* @__PURE__ */ React.createElement("a", { href: `${group.urls?.public}/releases`, className: "text-sm font-semibold text-sky-200 transition hover:text-sky-100" }, "View releases")), /* @__PURE__ */ React.createElement(ReleaseGrid, { releases: releases.slice(0, 3), emptyLabel: "No public releases yet." })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Curated"), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Featured collections"))), /* @__PURE__ */ React.createElement("a", { href: `${group.urls?.public}/collections`, className: "text-sm font-semibold text-sky-200 transition hover:text-sky-100" }, "View collections")), /* @__PURE__ */ React.createElement(CollectionGrid, { collections: featuredCollections.length > 0 ? featuredCollections : collections.slice(0, 2), emptyLabel: "No featured collections yet." })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8" }, group.pinned_post ? /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-amber-300/15 bg-amber-400/5 p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-amber-400/80 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-9 w-9 items-center justify-center rounded-[14px] border border-amber-300/20 bg-amber-400/10 text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-thumbtack fa-fw text-sm" })), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, "Pinned post")), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-xl font-semibold text-white" }, group.pinned_post.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-amber-50/80" }, group.pinned_post.excerpt || "Read the latest pinned update from this group."), /* @__PURE__ */ React.createElement("a", { href: group.pinned_post.url, className: "mt-4 inline-flex items-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open fa-fw" }), "Read post")) : null, /* @__PURE__ */ React.createElement(FocusCard, { eyebrow: "Releases", item: group.featured_release, badgeKey: "current_stage", ctaLabel: "Open release" }), /* @__PURE__ */ React.createElement(FocusCard, { eyebrow: "Projects", item: group.featured_project, ctaLabel: "Open project" }), /* @__PURE__ */ React.createElement(FocusCard, { eyebrow: "Challenges", item: group.active_challenge, ctaLabel: "View challenge" }), /* @__PURE__ */ React.createElement(FocusCard, { eyebrow: "Events", item: group.upcoming_event, badgeKey: "event_type", ctaLabel: "View event" }), /* @__PURE__ */ React.createElement(LeadershipPreview, { leadership }), /* @__PURE__ */ React.createElement(TrustSignalPanel, { signals: trustSignals }), /* @__PURE__ */ React.createElement(BadgeShowcase, { badges: badgeShowcase }), /* @__PURE__ */ React.createElement(ContributorHighlights, { contributors: topContributors.slice(0, 4) }), recruitment?.is_recruiting ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-emerald-300/20 bg-emerald-400/10 p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-emerald-100/80" }, "Recruiting"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, recruitment.headline || `${group.name} is looking for collaborators`), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-emerald-50/90" }, recruitment.description || "This group is currently open to new contributors."), Array.isArray(recruitment.roles) && recruitment.roles.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, recruitment.roles.map((role) => /* @__PURE__ */ React.createElement("span", { key: role, className: "rounded-full border border-white/10 bg-white/[0.08] px-3 py-1.5 text-xs font-semibold text-white" }, role))) : null) : null, /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-teal-400/70 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-9 w-9 items-center justify-center rounded-[14px] border border-teal-300/20 bg-teal-400/10 text-teal-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-download fa-fw text-sm" })), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-teal-200/70" }, "Resources")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Shared downloads"), /* @__PURE__ */ React.createElement(AssetGrid, { assets: assets.slice(0, 3) })), /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-9 w-9 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bolt fa-fw text-sm" })), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Public feed")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Recent activity"), /* @__PURE__ */ React.createElement(ActivityFeed$1, { items: activity.slice(0, 4) })), /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-slate-400/50 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-9 w-9 items-center justify-center rounded-[14px] border border-white/10 bg-white/[0.05] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-id-card fa-fw text-sm" })), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400/80" }, "About")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "About ", group.name), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, group.bio || "No long-form description yet."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3 text-xs text-slate-400" }, group.founded_at ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days text-slate-500" }), "Founded ", new Date(group.founded_at).toLocaleDateString()) : null, group.type ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tag text-slate-500" }), group.type) : null, group.website_url ? /* @__PURE__ */ React.createElement("a", { href: group.website_url, className: "inline-flex items-center gap-1.5 text-sky-200 underline underline-offset-4 transition hover:text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link" }), "Website") : null))))) : null, section === "artworks" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Artworks"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Filter the group archive by title or contributor credit label, then change the sort order."))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: artworkQuery, onChange: (event) => setArtworkQuery(event.target.value), placeholder: "Filter artworks", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Sort"), /* @__PURE__ */ React.createElement(NovaSelect, { value: artworkSort, onChange: (val) => setArtworkSort(val), searchable: false, options: [{ value: "latest", label: "Latest first" }, { value: "oldest", label: "Oldest first" }, { value: "title", label: "Title A-Z" }] })))), /* @__PURE__ */ React.createElement(ArtworkGrid, { artworks: filteredArtworks, emptyLabel: "No published artworks match the current filter." })) : null, section === "collections" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group fa-fw" })), /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Collections")), /* @__PURE__ */ React.createElement(CollectionGrid, { collections, emptyLabel: "No collections yet." })) : null, section === "posts" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center gap-4" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-newspaper fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Group updates"), /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Posts"))), posts.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, posts.map((post2) => {
    const typeKey = String(post2.type || "").toLowerCase();
    const typeStyle = POST_TYPE_ICONS[typeKey] || POST_TYPE_ICONS.announcement;
    return /* @__PURE__ */ React.createElement("a", { key: post2.id, href: post2.url, className: "group relative overflow-hidden rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:shadow-[0_8px_24px_rgba(2,6,23,0.4)]" }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[3px] rounded-t-[28px] bg-gradient-to-r ${typeStyle.bar}` }), /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("span", { className: `shrink-0 inline-flex h-10 w-10 items-center justify-center rounded-[14px] border ${typeStyle.border} ${typeStyle.bg} ${typeStyle.text}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${typeStyle.icon} fa-fw` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `text-[10px] font-semibold uppercase tracking-[0.18em] ${typeStyle.text}` }, post2.type || "post"), post2.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1 rounded-full border border-amber-300/20 bg-amber-400/10 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-thumbtack text-[9px]" }), "Pinned") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-1.5 text-base font-semibold text-white" }, post2.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-sm leading-6 text-slate-300" }, post2.excerpt || "Open the post to read more."))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex justify-end" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold text-sky-300 opacity-0 transition group-hover:opacity-100" }, "Read post ", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right ml-0.5" }))));
  })) : /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center gap-4 rounded-[32px] border border-white/8 bg-white/[0.02] py-16 text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-16 w-16 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-newspaper text-3xl" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-slate-300" }, "No posts published yet."), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-500" }, "Check back later for group updates and announcements.")))) : null, section === "projects" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-violet-400/70 via-sky-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-violet-300/20 bg-violet-400/10 text-violet-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-diagram-project fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Projects"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Structured releases, collaboration hubs, and production pages published by this group."))), /* @__PURE__ */ React.createElement(CompactCardGrid, { items: projects, emptyLabel: "No public projects yet." })) : null, section === "releases" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Releases"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Published drops, milestone pipelines, and linked showcases from this group."))), /* @__PURE__ */ React.createElement(ReleaseGrid, { releases, emptyLabel: "No public releases yet." })) : null, section === "challenges" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-amber-400/70 via-yellow-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-amber-300/20 bg-amber-400/10 text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Challenges"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Current and past prompts, internal sprints, and public-facing challenge runs."))), /* @__PURE__ */ React.createElement(CompactCardGrid, { items: challenges, emptyLabel: "No public challenges yet." })) : null, section === "events" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-violet-400/70 via-sky-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-violet-300/20 bg-violet-400/10 text-violet-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Events"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Launches, milestones, streams, and other moments on the group timeline."))), /* @__PURE__ */ React.createElement(CompactCardGrid, { items: events, emptyLabel: "No public events yet.", badgeKey: "event_type" })) : null, section === "activity" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-sky-400/70 via-cyan-300/40 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bolt fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Activity"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Public milestones from posts, releases, events, member changes, and challenge highlights."))), /* @__PURE__ */ React.createElement(ActivityFeed$1, { items: activity })) : null, section === "members" ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center gap-4" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-sky-300/20 bg-sky-400/10 text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-users fa-fw" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Community"), /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Members"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6" }, [
    ["Owner", "owner", groupedMembers.owner],
    ["Admins", "admin", groupedMembers.admins],
    ["Editors", "editor", groupedMembers.editors],
    ["Contributors", "contributor", groupedMembers.contributors]
  ].map(([label, roleKey, bucket]) => {
    if (bucket.length === 0) return null;
    const roleStyle = MEMBER_ROLE_COLORS[roleKey] || MEMBER_ROLE_COLORS.contributor;
    return /* @__PURE__ */ React.createElement("section", { key: label, className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r ${roleKey === "owner" ? "from-amber-400/70 to-transparent" : roleKey === "admin" ? "from-sky-400/70 to-transparent" : roleKey === "editor" ? "from-violet-400/70 to-transparent" : "from-emerald-400/70 to-transparent"}` }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-8 w-8 items-center justify-center rounded-xl border ${roleStyle.badge}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${roleStyle.icon} fa-fw text-sm ${roleStyle.iconColor}` })), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, label), /* @__PURE__ */ React.createElement("span", { className: "ml-auto rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, bucket.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, bucket.map((member) => /* @__PURE__ */ React.createElement("a", { key: member.id, href: member.user?.profile_url || "#", className: "group flex items-center gap-3 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4 transition hover:border-white/20 hover:bg-white/[0.04]" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-12 w-12 shrink-0 rounded-2xl object-cover ring-1 ring-white/10 transition group-hover:ring-white/20" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: `mt-1 inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${roleStyle.badge}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${roleStyle.icon} fa-fw text-[9px]` }), member.role_label || member.role))))));
  }))) : null, section === "about" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-slate-400/50 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-white/10 bg-white/[0.05] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-id-card fa-fw" })), /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "About")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4 text-sm leading-7 text-slate-300" }, /* @__PURE__ */ React.createElement("p", null, group.bio || "No long-form description yet."), group.website_url ? /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("a", { href: group.website_url, className: "inline-flex items-center gap-1.5 text-sky-200 underline underline-offset-4 transition hover:text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link" }), group.website_url)) : null, Array.isArray(group.links) && group.links.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, group.links.map((link2) => /* @__PURE__ */ React.createElement("a", { key: `${link2.label}-${link2.url}`, href: link2.url, className: "inline-flex items-center gap-2 rounded-[14px] border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-400" }), link2.label))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 border-t border-white/8 pt-4 text-xs text-slate-400" }, group.founded_at ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days text-slate-500" }), "Founded ", new Date(group.founded_at).toLocaleDateString()) : null, group.type ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tag text-slate-500" }), group.type) : null))) : null));
}
const __vite_glob_0_82 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: GroupShow
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$7 = [
  { id: "what-account-help-covers", label: "What this covers" },
  { id: "settings-areas", label: "Settings areas" },
  { id: "email-and-password", label: "Email and password" },
  { id: "profile-and-preferences", label: "Profile and preferences" },
  { id: "maintenance-habits", label: "Maintenance habits" },
  { id: "faq", label: "FAQ" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS$7 = [
  {
    label: "Best use case",
    value: "Access works, settings need attention",
    note: "This guide starts after login succeeds and you need help managing the account instead of regaining it."
  },
  {
    label: "Main surface",
    value: "Dashboard profile settings",
    note: "Most account, profile, notification, and password changes flow through the main settings area tied to your creator identity."
  },
  {
    label: "Common confusion",
    value: "Settings issue vs access issue",
    note: "A surprising number of “account problems” are really login, verification, or troubleshooting problems wearing a different label."
  }
];
const COVERAGE_ITEMS = [
  {
    title: "Account help is broader than login help",
    body: "Use this page when you are already in the account, or know how to get back into it, and need guidance for settings, identity details, preferences, or maintenance."
  },
  {
    title: "Settings shape both behavior and presentation",
    body: "Account choices affect how your public identity reads, how notifications reach you, and how safely you can recover or maintain access over time."
  },
  {
    title: "Not every question belongs in one settings panel",
    body: "Some issues live in profile setup, some in security and email care, and some in creator workflow pages such as Studio. Separating those questions keeps fixes faster."
  }
];
const SETTINGS_AREA_ITEMS = [
  {
    title: "Profile and public identity",
    body: "This is where presentation work matters most: avatar, bio, creator-facing details, and the way other people understand you when they land on the profile."
  },
  {
    title: "Account basics and email changes",
    body: "Your account email needs to stay current because recovery, verification, and important notices depend on it reaching the right inbox."
  },
  {
    title: "Security and password care",
    body: "Password updates and basic security hygiene belong to account maintenance, not crisis mode. They are easier to handle before something breaks."
  },
  {
    title: "Notifications and personal preferences",
    body: "Notification settings decide how noisy or quiet the platform feels. Personal details and preference changes can make the account feel more stable day to day."
  }
];
const EMAIL_PASSWORD_STEPS = [
  {
    title: "Open account settings intentionally",
    description: "Start from the authenticated settings surface instead of hunting for one-off forms across the product. That keeps related account changes in one place."
  },
  {
    title: "Confirm you are editing the correct account",
    description: "This matters most if you manage more than one identity, recently switched devices, or are returning after a recovery flow."
  },
  {
    title: "Change the minimum necessary fields carefully",
    description: "When updating email or password, reduce avoidable mistakes by changing one sensitive area at a time and confirming the result before moving on."
  },
  {
    title: "Watch for follow-up verification or confirmation",
    description: "Email-related changes often require a follow-up message or verification step. Do not assume the change finished until that path is complete."
  },
  {
    title: "Return to troubleshooting only if something blocks the change",
    description: "If an update fails, diagnose that failure directly instead of treating every blocked settings action as a generic login issue."
  }
];
const PROFILE_PREFERENCE_ITEMS = [
  "Keep your avatar, display details, and short bio current enough that the profile still feels like you.",
  "Use profile settings for public identity questions and the auth guide for account-entry questions so you do not mix two different problem types.",
  "Trim notification noise deliberately instead of turning everything on and then missing what actually matters.",
  "Treat personal details, messaging preferences, and creator-facing settings as maintenance work rather than last-minute cleanup."
];
const MAINTENANCE_HABITS = [
  "Keep the account email reachable so resets, verification, and important notices do not disappear into an abandoned inbox.",
  "Update passwords proactively when something feels off instead of waiting for a failure moment.",
  "Review settings after major workflow changes such as new devices, new collaboration patterns, or a shift in what you publish publicly.",
  "Use troubleshooting only when the settings surface feels blocked or broken, not for normal questions the guide can answer directly."
];
const FAQ_ITEMS$7 = [
  {
    question: "What is the difference between auth help and account help?",
    answer: "Auth help is about getting into the account. Account help is about what you manage after access works, such as settings, identity details, notifications, and password care."
  },
  {
    question: "Where should I change my profile details?",
    answer: "Use the main profile settings surface for public identity details such as avatar, bio, and related creator-facing information."
  },
  {
    question: "Where should I change my password?",
    answer: "Use the authenticated account settings surface for password changes. If you cannot reach that surface because access failed, switch to the auth help and recovery path instead."
  },
  {
    question: "What if changing email or password does not work?",
    answer: "Move into the troubleshooting page if the settings flow appears blocked, broken, or inconsistent instead of assuming the whole account is unusable."
  },
  {
    question: "Does account help replace profile help?",
    answer: "No. Profile help goes deeper on public identity and presentation. Account help stays broader and covers the settings side of maintaining the account over time."
  }
];
const RELATED_HELP_ITEMS$7 = [
  {
    eyebrow: "Access",
    title: "Signup and login help",
    body: "Use the auth guide when the problem is getting into the account at all rather than maintaining it after access succeeds.",
    linkKey: "help_auth",
    tone: "sky"
  },
  {
    eyebrow: "Identity",
    title: "Profile help",
    body: "Use the profile guide when the question is more about public identity, creator presentation, and what visitors actually see.",
    linkKey: "help_profile",
    tone: "white"
  },
  {
    eyebrow: "Fixes fast",
    title: "Troubleshooting help",
    body: "Use the troubleshooting page when settings actions feel blocked, inconsistent, or clearly broken and you need diagnosis first.",
    linkKey: "help_troubleshooting",
    tone: "amber"
  },
  {
    eyebrow: "Workflow",
    title: "Studio help",
    body: "Use the Studio guide when the issue stops being about the account itself and starts living in drafts, publishing, or creator workflows.",
    linkKey: "studio_help",
    tone: "white"
  }
];
function HeroMetric$7({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function InsightCard$5({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function BulletGrid$7({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function AccountHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const signedIn = Boolean(props.auth?.signed_in);
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Account Settings Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Account settings", "Profile settings", "Password changes", "Email changes", "Preferences"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$7.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$7.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_22%),radial-gradient(circle_at_bottom_right,_rgba(34,197,94,0.12),_transparent_20%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(74,222,128,0.14),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-emerald-200/80" }, "Account settings help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Account settings should feel like steady maintenance, not a maze you only visit when something is already on fire."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "Use this page when access already works and you need clearer guidance for profile settings, account details, email and password care, notifications, and the ongoing habits that keep the account easier to manage."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: signedIn ? links.profile_settings : links.login, className: "rounded-full border border-emerald-300/25 bg-emerald-300/12 px-5 py-3 text-sm font-semibold text-emerald-100 transition hover:border-emerald-300/40 hover:bg-emerald-300/18" }, signedIn ? "Open account settings" : "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Read auth help"), /* @__PURE__ */ React.createElement("a", { href: links.help_troubleshooting, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open troubleshooting"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$7.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$7, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$7, ariaLabel: "Account help sections", selectLabel: "Jump to account help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-account-help-covers",
      eyebrow: "Scope",
      title: "What account help covers",
      summary: "Account help sits between pure access recovery and deeper module-specific workflow guides. It is for the practical middle ground where the account works, but the settings still need attention."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, COVERAGE_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$5, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "settings-areas",
      eyebrow: "Areas",
      title: "The settings areas that matter most",
      summary: "Most account questions fall into a few repeat categories. Naming the category first makes the right next step much easier to see."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, SETTINGS_AREA_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$5, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "A useful way to think about settings" }, "Settings are not only administrative. They control recovery, trust, profile clarity, and how manageable the creator experience feels over time."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "email-and-password",
      eyebrow: "Sensitive changes",
      title: "Email and password changes",
      summary: "Treat identity and security changes carefully. These are not hard tasks, but they are the least forgiving when rushed."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: EMAIL_PASSWORD_STEPS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "profile-and-preferences",
      eyebrow: "Daily use",
      title: "Profile and preference maintenance",
      summary: "The account feels healthier when profile details, notification choices, and other core preferences stay aligned with how you actually use the platform."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$7, { items: PROFILE_PREFERENCE_ITEMS, tone: "sky" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "maintenance-habits",
      eyebrow: "Good habits",
      title: "Maintenance habits that prevent bigger problems",
      summary: "The easiest account problems to fix are the ones that never turn into a crisis because the basics stayed current."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$7, { items: MAINTENANCE_HABITS, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Account settings FAQ",
      summary: "These answers cover the common point where access is fine, but settings and maintenance still feel unclear."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$7 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these guides when the account question turns back into access recovery, identity presentation, faster troubleshooting, or broader creator workflow help."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: signedIn ? links.profile_settings : links.login, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, signedIn ? "Open account settings" : "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read auth help"), /* @__PURE__ */ React.createElement("a", { href: links.help_profile, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Profile help"), /* @__PURE__ */ React.createElement("a", { href: links.help_troubleshooting, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open troubleshooting"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-emerald-300/20 bg-emerald-400/10 p-4 text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-emerald-50/85" }, "The healthiest account is the one with a current email, a manageable password, and settings reviewed before they become emergency work.")))))));
}
const __vite_glob_0_83 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AccountHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$6 = [
  { id: "creating-an-account", label: "Creating an account" },
  { id: "logging-in", label: "Logging in" },
  { id: "password-reset-recovery", label: "Password reset / recovery" },
  { id: "access-and-verification", label: "Access and verification basics" },
  { id: "safety-and-protection", label: "Safety and protection" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS$6 = [
  {
    label: "What this unlocks",
    value: "Identity and workspace access",
    note: "Signup and login are how you reach your profile, enter Studio, and manage the rest of your creator workflow on Skinbase."
  },
  {
    label: "Most common blocker",
    value: "Recovery and verification confusion",
    note: "Many access problems are solved by the right recovery step, the right email, or a quick check of what the account is still waiting for."
  },
  {
    label: "Golden rule",
    value: "Slow down and check the basics",
    note: "The fastest fix usually comes from verifying the email, password, inbox, or permissions question before assuming the whole account is broken."
  }
];
const SIGNUP_STEPS = [
  {
    title: "Open signup",
    description: "Start from the account creation flow rather than trying to enter the platform through a sign-in screen that expects an existing account."
  },
  {
    title: "Enter the required details carefully",
    description: "Use the email address you actually want tied to your Skinbase identity and choose account details you can remember and manage later."
  },
  {
    title: "Create the account",
    description: "Finish the signup step, then watch for any confirmation or verification message the account may still need before it is fully usable."
  },
  {
    title: "Verify if required",
    description: "Some flows may ask you to confirm access through email or verification before certain parts of the platform open up completely."
  },
  {
    title: "Continue into profile setup or the platform",
    description: "Once access is working, the next useful step is usually profile setup, Studio access, or your first publishing workflow."
  }
];
const LOGIN_STEPS = [
  {
    title: "Open login",
    description: "Go to the sign-in flow when you already have an account and want to return to your Skinbase identity and creator tools."
  },
  {
    title: "Enter your credentials carefully",
    description: "Use the same email and password combination tied to the account you actually want to access. Small mismatches cause a surprising number of login problems."
  },
  {
    title: "Enter the platform",
    description: "A successful login takes you back into your account so you can continue to Studio, profile settings, and your other authenticated creator surfaces."
  },
  {
    title: "Use remembered sessions carefully",
    description: "If the device is personal, remembered sessions can save time. If it is shared, log out when you are done instead of leaving account access open."
  }
];
const RECOVERY_STEPS = [
  {
    title: "Open password recovery",
    description: "If you forgot the password, start with the reset flow instead of guessing repeatedly until you get locked into more confusion."
  },
  {
    title: "Request the reset message",
    description: "Enter the email you believe is tied to the account and let the recovery flow send the reset instructions."
  },
  {
    title: "Check the right inbox",
    description: "Look in spam, promotions, or other folders if the message does not show up immediately. Wrong inboxes and old emails are common causes of panic."
  },
  {
    title: "Finish the reset with a new password",
    description: "Choose a password you can manage safely and use the new credentials when returning to the login flow."
  }
];
const ACCESS_BASICS_ITEMS = [
  {
    title: "Verification can affect access",
    body: "Some accounts may still need email confirmation or another verification step before every feature behaves the way a fully active account would expect."
  },
  {
    title: "Access problems are not always login problems",
    body: "You can be logged in and still hit limits caused by verification state, incomplete setup, or permissions inside a Group or shared workflow."
  },
  {
    title: "Permissions and account access are different things",
    body: "Entering the account is not the same as having permission inside every collaboration surface. Group roles and approvals can still control what you see or can do."
  }
];
const SAFETY_ITEMS = [
  "Use a strong password that you are not reusing everywhere else.",
  "Do not share your credentials, even with collaborators or friends who work with you on Groups.",
  "Keep the account email current so recovery messages can actually reach you.",
  "Log out on shared devices instead of trusting remembered sessions in public or borrowed spaces.",
  "Review account and security-related settings when something about access changes or starts to feel off."
];
const COMMON_MISTAKES$5 = [
  "Signing up with the wrong email and then waiting for messages in a different inbox.",
  "Forgetting which credentials or login method belong to the account you are trying to access.",
  "Waiting for a reset or verification email while checking the wrong folder or wrong email account.",
  "Trying an outdated password repeatedly instead of moving directly into recovery.",
  "Assuming a Group or Profile workflow issue is a login problem when the account is actually signed in correctly.",
  "Confusing account access with Group permissions and expecting login alone to unlock restricted team actions."
];
const FAQ_ITEMS$6 = [
  {
    question: "How do I create an account?",
    answer: "Open signup, enter the required details carefully, finish the account creation step, and then complete any verification or follow-up setup the account still needs."
  },
  {
    question: "How do I log in?",
    answer: "Open the login page, enter the email and password tied to your account, and continue into your authenticated creator workspace once access succeeds."
  },
  {
    question: "What should I do if I forgot my password?",
    answer: "Use the password recovery flow instead of guessing repeatedly. It is the fastest route back into the account when the password is no longer clear."
  },
  {
    question: "Why didn’t I receive a verification or reset email?",
    answer: "Check the email address you used, then check spam or other inbox folders. A lot of recovery confusion comes from using the wrong email or watching the wrong inbox."
  },
  {
    question: "Why can’t I access certain features after login?",
    answer: "You may be signed in correctly but still dealing with verification state, incomplete setup, or permissions that belong to a Group or shared workflow rather than simple account access."
  },
  {
    question: "Is login the same as having permission inside a Group?",
    answer: "No. Login proves account access. Group permissions are separate and can still limit what you are allowed to do inside collaborative spaces."
  },
  {
    question: "Can I change account information later?",
    answer: "Yes. Once you are back in the account, profile and account settings can be updated through the normal authenticated settings surfaces."
  }
];
const TROUBLESHOOTING_ITEMS$6 = [
  {
    title: "I can’t log in",
    body: "Start with the login page, then slow down and re-check the email, password, and whether you are trying to enter the correct account.",
    linkKey: "login",
    linkLabel: "Open login"
  },
  {
    title: "I forgot my password",
    body: "Use recovery instead of repeated guessing. The password reset flow is the fastest path back when the credentials no longer feel reliable.",
    linkKey: "password_request",
    linkLabel: "Reset password"
  },
  {
    title: "I didn’t receive the email",
    body: "Check spam, promotions, and the exact email account you used during signup or recovery. Many “missing email” issues turn out to be inbox mix-ups.",
    linkKey: "password_request",
    linkLabel: "Retry recovery"
  },
  {
    title: "I signed up but can’t access something",
    body: "The missing step may be verification or post-signup setup rather than broken login. If access still feels partial, revisit the recovery and support paths carefully.",
    linkKey: "help_troubleshooting",
    linkLabel: "Open troubleshooting hub"
  },
  {
    title: "I’m logged in but still missing permissions",
    body: "That usually points to Group roles or workflow permissions rather than a sign-in failure. Check the Groups guide if the issue lives inside a shared workspace.",
    linkKey: "groups_help",
    linkLabel: "Read Groups help"
  },
  {
    title: "I think I used the wrong email",
    body: "Return to the recovery flow and try the email you most likely used at signup. If that still fails, contact support with a clear explanation instead of guessing endlessly.",
    linkKey: "contact_support",
    linkLabel: "Contact support"
  }
];
const RELATED_HELP_ITEMS$6 = [
  {
    eyebrow: "Live help",
    title: "Account settings help",
    body: "Use the account guide when access already works and the real question is about settings, email changes, password care, or ongoing account maintenance.",
    linkKey: "help_account",
    tone: "sky"
  },
  {
    eyebrow: "Live help",
    title: "Profile help",
    body: "Use the Profile guide once account access is working and you need help turning that access into a stronger public identity.",
    linkKey: "help_profile",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Studio help",
    body: "Use the Studio guide when the real question starts after login and moves into drafts, publishing, and the main creator workspace.",
    linkKey: "studio_help",
    tone: "amber"
  },
  {
    eyebrow: "Live help",
    title: "Groups help",
    body: "Use the Groups guide if you are signed in correctly but the real blocker is collaboration roles, permissions, or Group workflow behavior.",
    linkKey: "groups_help",
    tone: "white"
  },
  {
    eyebrow: "Support path",
    title: "Troubleshooting hub",
    body: "Use the dedicated troubleshooting page when the access problem is still unclear and you need faster diagnosis before opening a deeper module guide.",
    linkKey: "help_troubleshooting",
    tone: "white"
  }
];
function HeroMetric$6({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function BulletGrid$6({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function InsightCard$4({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function TroubleCard$5({ item, links }) {
  return /* @__PURE__ */ React.createElement("a", { href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")));
}
function AuthHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const signedIn = Boolean(props.auth?.signed_in);
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Signup and Login Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Signup", "Login", "Password recovery", "Verification", "Account access"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$6.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$6.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_23%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Signup and login help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Account access should feel clear, fixable, and much less stressful than it often does."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This page explains how signup, login, password recovery, and account verification basics work on Skinbase so you can get into your account, recover it when needed, and separate true access problems from workflow or permission confusion."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: signedIn ? links.open_studio : links.login, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, signedIn ? "Open Studio" : "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.register, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Create account"), /* @__PURE__ */ React.createElement("a", { href: links.password_request, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Reset password"), /* @__PURE__ */ React.createElement("a", { href: links.help_account, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Account settings help"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$6.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$6, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$6, ariaLabel: "Signup and login help sections", selectLabel: "Jump to auth help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "creating-an-account",
      eyebrow: "Signup",
      title: "Creating an account",
      summary: "Account creation should feel straightforward: start from signup, use the right email, finish the flow carefully, and complete any verification the account still needs afterward."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: SIGNUP_STEPS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "logging-in",
      eyebrow: "Login",
      title: "Logging in",
      summary: "Login is the return path into your Skinbase identity. When it works, it should bring you back into the account so you can continue with profile, Studio, and publishing work."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: LOGIN_STEPS }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Where login leads afterward" }, "The important point is not only getting signed in. It is getting back to the authenticated parts of Skinbase that depend on account access, such as Studio and creator settings."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "password-reset-recovery",
      eyebrow: "Recovery",
      title: "Password reset / recovery",
      summary: "If the password is missing or no longer reliable, recovery is the safer and faster route. This should feel like a reset process, not a panic moment."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: RECOVERY_STEPS }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Check the right inbox first" }, "Reset confusion often comes from watching the wrong email account or ignoring spam and promotions folders."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not keep guessing forever" }, "If the password is unclear, move into recovery instead of burning time on repeated failed guesses that only make the situation feel worse."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "access-and-verification",
      eyebrow: "Access basics",
      title: "Account access and verification basics",
      summary: "Being logged in, being verified, and having permission inside a specific workflow are related but not identical. Keeping those ideas separate reduces a lot of confusion."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, ACCESS_BASICS_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$4, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "safety-and-protection",
      eyebrow: "Safety",
      title: "Safety and account protection",
      summary: "Security guidance works best when it is simple enough to follow in real life. These habits protect access without turning basic account care into a technical lecture."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$6, { items: SAFETY_ITEMS, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid this",
      title: "Common mistakes",
      summary: "Most auth confusion comes from small mismatches: the wrong email, the wrong inbox, the wrong assumption about what login should solve, or a permissions issue being mistaken for an account-access failure."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$6, { items: COMMON_MISTAKES$5, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Signup and login FAQ",
      summary: "These are the fastest answers for the questions people most often ask when access is blocked, incomplete, or simply confusing."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$6 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Troubleshooting",
      summary: "Use these shortcuts when account access is failing, recovery feels unclear, or the problem may actually live in permissions and workflow rather than login itself."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, TROUBLESHOOTING_ITEMS$6.map((item) => /* @__PURE__ */ React.createElement(TroubleCard$5, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these links when account access is clear and the next question belongs to profile setup, creator workflows, Group permissions, or broader troubleshooting."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.login, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.register, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create account"), /* @__PURE__ */ React.createElement("a", { href: links.password_request, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Reset password"), /* @__PURE__ */ React.createElement("a", { href: links.help_account, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read account settings help"), /* @__PURE__ */ React.createElement("a", { href: links.help_troubleshooting, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open troubleshooting hub"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If access breaks, check four things first: the email, the password, the inbox, and whether the problem is really permissions rather than login.")))))));
}
const __vite_glob_0_84 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: AuthHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$5 = [
  { id: "what-cards-are", label: "What Cards are" },
  { id: "cards-vs-other-formats", label: "Cards vs other formats" },
  { id: "how-to-create", label: "How to create a Card" },
  { id: "publishing-and-ownership", label: "Publishing and ownership" },
  { id: "personal-and-group-workflows", label: "Personal and Group workflows" },
  { id: "best-practices", label: "Best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS$5 = [
  {
    label: "Format role",
    value: "Visual communication format",
    note: "Cards are best when you want a designed message, presentation, or editorial visual rather than a straightforward artwork upload."
  },
  {
    label: "Best for",
    value: "Short, styled ideas",
    note: "Use Cards for quote designs, promo visuals, themed statements, highlight pieces, and compact presentation content."
  },
  {
    label: "Golden rule",
    value: "Match the message to the format",
    note: "Choose Cards when design and presentation are part of the message, not just decoration added afterward."
  }
];
const WHAT_CARDS_ARE_ITEMS = [
  {
    title: "Cards are designed content units",
    body: "A Card is a creative format built for presentation, visual storytelling, and styled communication. It is meant to carry an idea clearly, not just display a raw asset."
  },
  {
    title: "Cards are flexible, not vague",
    body: "They can be visual statements, promo pieces, quote graphics, short editorial concepts, or support content around a wider project or collection."
  },
  {
    title: "Cards are not a replacement for everything",
    body: "Some ideas should stay artworks, some should be posts, and some belong inside collections. Cards work best when presentation and message need to live together in one polished format."
  }
];
const FORMAT_SIGNAL_ITEMS = [
  "Use Cards when layout, typography, or composition are part of the meaning.",
  "Use Cards when you want a clean public-facing visual without turning it into a full artwork upload.",
  "Use Cards when a post feels too plain but a collection feels too large for the idea you want to publish."
];
const COMPARISON_COLUMNS$1 = [
  { key: "topic", label: "Topic" },
  { key: "cards", label: "Cards" },
  { key: "artworks", label: "Artworks" },
  { key: "posts", label: "Posts" },
  { key: "collections", label: "Collections" }
];
const COMPARISON_ROWS$1 = [
  {
    id: "primary-job",
    topic: "Primary job",
    cards: "Designed visual communication, editorial presentation, or compact storytelling.",
    artworks: "A main creative work or finished visual creation published as its own piece.",
    posts: "Updates, announcements, status sharing, or direct communication.",
    collections: "Grouping related items into a bigger curated set or presentation."
  },
  {
    id: "best-when",
    topic: "Best when",
    cards: "The look, message, and layout all matter together.",
    artworks: "The work itself is the central thing being shown.",
    posts: "You need clarity and speed more than designed presentation.",
    collections: "You want to organize multiple related works into one structured view."
  },
  {
    id: "audience-expectation",
    topic: "Audience expectation",
    cards: "A polished visual statement or concise editorial piece.",
    artworks: "A primary artwork worthy of direct viewing and appreciation.",
    posts: "A message, update, or announcement to read quickly.",
    collections: "A curated journey through more than one item."
  },
  {
    id: "scale",
    topic: "Typical scale",
    cards: "One focused idea, concept, or promo moment.",
    artworks: "One major visual work.",
    posts: "One update or communication moment.",
    collections: "Multiple related works or references gathered together."
  },
  {
    id: "common-misuse",
    topic: "Common misuse",
    cards: "Turning every message into a design exercise even when a post would be clearer.",
    artworks: "Uploading presentation graphics that are not really artworks.",
    posts: "Using posts when the message needs stronger visual presentation.",
    collections: "Making a collection when one good Card or one good artwork would communicate faster."
  }
];
const CREATION_STEPS = [
  {
    title: "Open Studio",
    description: "Start in Studio so you are working inside the creator workspace rather than trying to manage Cards from public pages."
  },
  {
    title: "Choose the Cards area",
    description: "Move into the Cards workflow where you can create, edit, preview, and manage Card-specific content deliberately."
  },
  {
    title: "Create a new Card",
    description: "Begin a new Card when you know the message, idea, or visual concept you want the format to carry."
  },
  {
    title: "Add title, content, and design choices",
    description: "Fill in the content structure clearly. The best Cards feel intentional in both wording and presentation."
  },
  {
    title: "Preview the result",
    description: "Check readability, balance, visual hierarchy, and whether the Card still communicates well outside the editor context."
  },
  {
    title: "Publish when the Card feels clear",
    description: "Publish only when the message, design, and ownership context all feel correct for the public result you want."
  }
];
const OWNERSHIP_ITEMS = [
  {
    title: "Personal Cards",
    body: "Personal Cards are best for profile highlights, visual notes, branded self-presentation, concept pieces, and compact editorial content under your own creator identity."
  },
  {
    title: "Group Cards",
    body: "Group Cards are best for shared promos, event graphics, announcements, release support visuals, and presentation content that belongs to the Group rather than one member alone."
  }
];
const OWNERSHIP_BULLETS = [
  "Check the active context before publishing so the Card goes live under the right identity.",
  "If a Card represents a shared campaign, promo, or announcement, Group ownership is often the better fit.",
  "Make authorship and contribution clear whenever more than one person shaped the final Card.",
  "Treat publishing context as part of quality control, not as a detail to fix later."
];
const WORKFLOW_EXAMPLES = [
  {
    title: "Personal profile highlight Card",
    body: "Use a Card to introduce a creator direction, showcase a visual theme, or present a compact statement that sits well beside your published work."
  },
  {
    title: "Group promo Card",
    body: "Use a Group Card for launches, campaigns, member spotlights, collaborations, or audience-facing promo moments that need a shared identity."
  },
  {
    title: "Themed editorial Card",
    body: "Use a Card when you want one designed visual to communicate a mood, concept, or mini editorial idea without building a larger collection first."
  },
  {
    title: "Announcement Card",
    body: "If the message should feel polished and visual, a Card can carry an announcement more effectively than a plain post."
  },
  {
    title: "Quote or concept Card",
    body: "Cards are a strong fit for text-led ideas where typography, color, and layout are part of the creative statement."
  },
  {
    title: "Collection support Card",
    body: "Use a Card to frame, promote, or introduce a collection without turning the collection itself into a wall of explanation."
  }
];
const BEST_PRACTICES$4 = [
  "Keep one Card focused on one clear message, theme, or visual purpose.",
  "Prioritize readability before decoration so the Card still works on smaller screens and quick scrolls.",
  "Use Cards when presentation adds value, not as a default replacement for artworks or posts.",
  "Keep branding, typography, and visual tone consistent when Cards support a wider project or Group identity.",
  "Publish fewer stronger Cards instead of flooding the feed with low-value variations.",
  "Preview the Card as a viewer would see it, not only as the creator sees it while editing."
];
const COMMON_MISTAKES$4 = [
  "Using a Card when the content should really be a finished artwork.",
  "Using a Card when a plain post would communicate the message faster and more clearly.",
  "Adding too much text, too many visual ideas, or too many competing styles into one Card.",
  "Publishing under the wrong personal-or-Group context and creating avoidable ownership confusion.",
  "Treating Card design as decoration instead of making it support the message itself.",
  "Letting typography, spacing, or hierarchy become inconsistent enough that the Card feels cluttered."
];
const FAQ_ITEMS$5 = [
  {
    question: "What are Cards used for?",
    answer: "Cards are used for visual communication, styled presentation, compact editorial ideas, quote graphics, promos, announcements, and other creative content where layout and message belong together."
  },
  {
    question: "How are Cards different from artworks?",
    answer: "Artworks are primary creative works presented on their own. Cards are presentation-oriented content units that combine message, design, and visual framing more like a polished communication format."
  },
  {
    question: "Can Groups create Cards?",
    answer: "Yes. Groups can use Cards for shared promo pieces, announcements, release support visuals, and other communication that belongs under a Group identity."
  },
  {
    question: "Should I use a Card or a post?",
    answer: "Use a post when a straightforward update is enough. Use a Card when design and presentation are part of what makes the message land properly."
  },
  {
    question: "Can I manage Cards in Studio?",
    answer: "Yes. Studio is the main workspace for creating, editing, previewing, and managing Cards before and after publishing."
  },
  {
    question: "Are Cards public?",
    answer: "Cards become public when you publish them. Until then, the creation and management workflow belongs in Studio rather than on public profile or browse pages."
  },
  {
    question: "How should I design a good Card?",
    answer: "Start with one clear idea, keep the visual hierarchy readable, avoid clutter, and make sure typography, spacing, and composition all support the message instead of competing with it."
  }
];
const TROUBLESHOOTING_ITEMS$5 = [
  {
    title: "I can’t find Cards in Studio",
    body: "Start by reopening the Cards workspace directly. If the workflow still feels missing, check whether you are in the right account state or creator context first.",
    linkKey: "studio_cards",
    linkLabel: "Open Cards workspace"
  },
  {
    title: "I don’t know which content type to use",
    body: "When the choice between Card, artwork, post, and collection still feels blurry, the wider Studio guide helps place each format inside the overall creator workflow.",
    linkKey: "studio_help",
    linkLabel: "Read Studio help"
  },
  {
    title: "My Card looks cluttered",
    body: "If the Card feels overloaded, simplify the message, reduce competing styles, and preview the result again before you publish or keep editing.",
    linkKey: "create_card",
    linkLabel: "Return to card creation"
  },
  {
    title: "I published under the wrong context",
    body: "Ownership confusion often comes from publishing under a personal context when the Card belongs to a Group, or the other way around. Use the Groups guide to correct the workflow deliberately.",
    linkKey: "groups_help",
    linkLabel: "Read Groups help"
  },
  {
    title: "I can’t edit my Card",
    body: "Go back through Studio rather than public pages. Cards are managed inside the workspace, so the edit path usually starts from Studio or the Cards area.",
    linkKey: "open_studio",
    linkLabel: "Open Studio"
  },
  {
    title: "I expected Cards to behave like artworks",
    body: "Cards are a different format with different goals. If the problem is really about publishing files, metadata, or the artwork draft flow, the upload guide is the better next step.",
    linkKey: "upload_help",
    linkLabel: "Read Upload help"
  }
];
const RELATED_HELP_ITEMS$5 = [
  {
    eyebrow: "Live help",
    title: "Studio help",
    body: "Use the Studio guide when you want the wider workspace context around Cards, drafts, content management, and publishing decisions.",
    linkKey: "studio_help",
    tone: "sky"
  },
  {
    eyebrow: "Live help",
    title: "Groups help",
    body: "Use the Groups guide when Cards are part of a shared identity, campaign, review flow, or contributor-credit conversation.",
    linkKey: "groups_help",
    tone: "amber"
  },
  {
    eyebrow: "Live help",
    title: "Upload help",
    body: "Use the Upload guide if the real question is about artwork file publishing, drafts, metadata, or personal versus Group upload context.",
    linkKey: "upload_help",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Profile help",
    body: "Use the Profile guide if your Cards question is really about public identity, creator presentation, or how your personal presence should read to visitors.",
    linkKey: "help_profile",
    tone: "white"
  }
];
function HeroMetric$5({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function BulletGrid$5({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function InsightCard$3({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function TroubleCard$4({ item, links }) {
  return /* @__PURE__ */ React.createElement("a", { href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")));
}
function CardsHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Cards Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Cards", "Studio", "Publishing", "Visual communication", "Group workflows"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$5.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$5.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_23%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Cards help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Cards are for ideas that need design, presentation, and message to work together."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This page explains what Cards are on Skinbase, how they differ from artworks, posts, and collections, how to create and publish them, and how to use them well in both personal and Group workflows."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.create_card, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Create a Card"), /* @__PURE__ */ React.createElement("a", { href: links.studio_cards, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open Cards workspace"), /* @__PURE__ */ React.createElement("a", { href: links.cards_index, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Cards"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$5.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$5, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$5, ariaLabel: "Cards help sections", selectLabel: "Jump to Cards help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-cards-are",
      eyebrow: "Foundations",
      title: "What Cards are",
      summary: "Cards are a creative format for visual communication. They are made for ideas that need design, layout, and message to land together in one polished public-facing unit."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, WHAT_CARDS_ARE_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$3, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(BulletGrid$5, { items: FORMAT_SIGNAL_ITEMS, tone: "emerald" })),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "The simplest way to think about Cards" }, "Cards are not “smaller artworks” and they are not just decorated posts. They are a format for concise, designed visual communication."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "cards-vs-other-formats",
      eyebrow: "Format choice",
      title: "Cards vs artworks vs posts vs collections",
      summary: "Choose the format based on what the audience needs to experience. The right choice makes the content feel natural. The wrong choice creates friction immediately."
    },
    /* @__PURE__ */ React.createElement(DocsComparisonTable, { columns: COMPARISON_COLUMNS$1, rows: COMPARISON_ROWS$1, caption: "Comparison between Cards, artworks, posts, and collections" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Choose Cards when presentation is part of the point" }, "If the message needs typography, composition, or a designed editorial feel to work properly, Cards are usually the right format."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not force every idea into Cards" }, "If the content is really an artwork, keep it as an artwork. If it is really an update, keep it as a post. Better format choices create clearer public experiences."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "how-to-create",
      eyebrow: "Workflow",
      title: "How to create a Card",
      summary: "The creation flow should feel deliberate: enter Studio, open the Cards workflow, shape the idea clearly, preview the result, and publish only when the final presentation feels intentional."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: CREATION_STEPS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "publishing-and-ownership",
      eyebrow: "Ownership",
      title: "Publishing and ownership",
      summary: "Cards can be personal or Group-owned depending on the context. Before you publish, confirm whose identity the Card represents and whether any shared authorship should be made clear."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, OWNERSHIP_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$3, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(BulletGrid$5, { items: OWNERSHIP_BULLETS, tone: "sky" })),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Publishing context is part of quality" }, "A polished Card published under the wrong identity is still a bad result. Treat ownership checks as part of the final review, not as cleanup after the fact."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "personal-and-group-workflows",
      eyebrow: "Use cases",
      title: "Using Cards in personal and Group workflows",
      summary: "Cards become easier to understand once they are attached to real use cases. They are useful when you want a compact, designed surface for communication, mood, or presentation."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, WORKFLOW_EXAMPLES.map((item) => /* @__PURE__ */ React.createElement(InsightCard$3, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "best-practices",
      eyebrow: "Quality habits",
      title: "Best practices",
      summary: "Strong Cards feel focused, readable, and intentional. They communicate one idea clearly instead of fighting for attention with too many competing elements."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$5, { items: BEST_PRACTICES$4, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid this",
      title: "Common mistakes",
      summary: "Most Card problems come from using the wrong format, overloading the design, or ignoring publishing context until after the public result already exists."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$5, { items: COMMON_MISTAKES$4, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Cards FAQ",
      summary: "These answers cover the core questions people ask when they are deciding whether Cards fit the idea they want to publish."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$5 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Troubleshooting",
      summary: "Use these shortcuts when the Cards workflow feels unclear, the format choice feels wrong, or the result is not behaving the way you expected."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, TROUBLESHOOTING_ITEMS$5.map((item) => /* @__PURE__ */ React.createElement(TroubleCard$4, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these links when the Cards format is clear and you need the next layer of help around Studio, Group workflows, uploads, or creator identity."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.create_card, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create a Card"), /* @__PURE__ */ React.createElement("a", { href: links.studio_cards, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Cards workspace"), /* @__PURE__ */ React.createElement("a", { href: links.cards_index, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Cards"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If the content feels unclear, ask one question first: is this a Card, an artwork, a post, or a collection? The answer usually fixes the workflow too.")))))));
}
const __vite_glob_0_85 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: CardsHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const TONES = {
  sky: "border-sky-300/20 bg-sky-300/10",
  amber: "border-amber-300/20 bg-amber-400/10",
  white: "border-white/10 bg-black/20"
};
function HelpGuideCard({ item, links }) {
  const primaryHref = item.primaryLinkKey ? links[item.primaryLinkKey] : null;
  const secondaryHref = item.secondaryLinkKey ? links[item.secondaryLinkKey] : null;
  return /* @__PURE__ */ React.createElement("article", { className: `rounded-[30px] border p-5 shadow-[0_18px_50px_rgba(2,6,23,0.18)] transition hover:-translate-y-0.5 hover:border-white/20 ${TONES[item.tone] || TONES.white}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, item.eyebrow), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, item.title)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-300" }, item.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-200/90" }, item.description), item.plannedPath ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Planned help route: ", item.plannedPath) : null, Array.isArray(item.highlights) && item.highlights.length > 0 ? /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-2 text-sm text-slate-200/90" }, item.highlights.map((highlight) => /* @__PURE__ */ React.createElement("li", { key: highlight, className: "flex gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-2 h-2 w-2 shrink-0 rounded-full bg-white/80" }), /* @__PURE__ */ React.createElement("span", null, highlight)))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, primaryHref ? /* @__PURE__ */ React.createElement("a", { href: primaryHref, className: "rounded-full border border-white/15 bg-white/[0.08] px-4 py-2.5 text-sm font-semibold text-white transition hover:border-white/25 hover:bg-white/[0.12]" }, item.primaryLabel) : null, secondaryHref ? /* @__PURE__ */ React.createElement("a", { href: secondaryHref, className: "rounded-full border border-white/10 px-4 py-2.5 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, item.secondaryLabel) : null));
}
function HelpSearchBar({ value, onChange, onSelectSuggestion, onClear, resultSummary, suggestions = [] }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.03))] p-4 shadow-[0_22px_70px_rgba(2,6,23,0.22)] md:p-5" }, /* @__PURE__ */ React.createElement("label", { htmlFor: "help-center-search", className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Search the help hub"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-col gap-3 lg:flex-row" }, /* @__PURE__ */ React.createElement("div", { className: "relative flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "pointer-events-none absolute inset-y-0 left-4 flex items-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass" })), /* @__PURE__ */ React.createElement(
    "input",
    {
      id: "help-center-search",
      type: "search",
      value,
      onChange: (event) => onChange(event.target.value),
      placeholder: "Search upload image, group roles, create card, login issue...",
      className: "w-full rounded-[22px] border border-white/10 bg-black/20 py-3.5 pl-11 pr-4 text-sm text-white outline-none placeholder:text-slate-500"
    }
  )), value ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClear,
      className: "rounded-[22px] border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.08]"
    },
    "Clear search"
  ) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, suggestions.map((suggestion) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: suggestion,
      type: "button",
      onClick: () => onSelectSuggestion(suggestion),
      className: "rounded-full border border-white/10 bg-black/20 px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-slate-300 transition hover:border-white/20 hover:text-white"
    },
    suggestion
  ))), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-slate-400" }, resultSummary));
}
function HelpSupportCta({ items }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.title, href: item.href, className: "rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.03))] p-5 transition hover:-translate-y-0.5 hover:border-white/20" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, item.eyebrow), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description))));
}
function HelpTopicCard({ item, links }) {
  const primaryHref = item.primaryLinkKey ? links[item.primaryLinkKey] : null;
  const secondaryHref = item.secondaryLinkKey ? links[item.secondaryLinkKey] : null;
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.eyebrow), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, item.title)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-400" }, item.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description), item.plannedPath ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Planned route: ", item.plannedPath) : null, Array.isArray(item.tags) && item.tags.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.tags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-white/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.12em] text-slate-400" }, tag))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, primaryHref ? /* @__PURE__ */ React.createElement("a", { href: primaryHref, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, item.primaryLabel) : null, secondaryHref ? /* @__PURE__ */ React.createElement("a", { href: secondaryHref, className: "rounded-full border border-white/10 px-4 py-2.5 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, item.secondaryLabel) : null), Array.isArray(item.linkItems) && item.linkItems.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, item.linkItems.map((linkItem) => /* @__PURE__ */ React.createElement("a", { key: linkItem.label, href: links[linkItem.linkKey], className: "text-sm font-semibold text-sky-200 underline underline-offset-4" }, linkItem.label))) : null);
}
const SEARCH_SUGGESTIONS = [
  "upload image",
  "upload draft",
  "studio drafts",
  "group roles",
  "login issue",
  "auth help",
  "account settings",
  "change email",
  "troubleshooting",
  "forgot password",
  "create card",
  "create world",
  "cards help",
  "worlds help",
  "seasonal world",
  "attached relations",
  "profile help",
  "profile bio",
  "publish artwork",
  "edit profile"
];
const HIGHLIGHTED_GUIDES = [
  {
    eyebrow: "Live now",
    title: "Upload help",
    description: "A workflow-first guide to draft creation, metadata, previews, contributor credit, and final publish checks.",
    status: "Guide",
    tone: "amber",
    primaryLinkKey: "upload_help",
    primaryLabel: "Read Upload help",
    secondaryLinkKey: "upload",
    secondaryLabel: "Start upload",
    tags: ["upload", "drafts", "publish"]
  },
  {
    eyebrow: "Live now",
    title: "Studio help",
    description: "A creator-friendly guide to Personal Studio, Group Studio, drafts, publishing, and the main workspace areas.",
    status: "Guide",
    tone: "sky",
    primaryLinkKey: "studio_help",
    primaryLabel: "Read Studio help",
    secondaryLinkKey: "open_studio",
    secondaryLabel: "Open Studio",
    tags: ["studio", "drafts", "publishing"]
  },
  {
    eyebrow: "Live now",
    title: "Cards help",
    description: "A creator-friendly guide to what Cards are, when to use them, how to create them, and how they fit into personal and Group workflows.",
    status: "Guide",
    tone: "white",
    primaryLinkKey: "help_cards",
    primaryLabel: "Read Cards help",
    secondaryLinkKey: "cards_create",
    secondaryLabel: "Create a card",
    tags: ["cards", "design", "publishing"]
  },
  {
    eyebrow: "Live now",
    title: "Worlds help",
    description: "A complete guide to building editorial Worlds, attaching curated content, controlling sections, previewing the result, and publishing with confidence.",
    status: "Guide",
    tone: "sky",
    primaryLinkKey: "help_worlds",
    primaryLabel: "Read Worlds help",
    secondaryLinkKey: "create_world",
    secondaryLabel: "Create a world",
    tags: ["worlds", "campaigns", "editorial", "attached relations"]
  },
  {
    eyebrow: "Live now",
    title: "Profile help",
    description: "A creator-friendly guide to personal identity, profile setup, profile-versus-Group clarity, and stronger public presentation on Skinbase.",
    status: "Guide",
    tone: "white",
    primaryLinkKey: "help_profile",
    primaryLabel: "Read Profile help",
    secondaryLinkKey: "profile_settings",
    secondaryLabel: "Open profile settings",
    tags: ["profile", "identity", "onboarding"]
  },
  {
    eyebrow: "Live now",
    title: "Signup and login help",
    description: "A reassuring guide to account creation, sign-in, recovery, verification basics, and the fastest next steps for common access problems.",
    status: "Guide",
    tone: "amber",
    primaryLinkKey: "help_auth",
    primaryLabel: "Read auth help",
    secondaryLinkKey: "password_request",
    secondaryLabel: "Reset password",
    tags: ["login", "signup", "recovery"]
  },
  {
    eyebrow: "Live now",
    title: "Groups documentation",
    description: "The full Groups guide covering roles, publishing, contributor credit, workflows, and best practices.",
    status: "Guide",
    tone: "sky",
    primaryLinkKey: "groups_documentation",
    primaryLabel: "Read full guide",
    secondaryLinkKey: "group_studio",
    secondaryLabel: "Open Group Studio",
    tags: ["groups", "publishing", "roles"]
  },
  {
    eyebrow: "Fast start",
    title: "Groups quickstart",
    description: "The shortest route to creating a Group, inviting members, and publishing correctly under a shared identity.",
    status: "Quickstart",
    tone: "amber",
    primaryLinkKey: "groups_quickstart",
    primaryLabel: "Open quickstart",
    secondaryLinkKey: "create_group",
    secondaryLabel: "Create a Group",
    tags: ["groups", "quickstart", "onboarding"]
  },
  {
    eyebrow: "Answers fast",
    title: "Groups FAQ",
    description: "Quick answers about permissions, contributor credit, invites, approvals, and common troubleshooting.",
    status: "FAQ",
    tone: "white",
    primaryLinkKey: "groups_faq",
    primaryLabel: "Open FAQ",
    secondaryLinkKey: "groups_directory",
    secondaryLabel: "Browse Groups",
    tags: ["groups", "faq", "troubleshooting"]
  }
];
const FEATURED_GUIDES = [
  {
    eyebrow: "Priority topic",
    title: "Groups",
    description: "Create shared identities, invite members, and publish together while preserving contributor credit and accountability.",
    status: "Live now",
    tone: "sky",
    plannedPath: "/help/groups",
    primaryLinkKey: "groups_documentation",
    primaryLabel: "Read Groups help",
    secondaryLinkKey: "groups_quickstart",
    secondaryLabel: "Open quickstart",
    highlights: ["Full guide, quickstart, and FAQ already live", "Best for collaborative publishing and group workflows"],
    tags: ["groups", "contributors", "roles"]
  },
  {
    eyebrow: "Priority topic",
    title: "Studio",
    description: "Learn the workspace for drafts, scheduling, content management, publishing, analytics, and creator operations.",
    status: "Live now",
    tone: "white",
    plannedPath: "/help/studio",
    primaryLinkKey: "studio_help",
    primaryLabel: "Read Studio help",
    secondaryLinkKey: "open_studio",
    secondaryLabel: "Open Studio",
    highlights: ["Now live as the first non-Groups module help page", "Explains drafts, publishing, and context switching clearly"],
    tags: ["studio", "drafts", "publishing"]
  },
  {
    eyebrow: "Priority topic",
    title: "Upload",
    description: "Get help with preparing images, starting uploads, handling drafts, and publishing without losing context or metadata.",
    status: "Live now",
    tone: "white",
    plannedPath: "/help/upload",
    primaryLinkKey: "upload_help",
    primaryLabel: "Read Upload help",
    secondaryLinkKey: "studio_artworks",
    secondaryLabel: "Open Studio artworks",
    highlights: ["Now live as the dedicated upload workflow guide", "Explains draft flow, publish flow, and context clearly"],
    tags: ["upload", "artworks", "drafts"]
  },
  {
    eyebrow: "Priority topic",
    title: "Cards",
    description: "Understand what Cards are, how they differ from artworks, posts, and collections, and how to create and publish them well.",
    status: "Live now",
    tone: "white",
    plannedPath: "/help/cards",
    primaryLinkKey: "help_cards",
    primaryLabel: "Read Cards help",
    secondaryLinkKey: "cards_index",
    secondaryLabel: "Browse cards",
    highlights: ["Now live as the dedicated Cards format guide", "Explains format choice, ownership, and creator-friendly best practices"],
    tags: ["cards", "design", "editorial"]
  },
  {
    eyebrow: "Priority topic",
    title: "Worlds",
    description: "Learn how to build seasonal, event, and campaign destinations with curated attachments, section control, preview workflows, and homepage promotion readiness.",
    status: "Live now",
    tone: "sky",
    plannedPath: "/help/worlds",
    primaryLinkKey: "help_worlds",
    primaryLabel: "Read Worlds help",
    secondaryLinkKey: "worlds_index",
    secondaryLabel: "Browse public Worlds",
    highlights: ["Now live as the dedicated Worlds editorial workflow guide", "Explains attached content, recurrence, preview, and promotion clearly"],
    tags: ["worlds", "campaigns", "seasonal"]
  },
  {
    eyebrow: "Priority topic",
    title: "Profile",
    description: "Set up your public identity, understand profile-versus-Group clarity, and improve the way your creator presence reads to other people.",
    status: "Live now",
    tone: "white",
    plannedPath: "/help/profile",
    primaryLinkKey: "help_profile",
    primaryLabel: "Read Profile help",
    secondaryLinkKey: "profile_settings",
    secondaryLabel: "Open profile settings",
    highlights: ["Now live as the dedicated profile identity guide", "Explains setup, presentation, and profile-versus-Group clarity"],
    tags: ["profile", "identity", "settings"]
  },
  {
    eyebrow: "Priority topic",
    title: "Signup / Login",
    description: "Learn how access, registration, password recovery, and account entry work so creators can get in and stay productive.",
    status: "Live now",
    tone: "amber",
    plannedPath: "/help/auth",
    primaryLinkKey: "help_auth",
    primaryLabel: "Read auth help",
    secondaryLinkKey: "password_request",
    secondaryLabel: "Recover account access",
    highlights: ["Now live as the dedicated signup and login guide", "Explains recovery, verification basics, and permission-vs-access confusion clearly"],
    tags: ["login", "signup", "access"]
  }
];
const HELP_CATEGORIES = [
  {
    id: "core-platform",
    label: "Core platform",
    title: "Core platform",
    summary: "Account setup, identity, and platform basics for new and returning creators.",
    topics: [
      {
        eyebrow: "Get started",
        title: "Signup / Login",
        description: "Account access, registration, password recovery, and getting back into Skinbase quickly.",
        status: "Live",
        plannedPath: "/help/auth",
        primaryLinkKey: "help_auth",
        primaryLabel: "Read auth help",
        secondaryLinkKey: "register",
        secondaryLabel: "Create account",
        tags: ["login", "signup", "access"]
      },
      {
        eyebrow: "Identity",
        title: "Profile",
        description: "Learn how profiles work, how to present yourself better, and how to keep your personal identity distinct from Group identity.",
        status: "Live",
        plannedPath: "/help/profile",
        primaryLinkKey: "help_profile",
        primaryLabel: "Read Profile help",
        secondaryLinkKey: "profile_settings",
        secondaryLabel: "Open settings",
        tags: ["profile", "identity", "settings"]
      },
      {
        eyebrow: "Account",
        title: "Account settings",
        description: "Use account and dashboard settings to control profile details, security flows, and creator preferences.",
        status: "Live",
        plannedPath: "/help/account",
        primaryLinkKey: "help_account",
        primaryLabel: "Read account help",
        secondaryLinkKey: "profile_settings",
        secondaryLabel: "Open account settings",
        tags: ["account", "settings", "dashboard"]
      },
      {
        eyebrow: "Safety",
        title: "Privacy & safety",
        description: "Future help coverage for privacy decisions, safety guidance, and account support concerns.",
        status: "Planned",
        plannedPath: "/help/privacy",
        primaryLinkKey: "contact_support",
        primaryLabel: "Contact support",
        tags: ["privacy", "safety", "support"]
      }
    ]
  },
  {
    id: "creation-and-publishing",
    label: "Creation & publishing",
    title: "Creation and publishing",
    summary: "The main surfaces creators use to make, edit, organize, and publish work on Skinbase.",
    topics: [
      {
        eyebrow: "Workspace",
        title: "Studio",
        description: "Content workflows, drafts, scheduling, analytics, and the main creator workspace.",
        status: "Live",
        plannedPath: "/help/studio",
        primaryLinkKey: "studio_help",
        primaryLabel: "Read Studio help",
        secondaryLinkKey: "open_studio",
        secondaryLabel: "Open Studio",
        tags: ["studio", "drafts", "content"]
      },
      {
        eyebrow: "Publish",
        title: "Upload",
        description: "Start uploads, manage drafts, and publish artwork safely and correctly.",
        status: "Live",
        plannedPath: "/help/upload",
        primaryLinkKey: "upload_help",
        primaryLabel: "Read Upload help",
        secondaryLinkKey: "upload",
        secondaryLabel: "Open upload",
        tags: ["upload", "artwork", "publish"]
      },
      {
        eyebrow: "Portfolio",
        title: "Worlds",
        description: "Learn how to create and manage editorial Worlds with curated attachments, section visibility, preview, recurrence, and promotion workflows.",
        status: "Live",
        plannedPath: "/help/worlds",
        primaryLinkKey: "help_worlds",
        primaryLabel: "Read Worlds help",
        secondaryLinkKey: "studio_worlds",
        secondaryLabel: "Open Worlds workspace",
        tags: ["worlds", "editorial", "campaigns"]
      },
      {
        eyebrow: "Portfolio",
        title: "Artworks",
        description: "Future help for artwork editing, portfolio organization, and publishing workflows.",
        status: "Planned",
        plannedPath: "/help/artworks",
        primaryLinkKey: "studio_artworks",
        primaryLabel: "Open artworks",
        tags: ["artworks", "portfolio", "editing"]
      },
      {
        eyebrow: "Visual compositions",
        title: "Cards",
        description: "Learn what Cards are, when to use them, and how card creation, editing, and publishing fit into the platform.",
        status: "Live",
        plannedPath: "/help/cards",
        primaryLinkKey: "help_cards",
        primaryLabel: "Read Cards help",
        secondaryLinkKey: "cards_index",
        secondaryLabel: "Browse cards",
        tags: ["cards", "design", "workflow"]
      },
      {
        eyebrow: "Organization",
        title: "Collections",
        description: "Planned help for organizing work, saved collections, and multi-item presentation flows.",
        status: "Planned",
        plannedPath: "/help/collections",
        primaryLinkKey: "studio_home",
        primaryLabel: "Open Studio",
        tags: ["collections", "organization", "curation"]
      }
    ]
  },
  {
    id: "collaboration",
    label: "Collaboration",
    title: "Collaboration",
    summary: "Shared publishing, group operations, and the advanced teamwork modules that grow out of the Groups system.",
    topics: [
      {
        eyebrow: "Live ecosystem",
        title: "Groups",
        description: "Shared identity, member roles, contributor credit, review workflows, and Group publishing.",
        status: "Live",
        plannedPath: "/help/groups",
        primaryLinkKey: "groups_documentation",
        primaryLabel: "Read Groups guide",
        secondaryLinkKey: "group_studio",
        secondaryLabel: "Open Group Studio",
        linkItems: [
          { label: "Quickstart", linkKey: "groups_quickstart" },
          { label: "FAQ", linkKey: "groups_faq" },
          { label: "Create Group", linkKey: "create_group" }
        ],
        tags: ["groups", "members", "contributors"]
      },
      {
        eyebrow: "Planned next",
        title: "Projects",
        description: "Future help for structured collaboration, milestones, linked work, and team coordination.",
        status: "Planned",
        plannedPath: "/help/projects",
        primaryLinkKey: "groups_documentation",
        primaryLabel: "Start with Groups docs",
        tags: ["projects", "planning", "collaboration"]
      },
      {
        eyebrow: "Planned next",
        title: "Releases",
        description: "Future guidance for packaging major publication moments with notes, contributors, and linked work.",
        status: "Planned",
        plannedPath: "/help/releases",
        primaryLinkKey: "groups_documentation",
        primaryLabel: "Start with Groups docs",
        tags: ["releases", "launches", "publishing"]
      },
      {
        eyebrow: "Community format",
        title: "Challenges",
        description: "Planned help for challenge-based collaboration, themed prompts, and participation flows.",
        status: "Planned",
        plannedPath: "/help/challenges",
        primaryLinkKey: "groups_faq",
        primaryLabel: "See Group feature FAQ",
        tags: ["challenges", "prompts", "events"]
      },
      {
        eyebrow: "Events",
        title: "Events",
        description: "Planned help for launch moments, showcases, time-based activities, and team promotion flows.",
        status: "Planned",
        plannedPath: "/help/events",
        primaryLinkKey: "groups_faq",
        primaryLabel: "See Group feature FAQ",
        tags: ["events", "showcase", "launch"]
      },
      {
        eyebrow: "Resources",
        title: "Assets",
        description: "Future help for shared resource libraries, asset organization, and collaboration handoff materials.",
        status: "Planned",
        plannedPath: "/help/assets",
        primaryLinkKey: "groups_faq",
        primaryLabel: "See Group feature FAQ",
        tags: ["assets", "resources", "library"]
      }
    ]
  },
  {
    id: "discovery-and-interaction",
    label: "Discovery & interaction",
    title: "Discovery and interaction",
    summary: "Finding work, understanding notifications, and following what matters across the platform.",
    topics: [
      {
        eyebrow: "Search flows",
        title: "Search",
        description: "Future help for discovery, filtering, and finding creators, artworks, cards, or groups quickly.",
        status: "Planned",
        plannedPath: "/help/search",
        primaryLinkKey: "studio_home",
        primaryLabel: "Open Studio",
        tags: ["search", "discovery", "filters"]
      },
      {
        eyebrow: "Signals",
        title: "Notifications",
        description: "Planned help for notification flows, activity awareness, and follow-up actions.",
        status: "Planned",
        plannedPath: "/help/notifications",
        primaryLinkKey: "studio_home",
        primaryLabel: "Open Studio",
        tags: ["notifications", "updates", "activity"]
      },
      {
        eyebrow: "Relationships",
        title: "Following & activity",
        description: "Future help for understanding follows, feed behavior, activity surfaces, and creator engagement.",
        status: "Planned",
        plannedPath: "/help/following",
        primaryLinkKey: "groups_directory",
        primaryLabel: "Browse creators and groups",
        tags: ["following", "activity", "feed"]
      },
      {
        eyebrow: "Conversation",
        title: "Comments & engagement",
        description: "Planned help for community interaction, comment behavior, and response expectations across content.",
        status: "Planned",
        plannedPath: "/help/engagement",
        primaryLinkKey: "cards_index",
        primaryLabel: "Browse public content",
        tags: ["comments", "engagement", "community"]
      }
    ]
  },
  {
    id: "support-and-troubleshooting",
    label: "Support & troubleshooting",
    title: "Support and troubleshooting",
    summary: "Fast fixes, account recovery paths, and help surfaces built for users who need answers right now.",
    topics: [
      {
        eyebrow: "Fast fixes",
        title: "Troubleshooting",
        description: "A live support-oriented guide for diagnosing access, publishing, permissions, setup, and route-level problems faster.",
        status: "Live",
        plannedPath: "/help/troubleshooting",
        primaryLinkKey: "help_troubleshooting",
        primaryLabel: "Open troubleshooting hub",
        secondaryLinkKey: "report_issue",
        secondaryLabel: "Report a problem",
        tags: ["troubleshooting", "support", "issues"]
      },
      {
        eyebrow: "Self-service",
        title: "FAQs & quickstarts",
        description: "A scalable pattern for future FAQs, quickstarts, and module-specific fast-answer pages.",
        status: "Live pattern",
        plannedPath: "/help/{topic}/faq",
        primaryLinkKey: "groups_faq",
        primaryLabel: "See the pattern in Groups FAQ",
        secondaryLinkKey: "groups_quickstart",
        secondaryLabel: "See quickstart pattern",
        tags: ["faq", "quickstart", "help system"]
      },
      {
        eyebrow: "Human support",
        title: "Contact & issue reporting",
        description: "Reach the right support path when the answer is not in self-service content or when something is broken.",
        status: "Available now",
        primaryLinkKey: "contact_support",
        primaryLabel: "Contact support",
        secondaryLinkKey: "report_issue",
        secondaryLabel: "Report issue",
        tags: ["contact", "bug report", "support"]
      }
    ]
  }
];
const GETTING_STARTED_STEPS = [
  {
    title: "Create or access your account",
    description: "Start with account access so you can move into Studio, profile setup, and publishing without blockers."
  },
  {
    title: "Set up your profile",
    description: "Complete the basics of your public identity so your work has a stronger creator context from day one."
  },
  {
    title: "Open Studio",
    description: "Use Studio as the main operating surface for drafts, content management, and creator workflows."
  },
  {
    title: "Upload your first artwork",
    description: "Move from onboarding into actual publishing so you can learn the platform by doing real work."
  },
  {
    title: "Create your first card",
    description: "Explore the visual composition side of Nova once your core publishing flow feels comfortable."
  },
  {
    title: "Use Groups when collaboration starts",
    description: "Once work becomes shared, open the Groups quickstart and switch into the collaboration workflow deliberately."
  }
];
const GETTING_STARTED_LINKS = [
  { label: "Signup / Login help", linkKey: "help_auth" },
  { label: "Set up your profile", linkKey: "help_profile" },
  { label: "Using Studio", linkKey: "studio_home" },
  { label: "Upload your first artwork", linkKey: "upload" },
  { label: "Create your first card", linkKey: "cards_create" },
  { label: "Understanding Groups", linkKey: "groups_quickstart" }
];
const TROUBLESHOOTING_ITEMS$4 = [
  {
    title: "I can’t log in",
    description: "Start with access recovery, then move to support if the issue is bigger than a password reset.",
    linkKey: "password_request",
    linkLabel: "Recover account access",
    tags: ["login", "password", "access"]
  },
  {
    title: "Upload is not working",
    description: "Jump back into the upload flow or Studio to confirm you are in the right context before reporting a bug.",
    linkKey: "upload",
    linkLabel: "Open upload",
    tags: ["upload", "publishing", "artwork"]
  },
  {
    title: "I can’t publish",
    description: "Check whether the issue is personal publishing, Group permissions, or the wrong active context.",
    linkKey: "groups_faq",
    linkLabel: "Read Group publishing FAQ",
    tags: ["publish", "permissions", "context"]
  },
  {
    title: "I don’t see Studio",
    description: "Use sign-in and onboarding checks first, then re-open Studio from the main creator workspace.",
    linkKey: "studio_home",
    linkLabel: "Open Studio",
    tags: ["studio", "onboarding", "access"]
  },
  {
    title: "My Group role doesn’t allow something",
    description: "The Groups FAQ explains how roles, approvals, invites, and permissions differ between members.",
    linkKey: "groups_faq",
    linkLabel: "Open Groups FAQ",
    tags: ["group roles", "permissions", "members"]
  },
  {
    title: "My profile is incomplete",
    description: "Go to profile settings and finish the basics that shape how other creators understand your identity.",
    linkKey: "profile_settings",
    linkLabel: "Open profile settings",
    tags: ["profile", "settings", "identity"]
  },
  {
    title: "I published under the wrong context",
    description: "Use the Groups documentation and FAQ to correct personal-versus-group publishing mistakes deliberately.",
    linkKey: "groups_documentation",
    linkLabel: "Read publishing guidance",
    tags: ["publishing", "context", "groups"]
  }
];
const POPULAR_HELP_TOPICS = [
  {
    title: "How account settings work",
    description: "Read the account guide for settings, email and password care, notifications, and ongoing maintenance after login succeeds.",
    linkKey: "help_account",
    tags: ["account", "settings", "preferences"]
  },
  {
    title: "How Group publishing works",
    description: "Understand shared identity, contributor credit, and why individual attribution stays visible.",
    linkKey: "groups_documentation",
    tags: ["groups", "publishing", "credit"]
  },
  {
    title: "How contributor credit works",
    description: "Use the Groups FAQ to understand Published by, Uploaded by, Primary author, and Contributors.",
    linkKey: "groups_faq",
    tags: ["contributors", "credit", "faq"]
  },
  {
    title: "How Studio works",
    description: "Read the Studio guide for drafts, context switching, publishing, and the main creator workspace surfaces.",
    linkKey: "studio_help",
    tags: ["studio", "content", "workflow"]
  },
  {
    title: "How to upload artwork",
    description: "Read the upload guide for draft flow, metadata review, previews, context checks, and final publishing.",
    linkKey: "upload_help",
    tags: ["upload", "artworks", "publish"]
  },
  {
    title: "How to create cards",
    description: "Read the Cards guide when you need help choosing the format, creating a Card, and publishing it cleanly.",
    linkKey: "help_cards",
    tags: ["cards", "guide", "design"]
  },
  {
    title: "How Worlds work",
    description: "Read the Worlds guide to understand editorial purpose, attached content, preview, section control, recurrence, and homepage promotion.",
    linkKey: "help_worlds",
    tags: ["worlds", "campaigns", "editorial"]
  },
  {
    title: "How profiles work",
    description: "Read the Profile guide to understand setup, identity clarity, presentation, and how personal presence fits beside Group activity.",
    linkKey: "help_profile",
    tags: ["profile", "identity", "guide"]
  },
  {
    title: "How signup and login work",
    description: "Read the auth guide for account creation, sign-in, recovery, verification basics, and common access problems.",
    linkKey: "help_auth",
    tags: ["login", "signup", "recovery"]
  },
  {
    title: "How to troubleshoot faster",
    description: "Use the troubleshooting guide when the problem is urgent and you need faster diagnosis before jumping into a long module guide.",
    linkKey: "help_troubleshooting",
    tags: ["troubleshooting", "support", "issues"]
  },
  {
    title: "How to create a Group",
    description: "Use the quickstart if you are ready to switch from solo publishing into collaboration.",
    linkKey: "create_group",
    tags: ["groups", "quickstart", "collaboration"]
  }
];
const SUPPORT_ITEMS = [
  {
    eyebrow: "Fast fixes",
    title: "Open troubleshooting help",
    description: "Use this when the problem feels urgent and you want shorter diagnosis-first guidance before filing a report.",
    linkKey: "help_troubleshooting"
  },
  {
    eyebrow: "Human help",
    title: "Contact support",
    description: "Use this when the right answer is not in the help hub or when you need account-level guidance.",
    linkKey: "contact_support"
  },
  {
    eyebrow: "Problem reports",
    title: "Report a bug",
    description: "Use this when a route, workflow, permission, or publishing surface appears broken rather than unclear.",
    linkKey: "report_issue"
  }
];
function matchesQuery(item, query) {
  if (!query) return true;
  const haystack = [
    item.title,
    item.description,
    item.status,
    item.eyebrow,
    item.plannedPath,
    ...item.tags || [],
    ...item.highlights || [],
    ...(item.linkItems || []).map((linkItem) => linkItem.label)
  ].filter(Boolean).join(" ").toLowerCase();
  return haystack.includes(query);
}
function MiniLink({ item, href }) {
  return /* @__PURE__ */ React.createElement("a", { href, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, item.label);
}
function PopularTopicCard({ item, href }) {
  return /* @__PURE__ */ React.createElement("a", { href, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, item.description));
}
function HelpCenterPage() {
  const page = X$1();
  const { props, url } = page;
  const links = props.links || {};
  const signedIn = Boolean(props.auth?.signed_in);
  const urlQuery = new URLSearchParams(url.split("?")[1] || "").get("q") || "";
  const [query, setQuery] = reactExports.useState(urlQuery);
  const normalizedQuery = reactExports.useDeferredValue(query.trim().toLowerCase());
  reactExports.useEffect(() => {
    setQuery(urlQuery);
  }, [urlQuery]);
  const highlightedGuides = HIGHLIGHTED_GUIDES.filter((item) => matchesQuery(item, normalizedQuery));
  const featuredGuides = FEATURED_GUIDES.filter((item) => matchesQuery(item, normalizedQuery));
  const categories = HELP_CATEGORIES.map((category) => ({
    ...category,
    topics: category.topics.filter((topic) => matchesQuery(topic, normalizedQuery))
  })).filter((category) => category.topics.length > 0);
  const troubleshootingItems = TROUBLESHOOTING_ITEMS$4.filter((item) => matchesQuery(item, normalizedQuery));
  const popularTopics = POPULAR_HELP_TOPICS.filter((item) => matchesQuery(item, normalizedQuery));
  const totalMatches = highlightedGuides.length + featuredGuides.length + troubleshootingItems.length + popularTopics.length + categories.reduce((sum, category) => sum + category.topics.length, 0);
  const resultSummary = normalizedQuery ? `Showing ${totalMatches} matching help items for “${query.trim()}”.` : "Search across live guides, planned help topics, popular questions, and troubleshooting shortcuts.";
  const supportItems = SUPPORT_ITEMS.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "WebPage",
      name: "Help Center",
      description: props.description,
      url: props.seo?.canonical
    },
    {
      "@context": "https://schema.org",
      "@type": "ItemList",
      itemListElement: FEATURED_GUIDES.map((item, index2) => ({
        "@type": "ListItem",
        position: index2 + 1,
        name: item.title
      }))
    }
  ];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_22%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.16),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1480px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[38px] border border-white/10 bg-[linear-gradient(140deg,rgba(15,23,42,0.94),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.18),transparent_26%)] p-6 shadow-[0_32px_100px_rgba(2,6,23,0.34)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Skinbase Help Center"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Find the right guide, quickstart, FAQ, or fix without digging through scattered help."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This is the central help hub for Skinbase. Use it to get started, find module-specific guidance, open the live Groups documentation set, and move quickly toward the next useful answer."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "#featured-guides", className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Browse help topics"), /* @__PURE__ */ React.createElement("a", { href: links.groups_documentation, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open Groups help"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 max-w-3xl" }, /* @__PURE__ */ React.createElement(
    HelpSearchBar,
    {
      value: query,
      onChange: setQuery,
      onSelectSuggestion: setQuery,
      onClear: () => setQuery(""),
      suggestions: SEARCH_SUGGESTIONS,
      resultSummary
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Start here"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Studio help"), /* @__PURE__ */ React.createElement("a", { href: links.upload_help, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Upload help"), /* @__PURE__ */ React.createElement("a", { href: links.help_worlds, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Worlds help"), /* @__PURE__ */ React.createElement("a", { href: links.help_cards, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Cards help"), /* @__PURE__ */ React.createElement("a", { href: links.help_profile, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Profile help"), /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Signup / Login help"), /* @__PURE__ */ React.createElement("a", { href: links.help_troubleshooting, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Troubleshooting help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_quickstart, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Groups Quickstart"), /* @__PURE__ */ React.createElement("a", { href: signedIn ? links.open_studio : links.login, className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-4 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, signedIn ? "Open Studio workspace" : "Sign in to start")))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(
    DocsSidebarNav,
    {
      sections: [
        { id: "highlighted-guides", label: "Highlighted guides" },
        { id: "featured-guides", label: "Featured guides" },
        { id: "help-categories", label: "Help categories" },
        { id: "getting-started", label: "Getting started" },
        { id: "troubleshooting", label: "Troubleshooting" },
        { id: "popular-topics", label: "Popular topics" },
        { id: "support-direction", label: "Support direction" }
      ],
      ariaLabel: "Help center sections",
      selectLabel: "Jump to help center section"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, normalizedQuery ? /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Filtered help view" }, "Search is filtering the live guides, planned topics, popular questions, and troubleshooting shortcuts below. Clear the search anytime to return to the full Help Center view.") : /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "How to use the Help Center" }, "Start with the highlighted live guides if you need complete written help now. Use the category sections to see the long-term help architecture and the next high-priority modules that will expand after Groups."), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "highlighted-guides",
      eyebrow: "Live now",
      title: "Highlighted guides",
      summary: "These are the strongest live help surfaces in the current Help Center. They show the quality bar and structural pattern the wider system will follow."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, highlightedGuides.map((item) => /* @__PURE__ */ React.createElement(HelpGuideCard, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "featured-guides",
      eyebrow: "Featured",
      title: "Start with the highest-priority help topics",
      summary: "These are the first modules users most often need help with. Groups is already live, while the rest are surfaced here with real product entry points and clean future help paths."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, featuredGuides.map((item) => /* @__PURE__ */ React.createElement(HelpGuideCard, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement("section", { id: "help-categories", className: "space-y-6 scroll-mt-24" }, categories.map((category) => /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      key: category.id,
      id: category.id,
      eyebrow: "Help category",
      title: category.title,
      summary: category.summary
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, category.topics.map((topic) => /* @__PURE__ */ React.createElement(HelpTopicCard, { key: topic.title, item: topic, links })))
  ))), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "getting-started",
      eyebrow: "Onboarding",
      title: "Getting started with Skinbase",
      summary: "This path is designed for first-time creators who want a practical order of operations instead of a giant wall of documentation."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement(DocsStepList, { items: GETTING_STARTED_STEPS }), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick links"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, GETTING_STARTED_LINKS.map((item) => /* @__PURE__ */ React.createElement(MiniLink, { key: item.label, item, href: links[item.linkKey] })))))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Fixes first",
      title: "Troubleshooting shortcuts",
      summary: "These are the fast paths for users who are blocked and need a direct fix, not a longer article."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, troubleshootingItems.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.title, href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")))))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "popular-topics",
      eyebrow: "Popular",
      title: "Popular help topics",
      summary: "These common journeys make the Help Center feel immediately useful even before every module-specific help page is fully written."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, popularTopics.map((item) => /* @__PURE__ */ React.createElement(PopularTopicCard, { key: item.title, item, href: links[item.linkKey] })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "support-direction",
      eyebrow: "Next steps",
      title: "Need more help than the hub can give?",
      summary: "Use these routes when you need a person, need to report a product issue, or want the most complete live documentation surface right now."
    },
    /* @__PURE__ */ React.createElement(HelpSupportCta, { items: supportItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Help architecture"), /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("li", null, "Use ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "/help"), " as the main hub."), /* @__PURE__ */ React.createElement("li", null, "Use ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "/help/topic"), " for overview pages."), /* @__PURE__ */ React.createElement("li", null, "Use ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "/help/topic/subpage"), " for quickstarts, FAQs, and troubleshooting."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Current coverage"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Groups is the first complete multi-page topic family, and Studio, Upload, Cards, Profile, Signup / Login, Account Settings, and Troubleshooting are now live topic guides. The rest of the Help Center still follows the same predictable expansion path.")))))));
}
const __vite_glob_0_86 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: HelpCenterPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$4 = [
  { id: "what-profile-is", label: "What a profile is" },
  { id: "profile-vs-group", label: "Profile vs Group" },
  { id: "profile-setup-basics", label: "Profile setup basics" },
  { id: "what-to-put-on-your-profile", label: "What to put on your profile" },
  { id: "profile-content-and-activity", label: "Profile content and activity" },
  { id: "best-practices", label: "Best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS$4 = [
  {
    label: "Core role",
    value: "Personal public identity",
    note: "Your profile is the main place where other people understand who you are, what you make, and how you show up on Skinbase."
  },
  {
    label: "What it shapes",
    value: "Trust and recognition",
    note: "A strong profile makes your work easier to recognize, your contributions easier to understand, and your creative identity easier to remember."
  },
  {
    label: "Golden rule",
    value: "Keep it clear and current",
    note: "Profiles work best when they feel real, complete, and consistent with the kind of creator presence you want to build."
  }
];
const WHAT_PROFILE_IS_ITEMS = [
  {
    title: "Your profile is your personal identity",
    body: "A Skinbase profile represents you as an individual creator. It is the public-facing space where people connect your name, visual identity, and work together."
  },
  {
    title: "Profiles are discoverability surfaces",
    body: "People use profiles to understand what you create, what kind of style or focus you have, and whether they want to follow your work more closely."
  },
  {
    title: "Profiles can reflect more than one kind of contribution",
    body: "Your profile is not only about solo publishing. It can also help people understand your contributions, collaborations, and public activity across the platform."
  }
];
const PROFILE_COMPARISON_COLUMNS = [
  { key: "topic", label: "Topic" },
  { key: "profile", label: "Profile" },
  { key: "group", label: "Group" }
];
const PROFILE_COMPARISON_ROWS = [
  {
    id: "identity",
    topic: "Identity",
    profile: "One person or individual creator identity.",
    group: "A shared identity for a team, collective, or collaborative project."
  },
  {
    id: "purpose",
    topic: "Main purpose",
    profile: "Show who you are, what you make, and how you present yourself publicly.",
    group: "Represent shared publishing, shared operations, and collaborative creative activity."
  },
  {
    id: "ownership",
    topic: "Who owns the space",
    profile: "You manage your own profile and personal identity choices.",
    group: "Multiple members may participate, depending on role and permissions."
  },
  {
    id: "publishing",
    topic: "Publishing context",
    profile: "Personal work publishes under your own creator identity.",
    group: "Shared work publishes under the Group identity while still preserving individual credit where relevant."
  },
  {
    id: "coexistence",
    topic: "How they coexist",
    profile: "Your profile remains your personal home base even when you collaborate elsewhere.",
    group: "A Group does not replace your profile. It adds a shared layer on top of your personal identity."
  }
];
const SETUP_BASICS_ITEMS = [
  {
    title: "Avatar and recognizable identity",
    body: "Choose a profile image that people can recognize easily. A strong avatar gives your work a clearer anchor across comments, follows, and content surfaces."
  },
  {
    title: "Username and display identity",
    body: "Keep your identity naming clear and consistent so people do not have to guess whether the profile belongs to you, a project, or a Group."
  },
  {
    title: "Bio and about text",
    body: "A short, memorable bio is usually better than a vague paragraph. Tell people what you create, what you care about, or what makes your perspective distinctive."
  },
  {
    title: "Cover image and visual direction",
    body: "If your profile uses broader visual presentation elements, keep them aligned with the tone of your avatar, work, and overall identity."
  },
  {
    title: "Useful links only",
    body: "If you add socials or external links, keep them relevant. Profiles feel stronger when the links support your creative identity instead of distracting from it."
  },
  {
    title: "Visual consistency matters",
    body: "Your profile should feel like one person or one creator perspective, not a collection of unrelated identity choices thrown together over time."
  }
];
const PROFILE_IMPROVEMENT_TIPS = [
  "Use a recognizable avatar before you start publishing heavily.",
  "Write a bio that says what you create or what kind of creative identity you want people to remember.",
  "Keep your naming, visuals, and profile tone aligned across the page.",
  "Treat profile setup as part of your creative presentation, not as a settings chore you can ignore forever."
];
const WHAT_TO_PUT_ITEMS = [
  "A strong avatar that people can recognize quickly.",
  "A concise bio that gives your profile personality and direction.",
  "A clear sense of your creative focus, style, or themes.",
  "Useful links only, especially if they support your work or identity directly.",
  "Your strongest published work and the contributions you want people to notice first.",
  "Branding or visual consistency that helps the profile feel intentional rather than random."
];
const PROFILE_CONTENT_ITEMS = [
  {
    title: "Personal artworks",
    body: "Your profile can help people understand your personal published work and the direction of your creator identity over time."
  },
  {
    title: "Contributions to Group work",
    body: "Even when work is published by a Group, your profile still matters because it helps people understand your personal role, authorship, and creative history."
  },
  {
    title: "Cards, collections, and presentation surfaces",
    body: "As the platform grows, profiles can reflect more than one type of creative output. What matters most is whether the page still tells a coherent story about you."
  },
  {
    title: "Activity and community visibility",
    body: "Profiles are not only static pages. They can also reflect how active you are, what you engage with, and how consistently you participate in the platform."
  }
];
const BEST_PRACTICES$3 = [
  "Complete your profile early so your identity feels stronger from the beginning.",
  "Keep your bio clear, real, and easy to remember.",
  "Use an avatar people can recognize without effort.",
  "Keep the profile active by publishing, contributing, and updating it when your direction changes.",
  "Make your best work and strongest contributions easier to notice than low-value filler.",
  "Separate personal identity from Group identity intentionally so viewers do not get confused about what belongs to whom.",
  "Keep public information current instead of letting old links, old bios, or old visuals drift indefinitely."
];
const COMMON_MISTAKES$3 = [
  "Leaving the profile incomplete and expecting the work alone to explain who you are.",
  "Confusing your personal profile with a Group identity and making the page feel unclear.",
  "Using a weak, empty, or generic bio that gives people nothing to remember.",
  "Letting the avatar, naming, and visual presentation feel inconsistent with each other.",
  "Making it hard to notice your best work because the page feels cluttered or unfocused.",
  "Keeping low-value or outdated public information visible long after it stops helping your creator identity."
];
const FAQ_ITEMS$4 = [
  {
    question: "What is my profile for?",
    answer: "Your profile is your personal identity and public presence on Skinbase. It helps people understand who you are, what you create, and how your work fits together."
  },
  {
    question: "How is a profile different from a Group?",
    answer: "A profile represents one individual creator. A Group represents a shared team or collaborative identity. They can coexist without replacing each other."
  },
  {
    question: "Can I still have a personal identity if I publish in Groups?",
    answer: "Yes. Group publishing does not erase your personal identity. Your profile still matters because it shows your individual presence and can help people understand your contributions."
  },
  {
    question: "What should I add to my profile first?",
    answer: "Start with a recognizable avatar, a clear identity name, and a short bio that explains what you create or what kind of creative presence you want to build."
  },
  {
    question: "Can my contributions to Group work still appear on my profile?",
    answer: "They can still reflect on you as a creator even when the work belongs to a Group. That is one reason your personal profile remains important in collaborative publishing."
  },
  {
    question: "How do I make my profile look better?",
    answer: "Keep it simple, consistent, and real. Use a recognizable avatar, write a better bio, improve visual consistency, and make sure the strongest work is easier to notice than filler content."
  }
];
const TROUBLESHOOTING_ITEMS$3 = [
  {
    title: "I don’t know what to put on my profile",
    body: "Start with the basics first: avatar, bio, identity focus, and the work you most want people to notice. A profile does not need to say everything at once.",
    linkKey: "profile_settings",
    linkLabel: "Open profile settings"
  },
  {
    title: "My profile feels empty",
    body: "An empty profile is often a publishing or activity problem rather than a design problem. Use Studio and Upload help if the real issue is that your public work is still too thin.",
    linkKey: "upload_help",
    linkLabel: "Read Upload help"
  },
  {
    title: "I want my Group work to still reflect on me",
    body: "That is exactly why profile identity still matters alongside Groups. Use the Groups guide to understand shared publishing, contributor credit, and identity separation more clearly.",
    linkKey: "groups_help",
    linkLabel: "Read Groups help"
  },
  {
    title: "I changed something and it doesn’t look right",
    body: "Review your avatar, naming, bio, and overall visual consistency together rather than changing one field at a time without checking the full profile impression.",
    linkKey: "profile_settings",
    linkLabel: "Return to profile settings"
  },
  {
    title: "I don’t understand profile vs Group publishing",
    body: "If you are not sure whether the public identity should be yours or a Group’s, start with the Groups guide. Publishing context is usually the missing piece.",
    linkKey: "groups_help",
    linkLabel: "Open Groups guide"
  }
];
const RELATED_HELP_ITEMS$4 = [
  {
    eyebrow: "Live help",
    title: "Groups help",
    body: "Use the Groups guide when the real question is how your personal profile should coexist with a shared identity and collaborative publishing.",
    linkKey: "groups_help",
    tone: "sky"
  },
  {
    eyebrow: "Live help",
    title: "Studio help",
    body: "Use the Studio guide when you need the wider creator-workspace context around drafts, publishing, and profile-facing creator operations.",
    linkKey: "studio_help",
    tone: "amber"
  },
  {
    eyebrow: "Live help",
    title: "Upload help",
    body: "Use the Upload guide if the profile feels thin because the real issue is getting more of your work published and presented well.",
    linkKey: "upload_help",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Signup and login help",
    body: "Use the auth guide if the blocker is sign-in, registration, or access recovery before you can even update the profile properly.",
    linkKey: "help_auth",
    tone: "white"
  }
];
function HeroMetric$4({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function BulletGrid$4({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function InsightCard$2({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function TroubleCard$3({ item, links }) {
  return /* @__PURE__ */ React.createElement("a", { href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")));
}
function ProfileHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Profile Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Profile", "Creator identity", "Groups", "Studio", "Publishing"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$4.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$4.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_23%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Profile help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Your profile is the personal identity people remember when they discover your work."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This page explains what a profile is on Skinbase, how it differs from a Group, how to set it up well, and how to build a stronger public creator presence without turning the page into noise."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.profile_settings, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Open profile settings"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Read Groups help"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$4.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$4, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$4, ariaLabel: "Profile help sections", selectLabel: "Jump to Profile help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-profile-is",
      eyebrow: "Foundations",
      title: "What a profile is",
      summary: "Your profile is your personal public presence on Skinbase. It is where people build a first impression of who you are, what you create, and how your identity connects to the work they see."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, WHAT_PROFILE_IS_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$2, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "The simplest way to think about your profile" }, "Your profile is not just a settings page. It is the public identity layer that helps people recognize you as a creator."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "profile-vs-group",
      eyebrow: "Identity",
      title: "Profile vs Group",
      summary: "This is the most important distinction for many creators. Your profile represents you personally. A Group represents a shared identity. Both can exist at the same time without competing with each other."
    },
    /* @__PURE__ */ React.createElement(DocsComparisonTable, { columns: PROFILE_COMPARISON_COLUMNS, rows: PROFILE_COMPARISON_ROWS, caption: "Comparison between Profile and Group" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "You do not lose your personal identity inside Groups" }, "Group publishing adds a shared layer, but your own profile still matters because it helps people understand your individual presence and contribution history."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not let profile and Group identity blur together" }, "When the difference is unclear, people have a harder time understanding who is speaking, who owns the work, and what belongs to the shared team versus the individual creator."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "profile-setup-basics",
      eyebrow: "Setup",
      title: "Profile setup basics",
      summary: "The best profiles are not overbuilt. They are recognizable, readable, and consistent enough that people can understand the creator quickly."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, SETUP_BASICS_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$2, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(BulletGrid$4, { items: PROFILE_IMPROVEMENT_TIPS, tone: "emerald" }))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-to-put-on-your-profile",
      eyebrow: "Presentation",
      title: "What to put on your profile",
      summary: "Think of your profile as a curated introduction rather than a dumping ground. The strongest pages make your identity and best work easier to notice quickly."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$4, { items: WHAT_TO_PUT_ITEMS, tone: "sky" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "profile-content-and-activity",
      eyebrow: "Visibility",
      title: "Profile content and activity",
      summary: "Profiles are not only bios and avatars. They can also help people understand your personal work, your public contributions, and how active you are as a creator."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, PROFILE_CONTENT_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$2, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Profiles become stronger through activity, not decoration alone" }, "Better profile visuals help, but the strongest identity pages are backed by real work, visible contributions, and consistent public presence."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "best-practices",
      eyebrow: "Good habits",
      title: "Best practices",
      summary: "A strong profile does not need to be complicated. It needs to feel real, intentional, and easy for other people to understand."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$4, { items: BEST_PRACTICES$3, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid this",
      title: "Common mistakes",
      summary: "Most profile problems come from neglect, inconsistency, or mixing personal identity with other public surfaces until the page stops feeling coherent."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$4, { items: COMMON_MISTAKES$3, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Profile FAQ",
      summary: "These answers cover the most common questions people ask when they are trying to build a stronger public identity on Skinbase."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$4 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Troubleshooting",
      summary: "Use these shortcuts when your profile feels unclear, incomplete, or disconnected from the way you actually want to present yourself."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, TROUBLESHOOTING_ITEMS$3.map((item) => /* @__PURE__ */ React.createElement(TroubleCard$3, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these links when your profile setup question leads into shared identity, publishing workflows, or access issues elsewhere in the product."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.profile_settings, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open profile settings"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"), /* @__PURE__ */ React.createElement("a", { href: links.upload_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Upload help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "A better profile usually starts with three things: a recognizable avatar, a clearer bio, and a stronger sense of what you want people to remember about you.")))))));
}
const __vite_glob_0_87 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ProfileHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$3 = [
  { id: "what-is-studio", label: "What Studio is" },
  { id: "personal-vs-group", label: "Personal vs Group Studio" },
  { id: "main-studio-areas", label: "Main Studio areas" },
  { id: "drafts-and-publishing", label: "Drafts and publishing" },
  { id: "managing-artworks", label: "Managing artworks" },
  { id: "cards-and-collections", label: "Cards and collections" },
  { id: "advanced-modules", label: "Advanced modules" },
  { id: "best-practices", label: "Best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "related-help", label: "Related help" }
];
const STUDIO_COMPARISON_COLUMNS = [
  { key: "topic", label: "Topic" },
  { key: "personal", label: "Personal Studio" },
  { key: "group", label: "Group Studio" }
];
const STUDIO_COMPARISON_ROWS = [
  {
    id: "ownership",
    topic: "Who the work belongs to",
    personal: "Your own drafts, uploads, cards, collections, and creator activity.",
    group: "Work owned, published, or coordinated under a Group identity."
  },
  {
    id: "permissions",
    topic: "Why actions differ",
    personal: "You usually control the full flow for your own content.",
    group: "Available actions depend on Group role, trust level, and review workflow."
  },
  {
    id: "publishing",
    topic: "Publishing context",
    personal: "Publishes under your personal creator identity.",
    group: "Publishes under the Group identity while preserving individual credit."
  },
  {
    id: "drafts",
    topic: "Where drafts live",
    personal: "In your personal Studio draft and content views.",
    group: "Inside the Group context, often with shared review or approval behavior."
  },
  {
    id: "coordination",
    topic: "Coordination style",
    personal: "Best for solo publishing and direct control.",
    group: "Best for shared publishing, collaboration, reviews, member management, and structured releases."
  }
];
const HERO_METRICS$3 = [
  {
    label: "Core purpose",
    value: "Private creative workspace",
    note: "Studio is where you prepare, organize, review, and manage work before and after it goes public."
  },
  {
    label: "Common confusion",
    value: "Context changes behavior",
    note: "Personal Studio and Group Studio can expose different actions because ownership and permissions are different."
  },
  {
    label: "Golden rule",
    value: "Check context before publish",
    note: "Publishing from the wrong context is one of the easiest ways to create avoidable confusion."
  }
];
const STUDIO_AREAS = [
  {
    title: "Dashboard and content views",
    body: "Use the main Studio dashboard, content view, and analytics surfaces to see what is active, what is scheduled, and what still needs attention.",
    links: ["Open Studio", "View content dashboard"]
  },
  {
    title: "Artworks and drafts",
    body: "Artworks, drafts, scheduled items, calendar views, and archived work all live inside the management side of Studio rather than on public profile pages.",
    links: ["Open artworks", "Open drafts"]
  },
  {
    title: "Cards and collections",
    body: "Cards and collections are managed as creative tools inside Studio, where you can build, organize, and refine them before people see the result publicly.",
    links: ["Open cards", "Open collections"]
  },
  {
    title: "Groups and collaboration",
    body: "When collaboration is involved, Group Studio adds shared publishing, member management, review flows, projects, releases, challenges, events, assets, and related operations.",
    links: ["Open Group Studio", "Read Groups help"]
  },
  {
    title: "Settings and preferences",
    body: "Studio also includes settings, preferences, profile-facing tools, activity, and creator operations that do not belong on the public side of Skinbase.",
    links: ["Open settings", "Read Profile help"]
  },
  {
    title: "Future-ready workflow surface",
    body: "The current Studio already covers many creator operations, and the help page is written to stay useful as more modules grow into the workspace over time.",
    links: ["Help Center", "Report issue"]
  }
];
const DRAFT_STEPS = [
  {
    title: "Start work in the right context",
    description: "Before you upload, edit, or publish, confirm whether the work belongs to your personal Studio or to a Group context."
  },
  {
    title: "Treat drafts as unfinished workspace items",
    description: "Drafts are where unfinished work lives while you are still checking metadata, previews, contributor credit, timing, or overall quality."
  },
  {
    title: "Review metadata before publishing",
    description: "Titles, descriptions, tags, categories, previews, context, and contributor information should be reviewed before the final publish step."
  },
  {
    title: "Use review when collaboration needs it",
    description: "Group workflows may put work into review before publish so trusted members can check context, quality, and credit."
  },
  {
    title: "Publish only when the public version is ready",
    description: "Do not treat publish as a draft save button. Publish when the work is accurate, presentable, and in the right place."
  }
];
const ARTWORK_GUIDANCE = [
  "Create or upload the work into the correct Studio context first.",
  "Review title, description, and public-facing metadata before publish.",
  "Check tags, categories, and preview quality so the public version lands clearly.",
  "Make sure contributor credit reflects who authored, uploaded, and contributed to the work.",
  "Update published work intentionally instead of letting metadata drift over time."
];
const CARD_COLLECTION_GUIDANCE = [
  {
    title: "Cards",
    body: "Use Studio for card creation, remixing, editing, previews, and analytics. Cards are part of your creative workflow, not just a public gallery surface."
  },
  {
    title: "Collections",
    body: "Use Studio to organize groups of work, shape presentation, and manage curated content as a creative management task rather than an afterthought."
  }
];
const ADVANCED_MODULES = [
  "Projects help teams organize structured collaboration, milestones, and linked work.",
  "Releases package a larger publication moment into a clearer shared launch surface.",
  "Challenges, events, and assets extend Studio into themed collaboration, timed publishing, and shared resources.",
  "Group review queues, invitations, and join requests add operational structure when collaboration grows beyond simple direct publishing."
];
const BEST_PRACTICES$2 = [
  "Review drafts regularly so Studio stays usable instead of turning into a backlog graveyard.",
  "Keep personal and Group work clearly separated so ownership stays obvious.",
  "Publish only after metadata, previews, and contributor credit are truly ready.",
  "Use advanced modules only when they solve a real workflow problem.",
  "Treat Studio like a workspace for preparation and management, not as a public profile page.",
  "Keep contributor records accurate so teams avoid confusion later."
];
const COMMON_MISTAKES$2 = [
  "Publishing under the wrong context because the active Studio scope was not checked first.",
  "Leaving metadata half-finished and hoping to clean it up after the work is public.",
  "Forgetting to verify contributor credit before a collaborative publish.",
  "Treating Studio like a public page instead of a private working area.",
  "Giving too many Group members too much access when a smaller permission set would be safer.",
  "Ignoring drafts until lists become cluttered and hard to maintain."
];
const FAQ_ITEMS$3 = [
  {
    question: "What is Studio?",
    answer: "Studio is the private creator workspace on Skinbase. It is where you manage drafts, uploads, publishing, cards, collections, settings, and other operational parts of your creative work."
  },
  {
    question: "Why do Personal Studio and Group Studio look different?",
    answer: "Because the context changes ownership and permissions. Personal Studio manages your own work. Group Studio manages work under a shared identity, so some actions depend on your Group role and workflow."
  },
  {
    question: "Why can’t I publish from this area?",
    answer: "You may be in the wrong context, in a non-publishing step, or using a role that does not include direct publishing. Check the active scope first, then check whether review or approval is part of the workflow."
  },
  {
    question: "Where are my drafts?",
    answer: "Drafts live inside Studio, not on public pages. Look in the draft or artwork management views for the current context you are working in."
  },
  {
    question: "Can I manage both personal and Group content in Studio?",
    answer: "Yes, but they are not the same context. You should switch deliberately and confirm which identity owns the work before editing or publishing."
  },
  {
    question: "Why don’t I see some modules?",
    answer: "Some modules only appear in certain contexts, are tied to collaboration features, or depend on your Group role and permissions."
  },
  {
    question: "Is Studio public?",
    answer: "No. Studio is the private management layer. Public pages are what other people see after content has been published."
  }
];
const TROUBLESHOOTING_ITEMS$2 = [
  {
    title: "I can’t find my draft",
    body: "Check whether the draft belongs to your personal Studio or to a Group. Draft confusion often comes from opening the right workspace in the wrong context.",
    linkKey: "studio_drafts",
    linkLabel: "Open drafts"
  },
  {
    title: "I can’t publish",
    body: "Confirm the active context, then check whether your role, workflow, or review state allows direct publishing from that surface.",
    linkKey: "groups_faq",
    linkLabel: "Read the Groups FAQ"
  },
  {
    title: "I don’t see Group Studio",
    body: "You may not be in a Group yet, may not have accepted an invitation, or may not have the expected access in the current account state.",
    linkKey: "group_studio",
    linkLabel: "Open Group Studio"
  },
  {
    title: "I don’t understand why an action is missing",
    body: "Missing actions usually come from context, permissions, or workflow stage. The action may exist elsewhere, or it may be intentionally limited in this scope.",
    linkKey: "groups_help",
    linkLabel: "Read Groups help"
  },
  {
    title: "I changed context and now I can’t edit something",
    body: "The work may belong to the other context. Switch back and confirm whether the item is personal, Group-owned, or limited by role.",
    linkKey: "open_studio",
    linkLabel: "Open Studio"
  },
  {
    title: "My Studio looks empty",
    body: "Start by checking the active context, current filters, and whether you are looking at drafts, artworks, scheduled items, or another view entirely.",
    linkKey: "studio_content",
    linkLabel: "Open content dashboard"
  }
];
const RELATED_HELP_ITEMS$3 = [
  {
    eyebrow: "Live help",
    title: "Groups help",
    body: "Use the full Groups guide for roles, permissions, contributor credit, review queues, and shared publishing.",
    linkKey: "groups_help",
    tone: "sky"
  },
  {
    eyebrow: "Live help",
    title: "Upload help",
    body: "Use the Upload guide when the real question is about draft flow, metadata, previews, contributor credit, or final publish steps.",
    linkKey: "upload_help",
    tone: "amber"
  },
  {
    eyebrow: "Live help",
    title: "Cards help",
    body: "Use the Cards guide when you need help choosing the format, creating a Card, or understanding where Cards fit compared with other content types.",
    linkKey: "help_cards",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Profile help",
    body: "Use the Profile guide when the real question is how to build a stronger personal identity, cleaner presentation, and better profile-versus-Group clarity.",
    linkKey: "help_profile",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Signup and login help",
    body: "Use the auth guide when Studio access is blocked before you even get started or when the real problem is recovery, verification, or account entry.",
    linkKey: "help_auth",
    tone: "white"
  }
];
function HeroMetric$3({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function AreaCard({ item, links }) {
  const actions = [
    { label: "Open Studio", href: links.open_studio },
    { label: "View content dashboard", href: links.studio_content },
    { label: "Open artworks", href: links.studio_artworks },
    { label: "Open drafts", href: links.studio_drafts },
    { label: "Open cards", href: links.studio_cards },
    { label: "Open collections", href: links.studio_collections },
    { label: "Open Group Studio", href: links.group_studio },
    { label: "Read Groups help", href: links.groups_help },
    { label: "Open settings", href: links.studio_settings },
    { label: "Read Profile help", href: links.help_profile },
    { label: "Help Center", href: links.help_home },
    { label: "Report issue", href: links.report_issue }
  ];
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.links.map((label) => {
    const action = actions.find((candidate) => candidate.label === label);
    if (!action?.href) return null;
    return /* @__PURE__ */ React.createElement("a", { key: label, href: action.href, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.07]" }, label);
  })));
}
function BulletGrid$3({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function TroubleCard$2({ item, links }) {
  return /* @__PURE__ */ React.createElement("a", { href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")));
}
function StudioHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Studio Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Studio", "Drafts", "Publishing", "Creator workflow", "Group Studio"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$3.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$3.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_23%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Studio help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Studio is the creative control center of Skinbase."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "Use Studio to manage drafts, uploads, publishing, artworks, cards, collections, and collaborative work before and after it goes public. This page explains how Studio fits into the platform, how personal and Group contexts differ, and how to use the workspace without creating avoidable confusion."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.open_studio, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Open Studio"), /* @__PURE__ */ React.createElement("a", { href: links.upload_help, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Read Upload help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$3.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$3, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$3, ariaLabel: "Studio help sections", selectLabel: "Jump to Studio help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-is-studio",
      eyebrow: "Foundations",
      title: "What Studio is",
      summary: "Studio is the private management workspace for creators. Public pages show published work. Studio is where you prepare, organize, edit, review, and manage that work before and after it reaches the public side of Skinbase."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Studio is private"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Studio is not your public profile. It is the working area where creator actions happen, drafts live, and management choices are made.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Public pages are the result"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "The public side of Skinbase is what people see after you publish. Studio is where you shape that result intentionally."))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "The simplest mental model" }, "Think of Studio as your control room. It is where unfinished work is prepared, published work is managed, and context-sensitive actions live."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "personal-vs-group",
      eyebrow: "Context",
      title: "Personal Studio vs Group Studio",
      summary: "This is one of the most important parts of Studio. The active context changes ownership, available actions, and who is allowed to do what."
    },
    /* @__PURE__ */ React.createElement(
      DocsComparisonTable,
      {
        columns: STUDIO_COMPARISON_COLUMNS,
        rows: STUDIO_COMPARISON_ROWS,
        caption: "Comparison between Personal Studio and Group Studio"
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Check context before publishing" }, "If you do not confirm whether you are in personal or Group Studio, it becomes much easier to publish under the wrong identity or lose track of where a draft belongs."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Why actions can disappear" }, "In Group Studio, actions may change based on role, permissions, approvals, or workflow stage. Missing actions are often a context or permission issue, not a bug."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "main-studio-areas",
      eyebrow: "Workspace map",
      title: "Main Studio areas",
      summary: "Studio already includes a broad set of creator surfaces. You do not need to memorize every route, but it helps to understand the main areas and what each one is for."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, STUDIO_AREAS.map((item) => /* @__PURE__ */ React.createElement(AreaCard, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "drafts-and-publishing",
      eyebrow: "Workflow",
      title: "Drafts and publishing",
      summary: "Drafts are unfinished workspace items. Publishing is the moment work becomes public. Treat those as different stages with different responsibilities."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: DRAFT_STEPS }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Before you publish" }, "Review metadata, preview quality, contributor credit, and context every time. Publishing is fastest when those checks become a habit."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "managing-artworks",
      eyebrow: "Content",
      title: "Managing artworks",
      summary: "Studio is where artwork workflows happen: upload, draft review, metadata cleanup, preview checks, updates, and final publishing decisions."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$3, { items: ARTWORK_GUIDANCE, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "cards-and-collections",
      eyebrow: "Creative tools",
      title: "Managing cards and collections",
      summary: "Cards and collections are part of the creative management side of Studio. They are not only public-facing features; they also live inside the workspace where you build and organize them."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, CARD_COLLECTION_GUIDANCE.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.title, className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body))))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "advanced-modules",
      eyebrow: "Advanced workflows",
      title: "Projects, releases, and other advanced modules",
      summary: "As workflows become more collaborative or structured, Studio extends beyond simple drafts and publishes into richer operating surfaces."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$3, { items: ADVANCED_MODULES, tone: "amber" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Use advanced modules when they solve a real need" }, "Projects, releases, challenges, events, assets, and review queues are powerful, but they work best when the team actually needs more structure rather than more complexity."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "best-practices",
      eyebrow: "Habits",
      title: "Best practices",
      summary: "Good Studio habits reduce confusion, keep work organized, and make publishing smoother for both solo creators and teams."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$3, { items: BEST_PRACTICES$2, tone: "sky" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid this",
      title: "Common mistakes",
      summary: "Most Studio confusion does not come from the existence of many tools. It comes from using the right tool in the wrong context or skipping basic review steps."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$3, { items: COMMON_MISTAKES$2, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Studio FAQ",
      summary: "These fast answers cover the questions that come up most often when people are new to Studio or switching into collaborative workflows."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$3 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Troubleshooting",
      summary: "Use these shortcuts when Studio feels confusing, empty, or inconsistent. Most issues come down to context, filters, or permissions."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, TROUBLESHOOTING_ITEMS$2.map((item) => /* @__PURE__ */ React.createElement(TroubleCard$2, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these links when Studio has answered the workflow question and you need to go deeper into the right part of the help system or product surface."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.open_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Studio"), /* @__PURE__ */ React.createElement("a", { href: links.studio_drafts, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open drafts"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If something feels missing, check context first. Personal Studio and Group Studio are connected, but they are not identical workspaces.")))))));
}
const __vite_glob_0_88 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$2 = [
  { id: "first-checks", label: "First checks" },
  { id: "account-access", label: "Account access" },
  { id: "publishing-and-context", label: "Publishing and context" },
  { id: "profile-and-settings", label: "Profile and settings" },
  { id: "when-to-report", label: "When to report it" },
  { id: "faq", label: "FAQ" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS$2 = [
  {
    label: "Best first move",
    value: "Name the failure clearly",
    note: "Broken, blocked, and unclear are not the same thing. The faster you label the problem, the faster the right fix shows up."
  },
  {
    label: "Most common false alarm",
    value: "Permission or context confusion",
    note: "A lot of apparent product failures are actually caused by the wrong active context, incomplete setup, or missing collaboration permissions."
  },
  {
    label: "Escalate when",
    value: "A route is repeatably broken",
    note: "If the same steps fail consistently and the issue is not explained by access, context, or settings, it is time to report the problem clearly."
  }
];
const FIRST_CHECKS = [
  "Ask whether the problem is broken, blocked, or just unclear. Those three paths have different fixes.",
  "Re-open the exact route you intended to use instead of guessing from memory or following an outdated tab.",
  "Check whether you are signed in, in the right account, and in the right personal or Group context before assuming the product failed.",
  "Reduce the problem to one sentence. If you cannot describe the failure clearly, start with the auth or account guides first."
];
const ACCOUNT_ACCESS_ITEMS = [
  {
    title: "Login, reset, and verification come first",
    body: "If access itself is failing, do not over-diagnose a Studio, profile, or publishing bug yet. Start with the auth guide and recovery paths first."
  },
  {
    title: "Wrong email and wrong inbox cause a lot of panic",
    body: "Many access problems feel severe until you realize the account email, reset inbox, or verification message path was simply not the one you thought it was."
  },
  {
    title: "Partial access is still a useful clue",
    body: "If some features work and others do not, the issue may be permissions, setup state, or workflow context rather than a total account failure."
  }
];
const PUBLISHING_CONTEXT_ITEMS = [
  {
    title: "Personal vs Group context changes what you can do",
    body: "Publishing problems often come from being in the wrong context or expecting personal access to behave like Group access."
  },
  {
    title: "Missing permission is not always a bug",
    body: "If a Group role or shared workflow blocks an action, the fix usually lives in permissions guidance rather than product failure reporting."
  },
  {
    title: "Studio confusion often starts upstream",
    body: "When Studio feels wrong, check whether the real issue is authentication, onboarding state, or the route you expected to open."
  }
];
const PROFILE_SETTINGS_ITEMS = [
  {
    title: "Incomplete profile is usually a settings task",
    body: "When the profile looks thin, inconsistent, or outdated, the answer usually lives in profile or account settings rather than troubleshooting a broken surface."
  },
  {
    title: "Identity confusion can feel like a feature issue",
    body: "If the page feels wrong because personal and Group identity are blurred together, use profile and Groups help before filing a bug."
  },
  {
    title: "Notification or preference issues belong in settings",
    body: "If the platform feels too noisy, too quiet, or out of sync with what you expect, the account settings guide is usually the better first stop."
  }
];
const REPORTING_ITEMS = [
  "Report a bug when you can reproduce the same failure on the same route with the same steps.",
  "Contact support when ownership, account identity, or a sensitive account question needs a human response instead of a pure product diagnosis.",
  "Include the route, what you expected, what actually happened, and whether the issue is personal-only or also affects Group workflows.",
  "Mention what you already checked so support does not have to restart from the most obvious first steps."
];
const FAQ_ITEMS$2 = [
  {
    question: "How do I know whether something is broken or I am just in the wrong context?",
    answer: "Check whether the same route works after confirming login state, account identity, and personal-versus-Group context. If the failure disappears when context is corrected, it was not a product bug."
  },
  {
    question: "When should I use auth help instead of troubleshooting help?",
    answer: "Use auth help when the core problem is account entry, recovery, or verification. Use troubleshooting help when the failure is broader or less clearly labeled."
  },
  {
    question: "When should I use account help instead of troubleshooting help?",
    answer: "Use account help when access already works and the question is really about settings, profile maintenance, passwords, email care, or preferences."
  },
  {
    question: "What should I include in a bug report?",
    answer: "Include the route, the exact steps, what you expected, what happened instead, and whether the issue repeats consistently. Clear reproduction details save the most time."
  }
];
const RELATED_HELP_ITEMS$2 = [
  {
    eyebrow: "Access",
    title: "Signup and login help",
    body: "Use the auth guide when the real failure starts with account entry, reset messages, or verification confusion.",
    linkKey: "help_auth",
    tone: "sky"
  },
  {
    eyebrow: "Settings",
    title: "Account settings help",
    body: "Use the account guide when access already works and the real fix lives in profile settings, notifications, email care, or password maintenance.",
    linkKey: "help_account",
    tone: "amber"
  },
  {
    eyebrow: "Publishing",
    title: "Upload help",
    body: "Use the upload guide when the “broken” feeling is really about drafts, metadata, publishing flow, or file-specific workflow confusion.",
    linkKey: "upload_help",
    tone: "white"
  },
  {
    eyebrow: "Permissions",
    title: "Groups FAQ",
    body: "Use Groups guidance when the blocker is role-based access, contributor permissions, invites, or collaboration behavior.",
    linkKey: "groups_faq",
    tone: "white"
  }
];
function HeroMetric$2({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function InsightCard$1({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function BulletGrid$2({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function TroubleshootingHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const signedIn = Boolean(props.auth?.signed_in);
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Troubleshooting Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Troubleshooting", "Account access", "Permissions", "Publishing blockers", "Support"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$2.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$2.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(244,114,182,0.12),_transparent_20%),radial-gradient(circle_at_bottom_right,_rgba(56,189,248,0.16),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(244,114,182,0.12),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-rose-200/80" }, "Troubleshooting help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "When something feels broken, the fastest fix usually starts with diagnosing the right kind of problem."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "Use this page when you need shorter, support-oriented guidance for account entry issues, context confusion, publishing blockers, incomplete setup, permissions problems, or the point where a clean bug report becomes the right move."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: signedIn ? links.open_studio : links.login, className: "rounded-full border border-rose-300/25 bg-rose-300/12 px-5 py-3 text-sm font-semibold text-rose-100 transition hover:border-rose-300/40 hover:bg-rose-300/18" }, signedIn ? "Open Studio" : "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Read auth help"), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Report a problem"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$2.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$2, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$2, ariaLabel: "Troubleshooting help sections", selectLabel: "Jump to troubleshooting section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "first-checks",
      eyebrow: "Start here",
      title: "First checks before you spiral",
      summary: "Troubleshooting works better when you slow the situation down, label the failure clearly, and rule out the most common context mistakes first."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$2, { items: FIRST_CHECKS, tone: "sky" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "A useful troubleshooting split" }, "Ask whether the issue is about access, permissions, settings, or a truly broken route. Those categories lead to very different fixes."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not skip straight to bug reports" }, "Many urgent-feeling problems resolve much faster once you confirm the right account, inbox, route, or Group context."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "account-access",
      eyebrow: "Access",
      title: "Account access and recovery issues",
      summary: "If you cannot enter the account consistently, or can only reach part of the platform, start here before diagnosing deeper creator workflow surfaces."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, ACCOUNT_ACCESS_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$1, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "publishing-and-context",
      eyebrow: "Workflow",
      title: "Publishing and context problems",
      summary: "When uploads, Studio, or publishing actions feel blocked, the root cause is often context or permissions rather than a total platform failure."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, PUBLISHING_CONTEXT_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$1, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "profile-and-settings",
      eyebrow: "Settings",
      title: "Profile and account-settings confusion",
      summary: "Some problems feel technical when they are really profile maintenance, settings drift, or identity confusion that belongs in a guide instead of a support ticket."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, PROFILE_SETTINGS_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard$1, { key: item.title, item })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "when-to-report",
      eyebrow: "Escalation",
      title: "When to contact support or report a bug",
      summary: "Escalation works best when the problem is already described clearly enough that another person can follow it without guessing."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$2, { items: REPORTING_ITEMS, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Troubleshooting FAQ",
      summary: "These are the fast answers for the moment when a problem exists, but the category of the problem still feels uncertain."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$2 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these routes when the diagnosis points toward access recovery, account settings, publishing workflows, or role-based collaboration guidance."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read auth help"), /* @__PURE__ */ React.createElement("a", { href: links.help_account, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read account settings help"), /* @__PURE__ */ React.createElement("a", { href: links.upload_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Upload help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_faq, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Groups FAQ"), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Report a problem"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-rose-300/20 bg-rose-400/10 p-4 text-rose-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-rose-50/85" }, "A clear problem statement beats frantic guessing. Name the route, the context, and what changed before you decide the product is broken.")))))));
}
const __vite_glob_0_89 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: TroubleshootingHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS$1 = [
  { id: "how-uploading-works", label: "How uploading works" },
  { id: "prepare-before-upload", label: "What to prepare" },
  { id: "personal-vs-group", label: "Personal vs Group upload" },
  { id: "draft-flow", label: "Draft flow" },
  { id: "publish-flow", label: "Publish flow" },
  { id: "file-preview-metadata", label: "File, preview, metadata" },
  { id: "contributor-credit", label: "Contributor credit" },
  { id: "best-practices", label: "Best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS$1 = [
  {
    label: "Core idea",
    value: "Guided workflow, not raw submission",
    note: "Uploading is more than sending a file. It includes draft setup, metadata, previews, context, and publishing checks."
  },
  {
    label: "Most common mistake",
    value: "Wrong context at publish time",
    note: "Personal and Group uploads can look similar, but the published identity and review behavior can be very different."
  },
  {
    label: "Safest habit",
    value: "Review before final publish",
    note: "Drafts exist to help you finish details before the public version goes live."
  }
];
const WORKFLOW_STEPS = [
  {
    title: "Start the upload",
    description: "Begin with the file you want to publish and confirm whether the upload belongs to your personal identity or to a Group context."
  },
  {
    title: "The file is received",
    description: "Skinbase accepts the file and starts turning the upload into a manageable workspace item instead of sending it public immediately."
  },
  {
    title: "A draft is created",
    description: "Uploads usually start as drafts so you can review details, context, credits, and presentation before publishing."
  },
  {
    title: "Processing and previews happen",
    description: "Previews or processing steps may run so the upload is easier to review and present clearly."
  },
  {
    title: "Metadata is completed",
    description: "Titles, descriptions, tags, categories, and other public-facing details are finalized while the upload is still safe to edit."
  },
  {
    title: "Context and contributors are checked",
    description: "Before publishing, verify whether the work belongs to you or a Group and make sure contributor credit reflects the real people behind the upload."
  },
  {
    title: "Publish or submit for review",
    description: "Once the upload is ready, it is either published or routed into review depending on the workflow and permissions involved."
  }
];
const PREP_ITEMS = [
  "Final file you actually want people to see, not a rough placeholder.",
  "Clear title and description so the upload is understandable without extra cleanup later.",
  "Tags and categories if they apply to the content type you are publishing.",
  "Contributor information for collaborative work, especially if a Group is involved.",
  "The correct publish context: personal or Group.",
  "A good preview mindset so the public version feels intentional and discoverable."
];
const UPLOAD_COMPARISON_COLUMNS = [
  { key: "topic", label: "Topic" },
  { key: "personal", label: "Personal upload" },
  { key: "group", label: "Group upload" }
];
const UPLOAD_COMPARISON_ROWS = [
  {
    id: "published-as",
    topic: "Published identity",
    personal: "The work publishes under your personal creator identity.",
    group: "The work publishes under the Group identity."
  },
  {
    id: "credit",
    topic: "Human credit",
    personal: "Your own authorship and upload role are usually straightforward.",
    group: "Contributor credit still matters. Group identity does not replace human authorship."
  },
  {
    id: "permissions",
    topic: "Why behavior can differ",
    personal: "You usually control the full flow yourself.",
    group: "Roles, review queues, and approvals may affect whether you can publish directly."
  },
  {
    id: "drafts",
    topic: "Draft handling",
    personal: "Drafts stay in your personal workspace until you finish them.",
    group: "Drafts may be part of a team review flow before they are publicly published."
  }
];
const DRAFT_FLOW_ITEMS = [
  "Uploads usually begin as drafts so you can finish details without rushing a public release.",
  "Drafts are where metadata, context, previews, and contributor setup are reviewed.",
  "Drafts may still be processing while you are working on the rest of the upload.",
  "Incomplete drafts can be left temporarily, but they are best finished quickly so the workspace stays clean.",
  "In Group workflows, drafts may be submitted for review instead of publishing directly."
];
const PUBLISH_FLOW_ITEMS = [
  "Publishing should happen after file review, metadata review, and context confirmation.",
  "You should verify titles, descriptions, previews, and contributor information before the final step.",
  "Some Groups may route the upload into review instead of publishing immediately.",
  "Publishing under the wrong context is one of the most common avoidable mistakes."
];
const FILE_METADATA_ITEMS = [
  "Previews matter because people often decide whether to open or trust a piece based on its first impression.",
  "Metadata matters because clear titles and descriptions help the work feel intentional and improve discoverability.",
  "Final review matters because small mistakes feel much bigger after the upload is public.",
  "Taking a minute to review the presentation is usually faster than correcting avoidable problems later."
];
const CREDIT_EXAMPLE = [
  { label: "Published by", value: "Nightshift Collective" },
  { label: "Uploaded by", value: "Gregor" },
  { label: "Primary author", value: "Gregor" },
  { label: "Contributors", value: "Paula, Denis" }
];
const CREDIT_BULLETS = [
  "Group uploads still preserve human credit.",
  "Primary author should reflect the main author of the work, not just the person who clicked upload.",
  "Uploaded by and published identity are not always the same thing.",
  "Contributor lists should be intentional, accurate, and checked before publish."
];
const BEST_PRACTICES$1 = [
  "Prepare metadata before you start uploading whenever possible.",
  "Use strong files and previews so the public result feels finished.",
  "Check the publishing context before the final publish step.",
  "Do not rush final publish just because the file is already in the system.",
  "Give proper contributor credit for collaborative work.",
  "Keep drafts organized and return to incomplete uploads quickly."
];
const COMMON_MISTAKES$1 = [
  "Uploading under the wrong context and only noticing after publish.",
  "Forgetting contributor credit during a collaborative upload.",
  "Leaving metadata empty because the file itself looked finished.",
  "Abandoning drafts until the workspace becomes cluttered.",
  "Trying to publish before everything has been reviewed clearly.",
  "Misunderstanding review queue behavior in Group workflows."
];
const FAQ_ITEMS$1 = [
  {
    question: "How does upload work on Skinbase?",
    answer: "Uploads move through a guided workflow. The file is received, a draft is created, previews or processing may happen, metadata is completed, context and contributor credit are reviewed, and then the work is published or submitted for review."
  },
  {
    question: "Why is my upload a draft first?",
    answer: "Draft-first flow gives you a safe place to finish titles, descriptions, previews, context, and credit before the public version goes live."
  },
  {
    question: "Can I upload for a Group?",
    answer: "Yes, if your Group role and workflow allow it. Just make sure the active context is the Group and that contributor credit is set correctly before final publish."
  },
  {
    question: "Why can’t I publish immediately?",
    answer: "You may still need to finish metadata, wait for processing, confirm context, or pass through a review flow if the upload belongs to a Group workflow."
  },
  {
    question: "What should I do before publishing?",
    answer: "Check file quality, previews, metadata, tags, context, and contributor credit. Publishing should be the last review step, not the first one."
  },
  {
    question: "What happens if my upload is incomplete?",
    answer: "It can stay as a draft until you return and finish it, but it is best to complete incomplete drafts quickly so the workspace stays manageable."
  },
  {
    question: "Can I come back later?",
    answer: "Yes. Drafts exist so you can return later, but do not let unfinished uploads pile up without clear intent."
  }
];
const TROUBLESHOOTING_ITEMS$1 = [
  {
    title: "My upload is stuck",
    body: "Give processing a moment, then reopen the upload through Studio or the upload flow. If it still feels stuck, escalate instead of repeatedly retrying blindly.",
    linkKey: "upload",
    linkLabel: "Open upload flow"
  },
  {
    title: "Preview is missing",
    body: "Preview issues are often a sign that the upload is still processing or that you need to re-open the draft and review the current state before publishing.",
    linkKey: "studio_drafts",
    linkLabel: "Open drafts"
  },
  {
    title: "I can’t publish",
    body: "Check whether the issue is unfinished metadata, wrong context, or a Group review workflow that prevents direct publishing.",
    linkKey: "groups_faq",
    linkLabel: "Read Groups FAQ"
  },
  {
    title: "I uploaded under the wrong context",
    body: "Review the draft or published item immediately, then correct the personal-versus-Group context before more workflow steps build on top of the mistake.",
    linkKey: "studio_help",
    linkLabel: "Read Studio help"
  },
  {
    title: "My Group submission went into review",
    body: "That usually means the Group workflow expects approval before public publishing. This is often intentional, not a failure.",
    linkKey: "groups_help",
    linkLabel: "Read Groups help"
  },
  {
    title: "I can’t find my draft",
    body: "Draft confusion usually comes from checking the wrong context. Confirm whether the upload belongs to your personal workspace or a Group.",
    linkKey: "studio_drafts",
    linkLabel: "Open drafts"
  },
  {
    title: "Upload failed",
    body: "If the upload repeatedly fails, stop retrying blindly and use support or bug reporting with a clear description of what happened.",
    linkKey: "report_issue",
    linkLabel: "Report issue"
  }
];
const RELATED_HELP_ITEMS$1 = [
  {
    eyebrow: "Live help",
    title: "Studio help",
    body: "Use the Studio guide to understand the wider workspace where drafts, content management, and publishing decisions live.",
    linkKey: "studio_help",
    tone: "sky"
  },
  {
    eyebrow: "Live help",
    title: "Groups help",
    body: "Use the Groups guide if the upload belongs to a shared identity, needs contributor credit, or goes through Group review.",
    linkKey: "groups_help",
    tone: "amber"
  },
  {
    eyebrow: "Live help",
    title: "Profile help",
    body: "Use the Profile guide if upload confusion is really about creator identity, presentation, or how your public presence should look after publishing.",
    linkKey: "help_profile",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Cards help",
    body: "Use the Cards guide when the question is really about presentation content, Card creation, or choosing Cards instead of artworks or posts.",
    linkKey: "help_cards",
    tone: "white"
  }
];
function HeroMetric$1({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function BulletGrid$1({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function TroubleCard$1({ item, links }) {
  return /* @__PURE__ */ React.createElement("a", { href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")));
}
function UploadHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Upload Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Upload workflow", "Drafts", "Publishing", "Contributor credit", "Group uploads"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS$1.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS$1.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_23%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.14),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Upload help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Uploading on Skinbase is a guided workflow, not just a raw file submission."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This page explains how uploads move from file submission to draft, review, and final publish. It is designed to help you upload confidently, prepare the right details in advance, avoid common context mistakes, and understand what to do when something feels stuck."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.upload, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Start an upload"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Read Studio help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS$1.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric$1, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS$1, ariaLabel: "Upload help sections", selectLabel: "Jump to Upload help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "how-uploading-works",
      eyebrow: "Workflow",
      title: "How uploading works",
      summary: "Uploading is designed to feel understandable and safe. The workflow gives you space to review and finish the public version before it goes live."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: WORKFLOW_STEPS }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Why draft-first upload exists" }, "Drafts reduce rushed submissions. They give you a chance to review context, metadata, previews, and contributor credit before the upload becomes public."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "prepare-before-upload",
      eyebrow: "Preparation",
      title: "What to prepare before upload",
      summary: "The better prepared you are before upload starts, the less likely you are to end up with an unfinished draft, weak presentation, or incorrect publishing context."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$1, { items: PREP_ITEMS, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "personal-vs-group",
      eyebrow: "Context",
      title: "Personal upload vs Group upload",
      summary: "The most important upload decision is not just the file. It is whether the work should publish under your personal identity or under a Group."
    },
    /* @__PURE__ */ React.createElement(
      DocsComparisonTable,
      {
        columns: UPLOAD_COMPARISON_COLUMNS,
        rows: UPLOAD_COMPARISON_ROWS,
        caption: "Comparison between Personal upload and Group upload"
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Always verify context before final publish" }, "The wrong context can turn a correct upload into the wrong public record. Check whether the work belongs to you or to a Group before the final step."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "When in doubt, open Groups help" }, "If the upload involves shared ownership, contributor credit, or review queues, the Groups guide is the next best place to clarify how the upload should behave."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "draft-flow",
      eyebrow: "Drafts",
      title: "Draft flow",
      summary: "Uploads usually begin as drafts so you can finish the details deliberately instead of publishing a half-finished item by accident."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$1, { items: DRAFT_FLOW_ITEMS, tone: "sky" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "publish-flow",
      eyebrow: "Publish",
      title: "Publish flow",
      summary: "Publish is the final decision point. By the time you reach it, the file, context, metadata, and contributor details should already feel solid."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$1, { items: PUBLISH_FLOW_ITEMS, tone: "amber" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Treat final publish like a checklist moment" }, "If something still feels unclear, stop and review it before publishing. A short pause now is cheaper than cleaning up a public mistake later."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "file-preview-metadata",
      eyebrow: "Presentation",
      title: "File, preview, and metadata basics",
      summary: "Strong uploads are not only about file quality. They also depend on how clearly the work is presented and how understandable it feels to other people."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$1, { items: FILE_METADATA_ITEMS, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "contributor-credit",
      eyebrow: "Credit",
      title: "Contributor credit during upload",
      summary: "Upload identity, published identity, and authorship are related, but they are not always the same thing. That matters most in collaborative and Group uploads."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(BulletGrid$1, { items: CREDIT_BULLETS, tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Simple example"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, CREDIT_EXAMPLE.map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.label, className: "rounded-[20px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, entry.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, entry.value))))))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "best-practices",
      eyebrow: "Best practices",
      title: "Best practices",
      summary: "The best upload habits are simple: prepare before you start, review before you publish, and keep the workspace clean enough that you can trust what you are looking at."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$1, { items: BEST_PRACTICES$1, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid this",
      title: "Common mistakes",
      summary: "Most upload problems are not technical failures. They come from skipping review steps, using the wrong context, or leaving too many things unfinished at once."
    },
    /* @__PURE__ */ React.createElement(BulletGrid$1, { items: COMMON_MISTAKES$1, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Upload FAQ",
      summary: "These answers cover the most common questions people ask when an upload becomes a draft, stalls before publish, or behaves differently inside a Group."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS$1 })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Troubleshooting",
      summary: "Use these shortcuts when the upload workflow feels stalled, confusing, or inconsistent."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, TROUBLESHOOTING_ITEMS$1.map((item) => /* @__PURE__ */ React.createElement(TroubleCard$1, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these links when the upload workflow is clear and you need the next layer of guidance around Studio, Groups, profile context, or adjacent creative tools."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.upload, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Start upload"), /* @__PURE__ */ React.createElement("a", { href: links.studio_drafts, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open drafts"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If an upload feels wrong, check three things first: context, draft state, and contributor credit.")))))));
}
const __vite_glob_0_90 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: UploadHelpPage
}, Symbol.toStringTag, { value: "Module" }));
const SECTION_ITEMS = [
  { id: "what-worlds-are", label: "What Worlds are" },
  { id: "worlds-vs-other-surfaces", label: "Worlds vs other surfaces" },
  { id: "building-a-world", label: "Building a World" },
  { id: "attached-content-and-sections", label: "Attached content and sections" },
  { id: "preview-publishing-and-promotion", label: "Preview, publishing, and promotion" },
  { id: "recurrence-and-new-editions", label: "Recurrence and new editions" },
  { id: "media-seo-and-theme-presets", label: "Media, SEO, and theme presets" },
  { id: "best-practices", label: "Best practices" },
  { id: "common-mistakes", label: "Common mistakes" },
  { id: "faq", label: "FAQ" },
  { id: "troubleshooting", label: "Troubleshooting" },
  { id: "related-help", label: "Related help" }
];
const HERO_METRICS = [
  {
    label: "Core purpose",
    value: "Editorial campaign hub",
    note: "A World is a curated destination for seasonal, event, tribute, or campaign storytelling across multiple content types."
  },
  {
    label: "Operational strength",
    value: "Attached content with structure",
    note: "Worlds are built from explicit attachments, section order, section visibility, and preview-first editorial review."
  },
  {
    label: "Golden rule",
    value: "Curate, then publish",
    note: "A World should feel intentional before it goes live. Treat preview, section checks, and promotion scope as part of the workflow."
  }
];
const WHAT_WORLDS_ARE_ITEMS = [
  {
    title: "Worlds are not filters",
    body: "A World is not just a search result, category page, or tag landing page. It is an editorial surface shaped around a theme, moment, or campaign."
  },
  {
    title: "Worlds bundle multiple content types",
    body: "A single World can attach artworks, collections, creators, groups, news, challenges, events, releases, and cards into one public-facing story."
  },
  {
    title: "Worlds are designed for reuse",
    body: "Recurring campaigns such as Halloween, Pixel Week, or tribute weeks can be rolled forward into new editions instead of rebuilt from scratch."
  }
];
const COMPARISON_COLUMNS = [
  { key: "topic", label: "Topic" },
  { key: "world", label: "World" },
  { key: "collection", label: "Collection" },
  { key: "group", label: "Group page" }
];
const COMPARISON_ROWS = [
  {
    id: "purpose",
    topic: "Primary purpose",
    world: "Run a themed editorial or seasonal campaign with curated modules and promotion logic.",
    collection: "Organize a set of items into a more focused list or presentation set.",
    group: "Represent a shared identity, members, and collaboration activity under one collective surface."
  },
  {
    id: "composition",
    topic: "How content is assembled",
    world: "Explicit attachments are placed into named sections such as featured artworks, creators, events, and news.",
    collection: "Items are gathered into a collection-first structure rather than a multi-module campaign layout.",
    group: "Content is shaped by ownership, members, and shared publishing rather than editorial campaign modules."
  },
  {
    id: "public-output",
    topic: "Public output",
    world: "One hero, one intro, optional CTA and badge, then a controlled set of editorial modules.",
    collection: "A more focused item grouping surface.",
    group: "A public identity and activity surface for the collective itself."
  },
  {
    id: "promotion",
    topic: "Promotion role",
    world: "Can stand alone at its own URL or be promoted on Worlds surfaces and homepage spotlight areas.",
    collection: "Usually promoted as a collection destination rather than a campaign system.",
    group: "Promotion is about the Group and its output, not a dedicated campaign moment."
  },
  {
    id: "reuse",
    topic: "Operational reuse",
    world: "Supports duplication and next-edition workflows for recurring campaigns.",
    collection: "Usually reused by copying or curating a new collection manually.",
    group: "Persistent long-term identity, not a short-term edition workflow."
  }
];
const BUILD_WORLD_STEPS = [
  {
    title: "Choose the World type and title",
    description: "Pick the clearest campaign framing first: seasonal, event, campaign, or tribute. Use a title that still reads well in preview, homepage spotlight, and archive contexts."
  },
  {
    title: "Select a theme preset",
    description: "Theme presets can prefill accent colors, background motif, icon, related tags, and suggested badge or CTA labels, while still allowing manual overrides."
  },
  {
    title: "Write the intro and define the identity",
    description: "Add tagline, summary, description, badge, CTA, and the visual identity needed to make the public page feel coherent."
  },
  {
    title: "Attach curated content",
    description: "Use the relation picker to search supported entity types, assign them to sections, mark featured items, and add context labels when needed."
  },
  {
    title: "Adjust section order and visibility",
    description: "Control both where modules appear and whether they appear at all. A World should show only the sections that help the campaign land cleanly."
  },
  {
    title: "Set lifecycle and recurrence",
    description: "Define status, publish timing, campaign window, featured promotion state, and recurring edition metadata before the page goes live."
  },
  {
    title: "Preview before publish",
    description: "Use the mini preview for in-editor confidence and the full preview page for a public-surface check before publishing or featuring the World."
  }
];
const ATTACHMENT_WORKFLOW_ITEMS = [
  {
    title: "The relation picker is the composition tool",
    body: "Add relation opens a structured picker with entity type, search, result previews, section assignment, featured state, and optional context labels."
  },
  {
    title: "Attachments belong to specific sections",
    body: "Each attached item is placed intentionally into a section such as featured artworks, curated collections, related events, or themed cards."
  },
  {
    title: "Attached rows stay editable",
    body: "After attachment, relation cards support edit, remove, and reorder actions so the final World reads like deliberate editorial composition rather than a hidden data list."
  }
];
const SECTION_ITEMS_DETAIL = [
  { title: "Featured artworks", body: "Standout pieces curated for the World." },
  { title: "Curated collections", body: "Collections that deepen the theme and reward longer exploration." },
  { title: "Featured creators", body: "Creators shaping the atmosphere of the moment." },
  { title: "Featured groups", body: "Collectives, scenes, and crews connected to the campaign." },
  { title: "Related news", body: "Editorial context, announcements, and stories tied to the World." },
  { title: "Challenge spotlight", body: "Challenges attached to the campaign or recent participation around it." },
  { title: "Related events", body: "Upcoming or recent sessions, launches, and live moments." },
  { title: "Release spotlights", body: "Projects and releases that belong in the campaign space." },
  { title: "Themed cards", body: "Cards that extend the World identity into designed communication surfaces." }
];
const RELATION_TYPE_ITEMS = [
  "Artworks",
  "Collections",
  "Creators",
  "Groups",
  "News articles",
  "Challenges",
  "Events",
  "Releases",
  "Cards"
];
const LIFECYCLE_ITEMS = [
  {
    title: "Draft, scheduled, live, and archived thinking",
    body: "Worlds move through an editorial lifecycle. Drafts are private workspaces, published Worlds can be scheduled or already live, and archive state keeps past editions visible when the campaign has ended."
  },
  {
    title: "Featured promotion goes beyond the page itself",
    body: "When a World is marked for homepage and Worlds spotlight treatment, it moves from a standalone public page into platform-level campaign promotion readiness."
  },
  {
    title: "The summary card is operational, not decorative",
    body: "Use the editor summary to verify lifecycle state, campaign window, theme, recurrence, relation count, enabled sections, and current promotion scope at a glance."
  }
];
const RECURRENCE_GUIDANCE = [
  "Turn on recurring mode when the World belongs to a repeatable campaign family such as halloween, retro-month, or pixel-week.",
  "The recurrence key identifies the campaign family. The edition year identifies the current edition within that family.",
  "Duplicate plus new-edition actions exist so editors can roll successful Worlds forward into the next campaign cycle more safely.",
  "Recurring Worlds should not reuse the same recurrence key and edition year pair. Each edition needs its own distinct year value."
];
const MEDIA_AND_SEO_GUIDANCE = [
  "Theme presets are acceleration tools, not constraints. Editors can override autofilled colors, motif, icon, tags, badge label, and CTA label at any time.",
  "Cover and OG assets currently use absolute URLs or CDN storage paths. The editor already includes preview support and is prepared for a future shared media picker.",
  "CTA label and URL should represent the real campaign action: explore, join, enter, submit, discover, or a similar world-specific path.",
  "SEO title, SEO description, and OG image should describe the World as a public destination, not as an internal draft."
];
const BEST_PRACTICES = [
  "Lead with one strong hero idea instead of trying to make the World cover every possible related surface.",
  "Attach only the content that sharpens the campaign. More relations do not automatically create a better World.",
  "Use section visibility deliberately so empty or weak modules do not dilute the page.",
  "Preview the World before publish, especially when promotion scope or homepage spotlight is involved.",
  "Use recurrence metadata and new-edition workflows for annual campaigns instead of rebuilding the structure manually each year.",
  "Keep CTA, badge, summary, and theme signals aligned so the World feels like one coherent editorial destination."
];
const COMMON_MISTAKES = [
  "Treating a World like a generic dump of related content instead of an intentional editorial surface.",
  "Leaving sections enabled just because attachments exist, even when those modules do not strengthen the public story.",
  "Marking a World as featured without checking whether the campaign is truly ready for homepage or spotlight promotion.",
  "Ignoring recurrence fields until the next edition arrives and the campaign family becomes harder to manage.",
  "Using weak asset paths or unreviewed OG values that make the preview feel unfinished.",
  "Confusing Worlds with collections, group pages, or challenges when the real need is a different public surface."
];
const FAQ_ITEMS = [
  {
    question: "What is a World on Skinbase?",
    answer: "A World is a curated editorial destination for a seasonal moment, event, tribute, or campaign. It combines one strong hero with a controlled set of attached modules and optional promotion across public surfaces."
  },
  {
    question: "What can I attach to a World?",
    answer: "Worlds can attach artworks, collections, creators, groups, news, challenges, events, releases, and cards. Each item is assigned to a specific section so the page stays structured."
  },
  {
    question: "Can I preview a World before publishing?",
    answer: "Yes. The editor includes a mini preview for live confidence and a dedicated full preview page for saved Worlds so editors can check the public result before it goes live."
  },
  {
    question: "How is a World different from a collection?",
    answer: "A collection groups content. A World is a larger editorial campaign surface with multiple module types, lifecycle controls, promotion readiness, and recurrence support."
  },
  {
    question: "What does featured promotion mean?",
    answer: "Featured promotion means the World is eligible for promoted Worlds surfaces and homepage spotlight treatment once it is in the right lifecycle state."
  },
  {
    question: "How do recurring Worlds work?",
    answer: "Recurring Worlds use a recurrence key to identify the campaign family and an edition year to identify the specific edition. Duplicate and new-edition actions help you roll the structure forward."
  },
  {
    question: "Can I hide sections even if attachments exist?",
    answer: "Yes. Section visibility is explicit. A module can remain disabled on the public page even if attached relations exist for that section."
  }
];
const TROUBLESHOOTING_ITEMS = [
  {
    title: "I can’t find the Worlds workspace",
    body: "Start from Studio and open the Worlds index. If you still do not have access, the issue may be permission-related rather than route-related.",
    linkKey: "studio_worlds",
    linkLabel: "Open Worlds workspace"
  },
  {
    title: "My World does not look right in preview",
    body: "Review hero copy, attached relations, section visibility, theme overrides, and cover or OG asset paths before publishing.",
    linkKey: "create_world",
    linkLabel: "Open create World flow"
  },
  {
    title: "I’m not sure whether this should be a World",
    body: "If the need is a multi-module campaign hub with editorial curation and promotion, use a World. If not, the better answer may be a collection, group surface, or another publishing format.",
    linkKey: "help_cards",
    linkLabel: "Compare with other creative formats"
  },
  {
    title: "I can’t publish or feature the World",
    body: "Check the lifecycle state, campaign dates, and whether the attached content and section controls are ready for a public or promoted surface.",
    linkKey: "studio_help",
    linkLabel: "Read Studio workflow help"
  },
  {
    title: "The attached content feels messy",
    body: "Trim the relation list, move items into clearer sections, and disable weak modules. Worlds work best when the page is curated, not crowded.",
    linkKey: "worlds_index",
    linkLabel: "Browse live Worlds for reference"
  },
  {
    title: "A route or editor action feels broken",
    body: "Use support or bug reporting when the problem is not editorial uncertainty but an actual platform issue with the workflow.",
    linkKey: "report_issue",
    linkLabel: "Report a problem"
  }
];
const RELATED_HELP_ITEMS = [
  {
    eyebrow: "Live help",
    title: "Studio help",
    body: "Use the Studio guide when the real question is about workspace context, drafts, publishing behavior, or creator operations beyond Worlds.",
    linkKey: "studio_help",
    tone: "sky"
  },
  {
    eyebrow: "Live help",
    title: "Upload help",
    body: "Use Upload help when the blocker is asset preparation, artwork metadata, or the publishing workflow feeding into a World.",
    linkKey: "upload_help",
    tone: "amber"
  },
  {
    eyebrow: "Live help",
    title: "Cards help",
    body: "Use Cards help when the question is really about designed communication surfaces that may later be attached to a World.",
    linkKey: "help_cards",
    tone: "white"
  },
  {
    eyebrow: "Live help",
    title: "Groups help",
    body: "Use Groups help when the campaign work is tied to shared identity, contributors, collaboration, or group-owned publishing.",
    linkKey: "groups_help",
    tone: "white"
  }
];
function HeroMetric({ label, value, note }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, note));
}
function InsightCard({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body));
}
function BulletGrid({ items, tone = "sky" }) {
  const dotColor = tone === "amber" ? "bg-amber-300" : tone === "emerald" ? "bg-emerald-300" : "bg-sky-300";
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: `mt-2 h-2 w-2 shrink-0 rounded-full ${dotColor}` }), /* @__PURE__ */ React.createElement("span", null, item)))));
}
function TroubleCard({ item, links }) {
  return /* @__PURE__ */ React.createElement("a", { href: links[item.linkKey], className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-sky-200" }, item.linkLabel), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "→")));
}
function WorldsHelpPage() {
  const { props } = X$1();
  const links = props.links || {};
  const jsonLd = [
    {
      "@context": "https://schema.org",
      "@type": "Article",
      headline: "Worlds Help",
      description: props.description,
      url: props.seo?.canonical,
      author: {
        "@type": "Organization",
        name: "Skinbase"
      },
      about: ["Worlds", "Seasonal campaigns", "Editorial curation", "Studio workflows", "Homepage promotion"]
    },
    {
      "@context": "https://schema.org",
      "@type": "FAQPage",
      mainEntity: FAQ_ITEMS.map((item) => ({
        "@type": "Question",
        name: item.question,
        acceptedAnswer: {
          "@type": "Answer",
          text: item.answer
        }
      }))
    }
  ];
  const relatedHelpItems = RELATED_HELP_ITEMS.map((item) => ({
    ...item,
    href: links[item.linkKey]
  }));
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_23%),radial-gradient(circle_at_bottom_right,_rgba(249,115,22,0.16),_transparent_22%),linear-gradient(180deg,_#020617_0%,_#030712_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: props.title, description: props.description, jsonLd }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1500px]" }, /* @__PURE__ */ React.createElement("section", { id: "introduction", className: "rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(15,23,42,0.92),rgba(15,23,42,0.72)),radial-gradient(circle_at_top_right,rgba(125,211,252,0.16),transparent_28%)] p-6 shadow-[0_30px_100px_rgba(2,6,23,0.35)] md:p-8 lg:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Worlds help"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 max-w-4xl text-4xl font-semibold tracking-[-0.04em] text-white md:text-5xl xl:text-6xl" }, "Worlds are where Skinbase turns curated content into a live campaign surface."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-8 text-slate-300 md:text-lg" }, "This guide explains what Worlds are, how attached content works, how section visibility and order shape the result, and how to preview, publish, promote, and reuse Worlds for recurring campaigns."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: links.create_world, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/18" }, "Create a World"), /* @__PURE__ */ React.createElement("a", { href: links.studio_worlds, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, "Open Worlds workspace"), /* @__PURE__ */ React.createElement("a", { href: links.worlds_index, className: "rounded-full border border-white/10 bg-black/20 px-5 py-3 text-sm font-semibold text-slate-200 transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Worlds"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, HERO_METRICS.map((metric) => /* @__PURE__ */ React.createElement(HeroMetric, { key: metric.label, label: metric.label, value: metric.value, note: metric.note }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 lg:grid-cols-[240px_minmax(0,1fr)] xl:grid-cols-[240px_minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement(DocsSidebarNav, { sections: SECTION_ITEMS, ariaLabel: "Worlds help sections", selectLabel: "Jump to Worlds help section" }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "what-worlds-are",
      eyebrow: "Foundations",
      title: "What Worlds are",
      summary: "Worlds are premium editorial destinations for campaign moments, not just another listing surface. They combine identity, structure, and curation into one public result."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, WHAT_WORLDS_ARE_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-3" }, LIFECYCLE_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "The shortest useful definition" }, "A World is one hero, one short intro, one clear CTA, and a controlled set of attached modules arranged like an editorial campaign rather than a generic content pile."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "worlds-vs-other-surfaces",
      eyebrow: "Format choice",
      title: "Worlds vs other public surfaces",
      summary: "Use a World when the real need is a campaign hub. If the job is simpler, another surface may be a better fit."
    },
    /* @__PURE__ */ React.createElement(DocsComparisonTable, { columns: COMPARISON_COLUMNS, rows: COMPARISON_ROWS, caption: "Comparison between Worlds, collections, and Group pages" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Choose a World when curation needs structure" }, "If the page needs multiple content modules, campaign identity, timing, and possible homepage promotion, a World is usually the right answer."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Do not use Worlds when a simpler surface is enough" }, "If the content only needs a list, collection, or shared identity page, using a World can make the workflow heavier than necessary."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "building-a-world",
      eyebrow: "Workflow",
      title: "Building a World",
      summary: "The editorial workflow is deliberate: define the campaign identity, attach the right content, check structure, preview the result, then publish only when the page reads clearly."
    },
    /* @__PURE__ */ React.createElement(DocsStepList, { items: BUILD_WORLD_STEPS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "attached-content-and-sections",
      eyebrow: "Composition",
      title: "Attached content and sections",
      summary: "Attachments are the heart of the World system. They let editors compose a campaign hub out of explicit, curated relations instead of relying on vague automation."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, ATTACHMENT_WORKFLOW_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Supported attached entity types"), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(BulletGrid, { items: RELATION_TYPE_ITEMS, tone: "emerald" }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Built-in World sections"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-3" }, SECTION_ITEMS_DETAIL.map((item) => /* @__PURE__ */ React.createElement(InsightCard, { key: item.title, item })))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Section order and section presence are different controls" }, "Reordering changes where a module appears. Visibility decides whether that module appears at all. Strong Worlds use both intentionally."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Attached content can stay private to the editor layout" }, "A section can remain disabled on the public page even if attached items exist for it. This is useful when editors are still shaping the campaign or intentionally trimming the public result."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "preview-publishing-and-promotion",
      eyebrow: "Confidence",
      title: "Preview, publishing, and promotion",
      summary: "Worlds are meant for real campaign operations, so lifecycle and promotion state need to be visible and understandable before anything goes public."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, LIFECYCLE_ITEMS.map((item) => /* @__PURE__ */ React.createElement(InsightCard, { key: item.title, item }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Use preview as a safety check" }, "Check the hero, cover, CTA, badge, section order, and attached content hierarchy before moving a World into a public or promoted lifecycle state."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "warning", title: "Featured promotion is stronger than just publish" }, "A World can be publicly visible at its own URL without also being ready for homepage or spotlight promotion. Treat those decisions separately."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "recurrence-and-new-editions",
      eyebrow: "Reuse",
      title: "Recurrence and new editions",
      summary: "Recurring campaigns should be easy to understand operationally. Worlds include recurrence fields and duplication actions so campaign families can evolve cleanly over time."
    },
    /* @__PURE__ */ React.createElement(BulletGrid, { items: RECURRENCE_GUIDANCE, tone: "sky" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "practice", title: "Think in campaign families" }, "“Halloween 2026” and “Halloween 2027” should feel like different editions of the same family, not like unrelated Worlds with manually repeated structure."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "media-seo-and-theme-presets",
      eyebrow: "Presentation",
      title: "Media, SEO, and theme presets",
      summary: "Worlds are visual and promotional. Theme presets accelerate setup, while media and SEO fields shape how the page reads inside the platform and when shared outward."
    },
    /* @__PURE__ */ React.createElement(BulletGrid, { items: MEDIA_AND_SEO_GUIDANCE, tone: "amber" }),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DocsCallout, { tone: "note", title: "Current media workflow" }, "Worlds currently use absolute URLs or CDN storage paths for cover and OG assets. The editor includes asset previews and is already prepared for a future shared media picker."), /* @__PURE__ */ React.createElement(DocsCallout, { tone: "tip", title: "Use presets to move faster, not to stop thinking" }, "Theme presets should give you a strong start. Editors should still adjust the result when the campaign needs a sharper, more specific identity."))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "best-practices",
      eyebrow: "Quality habits",
      title: "Best practices",
      summary: "Strong Worlds feel editorially intentional. Every section, asset, and attached item should earn its place."
    },
    /* @__PURE__ */ React.createElement(BulletGrid, { items: BEST_PRACTICES, tone: "emerald" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "common-mistakes",
      eyebrow: "Avoid this",
      title: "Common mistakes",
      summary: "Most Worlds problems are not technical. They come from weak curation, unclear promotion decisions, or using the wrong format for the job."
    },
    /* @__PURE__ */ React.createElement(BulletGrid, { items: COMMON_MISTAKES, tone: "amber" })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "faq",
      eyebrow: "FAQ",
      title: "Worlds FAQ",
      summary: "These answers cover the most common editorial and workflow questions about creating, attaching, and promoting Worlds."
    },
    /* @__PURE__ */ React.createElement(DocsFaqAccordion, { items: FAQ_ITEMS })
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "troubleshooting",
      eyebrow: "Troubleshooting",
      title: "Troubleshooting",
      summary: "Use these routes when the problem is access, preview quality, format choice, publishing readiness, or an editor workflow issue."
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, TROUBLESHOOTING_ITEMS.map((item) => /* @__PURE__ */ React.createElement(TroubleCard, { key: item.title, item, links })))
  ), /* @__PURE__ */ React.createElement(
    DocsSection,
    {
      id: "related-help",
      eyebrow: "Next steps",
      title: "Related help",
      summary: "Use these links when Worlds are understood and the next question is about adjacent workflows such as Studio, uploads, cards, or Group collaboration."
    },
    /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems })
  )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.create_world, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create a World"), /* @__PURE__ */ React.createElement("a", { href: links.studio_worlds, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Worlds workspace"), /* @__PURE__ */ React.createElement("a", { href: links.worlds_index, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Worlds"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/20 bg-sky-400/10 p-4 text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-sky-50/85" }, "A World should feel like an editorial decision, not a container. If the page feels cluttered, the usual fix is stronger curation, fewer modules, and clearer promotion intent.")))))));
}
const __vite_glob_0_91 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: WorldsHelpPage
}, Symbol.toStringTag, { value: "Module" }));
function cx$4(...parts) {
  return parts.filter(Boolean).join(" ");
}
function LeaderboardTabs({ items, active, onChange, sticky = false, label }) {
  return /* @__PURE__ */ React.createElement("div", { className: cx$4(sticky ? "sticky top-16 z-20" : "", "rounded-2xl border border-white/10 bg-slate-950/85 p-2 backdrop-blur") }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2", role: "tablist", "aria-label": label || "Leaderboard tabs" }, items.map((item) => {
    const isActive = item.value === active;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: item.value,
        type: "button",
        role: "tab",
        "aria-selected": isActive,
        onClick: () => onChange(item.value),
        className: cx$4(
          "rounded-full px-4 py-2 text-sm font-semibold transition",
          isActive ? "bg-sky-400 text-slate-950 shadow-[0_12px_30px_rgba(56,189,248,0.28)]" : "bg-white/5 text-slate-300 hover:bg-white/10 hover:text-white"
        )
      },
      item.label
    );
  })));
}
const PODIUM_STYLES = {
  1: "border-yellow-300/40 bg-[linear-gradient(180deg,rgba(250,204,21,0.18),rgba(15,23,42,0.84))]",
  2: "border-slate-300/30 bg-[linear-gradient(180deg,rgba(226,232,240,0.16),rgba(15,23,42,0.84))]",
  3: "border-amber-700/40 bg-[linear-gradient(180deg,rgba(180,83,9,0.22),rgba(15,23,42,0.84))]"
};
function cx$3(...parts) {
  return parts.filter(Boolean).join(" ");
}
function formatScore(score) {
  return new Intl.NumberFormat().format(Math.round(Number(score || 0)));
}
function LeaderboardItem({ item, type: type2, highlight = false }) {
  const entity = item?.entity || {};
  const rank = Number(item?.rank || 0);
  const tone = highlight ? PODIUM_STYLES[rank] || PODIUM_STYLES[3] : "border-white/10 bg-white/[0.03]";
  const image2 = entity.avatar || entity.image || null;
  const groupSignals = Array.isArray(entity.trust_signals) ? entity.trust_signals.slice(0, 2) : [];
  return /* @__PURE__ */ React.createElement("article", { className: cx$3("rounded-3xl border p-4 shadow-lg transition", tone) }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: cx$3("flex shrink-0 items-center justify-center rounded-2xl border font-black", highlight ? "h-14 w-14 text-xl" : "h-11 w-11 text-base", "border-white/10 bg-slate-950/70 text-white") }, "#", rank), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("a", { href: entity.url || "#", className: "block text-lg font-semibold text-white hover:text-sky-300 transition" }, entity.name || "Unknown"), entity.creator_name ? /* @__PURE__ */ React.createElement("a", { href: entity.creator_url || "#", className: "mt-1 block text-sm text-slate-400 hover:text-sky-300 transition" }, "by ", entity.creator_name) : null, type2 === "group" && entity.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, entity.headline) : null, type2 === "world" && entity.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, entity.summary) : null, entity.username ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-500" }, "@", entity.username) : null), /* @__PURE__ */ React.createElement("div", { className: "text-right" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] uppercase tracking-[0.24em] text-slate-500" }, "Score"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-2xl font-black text-white" }, formatScore(item?.score)))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-3" }, type2 === "creator" ? /* @__PURE__ */ React.createElement(LevelBadge, { level: entity.level, rank: entity.rank, compact: true }) : null, type2 === "group" ? groupSignals.map((signal) => /* @__PURE__ */ React.createElement(GroupBadgePill, { key: signal.key, label: signal.label, tone: signal.tone })) : null, type2 === "group" && entity.is_recruiting ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Recruiting", tone: "emerald" }) : null, type2 !== "creator" && entity.creator_name ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] uppercase tracking-[0.14em] text-slate-300" }, type2) : null, type2 === "group" ? /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-400" }, Number(entity.artworks_count || 0).toLocaleString(), " artworks, ", Number(entity.members_count || 0).toLocaleString(), " members, ", Number(entity.followers_count || 0).toLocaleString(), " followers") : null, type2 === "world" ? /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-400" }, Number(entity.relations_count || 0).toLocaleString(), " curated links, ", Number(entity.approved_submissions_count || 0).toLocaleString(), " approved submissions", entity.timeframe_label ? `, ${entity.timeframe_label}` : "") : null, type2 === "world" && entity.badge_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] uppercase tracking-[0.14em] text-slate-300" }, entity.badge_label) : null, type2 === "world" && entity.theme_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] uppercase tracking-[0.14em] text-slate-300" }, entity.theme_label) : null)), image2 ? /* @__PURE__ */ React.createElement("a", { href: entity.url || "#", className: cx$3("block shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-900", type2 === "creator" ? "h-16 w-16" : "h-20 w-24") }, /* @__PURE__ */ React.createElement("img", { src: image2, alt: entity.name || "Leaderboard item", className: "h-full w-full object-cover", loading: "lazy" })) : null));
}
function LeaderboardList({ items = [], type: type2 }) {
  const podium = items.slice(0, 3);
  const rest = items.slice(3);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, podium.length > 0 ? /* @__PURE__ */ React.createElement("section", null, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-sm font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Top 3"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "Podium leaders")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-4 xl:grid-cols-3" }, podium.map((item) => /* @__PURE__ */ React.createElement(LeaderboardItem, { key: `${type2}-${item.rank}`, item, type: type2, highlight: true })))) : null, /* @__PURE__ */ React.createElement("section", null, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-sm font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Leaderboard"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, items.length, " ranked entries")), items.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-3xl border border-white/10 bg-white/[0.03] px-6 py-10 text-sm text-slate-400" }, "No leaderboard entries available yet for this period.") : /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, rest.map((item) => /* @__PURE__ */ React.createElement(LeaderboardItem, { key: `${type2}-${item.rank}`, item, type: type2 })))));
}
const TYPE_TABS = [
  { value: "creator", label: "Creators" },
  { value: "artwork", label: "Artworks" },
  { value: "group", label: "Groups" },
  { value: "story", label: "Stories" },
  { value: "world", label: "Worlds" }
];
const PERIOD_TABS = [
  { value: "daily", label: "Daily" },
  { value: "weekly", label: "Weekly" },
  { value: "monthly", label: "Monthly" },
  { value: "all_time", label: "All-time" }
];
const API_BY_TYPE = {
  creator: "/api/leaderboard/creators",
  artwork: "/api/leaderboard/artworks",
  group: "/api/leaderboard/groups",
  story: "/api/leaderboard/stories",
  world: "/api/leaderboard/worlds"
};
function LeaderboardPage() {
  const { props } = X$1();
  const { initialType = "creator", initialPeriod = "weekly", initialData = { items: [] }, seo = {} } = props;
  const [type2, setType] = reactExports.useState(initialType);
  const [period, setPeriod] = reactExports.useState(initialPeriod);
  const [data, setData] = reactExports.useState(initialData);
  const [loading, setLoading] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (type2 === initialType && period === initialPeriod) {
      return;
    }
    let cancelled = false;
    async function load() {
      setLoading(true);
      try {
        const response = await window.axios.get(`${API_BY_TYPE[type2]}?period=${period}`);
        if (!cancelled && response.data) {
          setData(response.data);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }
    load();
    try {
      const url = new URL(window.location.href);
      url.searchParams.set("type", type2 === "creator" ? "creators" : `${type2}s`);
      url.searchParams.set("period", period === "all_time" ? "all" : period);
      window.history.replaceState({}, "", url.toString());
    } catch (_2) {
    }
    return () => {
      cancelled = true;
    };
  }, [type2, period, initialType, initialPeriod]);
  const items = Array.isArray(data?.items) ? data.items : [];
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: seo?.title || "Leaderboard — Skinbase", description: seo?.description || "Top creators, groups, artworks, stories, and Worlds on Skinbase." }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[radial-gradient(circle_at_top,rgba(14,165,233,0.14),transparent_34%),linear-gradient(180deg,#020617_0%,#0f172a_48%,#020617_100%)] pb-16 text-slate-100" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("header", { className: "rounded-[2rem] border border-white/10 bg-slate-950/70 px-6 py-8 shadow-[0_35px_120px_rgba(2,6,23,0.75)] backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.28em] text-sky-300" }, "Skinbase Competition Board"), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 max-w-3xl text-4xl font-black tracking-tight text-white sm:text-5xl" }, "Top creators, groups, standout artworks, stories, and Worlds with momentum."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-6 text-slate-300 sm:text-base" }, "Switch between creators, groups, artworks, stories, and Worlds, then filter by daily, weekly, monthly, or all-time performance.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, /* @__PURE__ */ React.createElement(LeaderboardTabs, { items: TYPE_TABS, active: type2, onChange: setType, sticky: true, label: "Leaderboard type" }), /* @__PURE__ */ React.createElement(LeaderboardTabs, { items: PERIOD_TABS, active: period, onChange: setPeriod, label: "Leaderboard period" })), loading ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-3xl border border-white/10 bg-white/[0.03] px-6 py-5 text-sm text-slate-400" }, "Refreshing leaderboard...") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement(LeaderboardList, { items, type: type2 })))));
}
const __vite_glob_0_92 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: LeaderboardPage
}, Symbol.toStringTag, { value: "Module" }));
const browserWindow = typeof window !== "undefined" ? window : null;
const csrfToken$1 = typeof document !== "undefined" ? document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") : null;
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
if (csrfToken$1) {
  axios.defaults.headers.common["X-CSRF-TOKEN"] = csrfToken$1;
}
if (browserWindow) {
  browserWindow.axios = axios;
  browserWindow.Pusher = Pusher;
}
let echoInstance = null;
function isLoopbackHost(host) {
  return ["127.0.0.1", "0.0.0.0", "localhost", "::1"].includes(String(host || "").toLowerCase());
}
function getEcho() {
  if (echoInstance !== null) {
    return echoInstance || null;
  }
  if (!browserWindow) {
    echoInstance = false;
    return null;
  }
  const key = "jm0pq3ikcu3yequsbioc";
  const scheme = "https";
  const forceTLS = scheme === "https";
  const configuredHost = "ws.skinbase.org";
  const publicHostname = browserWindow.location.hostname;
  const useWindowHost = !isLoopbackHost(publicHostname) && isLoopbackHost(configuredHost);
  const resolvedHost = useWindowHost ? publicHostname : configuredHost;
  const resolvedPort = useWindowHost ? Number(443) : Number("443");
  const resolvedSecurePort = useWindowHost ? Number(443) : Number("443");
  echoInstance = new E$2({
    broadcaster: "reverb",
    key,
    wsHost: resolvedHost,
    wsPort: resolvedPort,
    wssPort: resolvedSecurePort,
    forceTLS,
    enabledTransports: ["ws", "wss"],
    authEndpoint: "/broadcasting/auth",
    auth: {
      headers: {
        "X-CSRF-TOKEN": csrfToken$1 || "",
        Accept: "application/json"
      }
    }
  });
  browserWindow.Echo = echoInstance;
  return echoInstance;
}
function ConversationList({ conversations, loading, activeId, currentUserId, onlineUserIds = [], typingByConversation = {}, onSelect }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-1 flex-col overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/[0.06] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Conversations"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/35" }, "Recent threads and group rooms")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-2.5 py-1 text-[11px] text-white/45" }, conversations.length)), /* @__PURE__ */ React.createElement("ul", { className: "nova-scrollbar-message flex-1 space-y-2 overflow-y-auto p-3 pr-2" }, loading ? /* @__PURE__ */ React.createElement("li", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.025] px-4 py-8 text-center text-sm text-white/40" }, "Loading conversations…") : null, !loading && conversations.length === 0 ? /* @__PURE__ */ React.createElement("li", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.025] px-4 py-8 text-center text-sm text-white/40" }, "No conversations yet.") : null, conversations.map((conversation) => /* @__PURE__ */ React.createElement(
    ConversationRow,
    {
      key: conversation.id,
      conv: conversation,
      isActive: conversation.id === activeId,
      currentUserId,
      onlineUserIds,
      typingUsers: typingByConversation[conversation.id] ?? [],
      onClick: () => onSelect(conversation.id)
    }
  ))));
}
function ConversationRow({ conv, isActive, currentUserId, onlineUserIds, typingUsers, onClick }) {
  const label = convLabel(conv, currentUserId);
  const lastMsg = Array.isArray(conv.latest_message) ? conv.latest_message[0] : conv.latest_message;
  const preview = typingUsers.length > 0 ? buildTypingPreview(typingUsers) : lastMsg?.body ? truncate(lastMsg.body, 88) : "No messages yet";
  const unread = conv.unread_count ?? 0;
  const myParticipant = conv.all_participants?.find((participant) => participant.user_id === currentUserId);
  const otherParticipant = conv.all_participants?.find((participant) => participant.user_id !== currentUserId);
  const isArchived = myParticipant?.is_archived ?? false;
  const isPinned = myParticipant?.is_pinned ?? false;
  const activeMembers = conv.all_participants?.filter((participant) => !participant.left_at).length ?? 0;
  const onlineMembers = conv.type === "group" ? conv.all_participants?.filter((participant) => participant.user_id !== currentUserId && onlineUserIds.includes(Number(participant.user_id)) && !participant.left_at).length ?? 0 : 0;
  const isDirectOnline = conv.type === "direct" && otherParticipant ? onlineUserIds.includes(Number(otherParticipant.user_id)) : false;
  const typeLabel2 = conv.type === "group" ? onlineMembers > 0 ? `${onlineMembers} online` : `${activeMembers} members` : isDirectOnline ? "Online now" : "Direct message";
  const senderLabel = lastMsg?.sender?.username ? `@${lastMsg.sender.username}` : null;
  const initials = label.split(/\s+/).filter(Boolean).slice(0, 2).map((part) => part.charAt(0).toUpperCase()).join("") || "M";
  return /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick,
      className: `w-full rounded-[24px] border px-4 py-4 text-left transition ${isActive ? "border-sky-400/28 bg-sky-500/[0.12] shadow-[0_0_0_1px_rgba(56,189,248,0.08)]" : "border-white/[0.06] bg-white/[0.03] hover:border-white/[0.1] hover:bg-white/[0.05]"} ${isArchived ? "opacity-65" : ""}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "relative shrink-0" }, /* @__PURE__ */ React.createElement("div", { className: `flex h-12 w-12 items-center justify-center rounded-2xl text-sm font-semibold text-white shadow-[0_10px_25px_rgba(0,0,0,0.18)] ${conv.type === "group" ? "bg-gradient-to-br from-fuchsia-500 to-violet-600" : "bg-gradient-to-br from-sky-500 to-cyan-500"}` }, initials), isDirectOnline ? /* @__PURE__ */ React.createElement("span", { className: "absolute -bottom-0.5 -right-0.5 h-3.5 w-3.5 rounded-full border-2 border-[#0a101a] bg-emerald-300 shadow-[0_0_0_6px_rgba(16,185,129,0.08)]" }) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `truncate text-sm font-semibold ${isActive ? "text-sky-100" : "text-white/90"}` }, label), isPinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-400/20 bg-amber-500/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-200" }, "Pinned") : null, isArchived ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-white/45" }, "Archived") : null), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[11px] uppercase tracking-[0.18em] text-white/30" }, typeLabel2)), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-col items-end gap-2" }, conv.last_message_at ? /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/30" }, relativeTime$1(conv.last_message_at)) : null, unread > 0 ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex min-w-[1.55rem] items-center justify-center rounded-full border border-sky-400/20 bg-sky-500/14 px-1.5 py-0.5 text-[11px] font-semibold text-sky-100" }, unread > 99 ? "99+" : unread) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/[0.04] bg-black/10 px-3 py-2.5" }, typingUsers.length === 0 && senderLabel ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-white/35" }, senderLabel) : null, /* @__PURE__ */ React.createElement("p", { "data-testid": `conversation-preview-${conv.id}`, className: `mt-1 flex items-center gap-2 truncate text-sm ${typingUsers.length > 0 ? "text-emerald-200" : "text-white/62"}` }, typingUsers.length > 0 ? /* @__PURE__ */ React.createElement(SidebarTypingIcon, null) : null, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, preview)))))
  ));
}
function convLabel(conv, currentUserId) {
  if (conv.type === "group") return conv.title ?? "Group";
  const other = conv.all_participants?.find((participant) => participant.user_id !== currentUserId);
  return other?.user?.username ?? "Direct message";
}
function truncate(str, max2) {
  if (!str) return "";
  return str.length > max2 ? `${str.slice(0, max2)}…` : str;
}
function buildTypingPreview(users) {
  const names = users.map((user) => `@${user.username}`);
  if (names.length === 1) return `${names[0]} is typing...`;
  if (names.length === 2) return `${names[0]} and ${names[1]} are typing...`;
  return `${names[0]}, ${names[1]} and ${names.length - 2} others are typing...`;
}
function SidebarTypingIcon() {
  return /* @__PURE__ */ React.createElement("span", { className: "inline-flex shrink-0 items-center gap-1" }, /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-emerald-300 animate-[pulse_1s_ease-in-out_infinite]" }), /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-emerald-300/80 animate-[pulse_1s_ease-in-out_150ms_infinite]" }), /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-emerald-300/60 animate-[pulse_1s_ease-in-out_300ms_infinite]" }));
}
function relativeTime$1(iso) {
  if (!iso) return "No activity";
  const diff = (Date.now() - new Date(iso).getTime()) / 1e3;
  if (diff < 60) return "Now";
  if (diff < 3600) return `${Math.floor(diff / 60)}m`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h`;
  return `${Math.floor(diff / 86400)}d`;
}
const QUICK_REACTIONS = ["👍", "❤️", "🔥", "😂", "👏", "😮"];
function MessageBubble({ message, isMine, showAvatar, endsSequence = true, isNewlyArrived = false, prefersReducedMotion = false, onReact, onUnreact, onEdit, onDelete = null, onReport = null, onOpenImage = null, seenText = null }) {
  const [showPicker, setShowPicker] = reactExports.useState(false);
  const [showActions, setShowActions] = reactExports.useState(false);
  const [editing, setEditing] = reactExports.useState(false);
  const [editBody, setEditBody] = reactExports.useState(message.body ?? "");
  const [savingEdit, setSavingEdit] = reactExports.useState(false);
  const [isArrivalVisible, setIsArrivalVisible] = reactExports.useState(true);
  const editRef = reactExports.useRef(null);
  const isDeleted = !!message.deleted_at;
  const isEdited = !!message.edited_at;
  const username = message.sender?.username ?? "Unknown";
  const time = formatTime(message.created_at);
  const initials = username.charAt(0).toUpperCase();
  reactExports.useEffect(() => {
    if (editing) {
      editRef.current?.focus();
      editRef.current?.setSelectionRange(editBody.length, editBody.length);
    }
  }, [editing, editBody.length]);
  reactExports.useEffect(() => {
    if (prefersReducedMotion || !isNewlyArrived) {
      setIsArrivalVisible(true);
      return void 0;
    }
    setIsArrivalVisible(false);
    const frame = window.requestAnimationFrame(() => setIsArrivalVisible(true));
    return () => window.cancelAnimationFrame(frame);
  }, [isNewlyArrived, prefersReducedMotion]);
  const reactionGroups = groupReactions(message.reactions ?? []);
  const handleSaveEdit = async () => {
    const trimmed = editBody.trim();
    if (!trimmed || trimmed === message.body || savingEdit) return;
    setSavingEdit(true);
    try {
      await onEdit(message.id, trimmed);
      setEditing(false);
    } finally {
      setSavingEdit(false);
    }
  };
  const handleEditKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSaveEdit();
    }
    if (e.key === "Escape") {
      setEditing(false);
      setEditBody(message.body);
    }
  };
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: message?.id ? `message-${message.id}` : void 0,
      className: `group flex items-end gap-2.5 sm:gap-3 ${isMine ? "flex-row-reverse" : "flex-row"} ${showAvatar ? "mt-4" : "mt-1"}`,
      style: prefersReducedMotion ? void 0 : {
        opacity: isArrivalVisible ? 1 : 0.55,
        transform: isArrivalVisible ? "translateY(0px)" : "translateY(10px)",
        filter: isNewlyArrived && isArrivalVisible ? "drop-shadow(0 0 20px rgba(56,189,248,0.12))" : "none",
        transition: "opacity 260ms ease, transform 320ms ease, filter 900ms ease"
      },
      onMouseEnter: () => !isDeleted && !editing && setShowPicker(true),
      onMouseLeave: () => {
        setShowPicker(false);
        setShowActions(false);
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: `h-9 w-9 shrink-0 ${showAvatar ? "visible" : "invisible"}` }, /* @__PURE__ */ React.createElement("div", { className: `flex h-9 w-9 items-center justify-center rounded-2xl text-xs font-semibold text-white shadow-[0_10px_20px_rgba(0,0,0,0.18)] ${isMine ? "bg-gradient-to-br from-sky-500 to-cyan-500" : "bg-gradient-to-br from-violet-500 to-fuchsia-600"}` }, initials)),
    /* @__PURE__ */ React.createElement("div", { className: `flex max-w-[84%] flex-col sm:max-w-[75%] ${isMine ? "items-end" : "items-start"}` }, showAvatar ? /* @__PURE__ */ React.createElement("div", { className: `mb-1.5 flex items-center gap-2 ${isMine ? "flex-row-reverse" : ""}` }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium text-white/78" }, username), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/30" }, time)) : null, /* @__PURE__ */ React.createElement("div", { className: "relative" }, !editing && !isDeleted ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowActions((prev) => !prev),
        className: `absolute z-[1] inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/[0.08] bg-[#0b1220]/88 text-white/40 shadow-[0_10px_20px_rgba(0,0,0,0.18)] transition hover:bg-[#11192a] hover:text-white ${isMine ? "-left-3 top-2 md:opacity-0 md:group-hover:opacity-100" : "-right-3 top-2 md:opacity-0 md:group-hover:opacity-100"}`,
        "aria-label": "Message actions"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-ellipsis text-[11px]" })
    ) : null, editing ? /* @__PURE__ */ React.createElement("div", { className: "w-72" }, /* @__PURE__ */ React.createElement(
      "textarea",
      {
        ref: editRef,
        value: editBody,
        onChange: (e) => setEditBody(e.target.value),
        onKeyDown: handleEditKeyDown,
        rows: 3,
        maxLength: 5e3,
        className: "w-full resize-none rounded-2xl border border-sky-400/30 bg-black/20 px-3 py-2 text-sm text-white outline-none transition focus:border-sky-300/40"
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex justify-end gap-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => {
          setEditing(false);
          setEditBody(message.body);
        },
        className: "text-xs text-white/35 transition hover:text-white/65"
      },
      "Cancel"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: handleSaveEdit,
        disabled: savingEdit || !editBody.trim() || editBody.trim() === message.body,
        className: "text-xs font-medium text-sky-300 transition hover:text-sky-200 disabled:opacity-40"
      },
      savingEdit ? "Saving…" : "Save"
    ))) : /* @__PURE__ */ React.createElement(
      "div",
      {
        className: `px-4 py-3 text-sm leading-relaxed shadow-[0_14px_35px_rgba(0,0,0,0.16)] ${bubbleShape({ isMine, showAvatar, endsSequence })} ${isMine ? "border border-sky-400/24 bg-sky-500/16 text-white" : "border border-white/[0.06] bg-white/[0.04] text-white/88"} ${isDeleted ? "italic opacity-60" : ""} ${message._optimistic ? "opacity-70" : ""}`
      },
      isDeleted ? /* @__PURE__ */ React.createElement("span", null, "This message was deleted.") : /* @__PURE__ */ React.createElement(React.Fragment, null, message.attachments?.length > 0 ? /* @__PURE__ */ React.createElement(AttachmentCluster, { attachments: message.attachments, isMine, onOpenImage }) : null, /* @__PURE__ */ React.createElement("div", { className: "prose prose-invert prose-sm max-w-none prose-headings:text-white prose-li:text-inherit prose-p:my-0 prose-pre:my-1 prose-strong:text-white text-white/90" }, /* @__PURE__ */ React.createElement(
        Markdown,
        {
          allowedElements: ["p", "strong", "em", "code", "pre", "ul", "ol", "li", "blockquote", "a", "br"],
          unwrapDisallowed: true,
          components: {
            a: ({ href, children }) => /* @__PURE__ */ React.createElement(
              "a",
              {
                href,
                target: "_blank",
                rel: "noopener noreferrer nofollow",
                className: isMine ? "text-sky-100 underline" : "text-sky-300 underline"
              },
              children
            ),
            code: ({ children, className }) => className ? /* @__PURE__ */ React.createElement("code", { className: `${className} text-xs` }, children) : /* @__PURE__ */ React.createElement("code", { className: `rounded px-1 py-0.5 text-xs ${isMine ? "bg-sky-500/20" : "bg-white/[0.08]"}` }, children)
          }
        },
        message.body
      )), isEdited ? /* @__PURE__ */ React.createElement("span", { className: `ml-1 text-xs ${isMine ? "text-sky-100/80" : "text-white/40"}` }, "(edited)") : null)
    ), (showPicker || showActions) && !editing && !isDeleted ? /* @__PURE__ */ React.createElement(
      "div",
      {
        className: `absolute bottom-full z-10 mb-2 flex items-center gap-1 whitespace-nowrap rounded-full border border-white/[0.08] bg-[#0b1220] px-2 py-1 shadow-[0_20px_40px_rgba(0,0,0,0.35)] ${isMine ? "right-0" : "left-0"}`,
        onMouseEnter: () => setShowPicker(true),
        onMouseLeave: () => {
          setShowPicker(false);
          setShowActions(false);
        }
      },
      QUICK_REACTIONS.map((emoji) => /* @__PURE__ */ React.createElement("button", { key: emoji, onClick: () => {
        onReact(message.id, emoji);
        setShowActions(false);
      }, className: "inline-flex h-8 w-8 items-center justify-center rounded-full text-base transition-transform hover:scale-125", title: `React ${emoji}` }, emoji)),
      isMine ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => {
            setEditing(true);
            setShowPicker(false);
            setShowActions(false);
          },
          className: "ml-1 inline-flex h-8 w-8 items-center justify-center rounded-full text-white/35 transition hover:bg-white/[0.06] hover:text-white/80",
          title: "Edit message"
        },
        /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", className: "h-3.5 w-3.5", viewBox: "0 0 20 20", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" }))
      ), onDelete ? /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => {
            onDelete(message.id);
            setShowPicker(false);
            setShowActions(false);
          },
          className: "inline-flex h-8 w-8 items-center justify-center rounded-full text-white/35 transition hover:bg-rose-500/10 hover:text-rose-300",
          title: "Delete message"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash text-[11px]" })
      ) : null) : null,
      !isMine && onReport ? /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => {
            onReport(message.id);
            setShowPicker(false);
            setShowActions(false);
          },
          className: "ml-1 inline-flex h-8 w-8 items-center justify-center rounded-full text-white/35 transition hover:bg-rose-500/10 hover:text-rose-300",
          title: "Report message"
        },
        "⚑"
      ) : null
    ) : null), reactionGroups.length > 0 && !isDeleted ? /* @__PURE__ */ React.createElement("div", { className: `mt-1 flex flex-wrap gap-1 ${isMine ? "justify-end" : "justify-start"} ${endsSequence ? "" : "mb-0.5"}` }, reactionGroups.map(({ emoji, count, iReacted }) => /* @__PURE__ */ React.createElement(
      "button",
      {
        key: emoji,
        onClick: () => iReacted ? onUnreact(message.id, emoji) : onReact(message.id, emoji),
        title: iReacted ? "Remove reaction" : `React ${emoji}`,
        className: `flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-xs transition-colors ${iReacted ? "border border-sky-400/20 bg-sky-500/14 text-sky-100" : "border border-white/[0.08] bg-white/[0.04] text-white/55 hover:bg-white/[0.08] hover:text-white"}`
      },
      /* @__PURE__ */ React.createElement("span", null, emoji),
      /* @__PURE__ */ React.createElement("span", null, count)
    ))) : null, isMine && seenText ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-white/30" }, seenText) : null)
  );
}
function formatTime(iso) {
  return new Date(iso).toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" });
}
function bubbleShape({ isMine, showAvatar, endsSequence }) {
  if (isMine) {
    return `${showAvatar ? "rounded-t-[24px]" : "rounded-tl-[24px] rounded-tr-[14px]"} ${endsSequence ? "rounded-bl-[24px] rounded-br-[8px]" : "rounded-bl-[24px] rounded-br-[14px]"}`;
  }
  return `${showAvatar ? "rounded-t-[24px]" : "rounded-tr-[24px] rounded-tl-[14px]"} ${endsSequence ? "rounded-br-[24px] rounded-bl-[8px]" : "rounded-br-[24px] rounded-bl-[14px]"}`;
}
function AttachmentCluster({ attachments, isMine, onOpenImage }) {
  const images = attachments.filter((attachment) => attachment.type === "image");
  const files = attachments.filter((attachment) => attachment.type !== "image");
  return /* @__PURE__ */ React.createElement("div", { className: "mb-3 space-y-2.5" }, images.length > 0 ? /* @__PURE__ */ React.createElement(AttachmentImageGrid, { images, onOpenImage }) : null, files.length > 0 ? /* @__PURE__ */ React.createElement(AttachmentFileStack, { files, isMine }) : null);
}
function AttachmentImageGrid({ images, onOpenImage }) {
  const gridClass = images.length === 1 ? "grid-cols-1" : "grid-cols-2";
  return /* @__PURE__ */ React.createElement("div", { className: `grid gap-2 ${gridClass}` }, images.slice(0, 4).map((attachment, index2) => {
    const remaining = images.length - 4;
    const showOverlay = remaining > 0 && index2 === 3;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: attachment.id,
        type: "button",
        onClick: () => onOpenImage?.({
          id: attachment.id,
          original_name: attachment.original_name,
          url: `/messages/attachments/${attachment.id}`
        }),
        className: `group/image relative overflow-hidden rounded-[20px] border border-white/15 bg-black/20 ${images.length === 1 ? "max-w-md" : ""}`
      },
      /* @__PURE__ */ React.createElement(
        "img",
        {
          src: `/messages/attachments/${attachment.id}`,
          alt: attachment.original_name,
          className: `w-full object-cover transition duration-200 group-hover/image:scale-[1.02] ${images.length === 1 ? "max-h-72" : "h-32 sm:h-36"}`,
          loading: "lazy"
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/60 to-transparent px-3 py-2 text-left text-xs text-white/80" }, /* @__PURE__ */ React.createElement("span", { className: "line-clamp-1" }, attachment.original_name)),
      showOverlay ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 flex items-center justify-center bg-black/45 text-lg font-semibold text-white" }, "+", remaining) : null
    );
  }));
}
function AttachmentFileStack({ files, isMine }) {
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[20px] border px-3 py-3 ${isMine ? "border-sky-400/18 bg-sky-500/10" : "border-white/[0.08] bg-black/20"}` }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-white/45" }, "Files"), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/35" }, files.length)), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, files.map((attachment) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: attachment.id,
      href: `/messages/attachments/${attachment.id}`,
      target: "_blank",
      rel: "noopener noreferrer",
      className: `flex items-center gap-3 rounded-2xl border px-3 py-2 text-left text-xs transition hover:translate-x-[1px] ${isMine ? "border-sky-400/12 bg-sky-500/10 text-sky-50 hover:bg-sky-500/14" : "border-white/[0.08] bg-white/[0.04] text-white/80 hover:bg-white/[0.06]"}`
    },
    /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-9 w-9 items-center justify-center rounded-xl ${isMine ? "bg-sky-500/16 text-sky-100" : "bg-white/[0.08] text-white/70"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-paperclip text-[11px]" })),
    /* @__PURE__ */ React.createElement("span", { className: "min-w-0 flex-1 truncate" }, attachment.original_name),
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-[10px] opacity-60" })
  ))));
}
function groupReactions(reactions) {
  const map = /* @__PURE__ */ new Map();
  for (const reaction of reactions) {
    if (!map.has(reaction.reaction)) map.set(reaction.reaction, { count: 0, iReacted: false });
    const entry = map.get(reaction.reaction);
    entry.count += 1;
    if (reaction._iMine) entry.iReacted = true;
  }
  return Array.from(map.entries()).map(([emoji, { count, iReacted }]) => ({ emoji, count, iReacted }));
}
function ConversationThread({
  conversationId,
  conversation,
  realtimeEnabled,
  realtimeStatus,
  currentUserId,
  currentUsername,
  onlineUserIds,
  apiFetch: apiFetch2,
  onBack,
  onMarkRead,
  onConversationPatched,
  onUnreadTotalPatched
}) {
  const [messages, setMessages] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [loadingMore, setLoadingMore] = reactExports.useState(false);
  const [nextCursor, setNextCursor] = reactExports.useState(null);
  const [body2, setBody] = reactExports.useState("");
  const [files, setFiles] = reactExports.useState([]);
  const [sending, setSending] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const [typingUsers, setTypingUsers] = reactExports.useState([]);
  const [participantState, setParticipantState] = reactExports.useState(conversation?.all_participants ?? []);
  const [presenceUsers, setPresenceUsers] = reactExports.useState([]);
  const [threadSearch, setThreadSearch] = reactExports.useState("");
  const [busyAction, setBusyAction] = reactExports.useState(null);
  const [lightbox, setLightbox] = reactExports.useState(null);
  const [draftTitle, setDraftTitle] = reactExports.useState(conversation?.title ?? "");
  const listRef = reactExports.useRef(null);
  const fileInputRef = reactExports.useRef(null);
  const typingRef = reactExports.useRef(null);
  const stopTypingRef = reactExports.useRef(null);
  const readReceiptRef = reactExports.useRef(null);
  const typingExpiryTimersRef = reactExports.useRef(/* @__PURE__ */ new Map());
  const messagesRef = reactExports.useRef([]);
  const lastStartRef = reactExports.useRef(0);
  const initialLoadRef = reactExports.useRef(true);
  const shouldStickToBottomRef = reactExports.useRef(true);
  const previousScrollHeightRef = reactExports.useRef(0);
  const pendingPrependRef = reactExports.useRef(false);
  const pendingComposerScrollRef = reactExports.useRef(false);
  const knownMessageIdsRef = reactExports.useRef(/* @__PURE__ */ new Set());
  const animatedMessageIdsRef = reactExports.useRef(/* @__PURE__ */ new Set());
  const [animatedMessageIds, setAnimatedMessageIds] = reactExports.useState({});
  const prefersReducedMotion = usePrefersReducedMotion();
  const draftStorageKey = reactExports.useMemo(() => conversationId ? `nova_draft_${conversationId}` : null, [conversationId]);
  const readDraftFromStorage = reactExports.useCallback(() => {
    if (!draftStorageKey || typeof window === "undefined") {
      return "";
    }
    try {
      return window.localStorage.getItem(draftStorageKey) ?? "";
    } catch {
      return "";
    }
  }, [draftStorageKey]);
  const persistDraftToStorage = reactExports.useCallback((value) => {
    if (!draftStorageKey || typeof window === "undefined") {
      return;
    }
    try {
      if (value.trim() === "") {
        window.localStorage.removeItem(draftStorageKey);
      } else {
        window.localStorage.setItem(draftStorageKey, value);
      }
    } catch {
    }
  }, [draftStorageKey]);
  const myParticipant = reactExports.useMemo(() => conversation?.my_participant ?? participantState.find((participant) => participant.user_id === currentUserId) ?? null, [conversation, currentUserId, participantState]);
  const participants = reactExports.useMemo(() => participantState, [participantState]);
  const participantNames = reactExports.useMemo(() => participants.map((participant) => participant.user?.username).filter(Boolean), [participants]);
  const remoteParticipantNames = reactExports.useMemo(() => participants.filter((participant) => participant.user_id !== currentUserId).map((participant) => participant.user?.username).filter(Boolean), [currentUserId, participants]);
  const directParticipant = reactExports.useMemo(() => participants.find((participant) => participant.user_id !== currentUserId) ?? null, [currentUserId, participants]);
  const remoteIsOnline = directParticipant ? onlineUserIds.includes(Number(directParticipant.user_id)) : false;
  const remoteIsViewingConversation = directParticipant ? presenceUsers.some((user) => Number(user?.id) === Number(directParticipant.user_id)) : false;
  const filteredMessages = reactExports.useMemo(() => {
    const query = threadSearch.trim().toLowerCase();
    if (!query) return messages;
    return messages.filter((message) => {
      const sender = message.sender?.username?.toLowerCase() ?? "";
      const text2 = message.body?.toLowerCase() ?? "";
      const attachmentNames = (message.attachments ?? []).map((attachment) => attachment.original_name?.toLowerCase() ?? "").join(" ");
      return sender.includes(query) || text2.includes(query) || attachmentNames.includes(query);
    });
  }, [messages, threadSearch]);
  const conversationLabel = reactExports.useMemo(() => {
    if (!conversation) return "Conversation";
    if (conversation.type === "group") return conversation.title ?? "Group conversation";
    return participants.find((participant) => participant.user_id !== currentUserId)?.user?.username ?? "Direct message";
  }, [conversation, currentUserId, participants]);
  const patchConversation = reactExports.useCallback((patch2) => {
    if (!patch2) {
      return;
    }
    onConversationPatched?.({
      id: conversationId,
      ...patch2
    });
  }, [conversationId, onConversationPatched]);
  const patchLastMessage = reactExports.useCallback((message, extra = {}) => {
    if (!message) {
      return;
    }
    patchConversation({
      latest_message: message,
      last_message_at: message.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
      ...extra
    });
  }, [patchConversation]);
  const patchMyParticipantState = reactExports.useCallback((changes) => {
    if (!changes) {
      return;
    }
    setParticipantState((prev) => prev.map((participant) => participant.user_id === currentUserId ? { ...participant, ...changes } : participant));
    patchConversation({
      my_participant: {
        ...myParticipant ?? {},
        ...changes
      }
    });
  }, [currentUserId, myParticipant, patchConversation]);
  const scrollToBottom = reactExports.useCallback(() => {
    if (!listRef.current) {
      return;
    }
    listRef.current.scrollTop = listRef.current.scrollHeight;
    shouldStickToBottomRef.current = true;
  }, []);
  const loadMessages = reactExports.useCallback(async ({ cursor = null, append: append2 = false, silent = false } = {}) => {
    if (append2) setLoadingMore(true);
    else if (!silent) setLoading(true);
    if (append2 && listRef.current) {
      previousScrollHeightRef.current = listRef.current.scrollHeight;
      pendingPrependRef.current = true;
    }
    try {
      const url = cursor ? `/api/messages/${conversationId}?cursor=${encodeURIComponent(cursor)}` : `/api/messages/${conversationId}`;
      const data = await apiFetch2(url);
      const incoming = normalizeMessages(data.data ?? [], currentUserId);
      setNextCursor(data.next_cursor ?? null);
      setMessages((prev) => append2 ? mergeMessageLists(incoming, prev) : incoming);
      setError(null);
    } catch (e) {
      setError(e.message);
    } finally {
      if (!silent) setLoading(false);
      setLoadingMore(false);
    }
  }, [apiFetch2, conversationId, currentUserId]);
  const loadTyping = reactExports.useCallback(async () => {
    try {
      const data = await apiFetch2(`/api/messages/${conversationId}/typing`);
      setTypingUsers(data.typing ?? []);
    } catch {
      setTypingUsers([]);
    }
  }, [apiFetch2, conversationId]);
  const markConversationRead = reactExports.useCallback(async (messageId = null) => {
    try {
      const response = await apiFetch2(`/api/messages/${conversationId}/read`, {
        method: "POST",
        body: JSON.stringify(messageId ? { message_id: messageId } : {})
      });
      setParticipantState((prev) => prev.map((participant) => participant.user_id === currentUserId ? {
        ...participant,
        last_read_at: response.last_read_at ?? (/* @__PURE__ */ new Date()).toISOString(),
        last_read_message_id: response.last_read_message_id ?? messageId ?? participant.last_read_message_id
      } : participant));
      onMarkRead?.(conversationId, response?.unread_total ?? null);
    } catch {
    }
  }, [apiFetch2, conversationId, currentUserId, onMarkRead]);
  const queueReadReceipt = reactExports.useCallback((messageId = null) => {
    if (readReceiptRef.current) {
      window.clearTimeout(readReceiptRef.current);
    }
    readReceiptRef.current = window.setTimeout(() => {
      markConversationRead(messageId);
    }, 220);
  }, [markConversationRead]);
  reactExports.useEffect(() => {
    initialLoadRef.current = true;
    shouldStickToBottomRef.current = true;
    previousScrollHeightRef.current = 0;
    pendingPrependRef.current = false;
    pendingComposerScrollRef.current = false;
    knownMessageIdsRef.current = /* @__PURE__ */ new Set();
    animatedMessageIdsRef.current = /* @__PURE__ */ new Set();
    setMessages([]);
    setPresenceUsers([]);
    setTypingUsers([]);
    setNextCursor(null);
    setBody(readDraftFromStorage());
    setFiles([]);
    loadMessages();
    if (!realtimeEnabled) {
      loadTyping();
    }
  }, [conversationId, loadMessages, loadTyping, readDraftFromStorage, realtimeEnabled]);
  reactExports.useEffect(() => {
    setParticipantState(conversation?.all_participants ?? []);
    setDraftTitle(conversation?.title ?? "");
  }, [conversation?.all_participants, conversation?.title]);
  reactExports.useEffect(() => {
    markConversationRead();
  }, [markConversationRead]);
  reactExports.useEffect(() => {
    if (realtimeEnabled) {
      return void 0;
    }
    const timer = window.setInterval(() => {
      loadTyping();
      loadMessages({ silent: true });
    }, 8e3);
    return () => window.clearInterval(timer);
  }, [loadMessages, loadTyping, realtimeEnabled]);
  reactExports.useEffect(() => () => {
    if (typingRef.current) window.clearTimeout(typingRef.current);
    if (stopTypingRef.current) window.clearTimeout(stopTypingRef.current);
    if (readReceiptRef.current) window.clearTimeout(readReceiptRef.current);
    typingExpiryTimersRef.current.forEach((timer) => window.clearTimeout(timer));
  }, []);
  reactExports.useEffect(() => {
    messagesRef.current = messages;
  }, [messages]);
  reactExports.useLayoutEffect(() => {
    const container = listRef.current;
    if (!container) {
      return;
    }
    if (initialLoadRef.current) {
      scrollToBottom();
      initialLoadRef.current = false;
      previousScrollHeightRef.current = container.scrollHeight;
      return;
    }
    if (pendingPrependRef.current) {
      const heightDelta = container.scrollHeight - previousScrollHeightRef.current;
      container.scrollTop += heightDelta;
      pendingPrependRef.current = false;
      previousScrollHeightRef.current = container.scrollHeight;
      return;
    }
    const latestMessage = messages[messages.length - 1] ?? null;
    const shouldScroll = pendingComposerScrollRef.current || shouldStickToBottomRef.current || latestMessage?._optimistic || latestMessage?.sender_id === currentUserId;
    if (shouldScroll) {
      scrollToBottom();
    }
    pendingComposerScrollRef.current = false;
    previousScrollHeightRef.current = container.scrollHeight;
  }, [currentUserId, messages, scrollToBottom]);
  reactExports.useEffect(() => {
    if (!realtimeEnabled) {
      return void 0;
    }
    const echo = getEcho();
    if (!echo) {
      return void 0;
    }
    const syncMissedMessages = async () => {
      const lastServerMessage = [...messagesRef.current].reverse().find((message) => Number.isFinite(Number(message.id)) && !message._optimistic);
      if (!lastServerMessage?.id) {
        return;
      }
      try {
        const data = await apiFetch2(`/api/messages/${conversationId}/delta?after_message_id=${encodeURIComponent(lastServerMessage.id)}`);
        const incoming = normalizeMessages(data.data ?? [], currentUserId);
        if (data?.conversation?.id) {
          patchConversation(data.conversation);
        }
        if (Number.isFinite(Number(data?.summary?.unread_total))) {
          onUnreadTotalPatched?.(data.summary.unread_total);
        }
        if (incoming.length > 0) {
          setMessages((prev) => mergeMessageLists(prev, incoming));
          const latestIncoming = incoming[incoming.length - 1] ?? null;
          const latestRemoteIncoming = [...incoming].reverse().find((message) => message.sender_id !== currentUserId) ?? null;
          if (latestIncoming) {
            patchLastMessage(latestIncoming);
          }
          if (latestRemoteIncoming && document.visibilityState === "visible") {
            queueReadReceipt(latestRemoteIncoming.id);
          }
        }
      } catch {
      }
    };
    const handleMessageCreated = (payload) => {
      if (!payload?.message) return;
      const incoming = normalizeMessage(payload.message, currentUserId);
      setMessages((prev) => mergeMessageLists(prev, [incoming]));
      patchLastMessage(incoming, { unread_count: 0 });
      if (incoming.sender_id !== currentUserId && document.visibilityState === "visible") {
        queueReadReceipt(incoming.id);
      }
    };
    const handleMessageUpdated = (payload) => {
      if (!payload?.message) return;
      const updated = normalizeMessage(payload.message, currentUserId);
      setMessages((prev) => mergeMessageLists(prev, [updated]));
      patchLastMessage(updated);
    };
    const handleMessageDeleted = (payload) => {
      const deletedAt = payload?.deleted_at ?? (/* @__PURE__ */ new Date()).toISOString();
      setMessages((prev) => prev.map((message) => messagesMatch(message, payload) ? { ...message, body: "", deleted_at: deletedAt, attachments: [] } : message));
      patchConversation({ last_message_at: deletedAt });
    };
    const handleMessageRead = (payload) => {
      if (!payload?.user?.id) return;
      setParticipantState((prev) => prev.map((participant) => participant.user_id === payload.user.id ? {
        ...participant,
        last_read_at: payload.last_read_at ?? participant.last_read_at,
        last_read_message_id: payload.last_read_message_id ?? participant.last_read_message_id
      } : participant));
    };
    const removeTypingUser = (userId) => {
      const existingTimer = typingExpiryTimersRef.current.get(userId);
      if (existingTimer) {
        window.clearTimeout(existingTimer);
        typingExpiryTimersRef.current.delete(userId);
      }
      setTypingUsers((prev) => prev.filter((user) => user.user_id !== userId && user.id !== userId));
    };
    const handleTypingStarted = (payload) => {
      const user = payload?.user;
      if (!user?.id || user.id === currentUserId) return;
      setTypingUsers((prev) => mergeTypingUsers(prev, {
        user_id: user.id,
        username: user.username
      }));
      removeTypingUser(user.id);
      const timeout = window.setTimeout(() => removeTypingUser(user.id), Number(payload?.expires_in_ms ?? 3500));
      typingExpiryTimersRef.current.set(user.id, timeout);
    };
    const handleTypingStopped = (payload) => {
      const userId = payload?.user?.id;
      if (!userId) return;
      removeTypingUser(userId);
    };
    const privateChannel = echo.private(`conversation.${conversationId}`);
    privateChannel.listen(".message.created", handleMessageCreated);
    privateChannel.listen(".message.updated", handleMessageUpdated);
    privateChannel.listen(".message.deleted", handleMessageDeleted);
    privateChannel.listen(".message.read", handleMessageRead);
    const presenceChannel = echo.join(`conversation.${conversationId}`);
    presenceChannel.here((users) => setPresenceUsers(normalizePresenceUsers(users, currentUserId))).joining((user) => setPresenceUsers((prev) => mergePresenceUsers(prev, user, currentUserId))).leaving((user) => setPresenceUsers((prev) => prev.filter((member) => member.id !== user?.id))).listen(".typing.started", handleTypingStarted).listen(".typing.stopped", handleTypingStopped);
    const connection = echo.connector?.pusher?.connection;
    connection?.bind?.("connected", syncMissedMessages);
    syncMissedMessages();
    return () => {
      connection?.unbind?.("connected", syncMissedMessages);
      typingExpiryTimersRef.current.forEach((timer) => window.clearTimeout(timer));
      typingExpiryTimersRef.current.clear();
      echo.leave(`conversation.${conversationId}`);
    };
  }, [apiFetch2, conversationId, currentUserId, onUnreadTotalPatched, patchConversation, patchLastMessage, queueReadReceipt, realtimeEnabled]);
  reactExports.useEffect(() => {
    const known = knownMessageIdsRef.current;
    const nextAnimatedIds = [];
    for (const message of messages) {
      if (known.has(message.id)) continue;
      known.add(message.id);
      if (!initialLoadRef.current && !message._optimistic && !animatedMessageIdsRef.current.has(message.id)) {
        animatedMessageIdsRef.current.add(message.id);
        nextAnimatedIds.push(message.id);
      }
    }
    if (prefersReducedMotion || nextAnimatedIds.length === 0) return void 0;
    setAnimatedMessageIds((prev) => {
      const next = { ...prev };
      nextAnimatedIds.forEach((id) => {
        next[id] = true;
      });
      return next;
    });
    const timer = window.setTimeout(() => {
      setAnimatedMessageIds((prev) => {
        const next = { ...prev };
        nextAnimatedIds.forEach((id) => {
          delete next[id];
        });
        return next;
      });
    }, 2200);
    return () => window.clearTimeout(timer);
  }, [messages, prefersReducedMotion]);
  const handleBodyChange = reactExports.useCallback((value) => {
    setBody(value);
    persistDraftToStorage(value);
    if (value.trim() === "") {
      if (stopTypingRef.current) window.clearTimeout(stopTypingRef.current);
      apiFetch2(`/api/messages/${conversationId}/typing/stop`, { method: "POST" }).catch(() => {
      });
      return;
    }
    const now = Date.now();
    if (now - lastStartRef.current > 2500) {
      lastStartRef.current = now;
      apiFetch2(`/api/messages/${conversationId}/typing`, { method: "POST" }).catch(() => {
      });
    }
    if (stopTypingRef.current) window.clearTimeout(stopTypingRef.current);
    stopTypingRef.current = window.setTimeout(() => {
      apiFetch2(`/api/messages/${conversationId}/typing/stop`, { method: "POST" }).catch(() => {
      });
    }, 1200);
  }, [apiFetch2, conversationId, persistDraftToStorage]);
  const handleFiles = reactExports.useCallback((selectedFiles) => {
    const nextFiles = Array.from(selectedFiles || []).slice(0, 5);
    setFiles(nextFiles);
  }, []);
  const handleSend = reactExports.useCallback(async (e) => {
    e.preventDefault();
    if (sending) return;
    const trimmed = body2.trim();
    if (!trimmed && files.length === 0) return;
    const optimisticId = `optimistic-${Date.now()}`;
    const clientTempId = `tmp_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
    const optimisticMessage = normalizeMessage({
      id: optimisticId,
      client_temp_id: clientTempId,
      body: trimmed,
      sender: { id: currentUserId, username: currentUsername },
      sender_id: currentUserId,
      created_at: (/* @__PURE__ */ new Date()).toISOString(),
      attachments: files.map((file, index2) => ({
        id: `${optimisticId}-${index2}`,
        type: file.type?.startsWith("image/") ? "image" : "file",
        original_name: file.name
      })),
      reactions: [],
      _optimistic: true
    }, currentUserId);
    pendingComposerScrollRef.current = true;
    shouldStickToBottomRef.current = true;
    setMessages((prev) => mergeMessageLists(prev, [optimisticMessage]));
    setBody("");
    persistDraftToStorage("");
    setFiles([]);
    if (fileInputRef.current) fileInputRef.current.value = "";
    setSending(true);
    setError(null);
    const formData = new FormData();
    if (trimmed) formData.append("body", trimmed);
    formData.append("client_temp_id", clientTempId);
    files.forEach((file) => formData.append("attachments[]", file));
    try {
      const created = await apiFetch2(`/api/messages/${conversationId}`, {
        method: "POST",
        body: formData
      });
      if (draftStorageKey && typeof window !== "undefined") {
        try {
          window.localStorage.removeItem(draftStorageKey);
        } catch {
        }
      }
      const normalized = normalizeMessage(created, currentUserId);
      setMessages((prev) => mergeMessageLists(prev, [normalized]));
      patchLastMessage(normalized, { unread_count: 0 });
    } catch (err) {
      setMessages((prev) => prev.filter((message) => !messagesMatch(message, { id: optimisticId, client_temp_id: clientTempId })));
      setBody(trimmed);
      persistDraftToStorage(trimmed);
      setFiles(files);
      setError(err.message);
    } finally {
      setSending(false);
      apiFetch2(`/api/messages/${conversationId}/typing/stop`, { method: "POST" }).catch(() => {
      });
    }
  }, [apiFetch2, body2, conversationId, currentUserId, currentUsername, files, patchLastMessage, persistDraftToStorage, sending]);
  const updateReactions = reactExports.useCallback((messageId, summary) => {
    setMessages((prev) => prev.map((message) => {
      if (message.id !== messageId) return message;
      return {
        ...message,
        reactions: summaryToReactionArray(summary, currentUserId)
      };
    }));
  }, [currentUserId]);
  const handleReact = reactExports.useCallback(async (messageId, reaction) => {
    const summary = await apiFetch2(`/api/messages/${messageId}/reactions`, {
      method: "POST",
      body: JSON.stringify({ reaction })
    });
    updateReactions(messageId, summary);
  }, [apiFetch2, updateReactions]);
  const handleUnreact = reactExports.useCallback(async (messageId, reaction) => {
    const summary = await apiFetch2(`/api/messages/${messageId}/reactions`, {
      method: "DELETE",
      body: JSON.stringify({ reaction })
    });
    updateReactions(messageId, summary);
  }, [apiFetch2, updateReactions]);
  const handleEdit = reactExports.useCallback(async (messageId, nextBody) => {
    const updated = await apiFetch2(`/api/messages/message/${messageId}`, {
      method: "PATCH",
      body: JSON.stringify({ body: nextBody })
    });
    setMessages((prev) => prev.map((message) => message.id === messageId ? normalizeMessage({ ...message, ...updated }, currentUserId) : message));
    patchLastMessage(normalizeMessage(updated, currentUserId));
  }, [apiFetch2, currentUserId, patchLastMessage]);
  const handleDelete = reactExports.useCallback(async (messageId) => {
    await apiFetch2(`/api/messages/message/${messageId}`, { method: "DELETE" });
    setMessages((prev) => prev.map((message) => message.id === messageId ? { ...message, body: "", deleted_at: (/* @__PURE__ */ new Date()).toISOString(), attachments: [] } : message));
    patchConversation({ last_message_at: (/* @__PURE__ */ new Date()).toISOString() });
  }, [apiFetch2, patchConversation]);
  const runConversationAction = reactExports.useCallback(async (action, url, apply) => {
    setBusyAction(action);
    setError(null);
    try {
      const response = await apiFetch2(url, { method: action === "leave" ? "DELETE" : "POST" });
      apply?.(response);
      if (action === "leave") onBack?.();
    } catch (e) {
      setError(e.message);
    } finally {
      setBusyAction(null);
    }
  }, [apiFetch2, onBack]);
  const handleRename = reactExports.useCallback(async () => {
    const title = draftTitle.trim();
    if (!title || title === conversation?.title) return;
    setBusyAction("rename");
    setError(null);
    try {
      await apiFetch2(`/api/messages/${conversationId}/rename`, {
        method: "POST",
        body: JSON.stringify({ title })
      });
      patchConversation({ title });
    } catch (e) {
      setError(e.message);
    } finally {
      setBusyAction(null);
    }
  }, [apiFetch2, conversation?.title, conversationId, draftTitle, patchConversation]);
  const visibleMessages = filteredMessages;
  const messagesWithDecorators = reactExports.useMemo(() => decorateMessages(visibleMessages, currentUserId, myParticipant), [visibleMessages, currentUserId, myParticipant]);
  const typingLabel = buildTypingLabel(typingUsers);
  const presenceLabel = conversation?.type === "group" ? presenceUsers.length > 0 ? `${presenceUsers.length} active now` : null : remoteIsViewingConversation ? "Viewing this conversation" : remoteIsOnline ? "Online now" : null;
  const typingSummary = typingUsers.length > 0 ? `${typingLabel} ${conversation?.type === "group" ? "" : "Reply will appear here instantly."}`.trim() : null;
  return /* @__PURE__ */ React.createElement("div", { className: "flex min-h-0 flex-1 flex-col" }, /* @__PURE__ */ React.createElement("header", { className: "border-b border-white/[0.06] px-3 py-4 sm:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 lg:hidden" }, /* @__PURE__ */ React.createElement("button", { onClick: onBack, className: "inline-flex h-11 w-11 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] text-white/60 transition hover:bg-white/[0.08] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-sm" })), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Inbox")), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h2", { className: "truncate text-2xl font-semibold text-white" }, conversationLabel), conversation?.type === "group" ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-fuchsia-400/20 bg-fuchsia-500/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-fuchsia-200" }, "Group") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-400/20 bg-sky-500/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-200" }, "Direct"), realtimeEnabled ? /* @__PURE__ */ React.createElement(RealtimeStatusBadge, { status: realtimeStatus }) : null, myParticipant?.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200" }, "Pinned") : null, myParticipant?.is_muted ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/45" }, "Muted") : null, myParticipant?.is_archived ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/45" }, "Archived") : null), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-white/50" }, conversation?.type === "group" ? `Participants: ${participantNames.join(", ")}` : `Private thread with ${participantNames.find((name2) => name2 !== currentUsername) ?? conversationLabel}.`), typingSummary ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 inline-flex items-center gap-2 rounded-full border border-emerald-400/18 bg-emerald-500/10 px-3 py-1.5 text-xs font-medium text-emerald-100/90" }, /* @__PURE__ */ React.createElement(TypingPulse, null), /* @__PURE__ */ React.createElement("span", null, typingSummary)) : presenceLabel ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-emerald-200/70" }, presenceLabel) : conversation?.type === "direct" && remoteParticipantNames.length > 0 ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/38" }, "Chatting with @", remoteParticipantNames[0], " in realtime.") : null), /* @__PURE__ */ React.createElement("div", { className: "-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 lg:mx-0 lg:flex-wrap lg:overflow-visible lg:px-0 lg:pb-0" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => runConversationAction("archive", `/api/messages/${conversationId}/archive`, (response) => {
        patchMyParticipantState({ is_archived: !!response.is_archived });
      }),
      className: actionButtonClass(busyAction === "archive")
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-box-archive text-[11px]" }),
    myParticipant?.is_archived ? "Unarchive" : "Archive"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => runConversationAction("mute", `/api/messages/${conversationId}/mute`, (response) => {
        patchMyParticipantState({ is_muted: !!response.is_muted });
      }),
      className: actionButtonClass(busyAction === "mute")
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bell-slash text-[11px]" }),
    myParticipant?.is_muted ? "Unmute" : "Mute"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => runConversationAction(myParticipant?.is_pinned ? "unpin" : "pin", `/api/messages/${conversationId}/${myParticipant?.is_pinned ? "unpin" : "pin"}`, (response) => {
        patchMyParticipantState({
          is_pinned: !!response.is_pinned,
          pinned_at: response.is_pinned ? (/* @__PURE__ */ new Date()).toISOString() : null
        });
      }),
      className: actionButtonClass(busyAction === "pin" || busyAction === "unpin")
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-thumbtack text-[11px]" }),
    myParticipant?.is_pinned ? "Unpin" : "Pin"
  ), conversation?.type === "group" ? /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => runConversationAction("leave", `/api/messages/${conversationId}/leave`),
      className: "inline-flex items-center gap-2 rounded-full border border-rose-400/18 bg-rose-500/10 px-4 py-2 text-sm font-medium text-rose-200 transition hover:bg-rose-500/16"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-right-from-bracket text-[11px]" }),
    "Leave"
  ) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-[minmax(0,1fr)_260px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-black/15 px-3 py-2.5 transition focus-within:border-sky-400/30 focus-within:bg-black/25" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass text-xs text-white/30" }), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: threadSearch,
      onChange: (e) => setThreadSearch(e.target.value),
      placeholder: "Search inside this thread…",
      className: "w-full bg-transparent text-sm text-white outline-none placeholder:text-white/25"
    }
  ))), conversation?.type === "group" ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2 sm:flex-row" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: draftTitle,
      onChange: (e) => setDraftTitle(e.target.value),
      placeholder: "Rename group",
      className: "min-w-0 flex-1 rounded-2xl border border-white/[0.08] bg-black/15 px-3 py-2.5 text-sm text-white outline-none placeholder:text-white/25 focus:border-sky-400/30 focus:bg-black/25"
    }
  ), /* @__PURE__ */ React.createElement("button", { onClick: handleRename, disabled: busyAction === "rename", className: actionButtonClass(busyAction === "rename") }, "Save")) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.03] px-4 py-2.5 text-sm text-white/45" }, participantNames.length, " participant", participantNames.length === 1 ? "" : "s"))), error ? /* @__PURE__ */ React.createElement("div", { className: "border-b border-rose-500/14 bg-rose-500/8 px-4 py-3 text-sm text-rose-200 sm:px-6" }, error) : null, /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: listRef,
      onScroll: () => {
        if (!listRef.current) {
          return;
        }
        shouldStickToBottomRef.current = isNearBottom(listRef.current);
      },
      className: "nova-scrollbar-message flex-1 overflow-y-auto px-3 py-4 pr-2 sm:px-6 sm:py-5"
    },
    nextCursor ? /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex justify-center" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: () => loadMessages({ cursor: nextCursor, append: true }),
        disabled: loadingMore,
        className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-xs font-medium text-white/60 transition hover:bg-white/[0.08] hover:text-white disabled:opacity-50"
      },
      loadingMore ? "Loading older messages…" : "Load older messages"
    )) : null,
    loading ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.03] px-5 py-4 text-sm text-white/45" }, "Loading conversation…")) : visibleMessages.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-md rounded-[28px] border border-white/[0.06] bg-white/[0.03] px-6 py-8 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-16 w-16 items-center justify-center rounded-[22px] border border-white/[0.08] bg-white/[0.04] text-white/35" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-message text-2xl" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-lg font-semibold text-white" }, threadSearch.trim() ? "No matching messages" : "No messages yet"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/45" }, threadSearch.trim() ? "Try a different search term or clear the filter to see the full thread." : "Start the conversation with a message, file, or quick note."))) : /* @__PURE__ */ React.createElement("div", { className: "space-y-1.5 sm:space-y-1" }, messagesWithDecorators.map(({ message, showUnreadMarker, dayLabel }, index2) => {
      const previous2 = messagesWithDecorators[index2 - 1]?.message;
      const next = messagesWithDecorators[index2 + 1]?.message;
      const showAvatar = !previous2 || previous2.sender_id !== message.sender_id;
      const endsSequence = !next || next.sender_id !== message.sender_id;
      const seenText = isLastMineMessage(visibleMessages, index2, currentUserId) ? buildSeenText(participants, currentUserId, message) : null;
      return /* @__PURE__ */ React.createElement("div", { key: message.id, className: "relative" }, dayLabel ? /* @__PURE__ */ React.createElement("div", { className: "sticky top-2 z-[1] my-4 flex justify-center first:mt-0" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-[#0b1220]/90 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white/45 shadow-[0_10px_30px_rgba(0,0,0,0.22)] backdrop-blur" }, dayLabel)) : null, showUnreadMarker ? /* @__PURE__ */ React.createElement(UnreadMarker, { prefersReducedMotion }) : null, /* @__PURE__ */ React.createElement(
        MessageBubble,
        {
          message,
          isMine: message.sender_id === currentUserId,
          showAvatar,
          endsSequence,
          isNewlyArrived: !!animatedMessageIds[message.id],
          prefersReducedMotion,
          onReact: handleReact,
          onUnreact: handleUnreact,
          onEdit: handleEdit,
          onDelete: handleDelete,
          onOpenImage: setLightbox,
          seenText
        }
      ));
    }))
  ), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] bg-white/[0.02] px-3 py-4 pb-[calc(1rem+env(safe-area-inset-bottom,0px))] sm:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-white/45" }, typingLabel ? /* @__PURE__ */ React.createElement("span", null, typingLabel) : /* @__PURE__ */ React.createElement("span", null, "Markdown supported. Images and files can be sent inline.")), files.length > 0 ? /* @__PURE__ */ React.createElement("span", { className: "text-xs text-white/30" }, files.length, "/5 attachments") : null), files.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex flex-wrap gap-2" }, files.map((file, index2) => /* @__PURE__ */ React.createElement("span", { key: `${file.name}-${index2}`, className: "inline-flex items-center gap-2 rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1.5 text-xs text-white/65" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${file.type?.startsWith("image/") ? "fa-image" : "fa-paperclip"} text-[10px]` }), file.name))) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSend, className: "rounded-[28px] border border-white/[0.08] bg-black/15 p-3 shadow-[0_18px_45px_rgba(0,0,0,0.2)] sm:p-3.5" }, /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: body2,
      onChange: (e) => handleBodyChange(e.target.value),
      placeholder: "Write a message…",
      rows: 3,
      maxLength: 5e3,
      className: "w-full resize-none bg-transparent px-2 py-2 text-sm leading-6 text-white outline-none placeholder:text-white/25"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-col gap-3 border-t border-white/[0.06] pt-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      ref: fileInputRef,
      type: "file",
      multiple: true,
      onChange: (e) => handleFiles(e.target.files),
      className: "hidden"
    }
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => fileInputRef.current?.click(),
      className: "inline-flex min-h-11 items-center gap-2 rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/65 transition hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-paperclip text-[11px]" }),
    "Attach files"
  ), files.length > 0 ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        setFiles([]);
        if (fileInputRef.current) fileInputRef.current.value = "";
      },
      className: "inline-flex min-h-11 items-center gap-2 rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/45 transition hover:bg-white/[0.08] hover:text-white"
    },
    "Clear"
  ) : null), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: sending || !body2.trim() && files.length === 0,
      className: "inline-flex min-h-11 items-center justify-center gap-2 rounded-full bg-sky-500 px-5 py-2.5 text-sm font-semibold text-slate-950 transition hover:bg-sky-400 disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${sending ? "fa-spinner fa-spin" : "fa-paper-plane"} text-[11px]` }),
    sending ? "Sending…" : "Send message"
  )))), lightbox ? /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-[#020611e6] p-4 backdrop-blur-md", onClick: () => setLightbox(null) }, /* @__PURE__ */ React.createElement("div", { className: "relative max-h-[90vh] max-w-5xl", onClick: (e) => e.stopPropagation() }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setLightbox(null),
      className: "absolute right-3 top-3 inline-flex h-10 w-10 items-center justify-center rounded-full border border-white/15 bg-black/30 text-white/80 transition hover:bg-black/45"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })
  ), /* @__PURE__ */ React.createElement("img", { src: lightbox.url, alt: lightbox.original_name ?? "Attachment", className: "max-h-[90vh] rounded-[28px] border border-white/10" }))) : null);
}
function actionButtonClass(isBusy) {
  return `inline-flex min-h-11 shrink-0 items-center gap-2 rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/65 transition hover:bg-white/[0.08] hover:text-white ${isBusy ? "opacity-60" : ""}`;
}
function normalizeMessages(messages, currentUserId) {
  return messages.map((message) => normalizeMessage(message, currentUserId));
}
function normalizeMessage(message, currentUserId) {
  const reactionSummary = message.reaction_summary ?? null;
  return {
    ...message,
    sender_id: message.sender_id ?? message.sender?.id ?? null,
    reactions: reactionSummary ? summaryToReactionArray(reactionSummary, currentUserId) : normalizeReactionArray(message.reactions ?? [], currentUserId)
  };
}
function normalizeReactionArray(reactions, currentUserId) {
  return reactions.map((reaction) => ({
    ...reaction,
    _iMine: reaction._iMine ?? reaction.user_id === currentUserId
  }));
}
function summaryToReactionArray(summary, currentUserId) {
  if (!summary || typeof summary !== "object") return [];
  const mine = Array.isArray(summary.me) ? summary.me : [];
  return Object.entries(summary).filter(([emoji]) => emoji !== "me").flatMap(([emoji, count]) => Array.from({ length: Number(count) || 0 }, (_2, index2) => ({
    id: `${emoji}-${index2}`,
    reaction: emoji,
    user_id: mine.includes(emoji) && index2 === 0 ? currentUserId : null,
    _iMine: mine.includes(emoji) && index2 === 0
  })));
}
function mergeMessageLists(existing, incoming) {
  const next = [...existing];
  for (const incomingMessage of incoming) {
    const existingIndex = next.findIndex((message) => messagesMatch(message, incomingMessage));
    if (existingIndex >= 0) {
      next[existingIndex] = {
        ...next[existingIndex],
        ...incomingMessage,
        _optimistic: false
      };
      continue;
    }
    next.push(incomingMessage);
  }
  return next.sort((a, b2) => new Date(a.created_at).getTime() - new Date(b2.created_at).getTime());
}
function messagesMatch(left, right) {
  if (!left || !right) return false;
  if (left.id && right.id && String(left.id) === String(right.id)) return true;
  if (left.uuid && right.uuid && left.uuid === right.uuid) return true;
  if (left.client_temp_id && right.client_temp_id && left.client_temp_id === right.client_temp_id) return true;
  return false;
}
function mergeTypingUsers(existing, incoming) {
  const matchIndex = existing.findIndex((user) => String(user.user_id ?? user.id) === String(incoming.user_id ?? incoming.id));
  if (matchIndex === -1) {
    return [...existing, incoming];
  }
  const next = [...existing];
  next[matchIndex] = { ...next[matchIndex], ...incoming };
  return next;
}
function normalizePresenceUsers(users, currentUserId) {
  return (users ?? []).filter((user) => user?.id !== currentUserId);
}
function mergePresenceUsers(existing, incoming, currentUserId) {
  if (!incoming?.id || incoming.id === currentUserId) {
    return existing;
  }
  const next = [...existing];
  const index2 = next.findIndex((user) => user.id === incoming.id);
  if (index2 >= 0) {
    next[index2] = { ...next[index2], ...incoming };
    return next;
  }
  next.push(incoming);
  return next;
}
function isNearBottom(container, threshold = 120) {
  return container.scrollHeight - container.scrollTop - container.clientHeight <= threshold;
}
function buildTypingLabel(users) {
  if (!users || users.length === 0) return "";
  const names = users.map((user) => `@${user.username}`);
  if (names.length === 1) return `${names[0]} is typing…`;
  if (names.length === 2) return `${names[0]} and ${names[1]} are typing…`;
  return `${names.slice(0, 2).join(", ")} and ${names.length - 2} others are typing…`;
}
function isLastMineMessage(messages, index2, currentUserId) {
  const current = messages[index2];
  if (!current || current.sender_id !== currentUserId) return false;
  for (let i = index2 + 1; i < messages.length; i += 1) {
    if (messages[i].sender_id === currentUserId) return false;
  }
  return true;
}
function buildSeenText(participants, currentUserId, message) {
  const seenBy = participants.filter((participant) => participant.user_id !== currentUserId && participantHasReadMessage(participant, message));
  if (seenBy.length === 0) return "Sent";
  if (seenBy.length === 1) {
    const readAt = seenBy[0]?.last_read_at;
    return readAt ? `Seen ${formatSeenTime(readAt)}` : "Seen";
  }
  return `Seen by ${seenBy.length} people`;
}
function decorateMessages(messages, currentUserId, participant) {
  let unreadMarked = false;
  const lastReadMessageId = Number(participant?.last_read_message_id ?? 0);
  const lastReadAt = participant?.last_read_at ?? null;
  return messages.map((message, index2) => {
    const previous2 = messages[index2 - 1];
    const currentDay = dayKey(message.created_at);
    const previousDay = previous2 ? dayKey(previous2.created_at) : null;
    const shouldMarkUnread = !unreadMarked && message.sender_id !== currentUserId && !message.deleted_at && (lastReadMessageId > 0 ? Number(message.id) > lastReadMessageId : lastReadAt ? new Date(message.created_at).getTime() > new Date(lastReadAt).getTime() : true);
    if (shouldMarkUnread) unreadMarked = true;
    return {
      message,
      showUnreadMarker: shouldMarkUnread,
      dayLabel: currentDay !== previousDay ? formatDayLabel(message.created_at) : null
    };
  });
}
function participantHasReadMessage(participant, message) {
  const lastReadMessageId = Number(participant?.last_read_message_id ?? 0);
  if (lastReadMessageId > 0) {
    return Number(message?.id ?? 0) > 0 && lastReadMessageId >= Number(message.id);
  }
  if (participant?.last_read_at && message?.created_at) {
    return new Date(participant.last_read_at).getTime() >= new Date(message.created_at).getTime();
  }
  return false;
}
function formatSeenTime(iso) {
  const then = new Date(iso).getTime();
  if (!Number.isFinite(then)) {
    return "moments ago";
  }
  const diffSeconds = Math.max(0, Math.floor((Date.now() - then) / 1e3));
  if (diffSeconds < 60) return "moments ago";
  if (diffSeconds < 3600) return `${Math.floor(diffSeconds / 60)}m ago`;
  if (diffSeconds < 86400) return `${Math.floor(diffSeconds / 3600)}h ago`;
  if (diffSeconds < 604800) return `${Math.floor(diffSeconds / 86400)}d ago`;
  return new Date(iso).toLocaleDateString(void 0, {
    month: "short",
    day: "numeric"
  });
}
function dayKey(iso) {
  const date = new Date(iso);
  return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
}
function formatDayLabel(iso) {
  const date = new Date(iso);
  const today = /* @__PURE__ */ new Date();
  const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const startOfDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  const diffDays = Math.round((startOfToday.getTime() - startOfDate.getTime()) / 864e5);
  if (diffDays === 0) return "Today";
  if (diffDays === 1) return "Yesterday";
  return date.toLocaleDateString(void 0, {
    weekday: "short",
    month: "short",
    day: "numeric"
  });
}
function UnreadMarker({ prefersReducedMotion }) {
  const [isVisible, setIsVisible] = reactExports.useState(prefersReducedMotion);
  reactExports.useEffect(() => {
    if (prefersReducedMotion) return void 0;
    setIsVisible(false);
    const frame = window.requestAnimationFrame(() => setIsVisible(true));
    return () => window.cancelAnimationFrame(frame);
  }, [prefersReducedMotion]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "my-4 flex items-center gap-3",
      style: prefersReducedMotion ? void 0 : {
        opacity: isVisible ? 1 : 0.45,
        transform: isVisible ? "scale(1)" : "scale(0.985)",
        transition: "opacity 280ms ease, transform 360ms ease"
      }
    },
    /* @__PURE__ */ React.createElement("span", { className: "h-px flex-1 bg-sky-400/25" }),
    /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-400/20 bg-sky-500/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200" }, "Unread messages"),
    /* @__PURE__ */ React.createElement("span", { className: "h-px flex-1 bg-sky-400/25" })
  );
}
function TypingPulse() {
  return /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1" }, /* @__PURE__ */ React.createElement("span", { className: "h-2 w-2 rounded-full bg-emerald-300 animate-[pulse_1s_ease-in-out_infinite]" }), /* @__PURE__ */ React.createElement("span", { className: "h-2 w-2 rounded-full bg-emerald-300/80 animate-[pulse_1s_ease-in-out_160ms_infinite]" }), /* @__PURE__ */ React.createElement("span", { className: "h-2 w-2 rounded-full bg-emerald-300/60 animate-[pulse_1s_ease-in-out_320ms_infinite]" }));
}
function RealtimeStatusBadge({ status: status2 }) {
  const label = status2 === "connected" ? "Socket live" : status2 === "connecting" ? "Socket connecting" : "Socket offline";
  const tone = status2 === "connected" ? "border-emerald-400/20 bg-emerald-500/10 text-emerald-200" : status2 === "connecting" ? "border-amber-400/20 bg-amber-500/10 text-amber-200" : "border-rose-400/18 bg-rose-500/10 text-rose-200";
  const dot = status2 === "connected" ? "bg-emerald-300" : status2 === "connecting" ? "bg-amber-300" : "bg-rose-300";
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-1.5 rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tone}` }, /* @__PURE__ */ React.createElement("span", { className: `h-1.5 w-1.5 rounded-full ${dot}` }), label);
}
function usePrefersReducedMotion() {
  const [prefersReducedMotion, setPrefersReducedMotion] = reactExports.useState(false);
  reactExports.useEffect(() => {
    const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
    const handleChange = () => setPrefersReducedMotion(mediaQuery.matches);
    handleChange();
    mediaQuery.addEventListener("change", handleChange);
    return () => mediaQuery.removeEventListener("change", handleChange);
  }, []);
  return prefersReducedMotion;
}
function NewConversationModal({ currentUserId, apiFetch: apiFetch2, onCreated, onClose }) {
  const [type2, setType] = reactExports.useState("direct");
  const [recipientInput, setRecipient] = reactExports.useState("");
  const [groupTitle, setGroupTitle] = reactExports.useState("");
  const [participantInputs, setParticipantInputs] = reactExports.useState(["", ""]);
  const [body2, setBody] = reactExports.useState("");
  const [sending, setSending] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const addParticipant = () => setParticipantInputs((prev) => [...prev, ""]);
  const updateParticipant = (index2, value) => setParticipantInputs((prev) => prev.map((entry, currentIndex) => currentIndex === index2 ? value : entry));
  const removeParticipant = (index2) => setParticipantInputs((prev) => prev.filter((_2, currentIndex) => currentIndex !== index2));
  const handleSubmit = reactExports.useCallback(async (e) => {
    e.preventDefault();
    setError(null);
    setSending(true);
    try {
      const payload = { type: type2, body: body2 };
      if (type2 === "direct") {
        const user = await resolveUsername(recipientInput.trim(), apiFetch2);
        payload.recipient_id = user.id;
      } else {
        const resolved = await Promise.all(
          participantInputs.map((entry) => entry.trim()).filter(Boolean).map((entry) => resolveUsername(entry, apiFetch2))
        );
        payload.participant_ids = resolved.map((user) => user.id);
        payload.title = groupTitle.trim();
      }
      const conv = await apiFetch2("/api/messages/conversation", {
        method: "POST",
        body: JSON.stringify(payload)
      });
      onCreated(conv);
    } catch (e2) {
      setError(e2.message);
    } finally {
      setSending(false);
    }
  }, [apiFetch2, body2, groupTitle, onCreated, participantInputs, recipientInput, type2]);
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-[#020611cc] p-4 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-xl overflow-hidden rounded-[32px] border border-white/[0.08] bg-[linear-gradient(180deg,rgba(12,18,29,0.98),rgba(7,11,18,0.96))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/35" }, "Compose"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Start a new conversation"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/50" }, "Send a direct message or set up a group thread with collaborators.")), /* @__PURE__ */ React.createElement("button", { onClick: onClose, className: "inline-flex h-10 w-10 items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] text-white/55 transition hover:bg-white/[0.08] hover:text-white" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", className: "h-5 w-5", viewBox: "0 0 20 20", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z", clipRule: "evenodd" }))))), /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit, className: "space-y-5 px-6 py-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, ["direct", "group"].map((entryType) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: entryType,
      type: "button",
      onClick: () => setType(entryType),
      className: `rounded-[24px] border px-4 py-4 text-left transition ${type2 === entryType ? "border-sky-400/28 bg-sky-500/[0.12] text-sky-100" : "border-white/[0.08] bg-white/[0.03] text-white/65 hover:bg-white/[0.05] hover:text-white"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-11 w-11 items-center justify-center rounded-2xl ${entryType === "direct" ? "bg-sky-500/14 text-sky-200" : "bg-fuchsia-500/14 text-fuchsia-200"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${entryType === "direct" ? "fa-user" : "fa-user-group"}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold" }, entryType === "direct" ? "Direct message" : "Group conversation"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/40" }, entryType === "direct" ? "One creator, one thread." : "Coordinate with multiple people.")))
  ))), type2 === "direct" ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Recipient username"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: recipientInput,
      onChange: (e) => setRecipient(e.target.value),
      placeholder: "username",
      required: true,
      className: "w-full rounded-2xl border border-white/[0.08] bg-black/15 px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/25 focus:border-sky-400/30 focus:bg-black/25"
    }
  )) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Group name"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: groupTitle,
      onChange: (e) => setGroupTitle(e.target.value),
      placeholder: "Group name",
      required: true,
      maxLength: 120,
      className: "w-full rounded-2xl border border-white/[0.08] bg-black/15 px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/25 focus:border-sky-400/30 focus:bg-black/25"
    }
  )), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("label", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Participants"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addParticipant, className: "text-xs font-medium text-sky-300 transition hover:text-sky-200" }, "+ Add participant")), participantInputs.map((value, index2) => /* @__PURE__ */ React.createElement("div", { key: index2, className: "mb-2 flex gap-2" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value,
      onChange: (e) => updateParticipant(index2, e.target.value),
      placeholder: `Username ${index2 + 1}`,
      required: true,
      className: "flex-1 rounded-2xl border border-white/[0.08] bg-black/15 px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/25 focus:border-sky-400/30 focus:bg-black/25"
    }
  ), participantInputs.length > 2 ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeParticipant(index2), className: "inline-flex h-12 w-12 items-center justify-center rounded-2xl border border-white/[0.08] bg-white/[0.04] text-white/45 transition hover:border-rose-400/18 hover:bg-rose-500/10 hover:text-rose-200" }, "×") : null)))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Opening message"), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: body2,
      onChange: (e) => setBody(e.target.value),
      placeholder: "Write your message…",
      required: true,
      rows: 3,
      maxLength: 5e3,
      className: "w-full resize-none rounded-2xl border border-white/[0.08] bg-black/15 px-4 py-3 text-sm text-white outline-none transition placeholder:text-white/25 focus:border-sky-400/30 focus:bg-black/25"
    }
  ), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-[11px] text-white/30" }, "Keep it clear. You can continue the thread after the conversation is created.")), error ? /* @__PURE__ */ React.createElement("p", { className: "rounded-2xl border border-rose-500/18 bg-rose-500/10 px-4 py-3 text-sm text-rose-200" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "flex justify-end gap-2 border-t border-white/[0.06] pt-5" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/65 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: sending,
      className: "rounded-full bg-sky-500 px-5 py-2 text-sm font-semibold text-slate-950 transition hover:bg-sky-400 disabled:opacity-50"
    },
    sending ? "Creating…" : "Create conversation"
  )))));
}
async function resolveUsername(username, apiFetch2) {
  const data = await apiFetch2(`/api/search/users?q=${encodeURIComponent(username)}&limit=1`);
  const user = data?.data?.[0] ?? data?.[0];
  if (!user) throw new Error(`User "${username}" not found.`);
  return user;
}
function getCsrf() {
  return document.querySelector('meta[name="csrf-token"]')?.content ?? "";
}
async function apiFetch(url, options = {}) {
  const isFormData2 = options.body instanceof FormData;
  const socketId = getEcho()?.socketId?.();
  const headers = {
    "X-CSRF-TOKEN": getCsrf(),
    Accept: "application/json",
    ...options.headers
  };
  if (socketId) {
    headers["X-Socket-ID"] = socketId;
  }
  if (!isFormData2) {
    headers["Content-Type"] = "application/json";
  }
  const res = await fetch(url, {
    headers,
    ...options
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.message ?? `HTTP ${res.status}`);
  }
  return res.json();
}
function relativeTime(iso) {
  if (!iso) return "No activity yet";
  const diff = (Date.now() - new Date(iso).getTime()) / 1e3;
  if (diff < 60) return "Just now";
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`;
  return new Date(iso).toLocaleDateString(void 0, {
    month: "short",
    day: "numeric"
  });
}
function buildSearchPreview(item) {
  const body2 = (item?.body || "").trim();
  return body2 || "(attachment only)";
}
function MessagesPage({ userId, username, activeConversationId: initialId }) {
  const [conversations, setConversations] = reactExports.useState([]);
  const [unreadTotal, setUnreadTotal] = reactExports.useState(null);
  const [loadingConvs, setLoadingConvs] = reactExports.useState(true);
  const [activeId, setActiveId] = reactExports.useState(initialId ?? null);
  const [realtimeEnabled, setRealtimeEnabled] = reactExports.useState(false);
  const [realtimeStatus, setRealtimeStatus] = reactExports.useState("offline");
  const [onlineUserIds, setOnlineUserIds] = reactExports.useState([]);
  const [typingByConversation, setTypingByConversation] = reactExports.useState({});
  const [showNewModal, setShowNewModal] = reactExports.useState(false);
  const [searchQuery, setSearchQuery] = reactExports.useState("");
  const [searchResults, setSearchResults] = reactExports.useState([]);
  const [searching, setSearching] = reactExports.useState(false);
  const loadConversations = reactExports.useCallback(async () => {
    try {
      const data = await apiFetch("/api/messages/conversations");
      setConversations(data.data ?? []);
      setUnreadTotal(Number.isFinite(Number(data?.summary?.unread_total)) ? Number(data.summary.unread_total) : null);
    } catch (e) {
      console.error("Failed to load conversations", e);
    } finally {
      setLoadingConvs(false);
    }
  }, []);
  reactExports.useEffect(() => {
    loadConversations();
    apiFetch("/api/messages/settings").then((data) => setRealtimeEnabled(!!data?.realtime_enabled)).catch(() => setRealtimeEnabled(false));
  }, [loadConversations]);
  reactExports.useEffect(() => {
    const handlePopState = () => {
      const match = window.location.pathname.match(/^\/messages\/(\d+)$/);
      setActiveId(match ? Number(match[1]) : null);
    };
    window.addEventListener("popstate", handlePopState);
    return () => window.removeEventListener("popstate", handlePopState);
  }, []);
  reactExports.useEffect(() => {
    if (realtimeEnabled) {
      return void 0;
    }
    const poll = window.setInterval(loadConversations, 15e3);
    return () => window.clearInterval(poll);
  }, [loadConversations, realtimeEnabled]);
  reactExports.useEffect(() => {
    if (!realtimeEnabled || !userId) {
      setRealtimeStatus("offline");
      return void 0;
    }
    const echo = getEcho();
    if (!echo) {
      setRealtimeStatus("offline");
      return void 0;
    }
    const connection = echo.connector?.pusher?.connection;
    let heartbeatId = null;
    const mapConnectionState = (state) => {
      if (state === "connected") {
        return "connected";
      }
      if (state === "connecting" || state === "initialized" || state === "connecting_in") {
        return "connecting";
      }
      return "offline";
    };
    const syncConnectionState = (payload = null) => {
      const nextState = typeof payload?.current === "string" ? payload.current : connection?.state;
      if (echo.socketId?.()) {
        setRealtimeStatus("connected");
        return;
      }
      setRealtimeStatus(mapConnectionState(nextState));
    };
    const handleVisibilitySync = () => {
      if (document.visibilityState === "visible") {
        syncConnectionState();
      }
    };
    syncConnectionState();
    connection?.bind?.("state_change", syncConnectionState);
    connection?.bind?.("connected", syncConnectionState);
    connection?.bind?.("unavailable", syncConnectionState);
    connection?.bind?.("disconnected", syncConnectionState);
    heartbeatId = window.setInterval(syncConnectionState, 1e3);
    window.addEventListener("focus", syncConnectionState);
    document.addEventListener("visibilitychange", handleVisibilitySync);
    const channel = echo.private(`user.${userId}`);
    const handleConversationUpdated = (payload) => {
      const nextConversation = payload?.conversation;
      if (!nextConversation?.id) {
        return;
      }
      setConversations((prev) => mergeConversationSummary(prev, nextConversation));
      const nextUnreadTotal = Number(payload?.summary?.unread_total);
      if (Number.isFinite(nextUnreadTotal)) {
        setUnreadTotal(nextUnreadTotal);
      }
    };
    channel.listen(".conversation.updated", handleConversationUpdated);
    return () => {
      connection?.unbind?.("state_change", syncConnectionState);
      connection?.unbind?.("connected", syncConnectionState);
      connection?.unbind?.("unavailable", syncConnectionState);
      connection?.unbind?.("disconnected", syncConnectionState);
      if (heartbeatId) {
        window.clearInterval(heartbeatId);
      }
      window.removeEventListener("focus", syncConnectionState);
      document.removeEventListener("visibilitychange", handleVisibilitySync);
      channel.stopListening(".conversation.updated", handleConversationUpdated);
      echo.leaveChannel(`private-user.${userId}`);
    };
  }, [realtimeEnabled, userId]);
  reactExports.useEffect(() => {
    if (!realtimeEnabled || !userId) {
      setOnlineUserIds([]);
      return void 0;
    }
    const echo = getEcho();
    if (!echo) {
      setOnlineUserIds([]);
      return void 0;
    }
    const setMembers = (users) => {
      const nextIds = (users ?? []).map((user) => Number(user?.id)).filter((id) => Number.isFinite(id) && id !== Number(userId));
      setOnlineUserIds(Array.from(new Set(nextIds)));
    };
    const channel = echo.join("messaging");
    channel.here(setMembers).joining((user) => setOnlineUserIds((prev) => prev.includes(Number(user?.id)) || Number(user?.id) === Number(userId) ? prev : [...prev, Number(user.id)])).leaving((user) => setOnlineUserIds((prev) => prev.filter((id) => id !== Number(user?.id))));
    return () => {
      echo.leave("messaging");
    };
  }, [realtimeEnabled, userId]);
  reactExports.useEffect(() => {
    if (!userId) {
      return void 0;
    }
    let intervalId = null;
    const sendHeartbeat = () => {
      if (document.visibilityState === "hidden") {
        return;
      }
      apiFetch("/api/messages/presence/heartbeat", {
        method: "POST",
        body: JSON.stringify(activeId ? { conversation_id: activeId } : {})
      }).catch(() => {
      });
    };
    const handleVisibilitySync = () => {
      if (document.visibilityState === "visible") {
        sendHeartbeat();
      }
    };
    sendHeartbeat();
    intervalId = window.setInterval(sendHeartbeat, 25e3);
    window.addEventListener("focus", sendHeartbeat);
    document.addEventListener("visibilitychange", handleVisibilitySync);
    return () => {
      if (intervalId) {
        window.clearInterval(intervalId);
      }
      window.removeEventListener("focus", sendHeartbeat);
      document.removeEventListener("visibilitychange", handleVisibilitySync);
    };
  }, [activeId, userId]);
  reactExports.useEffect(() => {
    if (!realtimeEnabled) {
      setTypingByConversation({});
      return void 0;
    }
    const echo = getEcho();
    if (!echo || conversations.length === 0) {
      return void 0;
    }
    const timers = /* @__PURE__ */ new Map();
    const joinedChannels = [];
    const removeTypingUser = (conversationId, userIdToRemove) => {
      const timerKey = `${conversationId}:${userIdToRemove}`;
      const existingTimer = timers.get(timerKey);
      if (existingTimer) {
        window.clearTimeout(existingTimer);
        timers.delete(timerKey);
      }
      setTypingByConversation((prev) => {
        const current = prev[conversationId] ?? [];
        const nextUsers = current.filter((user) => String(user.user_id ?? user.id) !== String(userIdToRemove));
        if (nextUsers.length === current.length) {
          return prev;
        }
        if (nextUsers.length === 0) {
          const next = { ...prev };
          delete next[conversationId];
          return next;
        }
        return {
          ...prev,
          [conversationId]: nextUsers
        };
      });
    };
    conversations.forEach((conversation) => {
      if (!conversation?.id) {
        return;
      }
      const conversationId = conversation.id;
      const channel = echo.join(`conversation.${conversationId}`);
      joinedChannels.push(conversationId);
      channel.listen(".typing.started", (payload) => {
        const user = payload?.user;
        if (!user?.id || user.id === userId) {
          return;
        }
        setTypingByConversation((prev) => {
          const current = prev[conversationId] ?? [];
          const index2 = current.findIndex((entry) => String(entry.user_id ?? entry.id) === String(user.id));
          const nextUser = { user_id: user.id, username: user.username };
          if (index2 === -1) {
            return {
              ...prev,
              [conversationId]: [...current, nextUser]
            };
          }
          const nextUsers = [...current];
          nextUsers[index2] = { ...nextUsers[index2], ...nextUser };
          return {
            ...prev,
            [conversationId]: nextUsers
          };
        });
        const timerKey = `${conversationId}:${user.id}`;
        const existingTimer = timers.get(timerKey);
        if (existingTimer) {
          window.clearTimeout(existingTimer);
        }
        const timeout = window.setTimeout(() => removeTypingUser(conversationId, user.id), Number(payload?.expires_in_ms ?? 3500));
        timers.set(timerKey, timeout);
      }).listen(".typing.stopped", (payload) => {
        const typingUserId = payload?.user?.id;
        if (!typingUserId) {
          return;
        }
        removeTypingUser(conversationId, typingUserId);
      });
    });
    return () => {
      timers.forEach((timer) => window.clearTimeout(timer));
      joinedChannels.forEach((conversationId) => {
        echo.leave(`conversation.${conversationId}`);
      });
    };
  }, [conversations, realtimeEnabled, userId]);
  const handleSelectConversation = reactExports.useCallback((id) => {
    setActiveId(id);
    history.replaceState(null, "", `/messages/${id}`);
  }, []);
  const handleConversationCreated = reactExports.useCallback((conv) => {
    setShowNewModal(false);
    loadConversations();
    setActiveId(conv.id);
    history.replaceState(null, "", `/messages/${conv.id}`);
  }, [loadConversations]);
  const handleMarkRead = reactExports.useCallback((conversationId, nextUnreadTotal = null) => {
    setConversations((prev) => prev.map((conversation) => conversation.id === conversationId ? { ...conversation, unread_count: 0 } : conversation));
    if (Number.isFinite(Number(nextUnreadTotal))) {
      setUnreadTotal(Number(nextUnreadTotal));
    }
  }, []);
  const handleConversationPatched = reactExports.useCallback((patch2) => {
    if (!patch2?.id) {
      return;
    }
    setConversations((prev) => mergeConversationSummary(prev, patch2));
  }, []);
  const handleUnreadTotalPatched = reactExports.useCallback((nextUnreadTotal) => {
    if (!Number.isFinite(Number(nextUnreadTotal))) {
      return;
    }
    setUnreadTotal(Math.max(0, Number(nextUnreadTotal)));
  }, []);
  reactExports.useEffect(() => {
    let cancelled = false;
    const run = async () => {
      const q2 = searchQuery.trim();
      if (q2.length < 2) {
        setSearchResults([]);
        setSearching(false);
        return;
      }
      setSearching(true);
      try {
        const data = await apiFetch(`/api/messages/search?q=${encodeURIComponent(q2)}`);
        if (!cancelled) {
          setSearchResults(data.data ?? []);
        }
      } catch {
        if (!cancelled) {
          setSearchResults([]);
        }
      } finally {
        if (!cancelled) {
          setSearching(false);
        }
      }
    };
    const timer = setTimeout(run, 250);
    return () => {
      cancelled = true;
      clearTimeout(timer);
    };
  }, [searchQuery]);
  const openSearchResult = reactExports.useCallback((item) => {
    if (!item?.conversation_id) return;
    setActiveId(item.conversation_id);
    history.replaceState(null, "", `/messages/${item.conversation_id}?focus=${item.id}`);
  }, []);
  const activeConversation = conversations.find((conversation) => conversation.id === activeId) ?? null;
  const unreadCount = Number.isFinite(Number(unreadTotal)) ? Number(unreadTotal) : conversations.reduce((sum, conversation) => sum + Number(conversation.unread_count || 0), 0);
  const pinnedCount = conversations.reduce((sum, conversation) => {
    const me2 = conversation.my_participant ?? conversation.all_participants?.find((participant) => participant.user_id === userId);
    return sum + (me2?.is_pinned ? 1 : 0);
  }, 0);
  const archivedCount = conversations.reduce((sum, conversation) => {
    const me2 = conversation.my_participant ?? conversation.all_participants?.find((participant) => participant.user_id === userId);
    return sum + (me2?.is_archived ? 1 : 0);
  }, 0);
  const activeSearch = searchQuery.trim().length >= 2;
  const activeConversationLabel = activeConversation?.title || activeConversation?.all_participants?.find((participant) => participant.user_id !== userId)?.user?.username || "Conversation";
  return /* @__PURE__ */ React.createElement("div", { className: "messages-page px-4 pb-16 pt-4 md:px-6 lg:px-8 lg:pt-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:items-start lg:grid-cols-[340px_minmax(0,1fr)] xl:grid-cols-[360px_minmax(0,1fr)] xl:gap-6" }, /* @__PURE__ */ React.createElement("aside", { className: `flex min-h-[calc(100vh-18rem)] flex-col overflow-hidden rounded-[30px] border border-white/[0.06] bg-[linear-gradient(180deg,rgba(10,16,26,0.96),rgba(7,11,18,0.92))] shadow-[0_20px_60px_rgba(0,0,0,0.28)] lg:sticky lg:top-6 lg:max-h-[calc(100vh-3rem)] ${activeId ? "hidden lg:flex" : "flex"}` }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-white/35" }, "Private inbox"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Messages"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/50" }, "Keep direct chats, group threads, and file drops in one focused workspace.")), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setShowNewModal(true),
      className: "inline-flex h-11 items-center justify-center gap-2 rounded-full border border-sky-400/20 bg-sky-500/12 px-4 text-sm font-medium text-sky-200 transition hover:bg-sky-500/18",
      title: "New message"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square text-xs" }),
    "Compose"
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-3 gap-2" }, /* @__PURE__ */ React.createElement(StatChip, { label: "Unread", value: unreadCount, tone: "sky" }), /* @__PURE__ */ React.createElement(StatChip, { label: "Pinned", value: pinnedCount, tone: "amber" }), /* @__PURE__ */ React.createElement(StatChip, { label: "Archived", value: archivedCount, tone: "slate" })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs text-white/45" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-1.5 rounded-full border px-3 py-1 ${connectionBadgeClass(realtimeEnabled, realtimeStatus)}` }, /* @__PURE__ */ React.createElement("span", { className: `h-1.5 w-1.5 rounded-full ${connectionDotClass(realtimeEnabled, realtimeStatus)}` }), connectionBadgeLabel(realtimeEnabled, realtimeStatus)), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/[0.08] bg-white/[0.04] px-3 py-1 text-white/55" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-comments text-[10px]" }), conversations.length, " conversations"))), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] p-4" }, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Search all messages"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-black/15 px-3 py-2.5 transition focus-within:border-sky-400/30 focus-within:bg-black/25" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass text-xs text-white/30" }), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: searchQuery,
      onChange: (e) => setSearchQuery(e.target.value),
      placeholder: "Find text, attachments, or senders…",
      className: "w-full bg-transparent text-sm text-white outline-none placeholder:text-white/25"
    }
  ))), searching ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-[11px] text-white/35" }, "Searching across your inbox…") : null), activeSearch ? /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-3 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center justify-between px-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/35" }, "Search results"), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/30" }, searchResults.length)), /* @__PURE__ */ React.createElement("div", { className: "max-h-64 space-y-2 overflow-y-auto pr-1" }, searchResults.length === 0 && !searching ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.06] bg-white/[0.025] px-4 py-4 text-sm text-white/40" }, "No results matched “", searchQuery.trim(), "”.") : null, searchResults.map((item) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `search-${item.id}`,
      onClick: () => openSearchResult(item),
      className: "block w-full rounded-2xl border border-white/[0.06] bg-white/[0.03] px-4 py-3 text-left transition hover:border-sky-400/20 hover:bg-sky-500/[0.08]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 text-[11px] text-white/35" }, /* @__PURE__ */ React.createElement("span", null, "@", item.sender?.username ?? "unknown"), /* @__PURE__ */ React.createElement("span", null, relativeTime(item.created_at))),
    /* @__PURE__ */ React.createElement("p", { className: "mt-2 line-clamp-2 text-sm leading-6 text-white/78" }, buildSearchPreview(item))
  )))) : null, /* @__PURE__ */ React.createElement(
    ConversationList,
    {
      conversations,
      loading: loadingConvs,
      activeId,
      currentUserId: userId,
      onlineUserIds,
      typingByConversation,
      onSelect: handleSelectConversation
    }
  )), /* @__PURE__ */ React.createElement("main", { className: `flex min-h-[calc(100vh-18rem)] min-w-0 flex-col overflow-hidden rounded-[30px] border border-white/[0.06] bg-[linear-gradient(180deg,rgba(10,16,26,0.96),rgba(7,11,18,0.92))] shadow-[0_20px_60px_rgba(0,0,0,0.28)] lg:h-[calc(100vh-3rem)] lg:max-h-[calc(100vh-3rem)] ${activeId ? "flex" : "hidden lg:flex"}` }, activeId ? /* @__PURE__ */ React.createElement(
    ConversationThread,
    {
      key: activeId,
      conversationId: activeId,
      conversation: activeConversation,
      realtimeEnabled,
      realtimeStatus,
      currentUserId: userId,
      currentUsername: username,
      onlineUserIds,
      apiFetch,
      onBack: () => {
        setActiveId(null);
        history.replaceState(null, "", "/messages");
      },
      onMarkRead: handleMarkRead,
      onConversationPatched: handleConversationPatched,
      onUnreadTotalPatched: handleUnreadTotalPatched
    }
  ) : /* @__PURE__ */ React.createElement("div", { className: "flex flex-1 items-center justify-center p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-xl text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-18 w-18 items-center justify-center rounded-[26px] border border-white/[0.08] bg-white/[0.03] text-white/35 shadow-[0_18px_45px_rgba(0,0,0,0.22)]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-comments text-3xl" })), /* @__PURE__ */ React.createElement("h2", { className: "mt-6 text-3xl font-semibold text-white" }, "Choose a conversation"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-white/55" }, "Jump back into a direct message, catch up on a group thread, or start a new conversation with creators and collaborators."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-center justify-center gap-2 text-sm text-white/55" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2" }, "Search your full message history"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2" }, "Share files inline"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2" }, "Track seen status")))))), activeId ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/[0.06] bg-white/[0.03] px-4 py-3 text-xs text-white/45 lg:hidden" }, "Viewing ", /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white/75" }, activeConversationLabel), ". Use the back button to return to your inbox list.") : null, showNewModal ? /* @__PURE__ */ React.createElement(
    NewConversationModal,
    {
      currentUserId: userId,
      apiFetch,
      onCreated: handleConversationCreated,
      onClose: () => setShowNewModal(false)
    }
  ) : null);
}
function StatChip({ label, value, tone = "sky" }) {
  const tones2 = {
    sky: "border-sky-400/20 bg-sky-500/10 text-sky-200",
    amber: "border-amber-400/20 bg-amber-500/10 text-amber-200",
    slate: "border-white/[0.08] bg-white/[0.04] text-white/65"
  };
  return /* @__PURE__ */ React.createElement("div", { "data-testid": `messages-stat-${String(label).toLowerCase()}`, className: `rounded-2xl border px-3 py-3 ${tones2[tone] || tones2.sky}` }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] opacity-70" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-lg font-semibold" }, Number(value || 0).toLocaleString()));
}
function mergeConversationSummary(existing, incoming) {
  const next = [...existing];
  const index2 = next.findIndex((conversation) => conversation.id === incoming.id);
  if (index2 >= 0) {
    next[index2] = { ...next[index2], ...incoming };
  } else {
    next.unshift(incoming);
  }
  return next.sort((left, right) => {
    const leftPinned = left.my_participant?.is_pinned ? 1 : 0;
    const rightPinned = right.my_participant?.is_pinned ? 1 : 0;
    if (leftPinned !== rightPinned) {
      return rightPinned - leftPinned;
    }
    const leftPinnedAt = left.my_participant?.pinned_at ? new Date(left.my_participant.pinned_at).getTime() : 0;
    const rightPinnedAt = right.my_participant?.pinned_at ? new Date(right.my_participant.pinned_at).getTime() : 0;
    if (leftPinnedAt !== rightPinnedAt) {
      return rightPinnedAt - leftPinnedAt;
    }
    const leftTime = left.last_message_at ? new Date(left.last_message_at).getTime() : 0;
    const rightTime = right.last_message_at ? new Date(right.last_message_at).getTime() : 0;
    return rightTime - leftTime;
  });
}
function connectionBadgeClass(realtimeEnabled, realtimeStatus) {
  if (!realtimeEnabled) {
    return "border-white/[0.08] bg-white/[0.04] text-white/55";
  }
  if (realtimeStatus === "connected") {
    return "border-emerald-400/20 bg-emerald-500/10 text-emerald-200";
  }
  if (realtimeStatus === "connecting") {
    return "border-amber-400/20 bg-amber-500/10 text-amber-200";
  }
  return "border-rose-400/18 bg-rose-500/10 text-rose-200";
}
function connectionDotClass(realtimeEnabled, realtimeStatus) {
  if (!realtimeEnabled) {
    return "bg-white/30";
  }
  if (realtimeStatus === "connected") {
    return "bg-emerald-300";
  }
  if (realtimeStatus === "connecting") {
    return "bg-amber-300";
  }
  return "bg-rose-300";
}
function connectionBadgeLabel(realtimeEnabled, realtimeStatus) {
  if (!realtimeEnabled) {
    return "Polling every 15s";
  }
  if (realtimeStatus === "connected") {
    return "Realtime connected";
  }
  if (realtimeStatus === "connecting") {
    return "Realtime connecting";
  }
  return "Realtime disconnected";
}
if (typeof document !== "undefined") {
  const el = document.getElementById("messages-root");
  if (el) {
    let parse2 = function(key, fallback = null) {
      try {
        return JSON.parse(el.dataset[key] ?? "null") ?? fallback;
      } catch {
        return fallback;
      }
    };
    clientExports.createRoot(el).render(
      /* @__PURE__ */ React.createElement(
        MessagesPage,
        {
          userId: parse2("userId"),
          username: parse2("username", ""),
          activeConversationId: parse2("activeConversationId")
        }
      )
    );
  }
}
const __vite_glob_0_93 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: MessagesPage
}, Symbol.toStringTag, { value: "Module" }));
function requestJson$b(url, { method = "GET", body: body2 } = {}) {
  return fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  }).then(async (response) => {
    const payload = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(payload?.message || "Request failed");
    }
    return payload;
  });
}
function Badge({ children, tone = "slate" }) {
  const tones2 = {
    slate: "border-white/10 bg-white/[0.05] text-slate-200",
    amber: "border-amber-300/20 bg-amber-400/10 text-amber-100",
    rose: "border-rose-300/20 bg-rose-400/10 text-rose-100",
    emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
    sky: "border-sky-300/20 bg-sky-400/10 text-sky-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tones2[tone] || tones2.slate}` }, children);
}
function ArtworkMaturityQueue() {
  const { props } = X$1();
  const [items, setItems] = reactExports.useState(props.initialItems || []);
  const [stats, setStats] = reactExports.useState(props.stats || {});
  const [status2, setStatus] = reactExports.useState(props.initialFilters?.status || "suspected");
  const [aiAction, setAiAction] = reactExports.useState(props.initialFilters?.ai_action || "all");
  const [aiStatus, setAiStatus] = reactExports.useState(props.initialFilters?.ai_status || "all");
  const [busyId, setBusyId] = reactExports.useState(null);
  const [noteById, setNoteById] = reactExports.useState({});
  const [error, setError] = reactExports.useState("");
  const [previewItem, setPreviewItem] = reactExports.useState(null);
  const endpoints = props.endpoints || {};
  const filterOptions = props.filterOptions || {};
  const reviewActions = props.reviewActions || [];
  function queueStatusKey(key) {
    return key === "mature" ? "reviewed" : key;
  }
  async function load(nextStatus, nextAiAction = aiAction, nextAiStatus = aiStatus) {
    setStatus(nextStatus);
    setAiAction(nextAiAction);
    setAiStatus(nextAiStatus);
    setError("");
    try {
      const query = new URLSearchParams({
        status: nextStatus,
        ai_action: nextAiAction,
        ai_status: nextAiStatus
      });
      const payload = await requestJson$b(`${endpoints.list}?${query.toString()}`);
      setItems(payload.data || []);
      setStats(payload.meta?.stats || {});
    } catch (loadError) {
      setError(loadError.message);
    }
  }
  async function review(itemId, action) {
    setBusyId(itemId);
    setError("");
    try {
      const payload = await requestJson$b(String(endpoints.reviewPattern || "").replace("__ARTWORK__", String(itemId)), {
        method: "POST",
        body: {
          action,
          note: noteById[itemId] || ""
        }
      });
      setStats(payload.stats || {});
      setItems((current) => current.filter((item) => item.id !== itemId).concat(status2 === "reviewed" ? [payload.artwork] : []));
      if (status2 !== "reviewed") {
        setItems((current) => current.filter((item) => item.id !== itemId));
      }
    } catch (reviewError) {
      setError(reviewError.message);
    } finally {
      setBusyId(null);
    }
  }
  const statusSummary = reactExports.useMemo(() => [
    { key: "suspected", label: "Suspected", value: Number(stats.suspected || 0) },
    { key: "audit", label: "Audit candidates", value: Number(stats.audit || 0) },
    { key: "reviewed", label: "Reviewed", value: Number(stats.reviewed || 0) },
    { key: "mature", label: "Marked mature", value: Number(stats.mature || 0) }
  ], [stats]);
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Artwork Maturity Queue" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(251,191,36,0.16),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-amber-200/80" }, "Moderator surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Artwork maturity review"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Review uploads where the uploader declaration and AI suspicion do not match, plus legacy artworks detected by the non-mutating thumbnail audit. Audit candidates stay read-only until a moderator confirms the final maturity state.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, statusSummary.map((entry) => (() => {
    const queueKey = queueStatusKey(entry.key);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: entry.key,
        type: "button",
        onClick: () => load(queueKey),
        className: `rounded-2xl border px-4 py-3 text-left transition ${status2 === queueKey ? "border-amber-300/30 bg-amber-400/10 text-white" : "border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.07]"}`
      },
      /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em]" }, entry.label),
      /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-2xl font-semibold tracking-tight" }, entry.value.toLocaleString())
    );
  })()))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "AI action hint"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: aiAction,
      onChange: (value) => load(status2, value, aiStatus),
      className: "mt-2",
      options: (filterOptions.aiAction || []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "AI processing status"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: aiStatus,
      onChange: (value) => load(status2, aiAction, value),
      className: "mt-2",
      options: (filterOptions.aiStatus || []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )))), error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-4" }, items.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-300" }, status2 === "audit" ? "No legacy artworks are currently flagged by the thumbnail audit." : "No artworks are waiting in this queue.") : items.map((item) => (() => {
    const evidence = item.audit || item.maturity || {};
    return /* @__PURE__ */ React.createElement("article", { key: item.id, className: "grid gap-5 rounded-[28px] border border-white/10 bg-[#08111d] p-5 shadow-[0_18px_48px_rgba(2,6,23,0.2)] lg:grid-cols-[280px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => item.preview_image ? setPreviewItem(item) : null,
        className: "group overflow-hidden rounded-[22px] border border-white/10 bg-slate-950/85 text-left transition hover:border-sky-300/30"
      },
      item.thumbnail ? /* @__PURE__ */ React.createElement("div", { className: "relative flex min-h-[360px] items-center justify-center p-3" }, /* @__PURE__ */ React.createElement("img", { src: item.thumbnail, alt: item.title, className: "max-h-[480px] w-full object-contain" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-3 bottom-3 flex items-center justify-between rounded-full border border-white/10 bg-[#07101bdd] px-3 py-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-100 opacity-0 transition group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("span", null, "Preview full image"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-expand text-[10px]" }))) : /* @__PURE__ */ React.createElement("div", { className: "min-h-[360px]" })
    ), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, item.audit ? /* @__PURE__ */ React.createElement(Badge, { tone: "sky" }, "audit candidate") : null, /* @__PURE__ */ React.createElement(Badge, { tone: item.maturity?.is_flagged ? "rose" : "amber" }, item.maturity?.status || "unknown"), item.maturity?.is_mature_effective ? /* @__PURE__ */ React.createElement(Badge, { tone: "amber" }, "effective mature") : /* @__PURE__ */ React.createElement(Badge, { tone: "emerald" }, "currently safe"), item.maturity?.source ? /* @__PURE__ */ React.createElement(Badge, { tone: "sky" }, "source: ", String(item.maturity.source).replaceAll("_", " ")) : null, item.audit?.legacy_unset ? /* @__PURE__ */ React.createElement(Badge, { tone: "slate" }, "legacy unset") : null, evidence.ai_action_hint ? /* @__PURE__ */ React.createElement(Badge, { tone: evidence.ai_action_hint === "flag_high" ? "rose" : evidence.ai_action_hint === "review" ? "amber" : "emerald" }, "AI: ", String(evidence.ai_action_hint).replaceAll("_", " ")) : null, evidence.ai_status ? /* @__PURE__ */ React.createElement(Badge, { tone: "slate" }, "status: ", String(evidence.ai_status).replaceAll("_", " ")) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, item.publisher, " ", item.category ? `• ${item.category}` : "", " ", item.content_type ? `• ${item.content_type}` : "")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-[10px]" }), "Open artwork"), item.admin_url ? /* @__PURE__ */ React.createElement("a", { href: item.admin_url, className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-amber-50 transition hover:bg-amber-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-screwdriver-wrench text-[10px]" }), "Open in cPad") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, Array.isArray(evidence.ai_labels) && evidence.ai_labels.length > 0 ? evidence.ai_labels.map((label) => /* @__PURE__ */ React.createElement(Badge, { key: `${item.id}-${label}`, tone: "rose" }, label)) : /* @__PURE__ */ React.createElement(Badge, { tone: "slate" }, "no AI labels")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "AI score"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xl font-semibold text-white" }, evidence.ai_score != null ? Number(evidence.ai_score).toFixed(4) : "n/a")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "AI label"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-relaxed text-slate-200" }, evidence.ai_label || "n/a")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, item.audit ? "Audit detected" : "Published"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, item.audit?.detected_at ? new Date(item.audit.detected_at).toLocaleString() : item.published_at ? new Date(item.published_at).toLocaleString() : "Draft / unavailable"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Confidence"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, evidence.ai_confidence != null ? Number(evidence.ai_confidence).toFixed(4) : "n/a")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Vision model"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, evidence.ai_model || "n/a")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Current DB state"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-relaxed text-slate-200" }, String(item.maturity?.source || "legacy").replaceAll("_", " "), " • ", String(item.maturity?.status || "clear").replaceAll("_", " ")))), evidence.ai_advisory ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm leading-relaxed text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "AI advisory"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, evidence.ai_advisory)) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("label", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Moderator note"), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: noteById[item.id] ?? item.review?.reviewer_note ?? "",
        onChange: (event) => setNoteById((current) => ({ ...current, [item.id]: event.target.value })),
        rows: 3,
        className: "mt-3 w-full rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-3 text-sm text-white outline-none transition focus:border-amber-300/40",
        placeholder: "Explain why you are confirming or changing the maturity state."
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, reviewActions.map((action) => /* @__PURE__ */ React.createElement(
      "button",
      {
        key: `${item.id}-${action.value}`,
        type: "button",
        disabled: busyId === item.id,
        onClick: () => review(item.id, action.value),
        className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:cursor-not-allowed disabled:opacity-60"
      },
      busyId === item.id ? "Saving…" : action.label
    ))))));
  })())), /* @__PURE__ */ React.createElement(
    ArtworkViewer,
    {
      isOpen: Boolean(previewItem),
      onClose: () => setPreviewItem(null),
      artwork: previewItem ? { title: previewItem.title, thumb: previewItem.thumbnail } : null,
      presentXl: previewItem?.preview_image ? { url: previewItem.preview_image } : null
    }
  ));
}
const __vite_glob_0_95 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ArtworkMaturityQueue
}, Symbol.toStringTag, { value: "Module" }));
function formatDate$c(value) {
  return formatEnhanceDate(value);
}
function ModerationEnhanceIndex() {
  const { props } = X$1();
  const [filters, setFilters] = React.useState(props.filters || {});
  const jobs = props.jobs?.data || [];
  const flash = props.flash || {};
  React.useEffect(() => {
    setFilters(props.filters || {});
  }, [props.filters]);
  function applyFilters(event) {
    event.preventDefault();
    At.get(props.indexUrl, filters, { preserveScroll: true, preserveState: true, replace: true });
  }
  return /* @__PURE__ */ React.createElement("div", { className: "w-full px-6 pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "Enhance Jobs" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Moderation surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Enhance Jobs"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Review queued, processing, failed, and completed image upscale jobs without changing original artwork assets.")), /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 grid gap-3 md:grid-cols-2 xl:grid-cols-7" }, /* @__PURE__ */ React.createElement("select", { value: filters.status || "all", onChange: (event) => setFilters((current) => ({ ...current, status: event.target.value })), className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }, (props.options?.statuses || []).map((option) => /* @__PURE__ */ React.createElement("option", { key: option, value: option }, option === "all" ? "All statuses" : option))), /* @__PURE__ */ React.createElement("select", { value: filters.engine || "all", onChange: (event) => setFilters((current) => ({ ...current, engine: event.target.value })), className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }, (props.options?.engines || []).map((option) => /* @__PURE__ */ React.createElement("option", { key: option, value: option }, option === "all" ? "All engines" : option))), /* @__PURE__ */ React.createElement("select", { value: filters.mode || "all", onChange: (event) => setFilters((current) => ({ ...current, mode: event.target.value })), className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }, (props.options?.modes || []).map((option) => /* @__PURE__ */ React.createElement("option", { key: option, value: option }, option === "all" ? "All modes" : option))), /* @__PURE__ */ React.createElement("select", { value: filters.scale || "all", onChange: (event) => setFilters((current) => ({ ...current, scale: event.target.value })), className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }, (props.options?.scales || []).map((option) => /* @__PURE__ */ React.createElement("option", { key: String(option), value: option }, option === "all" ? "All scales" : `${option}x`))), /* @__PURE__ */ React.createElement("input", { value: filters.user || "", onChange: (event) => setFilters((current) => ({ ...current, user: event.target.value })), placeholder: "User name or username", className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { type: "date", value: filters.date_from || "", onChange: (event) => setFilters((current) => ({ ...current, date_from: event.target.value })), className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { type: "date", value: filters.date_to || "", onChange: (event) => setFilters((current) => ({ ...current, date_to: event.target.value })), className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl border border-white/10 bg-white/[0.06] px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.1] xl:col-span-7" }, "Apply filters"))), /* @__PURE__ */ React.createElement(EnhanceStubWarning, { config: props.enhanceConfig, moderation: true, className: "mt-6" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 overflow-hidden rounded-[28px] border border-white/10 bg-[#08111d] shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-wider text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Preview"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Job"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "User"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Artwork"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Mode"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Scale"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Dimensions"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Created"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.04]" }, jobs.length === 0 ? /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 10, className: "px-5 py-12 text-center text-slate-400" }, "No enhance jobs match the current filters.")) : null, jobs.map((job) => /* @__PURE__ */ React.createElement("tr", { key: job.id, className: "transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-16 w-16 overflow-hidden rounded-xl border border-white/10 bg-black/20" }, job.preview_url || job.source_url ? /* @__PURE__ */ React.createElement("img", { src: job.preview_url || job.source_url, alt: `Enhance job ${job.id}`, className: "h-full w-full object-cover" }) : null)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, "#", job.id), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, job.engine)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, job.user?.name || "—", job.user?.username ? /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "@", job.user.username) : null), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, job.artwork?.title ? /* @__PURE__ */ React.createElement("a", { href: job.artwork.url, className: "text-sky-300 hover:text-sky-200" }, job.artwork.title) : "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement(EnhanceStatusBadge, { status: job.status })), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, job.mode), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, job.scale, "x"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, job.input_width, " × ", job.input_height, job.output_width && job.output_height ? /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "→ ", job.output_width, " × ", job.output_height) : null), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-400" }, formatDate$c(job.created_at)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement(xe, { href: job.show_url, className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Open")))))))));
}
const __vite_glob_0_96 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ModerationEnhanceIndex
}, Symbol.toStringTag, { value: "Module" }));
function formatDate$b(value) {
  return formatEnhanceDate(value);
}
function DetailRow({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4 border-b border-white/[0.06] py-3 last:border-b-0 last:pb-0" }, /* @__PURE__ */ React.createElement("dt", { className: "text-sm text-slate-400" }, label), /* @__PURE__ */ React.createElement("dd", { className: "text-right text-sm text-white" }, value));
}
function ModerationEnhanceShow() {
  const { props } = X$1();
  const job = props.job || {};
  const flash = props.flash || {};
  const errors = props.errors || {};
  return /* @__PURE__ */ React.createElement("div", { className: "w-full px-6 pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: `Enhance Job #${job.id || ""}` }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(EnhanceStatusBadge, { status: job.status }), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.scale, "x"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.mode), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, job.engine)), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Enhance job #", job.id), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Created by ", job.user?.name || "Unknown user", " ", job.user?.username ? `(@${job.user.username})` : "", ".")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: props.indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Back to list"), job.download_url ? /* @__PURE__ */ React.createElement("a", { href: job.download_url, className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-50 transition hover:bg-emerald-400/20" }, "Download output") : null, job.can_retry ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(job.retry_url), className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-amber-50 transition hover:bg-amber-400/20" }, "Retry") : null, job.can_mark_failed ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(job.mark_failed_url), className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 transition hover:bg-rose-400/20" }, "Mark failed") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    if (!window.confirm("Delete this enhance job and any owned enhance files?")) return;
    At.delete(job.delete_url);
  }, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Delete")))), /* @__PURE__ */ React.createElement(EnhanceStubWarning, { config: props.enhanceConfig, moderation: true, className: "mt-6" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, errors.job ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, errors.job) : null, job.source_url && job.output_url ? /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement(BeforeAfterSlider, { beforeUrl: job.source_url, afterUrl: job.output_url })) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_380px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Source image"), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, job.source_url ? /* @__PURE__ */ React.createElement("img", { src: job.source_url, alt: "Enhance source", className: "w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex min-h-[280px] items-center justify-center text-white/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-4xl" })))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Output image"), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, job.output_url ? /* @__PURE__ */ React.createElement("img", { src: job.output_url, alt: "Enhance output", className: "w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex min-h-[280px] items-center justify-center text-white/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-hourglass-half text-4xl" })))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Metadata"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("pre", { className: "overflow-x-auto whitespace-pre-wrap break-words" }, JSON.stringify(job.metadata || {}, null, 2)))), job.error_message ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-rose-300/20 bg-rose-400/10 p-6 text-sm text-rose-100 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, job.error_message) : null), /* @__PURE__ */ React.createElement("aside", { className: "rounded-[30px] border border-white/10 bg-[#08111d] p-6 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Processing details"), /* @__PURE__ */ React.createElement("dl", { className: "mt-4" }, /* @__PURE__ */ React.createElement(DetailRow, { label: "Created", value: formatDate$b(job.created_at) }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Queued", value: formatDate$b(job.queued_at) }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Started", value: formatDate$b(job.started_at) }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Finished", value: formatDate$b(job.finished_at) }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Expires", value: formatDate$b(job.expires_at) }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Input mime", value: job.input_mime || "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Input size", value: job.input_filesize ? `${(job.input_filesize / 1024 / 1024).toFixed(2)} MB` : "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Input dimensions", value: job.input_width && job.input_height ? `${job.input_width} × ${job.input_height}` : "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Output mime", value: job.output_mime || "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Output size", value: job.output_filesize ? `${(job.output_filesize / 1024 / 1024).toFixed(2)} MB` : "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Output dimensions", value: job.output_width && job.output_height ? `${job.output_width} × ${job.output_height}` : "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Processing seconds", value: job.processing_seconds ?? "—" }), /* @__PURE__ */ React.createElement(DetailRow, { label: "Artwork", value: job.artwork?.title ? /* @__PURE__ */ React.createElement("a", { href: job.artwork.url, className: "text-sky-300 hover:text-sky-200" }, job.artwork.title) : "Standalone upload" })))));
}
const __vite_glob_0_97 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ModerationEnhanceShow
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$5() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$a(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$5(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.errors?.story?.[0] || "Request failed.");
  }
  return payload;
}
function replacePattern$1(pattern, value) {
  return String(pattern || "").replace("__STORY__", String(value)).replace("__WORLD__", String(value));
}
function StatusBadge({ story }) {
  const tone = story.status === "published" ? "border-emerald-300/20 bg-emerald-400/12 text-emerald-100" : story.status === "archived" ? "border-amber-300/20 bg-amber-400/12 text-amber-100" : "border-white/10 bg-white/[0.06] text-slate-200";
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tone}` }, story.status);
}
function WorldWebStoriesIndex() {
  const { props } = X$1();
  const stories = props.stories || { data: [] };
  const endpoints = props.endpoints || {};
  const worldOptions = props.worldOptions || [];
  const [filters, setFilters] = React.useState(props.filters || { q: "", status: "all" });
  const [notice, setNotice] = React.useState("");
  const [error, setError] = React.useState("");
  const [busyKey, setBusyKey] = React.useState("");
  const [generator, setGenerator] = React.useState({ world_id: worldOptions[0]?.value || "", pages: 7, force: false, publish: false });
  React.useEffect(() => {
    setFilters(props.filters || { q: "", status: "all" });
  }, [props.filters]);
  function applyFilters(event) {
    event.preventDefault();
    At.get(endpoints.index, filters, { preserveState: true, replace: true, preserveScroll: true });
  }
  async function performAction(key, url, method = "POST", body2 = null) {
    setBusyKey(key);
    setNotice("");
    setError("");
    try {
      const payload = await requestJson$a(url, { method, body: body2 });
      setNotice(payload.message || "Action completed.");
      At.reload({ only: ["stories", "stats", "filters"], preserveScroll: true });
    } catch (requestError) {
      setError(requestError.message || "Action failed.");
    } finally {
      setBusyKey("");
    }
  }
  async function generateDraft(event) {
    event.preventDefault();
    if (!generator.world_id) return;
    setBusyKey("generate");
    setNotice("");
    setError("");
    try {
      const payload = await requestJson$a(replacePattern$1(endpoints.generatePattern, generator.world_id), {
        body: {
          pages: Number(generator.pages || 7),
          force: Boolean(generator.force),
          publish: Boolean(generator.publish)
        }
      });
      setNotice(payload.message || "Web story generated.");
      if (payload.story?.edit_url) {
        At.visit(payload.story.edit_url);
        return;
      }
      At.reload({ only: ["stories", "stats"], preserveScroll: true });
    } catch (requestError) {
      setError(requestError.message || "Generation failed.");
    } finally {
      setBusyKey("");
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: "World Web Stories" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_36%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Moderation surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "World Web Stories"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Create standalone AMP Web Stories for Skinbase Worlds, keep them self-canonical, and publish only when the story is complete and visible.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(xe, { href: endpoints.create, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-[10px]" }), "New story"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, [
    ["Total stories", props.stats?.total || 0],
    ["Published", props.stats?.published || 0],
    ["Drafts", props.stats?.draft || 0],
    ["Hidden", props.stats?.hidden || 0]
  ].map(([label, value]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, Number(value).toLocaleString())))), /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 grid gap-3 lg:grid-cols-[2fr_1fr_auto]" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      value: filters.q || "",
      onChange: (event) => setFilters((current) => ({ ...current, q: event.target.value })),
      placeholder: "Search by title, slug, or world",
      className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none"
    }
  ), /* @__PURE__ */ React.createElement(
    "select",
    {
      value: filters.status || "all",
      onChange: (event) => setFilters((current) => ({ ...current, status: event.target.value })),
      className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none"
    },
    /* @__PURE__ */ React.createElement("option", { value: "all" }, "All statuses"),
    /* @__PURE__ */ React.createElement("option", { value: "draft" }, "Draft"),
    /* @__PURE__ */ React.createElement("option", { value: "published" }, "Published"),
    /* @__PURE__ */ React.createElement("option", { value: "archived" }, "Archived")
  ), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl border border-white/10 bg-white/[0.06] px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.1]" }, "Apply")), /* @__PURE__ */ React.createElement("form", { onSubmit: generateDraft, className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Generate from World"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-[2fr_120px_auto_auto_auto]" }, /* @__PURE__ */ React.createElement(
    "select",
    {
      value: generator.world_id,
      onChange: (event) => setGenerator((current) => ({ ...current, world_id: event.target.value })),
      className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none"
    },
    /* @__PURE__ */ React.createElement("option", { value: "" }, "Select a World"),
    worldOptions.map((world) => /* @__PURE__ */ React.createElement("option", { key: world.value, value: world.value }, world.label))
  ), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "number",
      min: "5",
      max: "10",
      value: generator.pages,
      onChange: (event) => setGenerator((current) => ({ ...current, pages: event.target.value })),
      className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none"
    }
  ), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: generator.force, onChange: (event) => setGenerator((current) => ({ ...current, force: event.target.checked })) }), "Force"), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: generator.publish, onChange: (event) => setGenerator((current) => ({ ...current, publish: event.target.checked })) }), "Publish"), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busyKey === "generate", className: "rounded-2xl border border-sky-300/20 bg-sky-400/12 px-5 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20 disabled:opacity-60" }, "Generate")))), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, notice) : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-4 xl:grid-cols-2" }, (stories.data || []).map((story) => /* @__PURE__ */ React.createElement("article", { key: story.id, className: "overflow-hidden rounded-[28px] border border-white/10 bg-[#08111d] shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[180px_1fr]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[3/4] bg-black/30" }, story.poster_portrait_url ? /* @__PURE__ */ React.createElement("img", { src: story.poster_portrait_url, alt: story.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-white/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open-reader text-4xl" }))), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(StatusBadge, { story }), !story.active ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-amber-300/20 bg-amber-400/12 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "inactive") : null, story.noindex ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-rose-300/20 bg-rose-400/12 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-100" }, "noindex") : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, story.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "/", story.slug, story.world ? ` • ${story.world.title}` : ""), story.excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, story.excerpt) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, story.page_count, " pages"), story.published_at ? /* @__PURE__ */ React.createElement("span", null, new Date(story.published_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: replacePattern$1(endpoints.editPattern, story.id), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: story.public_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Open"), story.status === "published" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => performAction(`unpublish-${story.id}`, replacePattern$1(endpoints.unpublishPattern, story.id)), className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-amber-100 transition hover:bg-amber-400/18" }, "Unpublish") : /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => performAction(`publish-${story.id}`, replacePattern$1(endpoints.publishPattern, story.id)), className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-100 transition hover:bg-emerald-400/18" }, "Publish"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => performAction(`delete-${story.id}`, replacePattern$1(endpoints.destroyPattern, story.id), "DELETE"), className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 transition hover:bg-rose-400/18" }, "Delete"))))))));
}
const __vite_glob_0_98 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: WorldWebStoriesIndex
}, Symbol.toStringTag, { value: "Module" }));
function getCsrfToken$4() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function requestJson$9(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$4(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.errors?.story?.[0] || Object.values(payload?.errors || {})?.[0]?.[0] || "Request failed.");
  }
  return payload;
}
function replacePagePattern(pattern, pageId) {
  return String(pattern || "").replace("__PAGE__", String(pageId));
}
function Field({ label, children, hint }) {
  return /* @__PURE__ */ React.createElement("label", { className: "block rounded-2xl border border-white/10 bg-white/[0.04] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, children), hint ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, hint) : null);
}
function StoryPageCard({ page, endpoints, onChanged }) {
  const [localPage, setLocalPage] = React.useState(page);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState("");
  React.useEffect(() => {
    setLocalPage(page);
  }, [page]);
  async function save() {
    setBusy(true);
    setError("");
    try {
      await requestJson$9(replacePagePattern(endpoints.pagesUpdatePattern, page.id), {
        method: "PATCH",
        body: {
          ...localPage,
          overlay_strength: Number(localPage.overlay_strength || 35),
          active: Boolean(localPage.active)
        }
      });
      onChanged();
    } catch (requestError) {
      setError(requestError.message || "Unable to save page.");
    } finally {
      setBusy(false);
    }
  }
  async function destroy() {
    setBusy(true);
    setError("");
    try {
      await requestJson$9(replacePagePattern(endpoints.pagesDestroyPattern, page.id), { method: "DELETE" });
      onChanged();
    } catch (requestError) {
      setError(requestError.message || "Unable to delete page.");
    } finally {
      setBusy(false);
    }
  }
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Page ", page.position), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, page.headline || "Untitled page")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: save, disabled: busy, className: "rounded-full border border-sky-300/20 bg-sky-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20 disabled:opacity-60" }, "Save"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: destroy, disabled: busy, className: "rounded-full border border-rose-300/20 bg-rose-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-rose-100 transition hover:bg-rose-400/20 disabled:opacity-60" }, "Delete"))), error ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field, { label: "Headline" }, /* @__PURE__ */ React.createElement("input", { value: localPage.headline || "", onChange: (event) => setLocalPage((current) => ({ ...current, headline: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Caption" }, /* @__PURE__ */ React.createElement("input", { value: localPage.caption || "", onChange: (event) => setLocalPage((current) => ({ ...current, caption: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Body", hint: "Maximum 180 characters." }, /* @__PURE__ */ React.createElement("textarea", { value: localPage.body || "", onChange: (event) => setLocalPage((current) => ({ ...current, body: event.target.value })), rows: 3, className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Alt text" }, /* @__PURE__ */ React.createElement("input", { value: localPage.alt_text || "", onChange: (event) => setLocalPage((current) => ({ ...current, alt_text: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Layout" }, /* @__PURE__ */ React.createElement("select", { value: localPage.layout, onChange: (event) => setLocalPage((current) => ({ ...current, layout: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, ["cover", "artwork", "creator", "mood", "collection", "cta"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Background type" }, /* @__PURE__ */ React.createElement("select", { value: localPage.background_type, onChange: (event) => setLocalPage((current) => ({ ...current, background_type: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, ["image", "video", "gradient"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Background path" }, /* @__PURE__ */ React.createElement("input", { value: localPage.background_path || "", onChange: (event) => setLocalPage((current) => ({ ...current, background_path: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Mobile background path" }, /* @__PURE__ */ React.createElement("input", { value: localPage.background_mobile_path || "", onChange: (event) => setLocalPage((current) => ({ ...current, background_mobile_path: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "CTA label" }, /* @__PURE__ */ React.createElement("input", { value: localPage.cta_label || "", onChange: (event) => setLocalPage((current) => ({ ...current, cta_label: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "CTA URL" }, /* @__PURE__ */ React.createElement("input", { value: localPage.cta_url || "", onChange: (event) => setLocalPage((current) => ({ ...current, cta_url: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Text position" }, /* @__PURE__ */ React.createElement("select", { value: localPage.text_position, onChange: (event) => setLocalPage((current) => ({ ...current, text_position: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, ["top", "center", "bottom"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Animation" }, /* @__PURE__ */ React.createElement("select", { value: localPage.animation || "", onChange: (event) => setLocalPage((current) => ({ ...current, animation: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, /* @__PURE__ */ React.createElement("option", { value: "" }, "None"), ["fade-in", "fly-in-bottom", "pulse", "pan-left", "pan-right"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Overlay strength" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "0", max: "100", value: localPage.overlay_strength || 35, onChange: (event) => setLocalPage((current) => ({ ...current, overlay_strength: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Artwork ID" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "1", value: localPage.artwork_id || "", onChange: (event) => setLocalPage((current) => ({ ...current, artwork_id: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Position" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "1", value: localPage.position || 1, onChange: (event) => setLocalPage((current) => ({ ...current, position: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Credit text" }, /* @__PURE__ */ React.createElement("input", { value: localPage.credit_text || "", onChange: (event) => setLocalPage((current) => ({ ...current, credit_text: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(localPage.active), onChange: (event) => setLocalPage((current) => ({ ...current, active: event.target.checked })) }), "Page active")));
}
function WorldWebStoryEditor() {
  const { props } = X$1();
  const story = props.story;
  const endpoints = props.endpoints || {};
  const worldOptions = props.worldOptions || [];
  const isNew = Boolean(props.isNew);
  const [notice, setNotice] = React.useState("");
  const [error, setError] = React.useState("");
  const [pages2, setPages] = React.useState(story.pages || []);
  const [newPage, setNewPage] = React.useState({
    layout: "cover",
    background_type: "image",
    headline: "",
    body: "",
    cta_label: "",
    cta_url: "",
    alt_text: "",
    caption: "",
    credit_text: "",
    background_path: "",
    background_mobile_path: "",
    artwork_id: "",
    text_position: "bottom",
    overlay_strength: 35,
    animation: "",
    active: true
  });
  React.useEffect(() => {
    setPages(story.pages || []);
  }, [story.pages]);
  const form = G$1({
    world_id: story.world_id || "",
    slug: story.slug || "",
    title: story.title || "",
    subtitle: story.subtitle || "",
    excerpt: story.excerpt || "",
    description: story.description || "",
    seo_title: story.seo_title || "",
    seo_description: story.seo_description || "",
    poster_portrait_path: story.poster_portrait_path || "",
    poster_square_path: story.poster_square_path || "",
    publisher_logo_path: story.publisher_logo_path || "",
    status: story.status || "draft",
    featured: Boolean(story.featured),
    active: Boolean(story.active),
    noindex: Boolean(story.noindex),
    published_at: story.published_at || "",
    starts_at: story.starts_at || "",
    ends_at: story.ends_at || ""
  });
  function submit(event) {
    event.preventDefault();
    setError("");
    setNotice("");
    const options = {
      preserveScroll: true,
      onSuccess: () => setNotice("Web story saved."),
      onError: (errors) => setError(Object.values(errors)[0] || "Save failed.")
    };
    if (isNew) {
      form.post(endpoints.store, options);
      return;
    }
    form.patch(endpoints.update, options);
  }
  async function reloadEditor() {
    At.reload({ preserveScroll: true, only: ["story"] });
  }
  async function createPage(event) {
    event.preventDefault();
    setError("");
    setNotice("");
    try {
      await requestJson$9(endpoints.pagesStore, {
        body: {
          ...newPage,
          overlay_strength: Number(newPage.overlay_strength || 35),
          artwork_id: newPage.artwork_id ? Number(newPage.artwork_id) : null,
          active: Boolean(newPage.active)
        }
      });
      setNotice("Page created.");
      setNewPage({
        layout: "cover",
        background_type: "image",
        headline: "",
        body: "",
        cta_label: "",
        cta_url: "",
        alt_text: "",
        caption: "",
        credit_text: "",
        background_path: "",
        background_mobile_path: "",
        artwork_id: "",
        text_position: "bottom",
        overlay_strength: 35,
        animation: "",
        active: true
      });
      reloadEditor();
    } catch (requestError) {
      setError(requestError.message || "Unable to create page.");
    }
  }
  async function performStoryAction(url) {
    setError("");
    setNotice("");
    try {
      const payload = await requestJson$9(url);
      setNotice(payload.message || "Action completed.");
      reloadEditor();
    } catch (requestError) {
      setError(requestError.message || "Action failed.");
    }
  }
  async function reorder(pageId, direction) {
    const sorted = [...pages2].sort((left, right) => left.position - right.position);
    const currentIndex = sorted.findIndex((page) => page.id === pageId);
    const targetIndex = currentIndex + direction;
    if (currentIndex < 0 || targetIndex < 0 || targetIndex >= sorted.length) return;
    const next = [...sorted];
    [next[currentIndex], next[targetIndex]] = [next[targetIndex], next[currentIndex]];
    try {
      await requestJson$9(endpoints.pagesReorder, {
        body: { page_ids: next.map((page) => page.id) }
      });
      reloadEditor();
    } catch (requestError) {
      setError(requestError.message || "Unable to reorder pages.");
    }
  }
  async function generateFromWorld() {
    if (!form.data.world_id) return;
    try {
      const payload = await requestJson$9(endpoints.generateFromWorldPattern.replace("__WORLD__", String(form.data.world_id)), {
        body: { force: true, pages: Math.max(5, pages2.length || 7) }
      });
      setNotice(payload.message || "Draft regenerated from World.");
      if (payload.story?.edit_url) {
        At.visit(payload.story.edit_url);
        return;
      }
      reloadEditor();
    } catch (requestError) {
      setError(requestError.message || "Generation failed.");
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se$1, { title: isNew ? "New World Web Story" : `Edit ${story.title}` }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Moderation surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-2 text-3xl font-semibold tracking-[-0.04em] text-white" }, isNew ? "Create World Web Story" : story.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-relaxed text-slate-300" }, "Build a standalone AMP story companion for a Skinbase World without changing the canonical World route.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: endpoints.index, className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Back"), !isNew && story.public_url ? /* @__PURE__ */ React.createElement("a", { href: story.public_url, className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Open story") : null, !isNew ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => performStoryAction(endpoints.publish), className: "rounded-full border border-emerald-300/20 bg-emerald-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-100 transition hover:bg-emerald-400/18" }, "Publish") : null, !isNew ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => performStoryAction(endpoints.unpublish), className: "rounded-full border border-amber-300/20 bg-amber-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-amber-100 transition hover:bg-amber-400/18" }, "Unpublish") : null)), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, notice) : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "mt-6 rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field, { label: "Related World" }, /* @__PURE__ */ React.createElement("select", { value: form.data.world_id, onChange: (event) => form.setData("world_id", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, /* @__PURE__ */ React.createElement("option", { value: "" }, "No related World"), worldOptions.map((world) => /* @__PURE__ */ React.createElement("option", { key: world.value, value: world.value }, world.label)))), /* @__PURE__ */ React.createElement(Field, { label: "Slug" }, /* @__PURE__ */ React.createElement("input", { value: form.data.slug, onChange: (event) => form.setData("slug", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Title" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Subtitle" }, /* @__PURE__ */ React.createElement("input", { value: form.data.subtitle, onChange: (event) => form.setData("subtitle", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Excerpt" }, /* @__PURE__ */ React.createElement("textarea", { value: form.data.excerpt, onChange: (event) => form.setData("excerpt", event.target.value), rows: 3, className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Description" }, /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), rows: 3, className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "SEO title" }, /* @__PURE__ */ React.createElement("input", { value: form.data.seo_title, onChange: (event) => form.setData("seo_title", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "SEO description" }, /* @__PURE__ */ React.createElement("textarea", { value: form.data.seo_description, onChange: (event) => form.setData("seo_description", event.target.value), rows: 3, className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Poster portrait path" }, /* @__PURE__ */ React.createElement("input", { value: form.data.poster_portrait_path, onChange: (event) => form.setData("poster_portrait_path", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Poster square path" }, /* @__PURE__ */ React.createElement("input", { value: form.data.poster_square_path, onChange: (event) => form.setData("poster_square_path", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Publisher logo path" }, /* @__PURE__ */ React.createElement("input", { value: form.data.publisher_logo_path, onChange: (event) => form.setData("publisher_logo_path", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Status" }, /* @__PURE__ */ React.createElement("select", { value: form.data.status, onChange: (event) => form.setData("status", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, ["draft", "published", "archived"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Starts at" }, /* @__PURE__ */ React.createElement("input", { type: "datetime-local", value: form.data.starts_at ? form.data.starts_at.slice(0, 16) : "", onChange: (event) => form.setData("starts_at", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Ends at" }, /* @__PURE__ */ React.createElement("input", { type: "datetime-local", value: form.data.ends_at ? form.data.ends_at.slice(0, 16) : "", onChange: (event) => form.setData("ends_at", event.target.value), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4" }, /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(form.data.featured), onChange: (event) => form.setData("featured", event.target.checked) }), " Featured"), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(form.data.active), onChange: (event) => form.setData("active", event.target.checked) }), " Active"), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(form.data.noindex), onChange: (event) => form.setData("noindex", event.target.checked) }), " Noindex")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/20 bg-sky-400/12 px-5 py-2.5 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20 disabled:opacity-60" }, "Save story"), !isNew ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: generateFromWorld, className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Regenerate from World") : null)), !isNew ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, "Validation"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Publish only when poster, logo, page count, alt text, and CTA rules are satisfied.")), /* @__PURE__ */ React.createElement("div", { className: `rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] ${story.validation?.valid ? "border-emerald-300/20 bg-emerald-400/12 text-emerald-100" : "border-amber-300/20 bg-amber-400/12 text-amber-100"}` }, story.validation?.valid ? "Ready to publish" : "Needs fixes")), (story.validation?.errors || []).length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-4 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("ul", { className: "space-y-2" }, (story.validation.errors || []).map((item) => /* @__PURE__ */ React.createElement("li", { key: item }, item)))) : null), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, "Story pages"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Keep each page short, visual, and clearly tied back to the World narrative."))), /* @__PURE__ */ React.createElement("form", { onSubmit: createPage, className: "mt-6 grid gap-3 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field, { label: "New page headline" }, /* @__PURE__ */ React.createElement("input", { value: newPage.headline, onChange: (event) => setNewPage((current) => ({ ...current, headline: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "New page caption" }, /* @__PURE__ */ React.createElement("input", { value: newPage.caption, onChange: (event) => setNewPage((current) => ({ ...current, caption: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "New page body" }, /* @__PURE__ */ React.createElement("textarea", { value: newPage.body, onChange: (event) => setNewPage((current) => ({ ...current, body: event.target.value })), rows: 3, className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Alt text" }, /* @__PURE__ */ React.createElement("input", { value: newPage.alt_text, onChange: (event) => setNewPage((current) => ({ ...current, alt_text: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Layout" }, /* @__PURE__ */ React.createElement("select", { value: newPage.layout, onChange: (event) => setNewPage((current) => ({ ...current, layout: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, ["cover", "artwork", "creator", "mood", "collection", "cta"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Background type" }, /* @__PURE__ */ React.createElement("select", { value: newPage.background_type, onChange: (event) => setNewPage((current) => ({ ...current, background_type: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" }, ["image", "video", "gradient"].map((value) => /* @__PURE__ */ React.createElement("option", { key: value, value }, value)))), /* @__PURE__ */ React.createElement(Field, { label: "Background path" }, /* @__PURE__ */ React.createElement("input", { value: newPage.background_path, onChange: (event) => setNewPage((current) => ({ ...current, background_path: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field, { label: "Mobile background path" }, /* @__PURE__ */ React.createElement("input", { value: newPage.background_mobile_path, onChange: (event) => setNewPage((current) => ({ ...current, background_mobile_path: event.target.value })), className: "w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "xl:col-span-2 flex justify-end" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-sky-300/20 bg-sky-400/12 px-5 py-2.5 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/20" }, "Add page"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, pages2.sort((left, right) => left.position - right.position).map((page) => /* @__PURE__ */ React.createElement("div", { key: page.id }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex justify-end gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => reorder(page.id, -1), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Move up"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => reorder(page.id, 1), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Move down")), /* @__PURE__ */ React.createElement(StoryPageCard, { page, endpoints, onChanged: reloadEditor })))))) : null);
}
const __vite_glob_0_99 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: WorldWebStoryEditor
}, Symbol.toStringTag, { value: "Module" }));
const ABSOLUTE_DATE_FORMATTER = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "numeric",
  timeZone: "UTC"
});
const ABSOLUTE_DATE_TIME_FORMATTER = new Intl.DateTimeFormat("en-US", {
  year: "numeric",
  month: "short",
  day: "numeric",
  hour: "numeric",
  minute: "2-digit",
  timeZone: "UTC"
});
function formatAbsoluteDate(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return ABSOLUTE_DATE_FORMATTER.format(date);
}
function formatAbsoluteDateTime(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return ABSOLUTE_DATE_TIME_FORMATTER.format(date);
}
function formatCommentTime(primaryLabel, createdAt) {
  return primaryLabel || formatAbsoluteDate(createdAt);
}
function ReplyIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-3.5 w-3.5" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M7.793 2.232a.75.75 0 0 1-.025 1.06L3.622 7.25h10.003a5.375 5.375 0 0 1 0 10.75H10.75a.75.75 0 0 1 0-1.5h2.875a3.875 3.875 0 0 0 0-7.75H3.622l4.146 3.957a.75.75 0 0 1-1.036 1.085l-5.5-5.25a.75.75 0 0 1 0-1.085l5.5-5.25a.75.75 0 0 1 1.06.025Z", clipRule: "evenodd" }));
}
function TrashIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-3.5 w-3.5" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M7.5 2.75A1.75 1.75 0 0 0 5.75 4.5v.25H3.5a.75.75 0 0 0 0 1.5h.54l.853 9.1A2.25 2.25 0 0 0 7.133 17.5h5.734a2.25 2.25 0 0 0 2.24-2.15l.853-9.1h.54a.75.75 0 0 0 0-1.5h-2.25V4.5A1.75 1.75 0 0 0 12.5 2.75h-5Zm5.25 2V4.5a.25.25 0 0 0-.25-.25h-5a.25.25 0 0 0-.25.25v.25h5.5Zm-4 3a.75.75 0 0 1 .75.75v4.5a.75.75 0 0 1-1.5 0V8.5a.75.75 0 0 1 .75-.75Zm3.25.75a.75.75 0 0 0-1.5 0v4.5a.75.75 0 0 0 1.5 0V8.5Z", clipRule: "evenodd" }));
}
function ChatBubbleIcon() {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.2, stroke: "currentColor", className: "h-10 w-10 text-white/15" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.625 12a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0H8.25m4.125 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0H12m4.125 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 0 1-2.555-.337A5.972 5.972 0 0 1 5.41 20.97a5.969 5.969 0 0 1-.474-.065 4.48 4.48 0 0 0 .978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25Z" }));
}
function ChevronDownIcon({ className }) {
  return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z", clipRule: "evenodd" }));
}
function Avatar({ user, size = 36 }) {
  if (user?.avatar_url) {
    return /* @__PURE__ */ React.createElement(
      "img",
      {
        src: user.avatar_url,
        alt: user.display || user.username || "",
        width: size,
        height: size,
        className: "rounded-full object-cover shrink-0 ring-1 ring-white/10",
        style: { width: size, height: size },
        loading: "lazy",
        onError: (event) => {
          event.currentTarget.onerror = null;
          event.currentTarget.src = "https://files.skinbase.org/default/avatar_default.webp";
        }
      }
    );
  }
  const initials = (user?.display || user?.username || "?").slice(0, 1).toUpperCase();
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: "flex items-center justify-center rounded-full bg-gradient-to-br from-nova-600 to-nova-800 text-sm font-bold text-white/90 shrink-0 ring-1 ring-white/10",
      style: { width: size, height: size }
    },
    initials
  );
}
function DeleteButton({ onDelete, pending = false }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onDelete,
      disabled: pending,
      className: "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium uppercase tracking-wider text-white/35 transition-all duration-200 hover:bg-rose-500/10 hover:text-rose-100 disabled:pointer-events-none disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement(TrashIcon, null),
    "Remove"
  );
}
function ReplyItem({ reply, articleId, isLoggedIn, onReplyPosted, onDelete, deletePending = false, depth = 1 }) {
  const user = reply.user;
  const html2 = reply.rendered_content ?? null;
  const plain = reply.raw_content ?? "";
  const profileLabel = user?.display || user?.username || "Member";
  const replies = reply.replies || [];
  const reactionEndpoint = `/api/news/comments/${reply.id}/reactions`;
  const [showReplyForm, setShowReplyForm] = reactExports.useState(false);
  const [showAllReplies, setShowAllReplies] = reactExports.useState(false);
  const [reactionTotals, setReactionTotals] = reactExports.useState(reply.reactions ?? {});
  reactExports.useEffect(() => {
    if (reply.reactions || !reply.id) return;
    axios.get(reactionEndpoint).then(({ data }) => setReactionTotals(data.totals ?? {})).catch(() => {
    });
  }, [reply.id, reply.reactions, reactionEndpoint]);
  const handleReplyPosted = reactExports.useCallback((newReply) => {
    onReplyPosted?.(reply.id, newReply);
    setShowReplyForm(false);
    setShowAllReplies(true);
  }, [onReplyPosted, reply.id]);
  const visibleReplies = showAllReplies ? replies : replies.slice(0, 2);
  const hiddenReplyCount = replies.length - 2;
  const avatarSize = depth >= 3 ? 22 : 28;
  return /* @__PURE__ */ React.createElement("li", { className: "rounded-lg bg-white/[0.02] px-3 py-2.5", id: `comment-${reply.id}` }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-2.5" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "shrink-0 mt-0.5", tabIndex: -1 }, /* @__PURE__ */ React.createElement(Avatar, { user, size: avatarSize })) : /* @__PURE__ */ React.createElement("span", { className: "shrink-0 mt-0.5" }, /* @__PURE__ */ React.createElement(Avatar, { user, size: avatarSize })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 flex-wrap" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "text-[12px] font-semibold text-white/90 hover:text-accent transition-colors" }, profileLabel) : /* @__PURE__ */ React.createElement("span", { className: "text-[12px] font-semibold text-white/90" }, profileLabel), /* @__PURE__ */ React.createElement(LevelBadge, { level: user?.level, rank: user?.rank, compact: true, className: "shrink-0" }), /* @__PURE__ */ React.createElement("span", { className: "text-white/15", "aria-hidden": "true" }, "·"), /* @__PURE__ */ React.createElement(
    "time",
    {
      dateTime: reply.created_at,
      title: formatAbsoluteDateTime(reply.created_at),
      className: "text-[10px] font-medium tracking-wide text-white/25 uppercase"
    },
    formatCommentTime(reply.time_ago, reply.created_at)
  )), html2 ? /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "mt-1 text-[12.5px] leading-[1.65] text-white/70 prose prose-invert prose-sm max-w-none prose-p:my-1 prose-a:text-sky-400 prose-a:no-underline hover:prose-a:underline prose-code:bg-white/[0.07] prose-code:px-1 prose-code:py-0.5 prose-code:rounded-md prose-code:text-xs",
      dangerouslySetInnerHTML: { __html: html2 }
    }
  ) : /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[12.5px] leading-[1.65] text-white/70 whitespace-pre-line break-words" }, plain), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-1.5 pt-1" }, isLoggedIn && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShowReplyForm((value) => !value),
      className: [
        "inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] font-medium uppercase tracking-wider transition-all duration-200 focus:outline-none",
        showReplyForm ? "bg-accent/10 text-accent" : "text-white/35 hover:bg-white/[0.06] hover:text-white/65"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(ReplyIcon, null),
    "Reply"
  ), reply.can_delete ? /* @__PURE__ */ React.createElement(DeleteButton, { onDelete: () => onDelete(reply.id), pending: deletePending }) : null, /* @__PURE__ */ React.createElement(
    ReactionBar,
    {
      entityType: "comment",
      entityId: reply.id,
      initialTotals: reactionTotals,
      isLoggedIn,
      endpoint: reactionEndpoint
    }
  )), showReplyForm ? /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement(
    CommentForm$1,
    {
      artworkId: articleId,
      submitUrl: `/api/news/articles/${articleId}/comments`,
      contentField: "content",
      maxLength: 4e3,
      placeholder: "Share your thoughts about this article…",
      onPosted: handleReplyPosted,
      parentId: reply.id,
      replyTo: profileLabel,
      onCancelReply: () => setShowReplyForm(false),
      isLoggedIn,
      compact: true
    }
  )) : null, replies.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement("ul", { className: `space-y-1 pl-3 border-l-2 ${depth >= 3 ? "border-white/[0.03]" : "border-white/[0.05]"}` }, visibleReplies.map((child) => /* @__PURE__ */ React.createElement(
    ReplyItem,
    {
      key: child.id,
      reply: child,
      articleId,
      isLoggedIn,
      onReplyPosted,
      onDelete,
      deletePending: deletePending && child.id === reply.id,
      depth: depth + 1
    }
  ))), !showAllReplies && hiddenReplyCount > 0 ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShowAllReplies(true),
      className: "mt-1.5 ml-3 inline-flex items-center gap-1 text-[10px] font-medium text-accent/70 transition-colors hover:text-accent"
    },
    /* @__PURE__ */ React.createElement(ChevronDownIcon, { className: "h-3 w-3" }),
    "Show ",
    hiddenReplyCount,
    " more ",
    hiddenReplyCount === 1 ? "reply" : "replies"
  ) : null) : null)));
}
function CommentItem({ comment, isLoggedIn, articleId, onReplyPosted, onDelete, deletePending = false }) {
  const user = comment.user;
  const html2 = comment.rendered_content ?? null;
  const plain = comment.raw_content ?? "";
  const profileLabel = user?.display || user?.username || "Member";
  const replies = comment.replies || [];
  const flood = isFlood(plain);
  const reactionEndpoint = `/api/news/comments/${comment.id}/reactions`;
  const [expanded, setExpanded] = reactExports.useState(!flood);
  const [showReplyForm, setShowReplyForm] = reactExports.useState(false);
  const [showAllReplies, setShowAllReplies] = reactExports.useState(false);
  const [reactionTotals, setReactionTotals] = reactExports.useState(comment.reactions ?? {});
  reactExports.useEffect(() => {
    if (comment.reactions || !comment.id) return;
    axios.get(reactionEndpoint).then(({ data }) => setReactionTotals(data.totals ?? {})).catch(() => {
    });
  }, [comment.id, comment.reactions, reactionEndpoint]);
  const handleReplyPosted = reactExports.useCallback((newReply) => {
    onReplyPosted?.(comment.id, newReply);
    setShowReplyForm(false);
    setShowAllReplies(true);
  }, [comment.id, onReplyPosted]);
  const visibleReplies = showAllReplies ? replies : replies.slice(0, 2);
  const hiddenReplyCount = replies.length - 2;
  return /* @__PURE__ */ React.createElement(
    "li",
    {
      id: `comment-${comment.id}`,
      className: "group/comment rounded-2xl border border-white/[0.06] bg-white/[0.03] shadow-[0_1px_3px_rgba(0,0,0,.25)] backdrop-blur-sm transition-all duration-200 hover:border-white/[0.1] hover:bg-white/[0.05]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3.5" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "shrink-0 mt-0.5", tabIndex: -1, "aria-hidden": "true" }, /* @__PURE__ */ React.createElement(Avatar, { user, size: 38 })) : /* @__PURE__ */ React.createElement("span", { className: "shrink-0 mt-0.5" }, /* @__PURE__ */ React.createElement(Avatar, { user, size: 38 })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 flex-wrap" }, user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: user.profile_url, className: "text-[13px] font-semibold text-white/95 transition-colors hover:text-accent" }, profileLabel) : /* @__PURE__ */ React.createElement("span", { className: "text-[13px] font-semibold text-white/95" }, profileLabel), /* @__PURE__ */ React.createElement(LevelBadge, { level: user?.level, rank: user?.rank, compact: true, className: "shrink-0" }), /* @__PURE__ */ React.createElement("span", { className: "text-white/15", "aria-hidden": "true" }, "·"), /* @__PURE__ */ React.createElement(
      "time",
      {
        dateTime: comment.created_at,
        title: formatAbsoluteDateTime(comment.created_at),
        className: "text-[11px] font-medium tracking-wide text-white/30 uppercase"
      },
      formatCommentTime(comment.time_ago, comment.created_at)
    )), /* @__PURE__ */ React.createElement("div", { className: !expanded ? "overflow-hidden relative" : void 0, style: !expanded ? { maxHeight: "5em" } : void 0 }, html2 ? /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "text-[13px] leading-[1.7] text-white/80 prose prose-invert prose-sm max-w-none prose-p:my-1.5 prose-a:text-sky-400 prose-a:no-underline hover:prose-a:underline prose-code:bg-white/[0.07] prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded-md prose-code:text-xs prose-code:font-normal",
        dangerouslySetInnerHTML: { __html: html2 }
      }
    ) : /* @__PURE__ */ React.createElement("p", { className: "text-[13px] leading-[1.7] text-white/80 whitespace-pre-line break-words" }, plain), flood && !expanded ? /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 h-8 bg-gradient-to-t from-nova-900/95 to-transparent", "aria-hidden": "true" }) : null), flood ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setExpanded((value) => !value),
        className: "rounded-md px-2 py-0.5 text-xs font-medium text-sky-400 transition-all hover:bg-sky-500/10 hover:text-sky-300",
        "aria-expanded": expanded
      },
      expanded ? "↑ Collapse" : "↓ Show full comment"
    ) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-1.5 pt-0.5" }, isLoggedIn ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowReplyForm((value) => !value),
        className: [
          "inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[11px] font-medium uppercase tracking-wider transition-all duration-200 focus:outline-none",
          showReplyForm ? "bg-accent/10 text-accent" : "text-white/40 hover:bg-white/[0.06] hover:text-white/70"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement(ReplyIcon, null),
      "Reply"
    ) : null, comment.can_delete ? /* @__PURE__ */ React.createElement(DeleteButton, { onDelete: () => onDelete(comment.id), pending: deletePending }) : null, /* @__PURE__ */ React.createElement(
      ReactionBar,
      {
        entityType: "comment",
        entityId: comment.id,
        initialTotals: reactionTotals,
        isLoggedIn,
        endpoint: reactionEndpoint
      }
    ))))),
    replies.length > 0 || showReplyForm ? /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.04] bg-white/[0.01] px-4 pb-4 pt-3 sm:px-5 sm:pb-5" }, replies.length > 0 ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("ul", { className: "space-y-1 pl-4 border-l-2 border-white/[0.06]" }, visibleReplies.map((reply) => /* @__PURE__ */ React.createElement(
      ReplyItem,
      {
        key: reply.id,
        reply,
        articleId,
        isLoggedIn,
        onReplyPosted,
        onDelete,
        deletePending: deletePending && reply.id === comment.id
      }
    ))), !showAllReplies && hiddenReplyCount > 0 ? /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowAllReplies(true),
        className: "mt-2 ml-4 inline-flex items-center gap-1 text-[11px] font-medium text-accent/70 transition-colors hover:text-accent"
      },
      /* @__PURE__ */ React.createElement(ChevronDownIcon, { className: "h-3.5 w-3.5" }),
      "Show ",
      hiddenReplyCount,
      " more ",
      hiddenReplyCount === 1 ? "reply" : "replies"
    ) : null) : null, showReplyForm ? /* @__PURE__ */ React.createElement("div", { className: replies.length > 0 ? "mt-3 pl-4 border-l-2 border-accent/20" : "" }, /* @__PURE__ */ React.createElement(
      CommentForm$1,
      {
        artworkId: articleId,
        submitUrl: `/api/news/articles/${articleId}/comments`,
        contentField: "content",
        maxLength: 4e3,
        placeholder: "Share your thoughts about this article…",
        onPosted: handleReplyPosted,
        parentId: comment.id,
        replyTo: profileLabel,
        onCancelReply: () => setShowReplyForm(false),
        isLoggedIn,
        compact: true
      }
    )) : null) : null
  );
}
function Skeleton() {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, Array.from({ length: 3 }).map((_2, index2) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: index2,
      className: "flex gap-3.5 rounded-2xl border border-white/[0.04] bg-white/[0.02] p-5 animate-pulse",
      style: { animationDelay: `${index2 * 120}ms` }
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-[38px] h-[38px] rounded-full bg-white/[0.06] shrink-0" }),
    /* @__PURE__ */ React.createElement("div", { className: "flex-1 space-y-3 pt-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-2.5" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.06] rounded-full w-24" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.04] rounded-full w-14" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.05] rounded-full w-full" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.04] rounded-full w-4/5" }), /* @__PURE__ */ React.createElement("div", { className: "h-3 bg-white/[0.03] rounded-full w-2/5" })))
  )));
}
function NewsComments({ articleId, isLoggedIn = false, loginUrl = "/login" }) {
  const [comments, setComments] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [page, setPage] = reactExports.useState(1);
  const [lastPage, setLastPage] = reactExports.useState(1);
  const [total, setTotal] = reactExports.useState(0);
  const [deletingId, setDeletingId] = reactExports.useState(null);
  const initialized = reactExports.useRef(false);
  const loadComments = reactExports.useCallback(async (nextPage = 1) => {
    if (!articleId) return;
    setLoading(true);
    try {
      const { data } = await axios.get(`/api/news/articles/${articleId}/comments?page=${nextPage}`);
      if (nextPage === 1) {
        setComments(data.data ?? []);
      } else {
        setComments((current) => [...current, ...data.data ?? []]);
      }
      setPage(data.meta?.current_page ?? nextPage);
      setLastPage(data.meta?.last_page ?? 1);
      setTotal(data.meta?.total ?? 0);
    } catch {
    } finally {
      setLoading(false);
    }
  }, [articleId]);
  reactExports.useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;
    loadComments(1);
  }, [loadComments]);
  const handlePosted = reactExports.useCallback((newComment) => {
    const comment = { ...newComment, replies: newComment.replies || [] };
    setComments((current) => [comment, ...current]);
    setTotal((current) => current + 1);
  }, []);
  const handleReplyPosted = reactExports.useCallback((parentId, newReply) => {
    const insertReply = (nodes) => nodes.map((comment) => {
      if (comment.id === parentId) {
        return { ...comment, replies: [...comment.replies || [], { ...newReply, replies: [] }] };
      }
      if (comment.replies?.length) {
        return { ...comment, replies: insertReply(comment.replies) };
      }
      return comment;
    });
    setComments((current) => insertReply(current));
    setTotal((current) => current + 1);
  }, []);
  const handleDelete = reactExports.useCallback(async (commentId) => {
    if (!commentId || deletingId) return;
    setDeletingId(commentId);
    try {
      await axios.delete(`/api/news/articles/${articleId}/comments/${commentId}`);
      await loadComments(1);
    } catch {
    } finally {
      setDeletingId(null);
    }
  }, [articleId, deletingId, loadComments]);
  return /* @__PURE__ */ React.createElement("section", { "aria-label": "Comments", className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold tracking-tight text-white sm:text-xl" }, "Comments"), total > 0 ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full bg-white/[0.06] px-2.5 py-0.5 text-xs font-medium tabular-nums text-white/50" }, total) : null), loading && comments.length === 0 ? /* @__PURE__ */ React.createElement(Skeleton, null) : comments.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center gap-3 rounded-2xl border border-dashed border-white/[0.08] bg-white/[0.015] px-6 py-10 text-center" }, /* @__PURE__ */ React.createElement(ChatBubbleIcon, null), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/40" }, "No comments yet"), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/25" }, "Be the first to share your thoughts.")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("ul", { className: "space-y-3 sm:space-y-4" }, comments.map((comment) => /* @__PURE__ */ React.createElement(
    CommentItem,
    {
      key: comment.id,
      comment,
      articleId,
      isLoggedIn,
      onReplyPosted: handleReplyPosted,
      onDelete: handleDelete,
      deletePending: deletingId === comment.id
    }
  ))), page < lastPage ? /* @__PURE__ */ React.createElement("div", { className: "flex justify-center pt-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: loading,
      onClick: () => loadComments(page + 1),
      className: "group relative rounded-full border border-white/[0.08] bg-white/[0.03] px-6 py-2.5 text-sm font-medium text-white/50 transition-all duration-200 hover:border-white/[0.15] hover:bg-white/[0.06] hover:text-white/80 hover:shadow-lg hover:shadow-black/20 disabled:opacity-40 disabled:pointer-events-none"
    },
    loading ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 animate-spin", viewBox: "0 0 24 24", fill: "none" }, /* @__PURE__ */ React.createElement("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3" }), /* @__PURE__ */ React.createElement("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" })), "Loading…") : "Load more comments"
  )) : null), articleId ? /* @__PURE__ */ React.createElement(
    CommentForm$1,
    {
      artworkId: articleId,
      submitUrl: `/api/news/articles/${articleId}/comments`,
      contentField: "content",
      maxLength: 4e3,
      placeholder: "Share your thoughts about this article…",
      onPosted: handlePosted,
      isLoggedIn,
      loginUrl
    }
  ) : null);
}
if (typeof document !== "undefined") {
  const mountEl = document.getElementById("news-comments-root");
  const propsEl = document.getElementById("news-comments-props");
  if (mountEl && propsEl) {
    let props = {};
    try {
      props = JSON.parse(propsEl.textContent || "{}");
    } catch {
      props = {};
    }
    clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(NewsComments, { ...props }));
  }
}
const __vite_glob_0_100 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NewsComments
}, Symbol.toStringTag, { value: "Module" }));
let previewOverlay = null;
let previewImage = null;
let previewCaption = null;
let scrollPosition = 0;
function ensurePreviewOverlay() {
  if (previewOverlay) {
    return previewOverlay;
  }
  previewOverlay = document.createElement("div");
  previewOverlay.className = "fixed inset-0 z-[130] hidden items-center justify-center bg-[#020611bf] p-6 backdrop-blur-xl";
  previewOverlay.setAttribute("role", "dialog");
  previewOverlay.setAttribute("aria-modal", "true");
  previewOverlay.setAttribute("aria-label", "Image preview");
  const frame = document.createElement("div");
  frame.className = "relative flex max-h-[92vh] w-full max-w-6xl flex-col items-center gap-4";
  previewImage = document.createElement("img");
  previewImage.className = "max-h-[78vh] max-w-full rounded-[28px] border border-white/10 shadow-[0_28px_90px_rgba(2,6,23,0.45)]";
  previewImage.alt = "Image preview";
  previewCaption = document.createElement("div");
  previewCaption.className = "w-full max-w-4xl rounded-[24px] border border-white/10 bg-black/30 px-6 py-4 text-center text-sm font-medium leading-6 text-white/90 backdrop-blur-md";
  const closeButton = document.createElement("button");
  closeButton.type = "button";
  closeButton.setAttribute("aria-label", "Close image preview");
  closeButton.className = "absolute right-4 top-4 inline-flex h-11 w-11 items-center justify-center rounded-full border border-white/10 bg-black/35 text-white transition hover:border-white/25 hover:bg-white/10";
  closeButton.innerHTML = '<i class="fa-solid fa-xmark text-lg"></i>';
  closeButton.addEventListener("click", hidePreview);
  frame.appendChild(previewImage);
  frame.appendChild(previewCaption);
  frame.appendChild(closeButton);
  previewOverlay.appendChild(frame);
  previewOverlay.addEventListener("click", (event) => {
    if (event.target === previewOverlay) {
      hidePreview();
    }
  });
  document.body.appendChild(previewOverlay);
  return previewOverlay;
}
function showPreview(src2, alt) {
  if (!src2) return;
  ensurePreviewOverlay();
  scrollPosition = window.scrollY || document.documentElement.scrollTop || 0;
  document.body.style.position = "fixed";
  document.body.style.top = `-${scrollPosition}px`;
  document.body.style.left = "0";
  document.body.style.right = "0";
  document.body.style.width = "100%";
  previewImage.src = src2;
  previewImage.alt = alt;
  previewCaption.textContent = alt;
  previewOverlay.classList.remove("hidden");
  previewOverlay.classList.add("flex");
}
function hidePreview() {
  if (!previewOverlay) return;
  previewOverlay.classList.add("hidden");
  previewOverlay.classList.remove("flex");
  previewImage.removeAttribute("src");
  document.body.style.position = "";
  document.body.style.top = "";
  document.body.style.left = "";
  document.body.style.right = "";
  document.body.style.width = "";
  window.scrollTo(0, scrollPosition);
}
function handleNewsImagePreview(event) {
  const trigger = event.target?.closest?.("[data-news-image-preview]");
  if (!trigger) return;
  const src2 = trigger.getAttribute("data-news-image-src") || trigger.getAttribute("href");
  if (!src2) return;
  event.preventDefault();
  showPreview(src2, trigger.getAttribute("data-news-image-alt") || trigger.getAttribute("aria-label") || "Image preview");
}
function handleKeyDown(event) {
  if (event.key === "Escape") {
    hidePreview();
  }
}
if (typeof document !== "undefined") {
  document.addEventListener("click", handleNewsImagePreview);
  document.addEventListener("keydown", handleKeyDown);
}
const NewsImagePreview = null;
const __vite_glob_0_101 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: NewsImagePreview
}, Symbol.toStringTag, { value: "Module" }));
function clamp(value, min2, max2) {
  return Math.min(max2, Math.max(min2, value));
}
function ProfileCoverEditor({
  isOpen,
  onClose,
  coverUrl,
  coverPosition,
  onCoverUpdated,
  onCoverRemoved
}) {
  const previewRef = reactExports.useRef(null);
  const [saving, setSaving] = reactExports.useState(false);
  const [uploading, setUploading] = reactExports.useState(false);
  const [removing, setRemoving] = reactExports.useState(false);
  const [position2, setPosition] = reactExports.useState(coverPosition ?? 50);
  const csrfToken2 = reactExports.useMemo(() => {
    if (typeof document === "undefined") {
      return "";
    }
    return document.querySelector('meta[name="csrf-token"]')?.content ?? "";
  }, []);
  if (!isOpen) {
    return null;
  }
  const updatePositionFromPointer = (clientY) => {
    const el = previewRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    if (rect.height <= 0) return;
    const normalized = (clientY - rect.top) / rect.height * 100;
    setPosition(Math.round(clamp(normalized, 0, 100)));
  };
  const handlePointerDown = (event) => {
    updatePositionFromPointer(event.clientY);
    const onMove = (moveEvent) => updatePositionFromPointer(moveEvent.clientY);
    const onUp = () => {
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", onUp);
    };
    window.addEventListener("pointermove", onMove);
    window.addEventListener("pointerup", onUp);
  };
  const handleUpload = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    setUploading(true);
    try {
      const body2 = new FormData();
      body2.append("cover", file);
      const response = await fetch("/api/profile/cover/upload", {
        method: "POST",
        headers: {
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        },
        body: body2
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || payload?.error || "Cover upload failed.");
      }
      const nextPosition = Number.isFinite(payload.cover_position) ? payload.cover_position : 50;
      setPosition(nextPosition);
      onCoverUpdated(payload.cover_url, nextPosition);
    } catch (error) {
      window.alert(error?.message || "Cover upload failed.");
    } finally {
      setUploading(false);
      event.target.value = "";
    }
  };
  const handleSavePosition = async () => {
    if (!coverUrl) return;
    setSaving(true);
    try {
      const response = await fetch("/api/profile/cover/position", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        },
        body: JSON.stringify({ position: position2 })
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || payload?.error || "Could not save position.");
      }
      onCoverUpdated(coverUrl, payload.cover_position ?? position2);
      onClose();
    } catch (error) {
      window.alert(error?.message || "Could not save position.");
    } finally {
      setSaving(false);
    }
  };
  const handleRemove = async () => {
    if (!coverUrl) return;
    setRemoving(true);
    try {
      const response = await fetch("/api/profile/cover", {
        method: "DELETE",
        headers: {
          "X-CSRF-TOKEN": csrfToken2,
          Accept: "application/json"
        }
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || payload?.error || "Could not remove cover.");
      }
      setPosition(payload.cover_position ?? 50);
      onCoverRemoved();
      onClose();
    } catch (error) {
      window.alert(error?.message || "Could not remove cover.");
    } finally {
      setRemoving(false);
    }
  };
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/70 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-3xl rounded-2xl border border-white/10 bg-[#0d1524] shadow-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Edit Cover"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClose,
      className: "rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",
      "aria-label": "Close cover editor"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-dashed border-slate-600/70 bg-slate-900/50 p-3" }, /* @__PURE__ */ React.createElement("label", { className: "inline-flex cursor-pointer items-center gap-2 rounded-lg bg-sky-600 px-4 py-2 text-sm font-medium text-white hover:bg-sky-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-upload" }), uploading ? "Uploading..." : "Upload Cover", /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "file",
      accept: "image/jpeg,image/png,image/webp",
      className: "hidden",
      onChange: handleUpload,
      disabled: uploading
    }
  )), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-slate-400" }, "Allowed: JPG, PNG, WEBP. Max 5MB. Recommended: 1920x480.")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 text-sm text-slate-300" }, "Drag vertically to reposition the cover."), /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: previewRef,
      onPointerDown: handlePointerDown,
      className: "relative h-44 w-full cursor-ns-resize overflow-hidden rounded-xl border border-white/10 bg-[#101a2a]",
      style: {
        background: coverUrl ? `url('${coverUrl}') center ${position2}% / cover no-repeat` : "linear-gradient(135deg, #0f1724 0%, #151e2e 50%, #090f1a 100%)"
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-r from-[#0f1724]/70 to-[#0f1724]/30" }),
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "pointer-events-none absolute left-0 right-0 border-t border-dashed border-sky-400/80",
        style: { top: `${position2}%` }
      }
    )
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Position"), /* @__PURE__ */ React.createElement("span", null, position2, "%")))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-2 border-t border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleRemove,
      disabled: removing || !coverUrl,
      className: "inline-flex items-center gap-2 rounded-lg border border-red-400/30 px-4 py-2 text-sm font-medium text-red-300 hover:bg-red-500/10 disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${removing ? "fa-circle-notch fa-spin" : "fa-trash"}` }),
    "Remove Cover"
  ), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClose,
      className: "rounded-lg border border-white/15 px-4 py-2 text-sm text-slate-300 hover:bg-white/10"
    },
    "Cancel"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleSavePosition,
      disabled: saving || !coverUrl,
      className: "inline-flex items-center gap-2 rounded-lg bg-sky-600 px-4 py-2 text-sm font-medium text-white hover:bg-sky-500 disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${saving ? "fa-circle-notch fa-spin" : "fa-floppy-disk"}` }),
    "Save Position"
  )))));
}
function formatXp(value) {
  return new Intl.NumberFormat().format(Number(value || 0));
}
function clampPercent(value) {
  const numeric = Number(value || 0);
  if (!Number.isFinite(numeric)) return 0;
  return Math.max(0, Math.min(100, numeric));
}
function cx$2(...parts) {
  return parts.filter(Boolean).join(" ");
}
function XPProgressBar({
  xp = 0,
  currentLevelXp = 0,
  nextLevelXp = 100,
  progressPercent = 0,
  maxLevel = false,
  className = ""
}) {
  const percent = maxLevel ? 100 : clampPercent(progressPercent);
  return /* @__PURE__ */ React.createElement("div", { className: cx$2("space-y-2", className) }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, formatXp(xp), " XP"), /* @__PURE__ */ React.createElement("span", null, maxLevel ? "Max level reached" : `${formatXp(currentLevelXp)} / ${formatXp(nextLevelXp)} XP`)), /* @__PURE__ */ React.createElement("div", { className: "h-2.5 overflow-hidden rounded-full bg-white/10 ring-1 ring-white/10" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "h-full rounded-full bg-[linear-gradient(90deg,#38bdf8_0%,#a78bfa_55%,#f59e0b_100%)] transition-[width] duration-500",
      style: { width: `${percent}%` }
    }
  )));
}
function FollowersPreview({ users = [], label = "", href = null }) {
  if (!Array.isArray(users) || users.length === 0) return null;
  const preview = users.slice(0, 4);
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex -space-x-2" }, preview.map((user) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: user.id,
      href: user.profile_url || `/@${user.username}`,
      className: "inline-flex h-9 w-9 overflow-hidden rounded-full border border-[#09111f] bg-[#09111f] ring-1 ring-white/10",
      title: user.name || user.username
    },
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: user.avatar_url || "/images/avatar_default.webp",
        alt: user.username || user.name,
        className: "h-full w-full object-cover",
        loading: "lazy"
      }
    )
  ))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/90" }, label), href ? /* @__PURE__ */ React.createElement("a", { href, className: "text-xs text-sky-300/80 transition-colors hover:text-sky-200" }, "View network") : null)));
}
function MutualFollowersBadge({ context }) {
  const label = context?.follower_overlap?.label || context?.shared_following?.label || null;
  if (!label) return null;
  return /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-emerald-400/20 bg-emerald-400/10 px-3 py-1.5 text-xs font-medium text-emerald-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-group fa-fw text-[11px]" }), label);
}
function shinyFlagUrl(countryCode, filesCdnUrl = "") {
  const normalized = String(countryCode ?? "").trim().toUpperCase();
  if (!/^[A-Z]{2}$/.test(normalized)) {
    return null;
  }
  const base = String(filesCdnUrl ?? "").replace(/\/+$/, "");
  const relativePath = `/images/flags/shiny/24/${encodeURIComponent(normalized)}.png`;
  return base ? `${base}${relativePath}` : relativePath;
}
function formatCompactNumber$1(value) {
  const numeric = Number(value ?? 0);
  return numeric.toLocaleString("en-US");
}
function ProfileHero({ user, profile, isOwner, viewerIsFollowing, followerCount, recentFollowers = [], followContext = null, heroBgUrl, countryName, leaderboardRank, extraActions = null }) {
  const { props } = X$1();
  const [following, setFollowing] = reactExports.useState(viewerIsFollowing);
  const [count, setCount] = reactExports.useState(followerCount);
  const [editorOpen, setEditorOpen] = reactExports.useState(false);
  const [coverUrl, setCoverUrl] = reactExports.useState(user?.cover_url || heroBgUrl || null);
  const [coverPosition, setCoverPosition] = reactExports.useState(Number.isFinite(user?.cover_position) ? user.cover_position : 50);
  const flagUrl = shinyFlagUrl(profile?.country_code, props?.cdn?.files_url);
  const uname = user.username || user.name || "Unknown";
  const displayName = user.name || uname;
  const joinDate = user.created_at ? new Date(user.created_at).toLocaleDateString("en-US", { month: "long", year: "numeric" }) : null;
  const progressPercent = Math.round(Number(user?.progress_percent ?? 0));
  const heroStats = [
    { label: "Followers", value: formatCompactNumber$1(count) },
    { label: "Level", value: `Lv ${formatCompactNumber$1(user?.level ?? 1)}` }
  ];
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "relative mx-auto max-w-7xl px-4 pt-4 md:pt-6" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-x-10 top-8 -z-10 h-44 rounded-full blur-3xl",
      style: {
        background: "linear-gradient(90deg, rgba(56,189,248,0.18), rgba(249,115,22,0.14), rgba(59,130,246,0.12))"
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[32px] border border-white/10 bg-[#09111f]/80 shadow-[0_24px_80px_rgba(2,6,23,0.55)]" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "w-full h-[208px] md:h-[248px] xl:h-[288px]",
      style: {
        background: coverUrl ? `url('${coverUrl}') center ${coverPosition}% / cover no-repeat` : "linear-gradient(140deg, #07101d 0%, #0b1726 42%, #07111e 100%)",
        position: "relative"
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 z-20 flex flex-wrap items-center gap-2 md:left-6 md:top-6" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-black/30 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-200 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("span", { className: "h-2 w-2 rounded-full bg-sky-400 shadow-[0_0_12px_rgba(56,189,248,0.9)]" }), "Creator profile"), leaderboardRank?.rank ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sparkles text-[10px]" }), "Top #", leaderboardRank.rank, " this week") : null),
    isOwner ? /* @__PURE__ */ React.createElement("div", { className: "absolute right-4 top-4 z-20 md:right-6 md:top-6" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setEditorOpen(true),
        className: "inline-flex items-center gap-2 rounded-full border border-white/20 bg-black/35 px-3.5 py-2 text-xs font-medium text-white backdrop-blur-md transition-colors hover:bg-black/55",
        "aria-label": "Edit cover image"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" }),
      "Edit Cover"
    )) : null,
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "absolute inset-0",
        style: {
          background: coverUrl ? "linear-gradient(180deg, rgba(2,6,23,0.16) 0%, rgba(2,6,23,0.28) 38%, rgba(2,6,23,0.9) 100%)" : "radial-gradient(ellipse at 16% 40%, rgba(77,163,255,.18) 0%, transparent 60%), radial-gradient(ellipse at 84% 22%, rgba(224,122,33,.14) 0%, transparent 54%)"
        }
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 opacity-[0.06] pointer-events-none", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "32px" } })
  ), /* @__PURE__ */ React.createElement("div", { className: "relative px-4 pb-6 md:px-7 md:pb-7" }, /* @__PURE__ */ React.createElement("div", { className: "relative -mt-16 flex flex-col gap-5 md:-mt-20 md:flex-row md:items-start md:gap-6" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto z-10 shrink-0 md:mx-0" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: user.avatar_url || "/default/avatar_default.webp",
      alt: `${uname}'s avatar`,
      className: "h-[112px] w-[112px] rounded-[28px] border border-white/15 bg-[#0b1320] object-cover shadow-[0_0_0_8px_rgba(9,17,31,0.92),0_22px_44px_rgba(2,6,23,0.5)] md:h-[132px] md:w-[132px]"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 text-center md:text-left" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_430px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-center gap-2 md:justify-start" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-stars text-[10px] text-sky-300" }), "Profile spotlight")), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-[30px] font-semibold leading-tight tracking-[-0.03em] text-white md:text-[42px]" }, displayName), /* @__PURE__ */ React.createElement("p", { className: "mt-1 font-mono text-sm text-slate-400 md:text-[15px]" }, "@", uname), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center justify-center gap-2 md:justify-start" }, /* @__PURE__ */ React.createElement(LevelBadge, { level: user?.level, rank: user?.rank }), !isOwner ? /* @__PURE__ */ React.createElement(MutualFollowersBadge, { context: followContext }) : null, countryName ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300" }, flagUrl ? /* @__PURE__ */ React.createElement(
    "img",
    {
      src: flagUrl,
      alt: countryName,
      className: "h-auto w-4 rounded-sm",
      onError: (event) => {
        event.target.style.display = "none";
      }
    }
  ) : null, countryName) : null, joinDate ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/5 px-3 py-1.5 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days fa-fw text-slate-500" }), "Joined ", joinDate) : null, profile?.website ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: profile.website.startsWith("http") ? profile.website : `https://${profile.website}`,
      target: "_blank",
      rel: "nofollow noopener noreferrer",
      className: "inline-flex items-center gap-1.5 rounded-full border border-sky-400/20 bg-sky-400/10 px-3 py-1.5 text-xs text-sky-200 transition-colors hover:border-sky-300/35 hover:bg-sky-400/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link fa-fw" }),
    (() => {
      try {
        const url = profile.website.startsWith("http") ? profile.website : `https://${profile.website}`;
        return new URL(url).hostname;
      } catch {
        return profile.website;
      }
    })()
  ) : null), /* @__PURE__ */ React.createElement(
    XPProgressBar,
    {
      xp: user?.xp,
      currentLevelXp: user?.current_level_xp,
      nextLevelXp: user?.next_level_xp,
      progressPercent: user?.progress_percent,
      maxLevel: user?.max_level,
      className: "mt-4 max-w-3xl"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 xl:pt-1" }, !isOwner && recentFollowers?.length > 0 ? /* @__PURE__ */ React.createElement(
    FollowersPreview,
    {
      users: followContext?.follower_overlap?.users?.length ? followContext.follower_overlap.users : recentFollowers,
      label: followContext?.follower_overlap?.label || `${formatCompactNumber$1(followerCount)} followers`,
      href: `/@${uname}/activity`
    }
  ) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-center gap-2 xl:flex-nowrap xl:justify-end" }, extraActions, isOwner ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/dashboard/profile",
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/15 bg-white/[0.04] px-4 py-2.5 text-sm font-medium text-slate-200 transition-all hover:bg-white/[0.08] hover:text-white",
      "aria-label": "Edit profile"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw" }),
    "Edit Profile"
  ), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/studio",
      className: "inline-flex items-center gap-2 rounded-2xl bg-gradient-to-r from-sky-500 to-cyan-400 px-4 py-2.5 text-sm font-semibold text-slate-950 shadow-[0_18px_36px_rgba(14,165,233,0.28)] transition-transform hover:-translate-y-0.5",
      "aria-label": "Open Studio"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles fa-fw" }),
    "Studio"
  )) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    FollowButton,
    {
      username: uname,
      initialFollowing: following,
      initialCount: count,
      className: "shrink-0 whitespace-nowrap",
      followingClassName: "border border-emerald-400/40 bg-emerald-500/12 text-emerald-300 hover:bg-emerald-500/18",
      idleClassName: "border border-sky-400/40 bg-sky-500/12 text-sky-200 hover:bg-sky-500/20",
      sizeClassName: "px-3.5 py-2 text-sm",
      onChange: ({ following: nextFollowing, followersCount }) => {
        setFollowing(nextFollowing);
        setCount(followersCount);
      }
    }
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        if (navigator.share) {
          navigator.share({ title: `${displayName} on Skinbase`, url: window.location.href });
        } else {
          navigator.clipboard.writeText(window.location.href);
        }
      },
      "aria-label": "Share profile",
      className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-2xl border border-white/10 bg-white/[0.04] px-3.5 py-2 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes fa-fw" }),
    "Share"
  ))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.72),rgba(9,17,31,0.92))] p-3 text-left shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-2" }, heroStats.map((fact) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: fact.label,
      className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2.5"
    },
    /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, fact.label),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold tracking-tight text-white md:text-[15px]" }, fact.value)
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-2.5 flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-cyan-300" }), "Progress ", progressPercent, "%"), joinDate ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-medium text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days text-[10px] text-slate-500" }), "Since ", joinDate) : null))))))))), /* @__PURE__ */ React.createElement(
    ProfileCoverEditor,
    {
      isOpen: editorOpen,
      onClose: () => setEditorOpen(false),
      coverUrl,
      coverPosition,
      onCoverUpdated: (nextUrl, nextPosition) => {
        setCoverUrl(nextUrl);
        setCoverPosition(nextPosition);
      },
      onCoverRemoved: () => {
        setCoverUrl(null);
        setCoverPosition(50);
      }
    }
  ));
}
function getCsrfToken$3() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function sendDiscoveryEvent(endpoint, payload) {
  if (!endpoint) return;
  try {
    await fetch(endpoint, {
      method: "POST",
      credentials: "same-origin",
      keepalive: true,
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": getCsrfToken$3(),
        "X-Requested-With": "XMLHttpRequest"
      },
      body: JSON.stringify(payload)
    });
  } catch {
  }
}
const ROW_SIZE = 8;
const ROW_GAP = 16;
function applyMasonry(grid) {
  if (!grid) return;
  Array.from(grid.querySelectorAll(".nova-card")).forEach((card) => {
    const media = card.querySelector(".nova-card-media") || card;
    let height = media.getBoundingClientRect().height || 200;
    const cssMaxH = parseFloat(getComputedStyle(media).maxHeight);
    if (!isNaN(cssMaxH) && cssMaxH > 0 && cssMaxH < height) {
      height = cssMaxH;
    }
    const span = Math.max(1, Math.ceil((height + ROW_GAP) / (ROW_SIZE + ROW_GAP)));
    card.style.gridRowEnd = `span ${span}`;
  });
}
function waitForImages(el) {
  return Promise.all(
    Array.from(el.querySelectorAll("img")).map(
      (img) => img.decode ? img.decode().catch(() => null) : Promise.resolve()
    )
  );
}
async function fetchPageData(url) {
  const res = await fetch(url, {
    credentials: "same-origin",
    headers: { "X-Requested-With": "XMLHttpRequest" }
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const ct = res.headers.get("content-type") || "";
  if (ct.includes("application/json")) {
    const json = await res.json();
    const artworks2 = Array.isArray(json.artworks) ? json.artworks : Array.isArray(json.data) ? json.data : Array.isArray(json.items) ? json.items : Array.isArray(json.results) ? json.results : [];
    const nextCursor = json.next_cursor ?? json.nextCursor ?? json.meta?.next_cursor ?? null;
    const nextPageUrl = json.next_page_url ?? json.nextPageUrl ?? json.meta?.next_page_url ?? null;
    const hasMore = typeof json.has_more === "boolean" ? json.has_more : typeof json.hasMore === "boolean" ? json.hasMore : null;
    return {
      artworks: artworks2.map(normalizeArtworkItem),
      nextCursor,
      nextPageUrl,
      hasMore,
      meta: json.meta ?? null
    };
  }
  const html2 = await res.text();
  const doc = new DOMParser().parseFromString(html2, "text/html");
  const el = doc.querySelector("[data-react-masonry-gallery]");
  if (!el) return { artworks: [], nextCursor: null, nextPageUrl: null };
  let artworks = [];
  try {
    artworks = JSON.parse(el.dataset.artworks || "[]");
  } catch {
  }
  return {
    artworks: artworks.map(normalizeArtworkItem),
    nextCursor: el.dataset.nextCursor || null,
    nextPageUrl: el.dataset.nextPageUrl || null,
    hasMore: null,
    meta: null
  };
}
function normalizeArtworkItem(item) {
  if (!item || typeof item !== "object") return item;
  const category = item.category && typeof item.category === "object" ? item.category : null;
  const author = item.author && typeof item.author === "object" ? item.author : item.creator && typeof item.creator === "object" ? item.creator : null;
  const publisher = item.publisher && typeof item.publisher === "object" ? item.publisher : null;
  const w2 = item.dimensions?.width ?? item.width ?? null;
  const h = item.dimensions?.height ?? item.height ?? null;
  const thumb = item.thumbnail_url ?? item.thumb_url ?? item.thumb ?? item.image ?? null;
  const canonicalUrl = item.canonical_url ?? item.urls?.canonical ?? item.urls?.direct ?? item.url ?? item.href ?? item.urls?.web ?? category?.url ?? null;
  return {
    ...item,
    id: item.id ?? null,
    name: item.name ?? item.title ?? null,
    title: item.title ?? item.name ?? null,
    thumb: item.thumb ?? thumb,
    thumb_url: item.thumb_url ?? thumb,
    thumbnail_url: item.thumbnail_url ?? thumb,
    author,
    uname: item.uname ?? author?.name ?? item.author_name ?? "",
    username: item.username ?? (publisher?.type === "group" ? "" : author?.username ?? ""),
    avatar_url: item.avatar_url ?? author?.avatar_url ?? null,
    profile_url: item.profile_url ?? publisher?.profile_url ?? author?.profile_url ?? null,
    published_as_type: item.published_as_type ?? publisher?.type ?? null,
    publisher: publisher ?? null,
    content_type_name: item.content_type_name ?? category?.content_type_name ?? category?.content_type_slug ?? category?.content_type ?? "",
    content_type_slug: item.content_type_slug ?? category?.content_type_slug ?? category?.content_type ?? "",
    category_name: item.category_name ?? category?.name ?? (typeof item.category === "string" ? item.category : ""),
    category_slug: item.category_slug ?? category?.slug ?? "",
    category: typeof item.category === "string" ? item.category : category?.name ?? item.category_name ?? "",
    slug: item.slug ?? "",
    canonical_url: item.canonical_url ?? item.urls?.canonical ?? item.urls?.direct ?? null,
    url: canonicalUrl,
    width: w2,
    height: h
  };
}
function mapRankApiArtwork(item) {
  return normalizeArtworkItem(item);
}
async function fetchRankApiArtworks(endpoint, rankType) {
  try {
    const url = new URL(endpoint, window.location.href);
    if (rankType) url.searchParams.set("type", rankType);
    const res = await fetch(url.toString(), {
      credentials: "same-origin",
      headers: { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest" }
    });
    if (!res.ok) return { artworks: [] };
    const json = await res.json();
    const items = Array.isArray(json.data) ? json.data : [];
    return { artworks: items.map(mapRankApiArtwork) };
  } catch {
    return { artworks: [] };
  }
}
function getMasonryCardProps(art, idx) {
  (art.name || art.title || "Untitled artwork").trim();
  const hasDimensions = Number(art.width) > 0 && Number(art.height) > 0;
  const aspectRatio = hasDimensions ? Number(art.width) / Number(art.height) : null;
  const categorySlug = (art.category_slug || "").toLowerCase();
  const categoryName = (art.category_name || art.category || "").toLowerCase();
  const wideCategories = ["photography", "wallpapers", "photography-digital", "wallpaper"];
  const wideCategoryNames = ["photography", "wallpapers"];
  const isWideEligible = aspectRatio !== null && aspectRatio > 2 && (wideCategories.includes(categorySlug) || wideCategoryNames.includes(categoryName));
  return {
    articleClassName: `nova-card gallery-item artwork relative${isWideEligible ? " nova-card--wide" : ""}`,
    articleStyle: isWideEligible ? { gridColumn: "span 2" } : void 0,
    frameClassName: "rounded-2xl ring-1 ring-white/5 bg-black/20 shadow-lg shadow-black/40 hover:ring-white/15 hover:shadow-[0_8px_30px_rgba(0,0,0,0.6),0_0_0_1px_rgba(255,255,255,0.08)]",
    mediaClassName: "nova-card-media relative w-full overflow-hidden bg-neutral-900",
    mediaStyle: hasDimensions ? { aspectRatio: `${art.width} / ${art.height}` } : void 0,
    imageSrcSet: art.thumb_srcset || void 0,
    imageSizes: "(max-width: 768px) 50vw, (max-width: 1280px) 33vw, 20vw",
    imageWidth: hasDimensions ? art.width : void 0,
    imageHeight: hasDimensions ? art.height : void 0,
    loading: idx < 8 ? "eager" : "lazy",
    decoding: idx < 8 ? "sync" : "async",
    fetchPriority: idx === 0 ? "high" : void 0,
    imageClassName: "nova-card-main-image absolute inset-0 h-full w-full object-cover group-hover:scale-[1.03]",
    metricBadge: art.recommendation_reason ? {
      label: art.recommendation_reason,
      className: "bg-sky-500/14 text-sky-100 ring-sky-300/30 max-w-[15rem] truncate"
    } : null
  };
}
function MasonryGallery({
  artworks: initialArtworks = [],
  galleryType = "discover",
  cursorEndpoint = null,
  initialNextCursor = null,
  initialNextPageUrl = null,
  limit = 40,
  rankApiEndpoint = null,
  rankType = null,
  gridClassName = null,
  discoveryEndpoint = null,
  algoVersion: initialAlgoVersion = null
}) {
  const normalizedInitialArtworks = initialArtworks.map(normalizeArtworkItem);
  const [artworks, setArtworks] = reactExports.useState(normalizedInitialArtworks);
  const [nextCursor, setNextCursor] = reactExports.useState(initialNextCursor);
  const [nextPageUrl, setNextPageUrl] = reactExports.useState(initialNextPageUrl);
  const [loading, setLoading] = reactExports.useState(false);
  const [done, setDone] = reactExports.useState(!initialNextCursor && !initialNextPageUrl);
  const [algoVersion, setAlgoVersion] = reactExports.useState(initialAlgoVersion);
  const gridRef = reactExports.useRef(null);
  const triggerRef = reactExports.useRef(null);
  const viewedArtworkIdsRef = reactExports.useRef(/* @__PURE__ */ new Set());
  const clickedArtworkIdsRef = reactExports.useRef(/* @__PURE__ */ new Set());
  reactExports.useEffect(() => {
    if (normalizedInitialArtworks.length > 0) return;
    if (!rankApiEndpoint) return;
    let cancelled = false;
    setLoading(true);
    fetchRankApiArtworks(rankApiEndpoint, rankType).then(({ artworks: ranked }) => {
      if (cancelled) return;
      if (ranked.length > 0) {
        setArtworks(ranked);
        setDone(true);
      }
      setLoading(false);
    });
    return () => {
      cancelled = true;
    };
  }, []);
  const relayout = reactExports.useCallback(() => {
    const g2 = gridRef.current;
    if (!g2) return;
    applyMasonry(g2);
    waitForImages(g2).then(() => applyMasonry(g2));
  }, []);
  reactExports.useEffect(() => {
    const raf = requestAnimationFrame(() => relayout());
    return () => cancelAnimationFrame(raf);
  }, [artworks, relayout]);
  reactExports.useEffect(() => {
    const g2 = gridRef.current;
    if (!g2 || !("ResizeObserver" in window)) return;
    const ro = new ResizeObserver(relayout);
    ro.observe(g2);
    return () => ro.disconnect();
  }, [relayout]);
  const fetchNext = reactExports.useCallback(async () => {
    if (loading || done) return;
    let fetchUrl = null;
    if (cursorEndpoint && nextCursor) {
      const u2 = new URL(cursorEndpoint, window.location.href);
      u2.searchParams.set("cursor", nextCursor);
      u2.searchParams.set("limit", String(limit));
      fetchUrl = u2.toString();
    } else if (nextPageUrl) {
      fetchUrl = nextPageUrl;
    }
    if (!fetchUrl) {
      setDone(true);
      return;
    }
    setLoading(true);
    try {
      const { artworks: newItems, nextCursor: nc, nextPageUrl: np, hasMore, meta } = await fetchPageData(fetchUrl);
      if (meta?.algo_version) {
        setAlgoVersion(meta.algo_version);
      }
      if (!newItems.length) {
        setDone(true);
      } else {
        setArtworks((prev) => [...prev, ...newItems]);
        if (cursorEndpoint) {
          setNextCursor(nc);
          if (hasMore === false || !nc) setDone(true);
        } else {
          setNextPageUrl(np);
          if (!np) setDone(true);
        }
      }
    } catch {
      setDone(true);
    } finally {
      setLoading(false);
    }
  }, [loading, done, cursorEndpoint, nextCursor, nextPageUrl, limit]);
  reactExports.useEffect(() => {
    if (done) return;
    const trigger = triggerRef.current;
    if (!trigger || !("IntersectionObserver" in window)) return;
    const io = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) fetchNext();
      },
      { rootMargin: "900px", threshold: 0 }
    );
    io.observe(trigger);
    return () => io.disconnect();
  }, [done, fetchNext]);
  reactExports.useEffect(() => {
    if (galleryType !== "for-you" || !discoveryEndpoint) return void 0;
    const grid = gridRef.current;
    if (!grid || !window.IntersectionObserver) return void 0;
    const artworkIndex = new Map(artworks.map((art, index2) => [String(art.id), { art, index: index2 }]));
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting || entry.intersectionRatio < 0.65) {
            return;
          }
          const card = entry.target.closest("[data-art-id]");
          const artworkId = card?.getAttribute("data-art-id");
          if (!artworkId || viewedArtworkIdsRef.current.has(artworkId)) {
            return;
          }
          const candidate = artworkIndex.get(artworkId);
          if (!candidate?.art?.id) {
            return;
          }
          viewedArtworkIdsRef.current.add(artworkId);
          observer.unobserve(entry.target);
          sendDiscoveryEvent(discoveryEndpoint, {
            event_type: "view",
            artwork_id: Number(candidate.art.id),
            algo_version: candidate.art.recommendation_algo_version || algoVersion || void 0,
            meta: {
              gallery_type: galleryType,
              position: candidate.index + 1,
              source: candidate.art.recommendation_source || null,
              reason: candidate.art.recommendation_reason || null,
              score: candidate.art.recommendation_score ?? null
            }
          });
        });
      },
      { threshold: [0.65] }
    );
    const cards = grid.querySelectorAll("[data-art-id]");
    cards.forEach((card) => observer.observe(card));
    return () => observer.disconnect();
  }, [algoVersion, artworks, discoveryEndpoint, galleryType]);
  reactExports.useEffect(() => {
    if (galleryType !== "for-you" || !discoveryEndpoint) return void 0;
    const grid = gridRef.current;
    if (!grid) return void 0;
    const handleClick = (event) => {
      const card = event.target.closest("[data-art-id]");
      if (!card) return;
      const artworkId = card.getAttribute("data-art-id");
      if (!artworkId || clickedArtworkIdsRef.current.has(artworkId)) {
        return;
      }
      const artwork = artworks.find((item) => String(item.id) === artworkId);
      if (!artwork?.id) {
        return;
      }
      clickedArtworkIdsRef.current.add(artworkId);
      sendDiscoveryEvent(discoveryEndpoint, {
        event_type: "click",
        artwork_id: Number(artwork.id),
        algo_version: artwork.recommendation_algo_version || algoVersion || void 0,
        meta: {
          gallery_type: galleryType,
          source: artwork.recommendation_source || null,
          reason: artwork.recommendation_reason || null,
          score: artwork.recommendation_score ?? null,
          target_url: artwork.url || null
        }
      });
    };
    grid.addEventListener("click", handleClick, true);
    return () => grid.removeEventListener("click", handleClick, true);
  }, [algoVersion, artworks, discoveryEndpoint, galleryType]);
  const gridClass = gridClassName || "grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-6";
  return /* @__PURE__ */ React.createElement(
    "section",
    {
      className: "pb-10 pt-2 is-enhanced",
      "data-nova-gallery": true,
      "data-gallery-type": galleryType,
      "data-react-masonry-gallery": true,
      "data-artworks": JSON.stringify(artworks),
      "data-next-cursor": nextCursor ?? void 0,
      "data-next-page-url": nextPageUrl ?? void 0
    },
    artworks.length > 0 ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: gridRef
      },
      /* @__PURE__ */ React.createElement(
        ArtworkGallery,
        {
          items: artworks,
          layout: "masonry",
          className: gridClass,
          containerProps: { "data-gallery-grid": true },
          resolveCardProps: getMasonryCardProps
        }
      )
    ), !done && /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: triggerRef,
        className: "h-px w-full",
        "aria-hidden": "true"
      }
    ), loading && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center items-center gap-2 mt-8 py-4 text-white/30 text-sm" }, /* @__PURE__ */ React.createElement(
      "svg",
      {
        className: "animate-spin h-4 w-4 shrink-0",
        xmlns: "http://www.w3.org/2000/svg",
        fill: "none",
        viewBox: "0 0 24 24",
        "aria-hidden": "true"
      },
      /* @__PURE__ */ React.createElement(
        "circle",
        {
          className: "opacity-25",
          cx: "12",
          cy: "12",
          r: "10",
          stroke: "currentColor",
          strokeWidth: "4"
        }
      ),
      /* @__PURE__ */ React.createElement(
        "path",
        {
          className: "opacity-75",
          fill: "currentColor",
          d: "M4 12a8 8 0 018-8v8H4z"
        }
      )
    ), "Loading more…"), done && artworks.length > 0 && /* @__PURE__ */ React.createElement("p", { className: "text-center text-xs text-white/20 mt-8 py-2" }, "All caught up")) : (
      /* Empty state – gallery-type-specific messaging handled by caller */
      /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/[0.06] bg-white/[0.02] px-8 py-12 text-center" }, /* @__PURE__ */ React.createElement("p", { className: "text-white/40 text-sm" }, "No artworks found for this section yet."))
    )
  );
}
const MasonryGallery$1 = reactExports.memo(MasonryGallery);
const SORT_OPTIONS = [
  { value: "latest", label: "Latest" },
  { value: "trending", label: "Trending" },
  { value: "rising", label: "Rising" },
  { value: "views", label: "Most Viewed" },
  { value: "favs", label: "Most Favourited" }
];
function GalleryToolbar({ sort, onSort }) {
  return /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-wider text-slate-500" }, "Sort"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-1 rounded-2xl border border-white/10 bg-white/[0.03] p-1" }, SORT_OPTIONS.map((opt) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: opt.value,
      type: "button",
      onClick: () => onSort(opt.value),
      className: `rounded-xl px-3.5 py-2 text-xs font-medium transition-all ${sort === opt.value ? "bg-sky-500/20 text-sky-300 ring-1 ring-sky-400/40" : "text-slate-400 hover:bg-white/5 hover:text-white"}`
    },
    opt.label
  ))));
}
function ProfileGalleryPanel({ artworks, username }) {
  const [sort, setSort] = reactExports.useState("latest");
  const [items, setItems] = reactExports.useState(artworks?.data ?? artworks ?? []);
  const [nextCursor, setNextCursor] = reactExports.useState(artworks?.next_cursor ?? null);
  const handleSort = async (newSort) => {
    setSort(newSort);
    setItems([]);
    try {
      const response = await fetch(`/api/profile/${encodeURIComponent(username)}/artworks?sort=${newSort}`, {
        headers: { Accept: "application/json" }
      });
      if (!response.ok) {
        return;
      }
      const data = await response.json();
      setItems(data.data ?? data);
      setNextCursor(data.next_cursor ?? null);
    } catch (_2) {
    }
  };
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mx-auto w-full max-w-6xl px-4 md:px-6" }, /* @__PURE__ */ React.createElement(GalleryToolbar, { sort, onSort: handleSort })), /* @__PURE__ */ React.createElement("div", { className: "w-full px-4 md:px-6 xl:px-8" }, /* @__PURE__ */ React.createElement(
    MasonryGallery$1,
    {
      key: `profile-${username}-${sort}`,
      artworks: items,
      galleryType: "profile",
      cursorEndpoint: `/api/profile/${encodeURIComponent(username)}/artworks?sort=${encodeURIComponent(sort)}`,
      initialNextCursor: nextCursor,
      limit: 24
    }
  )));
}
function ProfileGallery() {
  const { props } = X$1();
  const {
    user,
    profile,
    artworks,
    featuredArtworks,
    followerCount,
    viewerIsFollowing,
    heroBgUrl,
    leaderboardRank,
    countryName,
    isOwner,
    profileUrl,
    seo = {}
  } = props;
  const username = user.username || user.name;
  const displayName = user.name || user.username || "Creator";
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen pb-16" }, /* @__PURE__ */ React.createElement(
    ProfileHero,
    {
      user,
      profile,
      isOwner,
      viewerIsFollowing,
      followerCount,
      heroBgUrl,
      countryName,
      leaderboardRank,
      extraActions: profileUrl ? /* @__PURE__ */ React.createElement(
        "a",
        {
          href: profileUrl,
          className: "inline-flex items-center gap-2 rounded-xl border border-white/15 px-4 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/5 hover:text-white"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user fa-fw" }),
        "View Profile"
      ) : null
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "border-y border-white/10 bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex max-w-6xl flex-col gap-4 px-4 py-5 md:flex-row md:items-end md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-sky-300/80" }, "Public Gallery"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold tracking-tight text-white md:text-3xl" }, displayName, "'s artworks"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-relaxed text-slate-400" }, "Browse published work with the same infinite-scroll gallery used across the profile experience.")), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: profileUrl || "#",
      className: "inline-flex items-center gap-2 self-start rounded-xl border border-white/10 bg-white/[0.03] px-4 py-2.5 text-sm font-medium text-slate-300 transition-all hover:bg-white/[0.06] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw" }),
    "Back to profile"
  ))), /* @__PURE__ */ React.createElement("div", { className: "w-full pt-6" }, /* @__PURE__ */ React.createElement(
    ProfileGalleryPanel,
    {
      artworks,
      username
    }
  ))));
}
const __vite_glob_0_102 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ProfileGallery
}, Symbol.toStringTag, { value: "Module" }));
const TABS$1 = [
  { id: "posts", label: "Posts", icon: "fa-newspaper" },
  { id: "artworks", label: "Artworks", icon: "fa-images" },
  { id: "stories", label: "Stories", icon: "fa-feather-pointed" },
  { id: "achievements", label: "Achievements", icon: "fa-trophy" },
  { id: "worlds", label: "Worlds", icon: "fa-globe" },
  { id: "collections", label: "Collections", icon: "fa-layer-group" },
  { id: "about", label: "About", icon: "fa-id-card" },
  { id: "stats", label: "Stats", icon: "fa-chart-bar" },
  { id: "favourites", label: "Favourites", icon: "fa-heart" },
  { id: "activity", label: "Activity", icon: "fa-bolt" }
];
function ProfileTabs({ activeTab, onTabChange }) {
  const navRef = reactExports.useRef(null);
  const activeRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (activeRef.current && navRef.current) {
      activeRef.current.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
    }
  }, [activeTab]);
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-0 z-30 border-b border-white/10 bg-[#08111f]/80 backdrop-blur-2xl" }, /* @__PURE__ */ React.createElement(
    "nav",
    {
      ref: navRef,
      className: "profile-tabs-sticky overflow-x-auto scrollbar-hide",
      "aria-label": "Profile sections",
      role: "tablist"
    },
    /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex w-max min-w-full gap-2 px-3 py-3 justify-center xl:items-stretch" }, TABS$1.map((tab2) => {
      const isActive = activeTab === tab2.id;
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          key: tab2.id,
          ref: isActive ? activeRef : null,
          onClick: () => onTabChange(tab2.id),
          role: "tab",
          "aria-selected": isActive,
          "aria-controls": `tabpanel-${tab2.id}`,
          className: `
                group relative flex items-center gap-2.5 rounded-2xl border px-3.5 py-3 text-sm font-medium whitespace-nowrap
                outline-none transition-all duration-150 focus-visible:ring-2 focus-visible:ring-sky-400/70
                ${isActive ? "border-sky-300/25 bg-gradient-to-br from-sky-400/18 via-white/[0.06] to-cyan-400/10 text-white shadow-[0_16px_32px_rgba(14,165,233,0.12)]" : "border-white/8 bg-white/[0.03] text-slate-400 hover:border-white/15 hover:bg-white/[0.05] hover:text-slate-100"}
              `
        },
        /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-9 w-9 items-center justify-center rounded-xl border text-sm ${isActive ? "border-sky-300/20 bg-sky-400/10 text-sky-200" : "border-white/10 bg-white/[0.04] text-slate-500 group-hover:text-slate-300"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${tab2.icon} fa-fw` })),
        tab2.label,
        isActive && /* @__PURE__ */ React.createElement(
          "span",
          {
            className: "absolute inset-x-4 bottom-0 h-0.5 rounded-full bg-sky-300 shadow-[0_0_10px_rgba(125,211,252,0.8)]",
            "aria-hidden": "true"
          }
        )
      );
    }))
  ));
}
function slugify(value) {
  return String(value ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
}
function formatNumber$9(value) {
  return Number(value ?? 0).toLocaleString();
}
function sortByPublishedAt(items) {
  return [...items].sort((left, right) => {
    const leftTime = left?.published_at ? new Date(left.published_at).getTime() : 0;
    const rightTime = right?.published_at ? new Date(right.published_at).getTime() : 0;
    return rightTime - leftTime;
  });
}
function isWallpaperArtwork(item) {
  const contentType = String(item?.content_type_slug || item?.content_type || "").toLowerCase();
  const category = String(item?.category_slug || item?.category || "").toLowerCase();
  return contentType.includes("wallpaper") || category.includes("wallpaper");
}
function useArtworkPreview(username, sort) {
  const [items, setItems] = reactExports.useState([]);
  reactExports.useEffect(() => {
    let active = true;
    async function load() {
      try {
        const response = await fetch(`/api/profile/${encodeURIComponent(username)}/artworks?sort=${encodeURIComponent(sort)}`, {
          headers: { Accept: "application/json" }
        });
        if (!response.ok) return;
        const data = await response.json();
        if (active) {
          setItems(Array.isArray(data?.data) ? data.data : []);
        }
      } catch (_2) {
      }
    }
    load();
    return () => {
      active = false;
    };
  }, [sort, username]);
  return items;
}
function SectionHeader({ eyebrow, title, description, action }) {
  return /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-300/80" }, eyebrow), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white md:text-3xl" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-relaxed text-slate-400" }, description) : null), action);
}
function artworkMeta(art) {
  return [art?.content_type, art?.category].filter(Boolean).join(" • ");
}
function artworkStats(art) {
  return [
    { label: "Views", value: formatNumber$9(art?.views ?? 0), icon: "fa-regular fa-eye" },
    { label: "Likes", value: formatNumber$9(art?.likes ?? 0), icon: "fa-regular fa-heart" },
    { label: "Downloads", value: formatNumber$9(art?.downloads ?? 0), icon: "fa-solid fa-download" }
  ];
}
function FeaturedShowcase({ featuredArtworks }) {
  if (!featuredArtworks?.length) return null;
  const leadArtwork = featuredArtworks[0];
  const secondaryArtworks = featuredArtworks.slice(1, 4);
  const leadMeta = artworkMeta(leadArtwork);
  const leadStats = artworkStats(leadArtwork);
  const leadShouldBlur = Boolean(leadArtwork?.maturity?.should_blur);
  const leadIsMature = Boolean(leadArtwork?.maturity?.is_mature_effective);
  return /* @__PURE__ */ React.createElement("section", { className: "relative mt-8 overflow-hidden rounded-[36px] border border-white/10 bg-[linear-gradient(135deg,rgba(56,189,248,0.14),rgba(255,255,255,0.04),rgba(249,115,22,0.12))] shadow-[0_30px_90px_rgba(2,6,23,0.3)]" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(250,204,21,0.12),transparent_30%),radial-gradient(circle_at_bottom_left,rgba(56,189,248,0.14),transparent_34%)]" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-6 p-5 md:p-7 xl:grid-cols-[minmax(0,1.28fr)_380px]" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/art/${leadArtwork.id}/${slugify(leadArtwork.name)}`,
      className: "group relative overflow-hidden rounded-[30px] border border-white/10 bg-slate-950/60 shadow-[0_24px_60px_rgba(2,6,23,0.28)]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.24),transparent_46%),linear-gradient(to_top,rgba(2,6,23,0.9),rgba(2,6,23,0.08))]" }),
    /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/9] overflow-hidden" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: leadArtwork.thumb,
        alt: leadArtwork.name,
        className: `h-full w-full object-cover transition-[transform,filter] duration-700 group-hover:scale-[1.05] ${leadShouldBlur ? "scale-[1.02] blur-xl" : ""}`,
        loading: "lazy"
      }
    )),
    leadIsMature ? /* @__PURE__ */ React.createElement("div", { className: "absolute left-5 top-20 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Mature content") : null,
    leadShouldBlur ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-5 bottom-28 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-center text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your settings") : null,
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 flex items-start justify-between p-5 md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-amber-100 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-star text-[10px]" }), "Featured spotlight"), /* @__PURE__ */ React.createElement("div", { className: "hidden rounded-2xl border border-white/10 bg-slate-950/35 px-4 py-3 backdrop-blur-md md:block" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Featured set"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-2xl font-semibold tracking-tight text-white" }, formatNumber$9(featuredArtworks.length)))),
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-5 md:p-7" }, leadMeta ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/85" }, leadMeta) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-3 max-w-2xl text-2xl font-semibold tracking-[-0.04em] text-white md:text-[2.7rem] md:leading-[1.02]" }, leadArtwork.name), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-relaxed text-slate-200/90 md:text-[15px]" }, "A standout first impression for the artwork landing page, built to pull attention before visitors move into trending picks and the full archive."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/20 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-100/90" }, "Top pick"), leadArtwork.width && leadArtwork.height ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/20 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-100/90" }, leadArtwork.width, "x", leadArtwork.height) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-3" }, leadStats.map((stat) => /* @__PURE__ */ React.createElement("div", { key: stat.label, className: "rounded-2xl border border-white/10 bg-slate-950/35 px-4 py-3 backdrop-blur-md" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300/75" }, /* @__PURE__ */ React.createElement("i", { className: `${stat.icon} text-[10px]` }), stat.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xl font-semibold tracking-tight text-white" }, stat.value)))))
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.66),rgba(2,6,23,0.5))] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Featured"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Curated gallery highlights"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-relaxed text-slate-300" }, "These picks create a cleaner visual entry point and give the artwork page more personality than a simple list of thumbnails."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200/85" }, "Editorial layout"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200/85" }, "Hero-led showcase"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-1" }, secondaryArtworks.map((art, index2) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: art.id,
      href: `/art/${art.id}/${slugify(art.name)}`,
      className: "group flex gap-4 rounded-[26px] border border-white/10 bg-white/[0.045] p-4 shadow-[0_14px_36px_rgba(2,6,23,0.18)] transition-all hover:-translate-y-0.5 hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "h-24 w-28 shrink-0 overflow-hidden rounded-[18px] bg-black/30 ring-1 ring-white/10" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: art.thumb,
        alt: art.name,
        className: `h-full w-full object-cover transition-[transform,filter] duration-300 group-hover:scale-[1.04] ${art?.maturity?.should_blur ? "scale-[1.02] blur-xl" : ""}`,
        loading: "lazy"
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Feature ", index2 + 2), artworkMeta(art) ? /* @__PURE__ */ React.createElement("div", { className: "truncate text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100/70" }, artworkMeta(art)) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-2 truncate text-lg font-semibold text-white" }, art.name), art.label ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 line-clamp-2 text-sm leading-relaxed text-slate-400" }, art.label) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-300/80" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, formatNumber$9(art?.views ?? 0), " views"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, formatNumber$9(art?.likes ?? 0), " likes")))
  ))))));
}
function PreviewRail({ eyebrow, title, description, items }) {
  if (!items.length) return null;
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement(SectionHeader, { eyebrow, title, description }), /* @__PURE__ */ React.createElement(
    ArtworkGallery,
    {
      items,
      compact: true,
      className: "grid grid-cols-1 gap-5 sm:grid-cols-2 xl:grid-cols-4",
      resolveCardProps: () => ({ showActions: false })
    }
  ));
}
function FullGalleryCta({ galleryUrl, username }) {
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-300/80" }, "Full archive"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white md:text-3xl" }, "Want the complete gallery?"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-relaxed text-slate-400" }, "The curated sections above are a friendlier starting point. The full gallery has the infinite-scroll archive with everything published by @", username, ".")), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: galleryUrl || "#",
      className: "inline-flex items-center gap-2 self-start rounded-2xl border border-sky-300/25 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition-colors hover:bg-sky-400/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right fa-fw" }),
    "Browse full gallery"
  )));
}
function TabArtworks({ artworks, featuredArtworks, username, galleryUrl }) {
  const initialItems = artworks?.data ?? artworks ?? [];
  const trendingItems = useArtworkPreview(username, "trending");
  const popularItems = useArtworkPreview(username, "views");
  const wallpaperItems = reactExports.useMemo(() => {
    const wallpapers = popularItems.filter(isWallpaperArtwork);
    return (wallpapers.length ? wallpapers : popularItems).slice(0, 4);
  }, [popularItems]);
  const latestItems = reactExports.useMemo(() => sortByPublishedAt(initialItems).slice(0, 4), [initialItems]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-artworks",
      role: "tabpanel",
      "aria-labelledby": "tab-artworks",
      className: "mx-auto max-w-7xl px-4 pt-2 pb-10 md:px-6"
    },
    /* @__PURE__ */ React.createElement(FeaturedShowcase, { featuredArtworks: featuredArtworks ?? [] }),
    /* @__PURE__ */ React.createElement(
      PreviewRail,
      {
        eyebrow: "Trending",
        title: "Trending artworks right now",
        description: "A quick scan of the work currently pulling the most momentum on the creator profile.",
        items: trendingItems.slice(0, 4)
      }
    ),
    /* @__PURE__ */ React.createElement(
      PreviewRail,
      {
        eyebrow: "Wallpaper picks",
        title: "Popular wallpapers",
        description: "Surface the strongest wallpaper-friendly pieces before sending people into the full archive.",
        items: wallpaperItems
      }
    ),
    /* @__PURE__ */ React.createElement(
      PreviewRail,
      {
        eyebrow: "Latest",
        title: "Recent additions",
        description: "Fresh uploads from the profile, presented as a preview instead of the full endless gallery.",
        items: latestItems
      }
    ),
    /* @__PURE__ */ React.createElement(FullGalleryCta, { galleryUrl, username })
  );
}
const TYPE_TONES = {
  Uploads: "border-amber-400/40 bg-amber-500/10 text-amber-100",
  Engagement: "border-rose-400/40 bg-rose-500/10 text-rose-100",
  Social: "border-sky-400/40 bg-sky-500/10 text-sky-100",
  Stories: "border-emerald-400/40 bg-emerald-500/10 text-emerald-100",
  Milestones: "border-violet-400/40 bg-violet-500/10 text-violet-100"
};
function cx$1(...parts) {
  return parts.filter(Boolean).join(" ");
}
function AchievementBadge({ achievement, compact = false, className = "" }) {
  const tone = TYPE_TONES[achievement?.type] || TYPE_TONES.Milestones;
  const unlocked = Boolean(achievement?.unlocked);
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: cx$1(
        "inline-flex items-center gap-2 rounded-full border px-2.5 py-1 font-semibold tracking-[0.08em]",
        compact ? "text-[10px] uppercase" : "text-[11px] uppercase",
        unlocked ? tone : "border-white/10 bg-white/5 text-slate-300",
        className
      )
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${achievement?.icon || "fa-trophy"} text-[0.9em]` }),
    /* @__PURE__ */ React.createElement("span", null, achievement?.type || "Achievement")
  );
}
function cx(...parts) {
  return parts.filter(Boolean).join(" ");
}
function AchievementCard({ achievement, className = "" }) {
  const unlocked = Boolean(achievement?.unlocked);
  const progress = Number(achievement?.progress || 0);
  const target = Number(achievement?.condition_value || 0);
  const percent = Math.max(0, Math.min(100, Number(achievement?.progress_percent || 0)));
  return /* @__PURE__ */ React.createElement(
    "article",
    {
      className: cx(
        "rounded-2xl border p-4 shadow-lg transition",
        unlocked ? "border-emerald-400/25 bg-[linear-gradient(180deg,rgba(16,185,129,0.08),rgba(15,23,42,0.72))]" : "border-white/10 bg-white/[0.04]",
        className
      )
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement(AchievementBadge, { achievement, compact: true }), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-base font-semibold text-white" }, achievement?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, achievement?.description)), /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/5 text-lg text-white/90" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${achievement?.icon || "fa-trophy"}` }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center justify-between gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, achievement?.xp_reward || 0, " XP reward"), unlocked ? /* @__PURE__ */ React.createElement("span", null, "Unlocked") : /* @__PURE__ */ React.createElement("span", null, progress, " / ", target)),
    /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/10 ring-1 ring-white/10" }, /* @__PURE__ */ React.createElement(
      "div",
      {
        className: cx("h-full rounded-full transition-[width] duration-500", unlocked ? "bg-emerald-400" : "bg-sky-400"),
        style: { width: `${unlocked ? 100 : percent}%` }
      }
    )),
    achievement?.unlocked_at ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-slate-500" }, "Unlocked ", new Date(achievement.unlocked_at).toLocaleDateString()) : null
  );
}
function AchievementsList({ unlocked = [], locked = [], limitLocked }) {
  const visibleLocked = typeof limitLocked === "number" ? locked.slice(0, limitLocked) : locked;
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", null, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Unlocked"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, unlocked.length, " earned")), unlocked.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-5 py-8 text-sm text-slate-400" }, "No achievements unlocked yet.") : /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3" }, unlocked.map((achievement) => /* @__PURE__ */ React.createElement(AchievementCard, { key: achievement.id, achievement })))), /* @__PURE__ */ React.createElement("section", null, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "In Progress"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, locked.length, " still locked")), visibleLocked.length === 0 ? null : /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3" }, visibleLocked.map((achievement) => /* @__PURE__ */ React.createElement(AchievementCard, { key: achievement.id, achievement })))));
}
function TabAchievements({ achievements, worldRewards, worldHistory, onTabChange }) {
  const unlocked = Array.isArray(achievements?.unlocked) ? achievements.unlocked : [];
  const locked = Array.isArray(achievements?.locked) ? achievements.locked : [];
  const historyAvailable = Boolean(worldHistory?.summary?.available);
  const worldAppearances = worldHistory?.summary?.world_appearances || worldHistory?.summary?.worlds_joined || worldRewards?.count || 0;
  const featuredCount = worldHistory?.summary?.featured_appearances || 0;
  const winnerFinalistCount = worldHistory?.summary?.finalist_winner_appearances || 0;
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-achievements",
      role: "tabpanel",
      "aria-labelledby": "tab-achievements",
      className: "pt-6"
    },
    /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Achievements"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "Milestones, creator wins, and level-based unlocks collected on Skinbase.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-3 py-1.5" }, achievements?.counts?.unlocked || 0, " unlocked"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-3 py-1.5" }, achievements?.counts?.total || 0, " total"))),
    /* @__PURE__ */ React.createElement(AchievementsList, { unlocked, locked }),
    historyAvailable ? /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_18px_44px_rgba(2,6,23,0.18)] md:p-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Worlds history"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "World participation and recognition now live in a dedicated history view so recurring editions, challenge results, and standout placements read like a creator story instead of a badge dump.")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "World Appearances"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold tracking-tight text-white" }, worldAppearances)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Featured"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold tracking-tight text-white" }, featuredCount)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Wins / Finalists"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold tracking-tight text-white" }, winnerFinalistCount))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => onTabChange?.("worlds"),
        className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-medium text-slate-100 transition-colors hover:bg-white/[0.08]"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-xs" }),
      "Open worlds history"
    )))) : null
  );
}
function formatDate$a(value) {
  if (!value) return null;
  try {
    return new Intl.DateTimeFormat("en", {
      month: "short",
      day: "numeric",
      year: "numeric"
    }).format(new Date(value));
  } catch {
    return null;
  }
}
function formatYear(value) {
  if (!value) return null;
  try {
    return new Intl.DateTimeFormat("en", { year: "numeric" }).format(new Date(value));
  } catch {
    return null;
  }
}
function iconForType(type2) {
  switch (type2) {
    case "first_upload":
      return "fa-solid fa-seedling";
    case "first_featured_artwork":
      return "fa-solid fa-star";
    case "first_group_release":
      return "fa-solid fa-people-group";
    case "biggest_download_spike":
      return "fa-solid fa-bolt";
    case "best_performing_work":
      return "fa-solid fa-trophy";
    case "most_productive_year":
      return "fa-solid fa-calendar-check";
    case "yearly_recap":
      return "fa-solid fa-chart-column";
    case "comeback_minor":
      return "fa-solid fa-rotate-right";
    case "comeback_major":
      return "fa-solid fa-person-walking-arrow-right";
    case "comeback_legendary":
      return "fa-solid fa-fire-flame-curved";
    case "upload_streak_3":
    case "upload_streak_6":
    case "upload_streak_12":
      return "fa-solid fa-fire";
    case "active_year_streak_3":
    case "active_year_streak_5":
      return "fa-solid fa-calendar-days";
    case "before_now":
      return "fa-solid fa-arrows-rotate";
    case "era_started":
      return "fa-solid fa-flag";
    default:
      return "fa-solid fa-sparkles";
  }
}
function colorForType(type2) {
  switch (type2) {
    case "first_featured_artwork":
      return { icon: "text-amber-200", bg: "bg-amber-400/12", border: "border-amber-300/20", accent: "from-amber-400/60" };
    case "best_performing_work":
      return { icon: "text-amber-200", bg: "bg-amber-400/12", border: "border-amber-300/20", accent: "from-amber-400/60" };
    case "biggest_download_spike":
      return { icon: "text-sky-200", bg: "bg-sky-400/12", border: "border-sky-300/20", accent: "from-sky-400/60" };
    case "first_upload":
      return { icon: "text-emerald-200", bg: "bg-emerald-400/12", border: "border-emerald-300/20", accent: "from-emerald-400/60" };
    case "first_group_release":
      return { icon: "text-violet-200", bg: "bg-violet-400/12", border: "border-violet-300/20", accent: "from-violet-400/60" };
    case "comeback_minor":
    case "comeback_major":
    case "comeback_legendary":
      return { icon: "text-orange-200", bg: "bg-orange-400/12", border: "border-orange-300/20", accent: "from-orange-400/60" };
    case "most_productive_year":
      return { icon: "text-teal-200", bg: "bg-teal-400/12", border: "border-teal-300/20", accent: "from-teal-400/60" };
    default:
      return { icon: "text-sky-200", bg: "bg-sky-400/12", border: "border-sky-300/20", accent: "from-sky-400/60" };
  }
}
function milestoneHref(item) {
  return item?.artwork?.url || item?.release?.url || null;
}
function StatPill({ label, value }) {
  if (value === null || value === void 0 || value === "") return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3.5 py-2.5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.24em] text-sky-200/60" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, value));
}
function EmptyJourneyState({ username, memberSinceYear, yearsOnSkinbase }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.05] text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-route text-lg" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-semibold text-white" }, "Creator Journey is just getting started"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "Public milestones will appear here as @", username, " builds more history on Skinbase."))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatPill, { label: "Member since", value: memberSinceYear || "Unknown" }), /* @__PURE__ */ React.createElement(StatPill, { label: "Years on Skinbase", value: yearsOnSkinbase ?? 0 }), /* @__PURE__ */ React.createElement(StatPill, { label: "Milestones saved", value: "0" })));
}
const ERA_COLORS = {
  early_years: { bg: "bg-slate-800/60", border: "border-slate-600/40", text: "text-slate-300", icon: "fa-solid fa-seedling", dot: "bg-slate-400" },
  breakthrough: { bg: "bg-amber-900/30", border: "border-amber-600/30", text: "text-amber-200", icon: "fa-solid fa-star", dot: "bg-amber-400" },
  experimental: { bg: "bg-violet-900/30", border: "border-violet-600/30", text: "text-violet-200", icon: "fa-solid fa-flask", dot: "bg-violet-400" },
  comeback: { bg: "bg-emerald-900/30", border: "border-emerald-600/30", text: "text-emerald-200", icon: "fa-solid fa-rotate-right", dot: "bg-emerald-400" },
  current: { bg: "bg-sky-900/30", border: "border-sky-600/30", text: "text-sky-200", icon: "fa-solid fa-bolt", dot: "bg-sky-400" }
};
function EraStrip({ eras }) {
  if (!eras?.length) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "mt-7" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-slate-400 mb-3" }, "Creator Eras"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, eras.map((era, i) => {
    const style = ERA_COLORS[era.type] ?? ERA_COLORS.current;
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: i,
        className: `flex items-start gap-3 rounded-2xl border ${style.border} ${style.bg} px-4 py-3 min-w-[180px] max-w-xs flex-1`
      },
      /* @__PURE__ */ React.createElement("div", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-white/5 ${style.text}` }, /* @__PURE__ */ React.createElement("i", { className: style.icon })),
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `text-sm font-semibold ${style.text}` }, era.title), era.is_current && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-white/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-slate-300" }, "Now")), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-[11px] text-slate-500" }, formatYear(era.starts_at), era.ends_at ? ` – ${formatYear(era.ends_at)}` : era.is_current ? " – present" : ""), era.description && /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-[11px] leading-relaxed text-slate-400 line-clamp-2" }, era.description), (era.stats?.uploads_count ?? 0) > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-[10px] text-slate-500" }, era.stats.uploads_count, " upload", era.stats.uploads_count !== 1 ? "s" : ""))
    );
  })));
}
function StreakBadge({ label, value, active = false }) {
  if (!value) return null;
  return /* @__PURE__ */ React.createElement("div", { className: `flex items-center gap-3 rounded-2xl border px-4 py-3 ${active ? "border-orange-500/30 bg-orange-900/20" : "border-white/10 bg-white/[0.03]"}` }, /* @__PURE__ */ React.createElement("div", { className: `flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${active ? "bg-orange-500/15 text-orange-300" : "bg-white/5 text-slate-400"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid fa-fire${active ? "" : ""}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: `text-base font-bold tabular-nums ${active ? "text-orange-200" : "text-white"}` }, value), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] text-slate-500" }, label)));
}
function StreaksSection({ streaks }) {
  if (!streaks) return null;
  const { current_monthly_upload_streak, best_monthly_upload_streak, current_active_year_streak, best_active_year_streak } = streaks;
  const hasAny = current_monthly_upload_streak > 0 || best_monthly_upload_streak > 0 || best_active_year_streak > 0;
  if (!hasAny) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "mt-7" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-slate-400 mb-3" }, "Creative Streaks"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3 sm:grid-cols-4" }, current_monthly_upload_streak > 0 && /* @__PURE__ */ React.createElement(StreakBadge, { label: "Current monthly streak", value: `${current_monthly_upload_streak}mo`, active: true }), best_monthly_upload_streak > 0 && /* @__PURE__ */ React.createElement(StreakBadge, { label: "Best monthly streak", value: `${best_monthly_upload_streak}mo` }), current_active_year_streak > 0 && /* @__PURE__ */ React.createElement(StreakBadge, { label: "Active year streak", value: `${current_active_year_streak}yr`, active: current_active_year_streak >= 3 }), best_active_year_streak > 0 && /* @__PURE__ */ React.createElement(StreakBadge, { label: "Best year streak", value: `${best_active_year_streak}yr` })));
}
const STATUS_BAR_COLOR = {
  breakout: { bar: "bg-emerald-400", label: "bg-emerald-400/12 text-emerald-200 border-emerald-400/20" },
  steady: { bar: "bg-sky-400", label: "bg-sky-400/12 text-sky-200 border-sky-400/20" },
  experimental: { bar: "bg-violet-400", label: "bg-violet-400/12 text-violet-200 border-violet-400/20" },
  comeback: { bar: "bg-amber-400", label: "bg-amber-400/12 text-amber-200 border-amber-400/20" },
  quiet: { bar: "bg-slate-500", label: "bg-slate-700/60 text-slate-400 border-slate-600/30" }
};
function YearlyProductivityChart({ recaps }) {
  if (!recaps?.length) return null;
  const sorted = [...recaps].filter((r) => r.metrics?.year && r.metrics?.uploads_count != null).sort((a, b2) => (a.metrics.year ?? 0) - (b2.metrics.year ?? 0));
  if (!sorted.length) return null;
  const maxUploads = Math.max(...sorted.map((r) => r.metrics.uploads_count), 1);
  return /* @__PURE__ */ React.createElement("div", { className: "mt-7 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Productivity"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, "Year-by-year upload activity")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-[11px] text-slate-500" }, Object.entries(STATUS_BAR_COLOR).filter(([key]) => sorted.some((r) => (r.metrics?.year_status ?? "steady") === key)).map(([key, val]) => /* @__PURE__ */ React.createElement("span", { key, className: "flex items-center gap-1.5 capitalize" }, /* @__PURE__ */ React.createElement("span", { className: `inline-block h-2 w-2 rounded-full ${val.bar}` }), key)))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-2" }, sorted.map((item) => {
    const uploads = item.metrics.uploads_count;
    const pct = Math.max(uploads / maxUploads, uploads > 0 ? 0.018 : 0);
    const status2 = item.metrics?.year_status ?? "steady";
    const colors = STATUS_BAR_COLOR[status2] ?? STATUS_BAR_COLOR.steady;
    const isBest = uploads === maxUploads;
    return /* @__PURE__ */ React.createElement("div", { key: item.metrics.year, className: "group grid grid-cols-[3.5rem_minmax(0,1fr)_4rem] items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: `text-right text-[13px] font-semibold tabular-nums ${isBest ? "text-white" : "text-slate-400"}` }, item.metrics.year), /* @__PURE__ */ React.createElement("div", { className: "relative h-7 overflow-hidden rounded-full bg-white/[0.04]" }, /* @__PURE__ */ React.createElement(
      "div",
      {
        className: `absolute inset-y-0 left-0 rounded-full ${colors.bar} opacity-80 transition-all duration-500 group-hover:opacity-100`,
        style: { width: `${(pct * 100).toFixed(1)}%` }
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-y-0 left-0 flex w-full items-center px-3 opacity-0 transition-opacity group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold text-white drop-shadow-sm" }, uploads, " upload", uploads !== 1 ? "s" : "", (item.metrics?.views ?? 0) > 0 ? ` · ${Number(item.metrics.views).toLocaleString()} views` : "", (item.metrics?.downloads ?? 0) > 0 ? ` · ${Number(item.metrics.downloads).toLocaleString()} dl` : ""))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ React.createElement("span", { className: `text-[13px] font-bold tabular-nums ${isBest ? "text-white" : "text-slate-300"}` }, uploads), isBest && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-400/25 bg-amber-400/10 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-amber-300" }, "best"), (item.metrics?.featured_count ?? 0) > 0 && !isBest && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-400/20 bg-sky-400/10 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-sky-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-star text-[8px]" }), " ", item.metrics.featured_count)));
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 border-t border-white/5 pt-4 text-[12px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, sorted.length), " active years"), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, sorted.reduce((s2, r) => s2 + r.metrics.uploads_count, 0).toLocaleString()), " total uploads"), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(sorted.reduce((s2, r) => s2 + (r.metrics.views ?? 0), 0)).toLocaleString()), " total views")));
}
const RELATION_LABELS = {
  remake_of: "Remake",
  remaster_of: "Remaster",
  revision_of: "Revision",
  inspired_by: "Inspired by own work",
  variation_of: "Variation"
};
function EvolutionSection({ evolution }) {
  if (!evolution?.length) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "mt-7 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Growth & Evolution"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, "Then & Now"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-5" }, evolution.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "grid gap-3 sm:grid-cols-[1fr_auto_1fr]" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: item.target_artwork?.url,
      className: "group flex items-start gap-3 rounded-2xl border border-white/8 bg-white/[0.03] p-3 transition-colors hover:border-white/20 hover:bg-white/[0.06]"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-white/5 text-slate-500 group-hover:text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })),
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-600" }, "Original"), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 truncate text-sm font-medium text-slate-300 group-hover:text-white" }, item.target_artwork?.title), /* @__PURE__ */ React.createElement("div", { className: "text-[10px] text-slate-600" }, formatYear(item.target_artwork?.published_at)))
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center gap-1 py-2 text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right-long" }), /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold uppercase tracking-wider text-slate-600" }, RELATION_LABELS[item.relation_type] ?? item.relation_type), item.years_between > 0 && /* @__PURE__ */ React.createElement("span", { className: "text-[10px] text-slate-700" }, item.years_between, "yr later")), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: item.source_artwork?.url,
      className: "group flex items-start gap-3 rounded-2xl border border-emerald-700/30 bg-emerald-900/10 p-3 transition-colors hover:border-emerald-600/50 hover:bg-emerald-900/20"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-emerald-500/10 text-emerald-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles" })),
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.2em] text-emerald-600" }, "New version"), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 truncate text-sm font-medium text-emerald-200 group-hover:text-white" }, item.source_artwork?.title), /* @__PURE__ */ React.createElement("div", { className: "text-[10px] text-emerald-800" }, formatYear(item.source_artwork?.published_at)))
  )))));
}
function CreatorJourneySection({ journey, username }) {
  const summary = journey?.summary ?? {};
  const highlights = Array.isArray(journey?.highlights) ? journey.highlights : [];
  const timeline = Array.isArray(journey?.timeline) ? journey.timeline.slice(0, 6) : [];
  const recaps = Array.isArray(journey?.yearly_recaps) ? journey.yearly_recaps.slice(0, 3) : [];
  const allRecaps = Array.isArray(journey?.yearly_recaps) ? journey.yearly_recaps : [];
  const eras = Array.isArray(journey?.eras) ? journey.eras : [];
  const evolution = Array.isArray(journey?.evolution) ? journey.evolution : [];
  const streaks = journey?.streaks ?? null;
  const latestMilestone = summary.latest_milestone ?? null;
  const available = !!summary.available;
  if (!available) {
    return /* @__PURE__ */ React.createElement("section", { className: "rounded-[34px] border border-white/10 bg-[linear-gradient(145deg,rgba(17,24,39,0.96),rgba(15,23,42,0.9))] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.28)] sm:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.3em] text-sky-200/70" }, "Creator Journey"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "A profile built as a story, not only a feed"))), /* @__PURE__ */ React.createElement(
      EmptyJourneyState,
      {
        username,
        memberSinceYear: summary.member_since_year,
        yearsOnSkinbase: summary.years_on_skinbase
      }
    ));
  }
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[34px] border border-white/10 bg-[linear-gradient(145deg,rgba(15,23,42,0.98),rgba(8,15,28,0.92))] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.32)] sm:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.3em] text-sky-200/70" }, "Creator Journey"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "A profile shaped by milestones, turning points, and yearly chapters."), latestMilestone && /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-xl text-sm leading-relaxed text-slate-300" }, "Latest moment: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, latestMilestone.title), latestMilestone.headline ? ` - ${latestMilestone.headline}` : "")), /* @__PURE__ */ React.createElement("div", { className: "grid min-w-[18rem] gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatPill, { label: "Member since", value: summary.member_since_year }), /* @__PURE__ */ React.createElement(StatPill, { label: "Years on Skinbase", value: summary.years_on_skinbase ?? 0 }), /* @__PURE__ */ React.createElement(StatPill, { label: "Milestones", value: summary.milestone_count ?? 0 }))), /* @__PURE__ */ React.createElement(EraStrip, { eras }), highlights.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-7 grid gap-4 xl:grid-cols-2" }, highlights.map((item) => {
    const href = milestoneHref(item);
    return /* @__PURE__ */ React.createElement(
      "article",
      {
        key: item.id,
        className: "relative overflow-hidden rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),rgba(255,255,255,0.02))] p-5 transition-colors hover:bg-[linear-gradient(180deg,rgba(255,255,255,0.09),rgba(255,255,255,0.03))]"
      },
      (() => {
        const c = colorForType(item.type);
        return /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[2px] bg-gradient-to-r ${c.accent} via-transparent to-transparent` });
      })(),
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: `flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl ${colorForType(item.type).bg} ${colorForType(item.type).icon}` }, /* @__PURE__ */ React.createElement("i", { className: iconForType(item.type) })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.22em] text-slate-400" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, item.headline || item.value))), item.value && /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-medium text-slate-200" }, item.value)),
      item.summary && /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-relaxed text-slate-300" }, item.summary),
      href && /* @__PURE__ */ React.createElement(
        "a",
        {
          href,
          className: "mt-4 inline-flex items-center gap-2 text-sm font-medium text-sky-200 transition-colors hover:text-white"
        },
        "Open source moment",
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-xs" })
      )
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "mt-7 grid gap-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Timeline"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, "Important creator milestones"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, timeline.map((item, index2) => {
    const href = milestoneHref(item);
    return /* @__PURE__ */ React.createElement("div", { key: item.id, className: "grid grid-cols-[2.5rem_minmax(0,1fr)] gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center" }, /* @__PURE__ */ React.createElement("div", { className: `flex h-10 w-10 items-center justify-center rounded-2xl border ${colorForType(item.type).border} ${colorForType(item.type).bg} ${colorForType(item.type).icon}` }, /* @__PURE__ */ React.createElement("i", { className: iconForType(item.type) })), index2 < timeline.length - 1 && /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-full w-px bg-white/10" })), /* @__PURE__ */ React.createElement("div", { className: "pb-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, item.title), formatDate$a(item.occurred_at) && /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.2em] text-slate-500" }, formatDate$a(item.occurred_at))), item.headline && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-sky-100" }, item.headline), item.summary && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm leading-relaxed text-slate-400" }, item.summary), href && /* @__PURE__ */ React.createElement("a", { href, className: "mt-2 inline-flex items-center gap-2 text-sm text-slate-200 transition-colors hover:text-white" }, "View linked work", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-xs" }))));
  }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Yearly recap"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, "Recent chapters")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, recaps.map((item) => {
    const status2 = item.metrics?.year_status;
    const statusColors = {
      breakout: "bg-emerald-400/12 text-emerald-200",
      steady: "bg-sky-400/12 text-sky-200",
      experimental: "bg-violet-400/12 text-violet-200",
      comeback: "bg-amber-400/12 text-amber-200",
      quiet: "bg-slate-700 text-slate-400"
    };
    return /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-2xl border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, item.value), status2 && /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2 py-0.5 text-[10px] font-semibold capitalize ${statusColors[status2] ?? statusColors.steady}` }, status2)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, item.headline)), /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl bg-amber-400/12 text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column" }))), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-relaxed text-slate-300" }, item.summary), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement(StatPill, { label: "Views", value: (item.metrics?.views ?? 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatPill, { label: "Downloads", value: (item.metrics?.downloads ?? 0).toLocaleString() }), (item.metrics?.featured_count ?? 0) > 0 && /* @__PURE__ */ React.createElement(StatPill, { label: "Featured", value: item.metrics.featured_count }), item.metrics?.top_category && /* @__PURE__ */ React.createElement(StatPill, { label: "Top category", value: item.metrics.top_category })));
  })))), /* @__PURE__ */ React.createElement(StreaksSection, { streaks }), /* @__PURE__ */ React.createElement(YearlyProductivityChart, { recaps: allRecaps }), /* @__PURE__ */ React.createElement(EvolutionSection, { evolution }));
}
const SOCIAL_ICONS = {
  twitter: { icon: "fa-brands fa-x-twitter", label: "X / Twitter", hoverClass: "hover:border-slate-300/30 hover:text-slate-100 hover:bg-white/[0.08]" },
  deviantart: { icon: "fa-brands fa-deviantart", label: "DeviantArt", hoverClass: "hover:border-green-400/35 hover:text-green-300 hover:bg-green-900/20" },
  instagram: { icon: "fa-brands fa-instagram", label: "Instagram", hoverClass: "hover:border-pink-400/35 hover:text-pink-300 hover:bg-pink-900/20" },
  behance: { icon: "fa-brands fa-behance", label: "Behance", hoverClass: "hover:border-blue-400/35 hover:text-blue-300 hover:bg-blue-900/20" },
  artstation: { icon: "fa-solid fa-palette", label: "ArtStation", hoverClass: "hover:border-orange-400/35 hover:text-orange-300 hover:bg-orange-900/20" },
  youtube: { icon: "fa-brands fa-youtube", label: "YouTube", hoverClass: "hover:border-red-400/35 hover:text-red-300 hover:bg-red-900/20" },
  website: { icon: "fa-solid fa-link", label: "Website", hoverClass: "hover:border-sky-400/35 hover:text-sky-200 hover:bg-sky-900/20" }
};
const CATEGORY_ICONS = {
  animals: "fa-solid fa-paw",
  birds: "fa-solid fa-dove",
  flowers: "fa-solid fa-seedling",
  fruit: "fa-solid fa-apple-whole",
  "sci-fi": "fa-solid fa-rocket",
  scifi: "fa-solid fa-rocket",
  fantasy: "fa-solid fa-dragon",
  nature: "fa-solid fa-leaf",
  landscape: "fa-solid fa-mountain",
  abstract: "fa-solid fa-shapes",
  architecture: "fa-solid fa-building",
  people: "fa-solid fa-person",
  portrait: "fa-solid fa-face-smile",
  cars: "fa-solid fa-car",
  space: "fa-solid fa-star",
  games: "fa-solid fa-gamepad",
  food: "fa-solid fa-utensils",
  travel: "fa-solid fa-plane",
  sports: "fa-solid fa-football",
  ocean: "fa-solid fa-water",
  underwater: "fa-solid fa-fish",
  insects: "fa-solid fa-bug",
  reptiles: "fa-solid fa-dragon",
  cats: "fa-solid fa-cat",
  dogs: "fa-solid fa-dog"
};
const CONTENT_TYPE_ICONS = {
  photography: "fa-solid fa-camera",
  wallpapers: "fa-solid fa-desktop",
  "digital art": "fa-solid fa-wand-magic-sparkles",
  illustration: "fa-solid fa-pen-nib",
  "3d": "fa-solid fa-cube",
  vector: "fa-solid fa-bezier-curve",
  fractal: "fa-solid fa-infinity",
  gif: "fa-solid fa-film",
  drawing: "fa-solid fa-pencil",
  painting: "fa-solid fa-paintbrush",
  photo: "fa-solid fa-camera"
};
function getCategoryIcon(label) {
  const key = String(label || "").toLowerCase().trim();
  return CATEGORY_ICONS[key] ?? null;
}
function getContentTypeIcon(label) {
  const key = String(label || "").toLowerCase().trim();
  return CONTENT_TYPE_ICONS[key] ?? null;
}
function formatNumber$8(value) {
  return Number(value ?? 0).toLocaleString();
}
function formatRelativeDate(value) {
  if (!value) return null;
  try {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return null;
    const now = /* @__PURE__ */ new Date();
    const diffSeconds = Math.round((date.getTime() - now.getTime()) / 1e3);
    const absSeconds = Math.abs(diffSeconds);
    const formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
    if (absSeconds < 3600) {
      return formatter.format(Math.round(diffSeconds / 60), "minute");
    }
    if (absSeconds < 86400) {
      return formatter.format(Math.round(diffSeconds / 3600), "hour");
    }
    if (absSeconds < 604800) {
      return formatter.format(Math.round(diffSeconds / 86400), "day");
    }
    if (absSeconds < 2629800) {
      return formatter.format(Math.round(diffSeconds / 604800), "week");
    }
    return formatter.format(Math.round(diffSeconds / 2629800), "month");
  } catch {
    return null;
  }
}
function formatShortDate$2(value) {
  if (!value) return null;
  try {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return null;
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  } catch {
    return null;
  }
}
function truncateText$1(value, maxLength = 140) {
  const text2 = String(value ?? "").trim();
  if (!text2) return "";
  if (text2.length <= maxLength) return text2;
  return `${text2.slice(0, maxLength).trimEnd()}...`;
}
function formatContributionDate(value) {
  if (!value) return null;
  try {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return null;
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  } catch {
    return null;
  }
}
function buildInterestGroups(artworks = []) {
  const categoryMap = /* @__PURE__ */ new Map();
  const contentTypeMap = /* @__PURE__ */ new Map();
  artworks.forEach((artwork) => {
    const categoryKey = String(artwork?.category_slug || artwork?.category || "").trim().toLowerCase();
    const categoryLabel = String(artwork?.category || "").trim();
    const contentTypeKey = String(artwork?.content_type_slug || artwork?.content_type || "").trim().toLowerCase();
    const contentTypeLabel = String(artwork?.content_type || "").trim();
    if (categoryKey && categoryLabel) {
      categoryMap.set(categoryKey, {
        label: categoryLabel,
        count: (categoryMap.get(categoryKey)?.count ?? 0) + 1
      });
    }
    if (contentTypeKey && contentTypeLabel) {
      contentTypeMap.set(contentTypeKey, {
        label: contentTypeLabel,
        count: (contentTypeMap.get(contentTypeKey)?.count ?? 0) + 1
      });
    }
  });
  const toSortedList = (source) => Array.from(source.values()).sort((left, right) => right.count - left.count || left.label.localeCompare(right.label)).slice(0, 5);
  return {
    categories: toSortedList(categoryMap),
    contentTypes: toSortedList(contentTypeMap)
  };
}
function InfoRow({ icon, label, children }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/[0.07] bg-white/[0.025] px-3.5 py-3 transition-colors hover:bg-white/[0.045]" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} fa-fw text-[13px]` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500 block" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-sm text-slate-200" }, children)));
}
function StatCard$3({ icon, label, value, tone = "sky" }) {
  const tones2 = {
    sky: { icon: "text-sky-300 bg-sky-400/10 border-sky-300/20", bar: "from-sky-400/60 via-sky-400/20 to-transparent", glow: "shadow-[0_0_28px_rgba(56,189,248,0.10)]" },
    amber: { icon: "text-amber-200 bg-amber-300/10 border-amber-300/20", bar: "from-amber-400/60 via-amber-400/20 to-transparent", glow: "shadow-[0_0_28px_rgba(251,191,36,0.10)]" },
    emerald: { icon: "text-emerald-200 bg-emerald-400/10 border-emerald-300/20", bar: "from-emerald-400/60 via-emerald-400/20 to-transparent", glow: "shadow-[0_0_28px_rgba(52,211,153,0.10)]" },
    violet: { icon: "text-violet-200 bg-violet-400/10 border-violet-300/20", bar: "from-violet-400/60 via-violet-400/20 to-transparent", glow: "shadow-[0_0_28px_rgba(167,139,250,0.10)]" }
  };
  const t = tones2[tone] || tones2.sky;
  return /* @__PURE__ */ React.createElement("div", { className: `relative overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04] p-4 shadow-[0_18px_44px_rgba(2,6,23,0.18)] ${t.glow}` }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[2px] bg-gradient-to-r ${t.bar}` }), /* @__PURE__ */ React.createElement("div", { className: `inline-flex h-11 w-11 items-center justify-center rounded-2xl border ${t.icon}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-base` })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-2xl font-bold tracking-tight text-white" }, value));
}
function SectionCard$2({ icon, eyebrow, title, children, className = "" }) {
  return /* @__PURE__ */ React.createElement("section", { className: `rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_52px_rgba(2,6,23,0.18)] md:p-6 ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.05] text-sky-300" }, /* @__PURE__ */ React.createElement("i", { className: `${icon} text-base` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, eyebrow), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-xl font-semibold tracking-[-0.02em] text-white md:text-2xl" }, title))), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children));
}
function TabAbout({ user, profile, stats, achievements, worldRewards, artworks, creatorStories, profileComments, socialLinks, countryName, followerCount, recentFollowers, leaderboardRank, groupContributionHistory, journey }) {
  const { props } = X$1();
  const uname = user.username || user.name;
  const displayName = user.name || uname;
  const about = profile?.about;
  const website = profile?.website;
  const flagUrl = shinyFlagUrl(profile?.country_code, props?.cdn?.files_url);
  const joinDate = user.created_at ? new Date(user.created_at).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }) : null;
  const lastVisit = user.last_visit_at ? (() => {
    try {
      const d2 = new Date(user.last_visit_at);
      return d2.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
    } catch {
      return null;
    }
  })() : null;
  const genderMap = { M: "Male", F: "Female", X: "Non-binary / N/A" };
  const genderLabel = genderMap[profile?.gender?.toUpperCase()] ?? null;
  const birthDate = profile?.birthdate ? (() => {
    try {
      return new Date(profile.birthdate).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" });
    } catch {
      return null;
    }
  })() : null;
  const lastSeenRelative = formatRelativeDate(user.last_visit_at);
  const socialEntries = socialLinks ? Object.entries(socialLinks).filter(([, link2]) => link2?.url) : [];
  const followers = recentFollowers ?? [];
  const recentAchievements = Array.isArray(achievements?.recent) ? achievements.recent : [];
  const recentWorldRewards = Array.isArray(worldRewards?.recent) ? worldRewards.recent : [];
  const stories = Array.isArray(creatorStories) ? creatorStories : [];
  const comments = Array.isArray(profileComments) ? profileComments : [];
  const contributionHistory = Array.isArray(groupContributionHistory) ? groupContributionHistory : [];
  const interestGroups = buildInterestGroups(Array.isArray(artworks) ? artworks : []);
  const summaryCards2 = [
    { icon: "fa-user-group", label: "Followers", value: formatNumber$8(followerCount), tone: "sky" },
    { icon: "fa-images", label: "Uploads", value: formatNumber$8(stats?.uploads_count ?? 0), tone: "violet" },
    { icon: "fa-eye", label: "Profile views", value: formatNumber$8(stats?.profile_views_count ?? 0), tone: "emerald" },
    { icon: "fa-trophy", label: "Weekly rank", value: leaderboardRank?.rank ? `#${formatNumber$8(leaderboardRank.rank)}` : "Unranked", tone: "amber" }
  ];
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-about",
      role: "tabpanel",
      "aria-labelledby": "tab-about",
      className: "pt-4 pb-10"
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, summaryCards2.map((card) => /* @__PURE__ */ React.createElement(StatCard$3, { key: card.label, ...card }))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_380px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-circle-info", eyebrow: "Profile story", title: `About ${displayName}`, className: "bg-[linear-gradient(135deg,rgba(56,189,248,0.08),rgba(255,255,255,0.04),rgba(249,115,22,0.05))]" }, about ? /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("div", { className: "-mt-2 mb-0 select-none font-serif text-7xl leading-none text-slate-500/20", "aria-hidden": "true" }, "“"), /* @__PURE__ */ React.createElement("p", { className: "whitespace-pre-line text-[15px] leading-8 text-slate-200/90" }, about)) : /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center gap-3 rounded-2xl border border-dashed border-white/10 bg-white/[0.03] px-5 py-8 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-comment-dots text-lg" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "This creator has not written a public bio yet."))), /* @__PURE__ */ React.createElement(CreatorJourneySection, { journey, username: uname }), /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-address-card", eyebrow: "Details", title: "Profile information" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, displayName && displayName !== uname ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-user", label: "Display name" }, displayName) : null, /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-at", label: "Username" }, /* @__PURE__ */ React.createElement("span", { className: "font-mono" }, "@", uname)), genderLabel ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-venus-mars", label: "Gender" }, genderLabel) : null, countryName ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-earth-americas", label: "Country" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-2" }, flagUrl ? /* @__PURE__ */ React.createElement(
      "img",
      {
        src: flagUrl,
        alt: countryName,
        className: "h-auto w-4 rounded-sm",
        onError: (e) => {
          e.target.style.display = "none";
        }
      }
    ) : null, countryName)) : null, website ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-link", label: "Website" }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: website.startsWith("http") ? website : `https://${website}`,
        target: "_blank",
        rel: "nofollow noopener noreferrer",
        className: "text-sky-300 transition-colors hover:text-sky-200 hover:underline"
      },
      (() => {
        try {
          const url = website.startsWith("http") ? website : `https://${website}`;
          return new URL(url).hostname;
        } catch {
          return website;
        }
      })()
    )) : null, birthDate ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-cake-candles", label: "Birth date" }, birthDate) : null, joinDate ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-calendar-days", label: "Member since" }, joinDate) : null, lastVisit ? /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-clock", label: "Last seen" }, lastSeenRelative ? `${lastSeenRelative} · ${lastVisit}` : lastVisit) : null)), contributionHistory.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-people-group", eyebrow: "Collaborative work", title: "Group contribution history" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, contributionHistory.map((entry) => /* @__PURE__ */ React.createElement(
      "a",
      {
        key: entry.group?.slug,
        href: entry.group?.profile_url || "#",
        className: "rounded-[24px] border border-white/8 bg-white/[0.03] p-4 transition-colors hover:border-white/14 hover:bg-white/[0.06]"
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, entry.group?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: entry.group.avatar_url, alt: entry.group?.name, className: "h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, entry.group?.name), entry.role ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, String(entry.role).replaceAll("_", " ")) : null, entry.trusted_indicator ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Trusted") : null), entry.group?.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, truncateText$1(entry.group.headline, 100)) : null, entry.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, entry.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-3 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, Number(entry.counts?.credited_artworks || 0).toLocaleString(), " credited artworks"), /* @__PURE__ */ React.createElement("span", null, Number(entry.counts?.releases || 0).toLocaleString(), " releases"), /* @__PURE__ */ React.createElement("span", null, Number(entry.counts?.projects || 0).toLocaleString(), " projects"), entry.joined_at ? /* @__PURE__ */ React.createElement("span", null, "Joined ", formatContributionDate(entry.joined_at)) : null), Array.isArray(entry.role_labels) && entry.role_labels.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, entry.role_labels.map((label) => /* @__PURE__ */ React.createElement("span", { key: `${entry.group?.slug}-${label}`, className: "rounded-full border border-sky-300/15 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, label))) : null, Array.isArray(entry.recent_release_titles) && entry.recent_release_titles.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "Recent releases: ", entry.recent_release_titles.join(" • ")) : null))
    )))) : null, followers.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-user-group", eyebrow: "Community", title: "Recent followers" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, followers.slice(0, 6).map((follower) => /* @__PURE__ */ React.createElement(
      "a",
      {
        key: follower.id,
        href: follower.profile_url ?? `/@${follower.username}`,
        className: "group flex items-center gap-3 rounded-2xl border border-white/8 bg-white/[0.03] px-4 py-3 transition-colors hover:border-white/14 hover:bg-white/[0.06]"
      },
      /* @__PURE__ */ React.createElement(
        "img",
        {
          src: follower.avatar_url ?? "/images/avatar_default.webp",
          alt: follower.username,
          className: "h-11 w-11 rounded-2xl object-cover ring-1 ring-white/10 transition-all group-hover:ring-sky-400/30",
          loading: "lazy"
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-medium text-slate-200 group-hover:text-white" }, follower.uname || follower.username), /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs text-slate-500" }, "@", follower.username))
    )))) : null, recentAchievements.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-trophy", eyebrow: "Recent wins", title: "Latest achievements" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, recentAchievements.slice(0, 4).map((achievement) => /* @__PURE__ */ React.createElement(
      "div",
      {
        key: achievement.id,
        className: "group relative overflow-hidden rounded-2xl border border-amber-300/10 bg-white/[0.03] px-4 py-4 transition-all hover:border-amber-300/25 hover:bg-white/[0.06]"
      },
      /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[2px] bg-gradient-to-r from-amber-400/50 via-amber-400/20 to-transparent" }),
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-amber-300/20 bg-amber-300/10 text-amber-200 shadow-[0_0_18px_rgba(251,191,36,0.12)] transition-shadow group-hover:shadow-[0_0_24px_rgba(251,191,36,0.2)]" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${achievement.icon || "fa-trophy"} text-base` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, achievement.name), achievement.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 line-clamp-2 text-sm leading-relaxed text-slate-400" }, achievement.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, achievement.unlocked_at ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/10 bg-black/20 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-check text-[10px]" }), formatShortDate$2(achievement.unlocked_at) || "Unlocked") : null, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-1 text-[11px] font-bold uppercase tracking-[0.14em] text-amber-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bolt text-[9px]" }), "+", formatNumber$8(achievement.xp_reward ?? 0), " XP"))))
    )))) : null, recentWorldRewards.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-globe", eyebrow: "World recognition", title: "Latest world rewards" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, recentWorldRewards.slice(0, 4).map((reward) => /* @__PURE__ */ React.createElement(
      "a",
      {
        key: reward.id,
        href: reward.world?.url || reward.artwork?.url || "#",
        className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-4 transition hover:border-white/15 hover:bg-white/[0.06]"
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, reward.badge_label), reward.artwork?.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, reward.artwork.title) : null), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, reward.reward_label)),
      reward.granted_at ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, formatShortDate$2(reward.granted_at) || "Rewarded") : null
    )))) : null, stories.length > 0 || comments.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-wave-square", eyebrow: "Fresh from this creator", title: "Recent activity" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-2" }, stories.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/8 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Latest story"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/15 bg-sky-400/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-sky-100/80" }, formatShortDate$2(stories[0]?.published_at) || "Published")), /* @__PURE__ */ React.createElement(
      "a",
      {
        href: `/stories/${stories[0].slug}`,
        className: "mt-3 block text-lg font-semibold tracking-tight text-white transition-colors hover:text-sky-200"
      },
      stories[0].title
    ), stories[0].excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, truncateText$1(stories[0].excerpt, 180)) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-300/75" }, stories[0].reading_time ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, stories[0].reading_time, " min read") : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, formatNumber$8(stories[0].views ?? 0), " views"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/20 px-2.5 py-1" }, formatNumber$8(stories[0].comments_count ?? 0), " comments"))) : null, comments.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/8 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Latest guestbook comment"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/15 bg-amber-300/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-amber-100/80" }, formatRelativeDate(comments[0]?.created_at) || "Recently")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-start gap-3" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: comments[0].author_avatar || "/images/avatar_default.webp",
        alt: comments[0].author_name,
        className: "h-11 w-11 rounded-2xl object-cover ring-1 ring-white/10",
        loading: "lazy",
        onError: (e) => {
          e.target.src = "/images/avatar_default.webp";
        }
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement(
      "a",
      {
        href: comments[0].author_profile_url,
        className: "text-sm font-semibold text-white transition-colors hover:text-sky-200"
      },
      comments[0].author_name
    ), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, truncateText$1(comments[0].body, 180))))) : null)) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-sparkles", eyebrow: "Creator snapshot", title: "Profile snapshot", className: "bg-[linear-gradient(180deg,rgba(15,23,42,0.72),rgba(2,6,23,0.5))]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Creator level"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-3xl font-semibold tracking-tight text-white" }, "Lv ", formatNumber$8(user?.level ?? 1)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, user?.rank || "Creator")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-sky-300/15 bg-sky-400/10 px-3 py-2 text-right" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100/70" }, "XP"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-sky-100" }, formatNumber$8(user?.xp ?? 0)))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-2 overflow-hidden rounded-full bg-white/8" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-[linear-gradient(90deg,#38bdf8,#60a5fa,#f59e0b)]", style: { width: `${Math.max(0, Math.min(100, Number(user?.progress_percent ?? 0)))}%` } }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Weekly rank"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold tracking-tight text-white" }, leaderboardRank?.rank ? `#${formatNumber$8(leaderboardRank.rank)}` : "Not ranked"), leaderboardRank?.score ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "Score ", formatNumber$8(leaderboardRank.score)) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Community size"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold tracking-tight text-white" }, formatNumber$8(followerCount)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "Followers"))))), /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-chart-simple", eyebrow: "Highlights", title: "Useful stats" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-images", label: "Uploads" }, formatNumber$8(stats?.uploads_count ?? 0)), /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-eye", label: "Artwork views received" }, formatNumber$8(stats?.artwork_views_received_count ?? 0)), /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-download", label: "Downloads received" }, formatNumber$8(stats?.downloads_received_count ?? 0)), /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-heart", label: "Favourites received" }, formatNumber$8(stats?.favourites_received_count ?? 0)), /* @__PURE__ */ React.createElement(InfoRow, { icon: "fa-comment", label: "Comments received" }, formatNumber$8(stats?.comments_received_count ?? 0)))), interestGroups.categories.length > 0 || interestGroups.contentTypes.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-layer-group", eyebrow: "Creative focus", title: "Favourite categories & formats" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, interestGroups.categories.length > 0 ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tag text-slate-600" }), "Top categories"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2.5" }, interestGroups.categories.map((category) => {
      const catIcon = getCategoryIcon(category.label);
      return /* @__PURE__ */ React.createElement(
        "span",
        {
          key: category.label,
          className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-3.5 py-2 text-sm text-slate-200 transition-colors hover:bg-white/[0.07]"
        },
        catIcon ? /* @__PURE__ */ React.createElement("i", { className: `${catIcon} text-[12px] text-slate-400` }) : null,
        /* @__PURE__ */ React.createElement("span", null, category.label),
        /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-black/20 px-2 py-0.5 text-[11px] font-semibold text-slate-400" }, formatNumber$8(category.count))
      );
    }))) : null, interestGroups.contentTypes.length > 0 ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-slate-600" }), "Preferred formats"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2.5" }, interestGroups.contentTypes.map((contentType) => {
      const ctIcon = getContentTypeIcon(contentType.label);
      return /* @__PURE__ */ React.createElement(
        "span",
        {
          key: contentType.label,
          className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-3.5 py-2 text-sm text-sky-100 transition-colors hover:bg-sky-400/15"
        },
        ctIcon ? /* @__PURE__ */ React.createElement("i", { className: `${ctIcon} text-[12px] text-sky-300/70` }) : null,
        /* @__PURE__ */ React.createElement("span", null, contentType.label),
        /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-black/20 px-2 py-0.5 text-[11px] font-semibold text-sky-100/70" }, formatNumber$8(contentType.count))
      );
    }))) : null)) : null, socialEntries.length > 0 ? /* @__PURE__ */ React.createElement(SectionCard$2, { icon: "fa-solid fa-share-nodes", eyebrow: "Links", title: "Social links" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2.5" }, socialEntries.map(([platform2, link2]) => {
      const si = SOCIAL_ICONS[platform2] ?? { icon: "fa-solid fa-link", label: platform2 };
      const href = link2.url.startsWith("http") ? link2.url : `https://${link2.url}`;
      return /* @__PURE__ */ React.createElement(
        "a",
        {
          key: platform2,
          href,
          target: "_blank",
          rel: "nofollow noopener noreferrer",
          className: `inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-3.5 py-2.5 text-sm text-slate-300 transition-all ${si.hoverClass || "hover:border-sky-400/30 hover:bg-white/[0.07] hover:text-white"}`,
          "aria-label": si.label
        },
        /* @__PURE__ */ React.createElement("i", { className: `${si.icon} fa-fw` }),
        /* @__PURE__ */ React.createElement("span", null, si.label)
      );
    }))) : null))
  );
}
function KpiCard$1({ icon, label, value, color: color2 = "text-sky-400" }) {
  return /* @__PURE__ */ React.createElement("div", { className: "bg-white/4 ring-1 ring-white/10 rounded-2xl p-5 shadow-xl shadow-black/20 backdrop-blur flex items-center gap-4" }, /* @__PURE__ */ React.createElement("div", { className: `w-12 h-12 rounded-xl bg-white/5 flex items-center justify-center shrink-0 ${color2}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-xl` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-2xl font-bold text-white tabular-nums" }, Number(value ?? 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mt-0.5 uppercase tracking-wider" }, label)));
}
function TabStats({ stats, followerCount, followAnalytics }) {
  const medalTotals = stats?.medal_totals ?? null;
  const kpis = [
    { icon: "fa-eye", label: "Profile Views", value: stats?.profile_views_count, color: "text-sky-400" },
    { icon: "fa-images", label: "Uploads", value: stats?.uploads_count, color: "text-violet-400" },
    { icon: "fa-download", label: "Downloads", value: stats?.downloads_received_count, color: "text-green-400" },
    { icon: "fa-eye", label: "Artwork Views", value: stats?.artwork_views_received_count, color: "text-blue-400" },
    { icon: "fa-heart", label: "Favourites Received", value: stats?.favourites_received_count, color: "text-pink-400" },
    { icon: "fa-users", label: "Followers", value: followerCount, color: "text-amber-400" },
    { icon: "fa-trophy", label: "Awards Received", value: stats?.awards_received_count, color: "text-yellow-400" },
    { icon: "fa-comment", label: "Comments Received", value: stats?.comments_received_count, color: "text-orange-400" }
  ];
  const trendCards = [
    { icon: "fa-arrow-trend-up", label: "Followers Today", value: followAnalytics?.daily?.gained ?? 0, color: "text-emerald-400" },
    { icon: "fa-user-minus", label: "Unfollows Today", value: followAnalytics?.daily?.lost ?? 0, color: "text-rose-400" },
    { icon: "fa-chart-line", label: "Weekly Net", value: followAnalytics?.weekly?.net ?? 0, color: "text-sky-400" },
    { icon: "fa-percent", label: "Weekly Growth %", value: followAnalytics?.weekly?.growth_rate ?? 0, color: "text-amber-400" }
  ];
  const hasStats = stats !== null && stats !== void 0;
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-stats",
      role: "tabpanel",
      "aria-labelledby": "tab-stats",
      className: "pt-6"
    },
    !hasStats ? /* @__PURE__ */ React.createElement("div", { className: "bg-white/4 ring-1 ring-white/10 rounded-2xl p-10 text-center shadow-xl shadow-black/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-bar text-3xl text-slate-600 mb-3 block" }), /* @__PURE__ */ React.createElement("p", { className: "text-slate-400 font-medium" }, "No stats available yet"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-600 text-sm mt-1" }, "Stats will appear once there is activity on this profile.")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("h2", { className: "text-xs font-semibold uppercase tracking-widest text-slate-500 mb-4 flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-bar text-green-400 fa-fw" }), "Lifetime Statistics"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3" }, kpis.map((kpi) => /* @__PURE__ */ React.createElement(KpiCard$1, { key: kpi.label, ...kpi }))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 rounded-2xl border border-white/10 bg-white/4 p-5 shadow-xl shadow-black/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xs font-semibold uppercase tracking-widest text-slate-500" }, "Medal Breakdown"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, "Real medal totals collected across all public artworks.")), /* @__PURE__ */ React.createElement("div", { className: "text-right" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-widest text-slate-500" }, "Weighted Score"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-2xl font-bold text-white tabular-nums" }, Number(medalTotals?.score_total ?? 0).toLocaleString()))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3 md:grid-cols-4" }, [
      { label: "Gold", value: medalTotals?.gold ?? 0, color: "text-amber-300" },
      { label: "Silver", value: medalTotals?.silver ?? 0, color: "text-slate-300" },
      { label: "Bronze", value: medalTotals?.bronze ?? 0, color: "text-orange-300" },
      { label: "Total Medals", value: medalTotals?.count ?? 0, color: "text-cyan-300" }
    ].map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "rounded-2xl border border-white/10 bg-black/15 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-widest text-slate-500" }, item.label), /* @__PURE__ */ React.createElement("div", { className: `mt-2 text-2xl font-semibold tabular-nums ${item.color}` }, Number(item.value).toLocaleString()))))), /* @__PURE__ */ React.createElement("h3", { className: "mt-8 mb-4 text-xs font-semibold uppercase tracking-widest text-slate-500 flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-group text-emerald-400 fa-fw" }), "Follow Growth"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3" }, trendCards.map((card) => /* @__PURE__ */ React.createElement(KpiCard$1, { key: card.label, ...card }))), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-600 mt-6 text-center" }, "More detailed analytics (charts, trends) coming soon."))
  );
}
function FavSkeleton() {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl overflow-hidden bg-white/5 animate-pulse" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square bg-white/8" }));
}
function TabFavourites({ favourites, isOwner, username }) {
  const initialItems = Array.isArray(favourites) ? favourites : favourites?.data ?? [];
  const [items, setItems] = reactExports.useState(initialItems);
  const [nextCursor, setNextCursor] = reactExports.useState(favourites?.next_cursor ?? null);
  const [loadingMore, setLoadingMore] = reactExports.useState(false);
  const loadMoreRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    setItems(initialItems);
    setNextCursor(favourites?.next_cursor ?? null);
  }, [favourites, initialItems]);
  const loadMore = reactExports.useCallback(async () => {
    if (!nextCursor || loadingMore) return;
    setLoadingMore(true);
    try {
      const res = await fetch(
        `/api/profile/${encodeURIComponent(username)}/favourites?cursor=${encodeURIComponent(nextCursor)}`,
        { headers: { Accept: "application/json" } }
      );
      if (res.ok) {
        const data = await res.json();
        setItems((prev) => [...prev, ...data.data ?? data]);
        setNextCursor(data.next_cursor ?? null);
      }
    } catch (_2) {
    }
    setLoadingMore(false);
  }, [loadingMore, nextCursor, username]);
  reactExports.useEffect(() => {
    const node2 = loadMoreRef.current;
    if (!node2 || !nextCursor) {
      return void 0;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries.some((entry) => entry.isIntersecting)) {
          loadMore();
        }
      },
      {
        rootMargin: "320px 0px"
      }
    );
    observer.observe(node2);
    return () => observer.disconnect();
  }, [loadMore, nextCursor]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-favourites",
      role: "tabpanel",
      "aria-labelledby": "tab-favourites",
      className: "pt-6"
    },
    /* @__PURE__ */ React.createElement("h2", { className: "text-xs font-semibold uppercase tracking-widest text-slate-500 mb-4 flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-heart text-pink-400 fa-fw" }), isOwner ? "Your Favourites" : "Favourites"),
    items.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center py-20 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "w-20 h-20 rounded-2xl bg-white/5 flex items-center justify-center mb-5 text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-heart text-3xl" })), /* @__PURE__ */ React.createElement("p", { className: "text-slate-400 font-medium" }, "No favourites yet"), /* @__PURE__ */ React.createElement("p", { className: "text-slate-600 text-sm mt-1" }, "Artworks added to favourites will appear here.")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
      ArtworkGallery,
      {
        items,
        layout: "grid",
        className: "grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-4",
        resolveCardProps: (_2, index2) => ({
          loading: index2 < 8 ? "eager" : "lazy"
        })
      },
      loadingMore && Array.from({ length: 4 }).map((_2, i) => /* @__PURE__ */ React.createElement(FavSkeleton, { key: `sk-${i}` }))
    ), nextCursor && /* @__PURE__ */ React.createElement("div", { ref: loadMoreRef, className: "h-6 w-full", "aria-hidden": "true" }), nextCursor && /* @__PURE__ */ React.createElement("div", { className: "mt-8 text-center" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: loadMore,
        disabled: loadingMore,
        className: "inline-flex items-center gap-2 px-6 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 text-slate-300 text-sm font-medium border border-white/10 transition-all"
      },
      loadingMore ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-notch fa-spin fa-fw" }), " Loading…") : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-down fa-fw" }), " Load more")
    )))
  );
}
function CollectionEmptyState({ isOwner, createUrl }) {
  const smartUrl = createUrl ? `${createUrl}?mode=smart` : null;
  return /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[28px] border border-white/10 bg-[linear-gradient(135deg,rgba(56,189,248,0.08),rgba(255,255,255,0.04),rgba(249,115,22,0.1))] px-6 py-14 text-center shadow-[0_26px_80px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.12),transparent_32%),radial-gradient(circle_at_bottom_right,rgba(249,115,22,0.12),transparent_30%)]" }), /* @__PURE__ */ React.createElement("div", { className: "relative mx-auto max-w-xl" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto mb-5 flex h-20 w-20 items-center justify-center rounded-[24px] border border-white/12 bg-white/[0.06] text-sky-200 shadow-[0_18px_40px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-3xl" })), /* @__PURE__ */ React.createElement("h3", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, isOwner ? "Create your first collection" : "No public collections yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-md text-sm leading-relaxed text-slate-300" }, isOwner ? "Collections turn your gallery into intentional showcases. Build them manually or let smart rules keep them fresh from your own artwork library." : "This creator has not published any collections."), isOwner && createUrl ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-center justify-center gap-3" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: createUrl,
      className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/25 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus fa-fw" }),
    "Create Manual Collection"
  ), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: smartUrl || createUrl,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/12 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles fa-fw" }),
    "Create Smart Collection"
  )) : null, isOwner ? /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-6 max-w-lg text-xs uppercase tracking-[0.18em] text-slate-400" }, "Examples: Featured wallpapers, best of 2026, cyberpunk studies, blue neon universe") : null));
}
function getCsrfToken$2() {
  if (typeof document === "undefined") return "";
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function deleteCollection(url) {
  const response = await fetch(url, {
    method: "DELETE",
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$2(),
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Unable to delete collection.");
  }
  return payload;
}
async function requestJson$8(url, { method = "POST", body: body2 } = {}) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": getCsrfToken$2(),
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Unable to update collection presentation.");
  }
  return payload;
}
const FILTERS$1 = ["all", "featured", "smart", "manual"];
function TabCollections({ collections, isOwner, createUrl, reorderUrl, featuredUrl, featureLimit = 3 }) {
  const [items, setItems] = reactExports.useState(Array.isArray(collections) ? collections : []);
  const [busyId, setBusyId] = reactExports.useState(null);
  const [filter2, setFilter] = reactExports.useState("all");
  reactExports.useEffect(() => {
    setItems(Array.isArray(collections) ? collections : []);
  }, [collections]);
  async function handleDelete(collection) {
    if (!collection?.delete_url) return;
    if (!window.confirm(`Delete "${collection.title}"? Artworks will remain untouched.`)) return;
    setBusyId(collection.id);
    try {
      await deleteCollection(collection.delete_url);
      setItems((current) => current.filter((item) => item.id !== collection.id));
    } catch (error) {
      window.alert(error.message);
    } finally {
      setBusyId(null);
    }
  }
  async function handleToggleFeature(collection) {
    const url = collection?.is_featured ? collection?.unfeature_url : collection?.feature_url;
    const method = collection?.is_featured ? "DELETE" : "POST";
    if (!url) return;
    setBusyId(collection.id);
    try {
      const payload = await requestJson$8(url, { method });
      setItems((current) => current.map((item) => item.id === collection.id ? {
        ...item,
        is_featured: payload?.collection?.is_featured ?? !item.is_featured,
        featured_at: payload?.collection?.featured_at ?? item.featured_at,
        updated_at: payload?.collection?.updated_at ?? item.updated_at
      } : item));
    } catch (error) {
      window.alert(error.message);
    } finally {
      setBusyId(null);
    }
  }
  async function handleMove(collection, direction) {
    const index2 = items.findIndex((item) => item.id === collection.id);
    const nextIndex = index2 + direction;
    if (index2 < 0 || nextIndex < 0 || nextIndex >= items.length || !reorderUrl) return;
    const next = [...items];
    const temp = next[index2];
    next[index2] = next[nextIndex];
    next[nextIndex] = temp;
    setItems(next);
    try {
      const payload = await requestJson$8(reorderUrl, {
        method: "POST",
        body: { collection_ids: next.map((item) => item.id) }
      });
      if (Array.isArray(payload?.collections)) {
        setItems(payload.collections);
      }
    } catch (error) {
      window.alert(error.message);
      setItems(Array.isArray(collections) ? collections : []);
    }
  }
  const featuredItems = items.filter((collection) => collection.is_featured);
  const smartItems = items.filter((collection) => collection.mode === "smart");
  const filteredItems = items.filter((collection) => {
    if (filter2 === "featured") return collection.is_featured;
    if (filter2 === "smart") return collection.mode === "smart";
    if (filter2 === "manual") return collection.mode !== "smart";
    return true;
  });
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-collections",
      role: "tabpanel",
      "aria-labelledby": "tab-collections",
      className: "pt-6"
    },
    /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-col gap-3 md:flex-row md:items-end md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Collections"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Curated showcases from the gallery"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-relaxed text-slate-300" }, "Collections now support featured presentation, smart rule-based curation, and richer profile storytelling.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, featuredUrl ? /* @__PURE__ */ React.createElement("a", { href: featuredUrl, className: "inline-flex items-center gap-2 self-start rounded-2xl border border-white/12 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass fa-fw" }), "Browse Featured") : null, isOwner && createUrl ? /* @__PURE__ */ React.createElement("a", { href: createUrl, className: "inline-flex items-center gap-2 self-start rounded-2xl border border-sky-300/25 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus fa-fw" }), "Create Collection") : null)),
    /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap items-center gap-2" }, FILTERS$1.map((value) => /* @__PURE__ */ React.createElement(
      "button",
      {
        key: value,
        type: "button",
        onClick: () => setFilter(value),
        className: `inline-flex items-center gap-2 rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition ${filter2 === value ? "border-sky-300/25 bg-sky-400/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.07]"}`
      },
      value
    ))),
    items.length > 0 && featuredItems.length > 0 && filter2 === "all" ? /* @__PURE__ */ React.createElement("section", { className: "mb-6 overflow-hidden rounded-[28px] border border-amber-300/15 bg-[linear-gradient(135deg,rgba(251,191,36,0.08),rgba(255,255,255,0.04),rgba(56,189,248,0.08))] p-5 shadow-[0_26px_70px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, "Featured Collections"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold text-white" }, "Premium profile showcases")), isOwner ? /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-[0.18em] text-slate-300" }, featuredItems.length, "/", featureLimit, " featured") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, featuredItems.map((collection, index2) => /* @__PURE__ */ React.createElement(
      CollectionCard,
      {
        key: `featured-${collection.id}`,
        collection,
        isOwner,
        onDelete: handleDelete,
        onToggleFeature: handleToggleFeature,
        onMoveUp: isOwner ? () => handleMove(collection, -1) : null,
        onMoveDown: isOwner ? () => handleMove(collection, 1) : null,
        canMoveUp: index2 > 0,
        canMoveDown: index2 < featuredItems.length - 1,
        busy: busyId === collection.id
      }
    )))) : null,
    isOwner && items.length > 0 && featuredItems.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mb-5 rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-4 text-sm text-slate-300" }, "Feature your best collections to pin them at the top of your profile.") : null,
    isOwner && items.length > 0 && smartItems.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mb-5 rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-4 text-sm text-slate-300" }, "Create a smart collection from your tags or categories to keep a showcase updated automatically.") : null,
    items.length === 0 ? /* @__PURE__ */ React.createElement(CollectionEmptyState, { isOwner, createUrl }) : /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, filteredItems.map((collection, index2) => /* @__PURE__ */ React.createElement(
      CollectionCard,
      {
        key: collection.id,
        collection,
        isOwner,
        onDelete: handleDelete,
        onToggleFeature: handleToggleFeature,
        onMoveUp: isOwner ? () => handleMove(collection, -1) : null,
        onMoveDown: isOwner ? () => handleMove(collection, 1) : null,
        canMoveUp: index2 > 0,
        canMoveDown: index2 < filteredItems.length - 1,
        busy: busyId === collection.id
      }
    )))
  );
}
function typeMeta(type2) {
  switch (type2) {
    case "upload":
      return { icon: "fa-solid fa-image", label: "Upload", tone: "text-sky-200 bg-sky-400/12 border-sky-300/20" };
    case "comment":
      return { icon: "fa-solid fa-comment-dots", label: "Comment", tone: "text-amber-100 bg-amber-400/12 border-amber-300/20" };
    case "reply":
      return { icon: "fa-solid fa-reply", label: "Reply", tone: "text-orange-100 bg-orange-400/12 border-orange-300/20" };
    case "like":
      return { icon: "fa-solid fa-heart", label: "Like", tone: "text-rose-100 bg-rose-400/12 border-rose-300/20" };
    case "favourite":
      return { icon: "fa-solid fa-bookmark", label: "Favourite", tone: "text-pink-100 bg-pink-400/12 border-pink-300/20" };
    case "follow":
      return { icon: "fa-solid fa-user-plus", label: "Follow", tone: "text-emerald-100 bg-emerald-400/12 border-emerald-300/20" };
    case "achievement":
      return { icon: "fa-solid fa-trophy", label: "Achievement", tone: "text-yellow-100 bg-yellow-400/12 border-yellow-300/20" };
    case "world_reward":
      return { icon: "fa-solid fa-globe", label: "World reward", tone: "text-sky-100 bg-sky-400/12 border-sky-300/20" };
    case "forum_post":
      return { icon: "fa-solid fa-signs-post", label: "Forum thread", tone: "text-violet-100 bg-violet-400/12 border-violet-300/20" };
    case "forum_reply":
      return { icon: "fa-solid fa-comments", label: "Forum reply", tone: "text-indigo-100 bg-indigo-400/12 border-indigo-300/20" };
    default:
      return { icon: "fa-solid fa-bolt", label: "Activity", tone: "text-slate-100 bg-white/6 border-white/10" };
  }
}
function profileName(actor) {
  if (!actor) return "Creator";
  return actor.username ? `@${actor.username}` : actor.name || "Creator";
}
function headline(activity) {
  switch (activity?.type) {
    case "upload":
      return activity?.artwork?.title ? `Uploaded ${activity.artwork.title}` : "Uploaded new artwork";
    case "comment":
      return activity?.artwork?.title ? `Commented on ${activity.artwork.title}` : "Posted a new comment";
    case "reply":
      return activity?.artwork?.title ? `Replied on ${activity.artwork.title}` : "Posted a reply";
    case "like":
      return activity?.artwork?.title ? `Liked ${activity.artwork.title}` : "Liked an artwork";
    case "favourite":
      return activity?.artwork?.title ? `Favourited ${activity.artwork.title}` : "Saved an artwork";
    case "follow":
      return activity?.target_user ? `Started following @${activity.target_user.username || activity.target_user.name}` : "Started following a creator";
    case "achievement":
      return activity?.achievement?.name ? `Unlocked ${activity.achievement.name}` : "Unlocked a new achievement";
    case "world_reward":
      return activity?.world_reward?.badge_label ? `Earned ${activity.world_reward.badge_label}` : "Earned a new world reward";
    case "forum_post":
      return activity?.forum?.thread?.title ? `Started forum thread ${activity.forum.thread.title}` : "Started a new forum thread";
    case "forum_reply":
      return activity?.forum?.thread?.title ? `Replied in ${activity.forum.thread.title}` : "Posted a forum reply";
    default:
      return "Shared new activity";
  }
}
function body(activity) {
  if (activity?.comment?.body) return activity.comment.body;
  if (activity?.forum?.post?.excerpt) return activity.forum.post.excerpt;
  if (activity?.achievement?.description) return activity.achievement.description;
  if (activity?.world_reward?.note) return activity.world_reward.note;
  return "";
}
function cta(activity) {
  if (activity?.comment?.url) return { href: activity.comment.url, label: "Open comment" };
  if (activity?.artwork?.url) return { href: activity.artwork.url, label: "View artwork" };
  if (activity?.forum?.post?.url) return { href: activity.forum.post.url, label: "Open reply" };
  if (activity?.forum?.thread?.url) return { href: activity.forum.thread.url, label: "Open thread" };
  if (activity?.target_user?.profile_url) return { href: activity.target_user.profile_url, label: "View profile" };
  if (activity?.world_reward?.world?.url) return { href: activity.world_reward.world.url, label: "Open world" };
  return null;
}
function AchievementIcon({ achievement }) {
  const raw = String(achievement?.icon || "").trim();
  const className = raw.startsWith("fa-") ? raw : `fa-solid ${raw || "fa-trophy"}`;
  return /* @__PURE__ */ React.createElement("div", { className: "inline-flex h-12 w-12 items-center justify-center rounded-2xl border border-yellow-300/20 bg-yellow-400/12 text-yellow-100" }, /* @__PURE__ */ React.createElement("i", { className }));
}
function ActivityCard$1({ activity }) {
  const meta = typeMeta(activity?.type);
  const nextAction = cta(activity);
  const copy = body(activity);
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/[0.06] bg-[linear-gradient(180deg,rgba(11,16,26,0.96),rgba(7,11,19,0.92))] p-5 shadow-[0_18px_45px_rgba(0,0,0,0.28)] backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 md:w-[17rem] md:shrink-0" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-14 w-14 shrink-0 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950/70" }, activity?.actor?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: activity.actor.avatar_url, alt: profileName(activity.actor), className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, profileName(activity.actor)), activity?.actor?.badge?.label ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 inline-flex items-center rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, activity.actor.badge.label) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs uppercase tracking-[0.18em] text-slate-500" }, activity?.time_ago || ""))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-2 rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] ${meta.tone}` }, /* @__PURE__ */ React.createElement("i", { className: meta.icon }), meta.label)), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-lg font-semibold tracking-[-0.02em] text-white" }, headline(activity)), copy ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-7 text-slate-400" }, copy) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500 md:text-right" }, activity?.created_at ? new Date(activity.created_at).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }) : "")), activity?.artwork ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center gap-3 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-3" }, activity.artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: activity.artwork.thumb, alt: activity.artwork.title, className: "h-16 w-16 rounded-2xl object-cover ring-1 ring-white/10", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-medium text-white" }, activity.artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, Number(activity.artwork.stats?.likes || 0).toLocaleString(), " likes"), /* @__PURE__ */ React.createElement("span", null, Number(activity.artwork.stats?.views || 0).toLocaleString(), " views"), /* @__PURE__ */ React.createElement("span", null, Number(activity.artwork.stats?.comments || 0).toLocaleString(), " comments")))) : null, activity?.target_user ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center gap-3 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-12 w-12 overflow-hidden rounded-2xl border border-white/10 bg-slate-950/70" }, activity.target_user.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: activity.target_user.avatar_url, alt: activity.target_user.username || activity.target_user.name, className: "h-full w-full object-cover", loading: "lazy" }) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Target creator"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white" }, "@", activity.target_user.username || activity.target_user.name))) : null, activity?.achievement ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center gap-3 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement(AchievementIcon, { achievement: activity.achievement }), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Achievement unlocked"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white" }, activity.achievement.name), activity.achievement.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, activity.achievement.description) : null)) : null, activity?.world_reward ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "World reward"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white" }, activity.world_reward.badge_label), activity.world_reward.artwork?.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, "Artwork: ", activity.world_reward.artwork.title) : null) : null, activity?.forum?.thread ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/[0.06] bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Forum activity"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white" }, activity.forum.thread.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-400" }, activity.forum.thread.category_name)) : null, nextAction ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: nextAction.href,
      className: "mt-4 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3.5 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-200 transition hover:border-white/20 hover:bg-white/[0.1] hover:text-white"
    },
    nextAction.label,
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-[10px]" })
  ) : null)));
}
function ActivityFeed({ activities, loading, loadingMore, error, sentinelRef }) {
  if (loading) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.06] bg-[linear-gradient(180deg,rgba(10,16,26,0.92),rgba(6,10,18,0.88))] p-6 text-sm text-slate-400 shadow-[0_20px_60px_rgba(0,0,0,0.25)]" }, "Loading activity...");
  }
  if (error) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-rose-300/20 bg-rose-500/10 p-6 text-sm text-rose-100 shadow-[0_20px_60px_rgba(0,0,0,0.25)]" }, error);
  }
  if (!activities.length) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 bg-[linear-gradient(180deg,rgba(10,16,26,0.92),rgba(6,10,18,0.88))] px-6 py-12 text-center shadow-[0_20px_60px_rgba(0,0,0,0.25)]" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-16 w-16 items-center justify-center rounded-3xl border border-white/10 bg-white/[0.04] text-sky-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wave-square text-xl" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-5 text-lg font-semibold text-white" }, "No activity yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-2 max-w-lg text-sm leading-7 text-slate-400" }, "Upload artwork, join a conversation, follow creators, or post in the forum to start building this profile timeline."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap justify-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/upload", className: "inline-flex items-center gap-2 rounded-full border border-sky-300/30 bg-sky-400/12 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100 transition hover:border-sky-200/50 hover:bg-sky-400/18" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-upload" }), "Upload artwork"), /* @__PURE__ */ React.createElement("a", { href: "/uploads/latest", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-200 transition hover:border-white/20 hover:bg-white/[0.1] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-comment-dots" }), "Comment on artwork"), /* @__PURE__ */ React.createElement("a", { href: "/discover/trending", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-200 transition hover:border-white/20 hover:bg-white/[0.1] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-plus" }), "Follow creators")));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, activities.map((activity) => /* @__PURE__ */ React.createElement(ActivityCard$1, { key: activity.id, activity })), /* @__PURE__ */ React.createElement("div", { ref: sentinelRef, className: "h-12", "aria-hidden": "true" }), loadingMore ? /* @__PURE__ */ React.createElement("div", { className: "text-center text-sm text-slate-400" }, "Loading more activity...") : null);
}
const FILTERS = [
  { key: "all", label: "All" },
  { key: "uploads", label: "Uploads" },
  { key: "comments", label: "Comments" },
  { key: "likes", label: "Likes" },
  { key: "forum", label: "Forum" },
  { key: "following", label: "Following" }
];
function ActivityFilters({ activeFilter, onChange }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, FILTERS.map((filter2) => {
    const active = activeFilter === filter2.key;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: filter2.key,
        type: "button",
        onClick: () => onChange(filter2.key),
        className: [
          "inline-flex items-center rounded-full border px-3.5 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] transition-all",
          active ? "border-sky-300/35 bg-sky-400/14 text-sky-100 shadow-[0_0_0_1px_rgba(125,211,252,0.1)]" : "border-white/10 bg-white/[0.04] text-slate-300 hover:border-white/20 hover:bg-white/[0.08] hover:text-white"
        ].join(" ")
      },
      filter2.label
    );
  }));
}
function endpointForUser(user) {
  return `/api/profile/${encodeURIComponent(user.username || user.name || "")}/activity`;
}
function ActivityTab({ user }) {
  const [activeFilter, setActiveFilter] = reactExports.useState("all");
  const [activities, setActivities] = reactExports.useState([]);
  const [meta, setMeta] = reactExports.useState({ current_page: 1, has_more: false, total: 0 });
  const [loading, setLoading] = reactExports.useState(true);
  const [loadingMore, setLoadingMore] = reactExports.useState(false);
  const [error, setError] = reactExports.useState("");
  const requestIdRef = reactExports.useRef(0);
  const sentinelRef = reactExports.useRef(null);
  const fetchFeed = reactExports.useCallback(async ({ filter: filter2, page, append: append2 }) => {
    const requestId = requestIdRef.current + 1;
    requestIdRef.current = requestId;
    if (append2) {
      setLoadingMore(true);
    } else {
      setLoading(true);
    }
    try {
      setError("");
      const params = new URLSearchParams({
        filter: filter2,
        page: String(page),
        per_page: "20"
      });
      const response = await fetch(`${endpointForUser(user)}?${params.toString()}`, {
        headers: {
          Accept: "application/json"
        },
        credentials: "same-origin"
      });
      if (!response.ok) {
        throw new Error("Failed to load profile activity.");
      }
      const payload = await response.json();
      if (requestId !== requestIdRef.current) return;
      setActivities((current) => append2 ? [...current, ...payload.data || []] : payload.data || []);
      setMeta(payload.meta || { current_page: page, has_more: false, total: 0 });
    } catch {
      if (requestId === requestIdRef.current) {
        setError("Could not load this activity timeline right now.");
      }
    } finally {
      if (requestId === requestIdRef.current) {
        setLoading(false);
        setLoadingMore(false);
      }
    }
  }, [user]);
  reactExports.useEffect(() => {
    fetchFeed({ filter: activeFilter, page: 1, append: false });
  }, [activeFilter, fetchFeed]);
  const hasMore = Boolean(meta?.has_more);
  const nextPage = Number(meta?.current_page || 1) + 1;
  reactExports.useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || loading || loadingMore || !hasMore || !("IntersectionObserver" in window)) {
      return void 0;
    }
    const observer = new IntersectionObserver((entries) => {
      const [entry] = entries;
      if (entry?.isIntersecting) {
        fetchFeed({ filter: activeFilter, page: nextPage, append: true });
      }
    }, { rootMargin: "240px 0px" });
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [activeFilter, fetchFeed, hasMore, loading, loadingMore, nextPage]);
  const summary = reactExports.useMemo(() => {
    const total = Number(meta?.total || activities.length || 0);
    return total ? `${total.toLocaleString()} recent actions` : "No recent actions";
  }, [activities.length, meta?.total]);
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-activity",
      role: "tabpanel",
      "aria-labelledby": "tab-activity",
      className: "mx-auto max-w-7xl px-4 pt-4 pb-10 md:px-6"
    },
    /* @__PURE__ */ React.createElement("div", { className: "rounded-[32px] border border-white/[0.06] bg-[linear-gradient(135deg,rgba(56,189,248,0.14),rgba(10,16,26,0.94),rgba(249,115,22,0.08))] p-5 shadow-[0_22px_70px_rgba(0,0,0,0.26)] md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/75" }, "Activity"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white md:text-3xl" }, "Recent actions and contributions"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300 md:text-[15px]" }, "A living timeline of uploads, discussions, follows, achievements, and forum participation from ", user.username || user.name, ".")), /* @__PURE__ */ React.createElement("div", { className: "self-start rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-300" }, summary)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement(ActivityFilters, { activeFilter, onChange: setActiveFilter }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bolt text-sky-300" }), "Timeline updates automatically as new actions are logged")))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(
      ActivityFeed,
      {
        activities,
        loading,
        loadingMore,
        error,
        sentinelRef
      }
    ))
  );
}
function TabActivity({ user }) {
  return /* @__PURE__ */ React.createElement(ActivityTab, { user });
}
const VISIBILITY_OPTIONS$1 = [
  { value: "public", icon: "fa-globe", label: "Public" },
  { value: "followers", icon: "fa-user-friends", label: "Followers" },
  { value: "private", icon: "fa-lock", label: "Private" }
];
function ArtworkResult({ artwork, onSelect }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => onSelect(artwork),
      className: "w-full flex gap-3 p-3 rounded-xl hover:bg-white/5 transition-colors text-left group"
    },
    /* @__PURE__ */ React.createElement("div", { className: "w-14 h-12 rounded-lg overflow-hidden shrink-0 bg-white/5" }, artwork.thumb_url ? /* @__PURE__ */ React.createElement(
      "img",
      {
        src: artwork.thumb_url,
        alt: artwork.title,
        className: "w-full h-full object-cover",
        loading: "lazy"
      }
    ) : /* @__PURE__ */ React.createElement("div", { className: "w-full h-full flex items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" }))),
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/90 truncate group-hover:text-sky-400 transition-colors" }, artwork.title), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mt-0.5 truncate" }, "by ", artwork.user?.name ?? artwork.author_name ?? "Unknown"))
  );
}
function ShareArtworkModal({ isOpen, onClose, onShared, preselectedArtwork = null }) {
  const [query, setQuery] = reactExports.useState("");
  const [results, setResults] = reactExports.useState([]);
  const [searching, setSearching] = reactExports.useState(false);
  const [selected, setSelected] = reactExports.useState(preselectedArtwork);
  const [body2, setBody] = reactExports.useState("");
  const [visibility, setVisibility] = reactExports.useState("public");
  const [submitting, setSubmitting] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const searchTimer = reactExports.useRef(null);
  const inputRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (isOpen && !preselectedArtwork) {
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [isOpen]);
  reactExports.useEffect(() => {
    setSelected(preselectedArtwork);
  }, [preselectedArtwork]);
  const handleSearch = (q2) => {
    setQuery(q2);
    clearTimeout(searchTimer.current);
    if (!q2.trim()) {
      setResults([]);
      return;
    }
    searchTimer.current = setTimeout(async () => {
      setSearching(true);
      try {
        const { data } = await axios.get("/api/search/artworks", {
          params: { q: q2, shareable: 1, per_page: 12 }
        });
        setResults(data.data ?? data.hits ?? []);
      } catch {
        setResults([]);
      } finally {
        setSearching(false);
      }
    }, 300);
  };
  const handleSubmit = async () => {
    if (!selected) return;
    setSubmitting(true);
    setError(null);
    try {
      const { data } = await axios.post(`/api/posts/share/artwork/${selected.id}`, {
        body: body2.trim() || null,
        visibility
      });
      onShared?.(data.post);
      handleClose();
    } catch (err) {
      setError(err.response?.data?.errors?.artwork_id?.[0] ?? err.response?.data?.message ?? "Failed to share.");
    } finally {
      setSubmitting(false);
    }
  };
  const handleClose = () => {
    setQuery("");
    setResults([]);
    setSelected(preselectedArtwork);
    setBody("");
    setVisibility("public");
    setError(null);
    onClose?.();
  };
  if (!isOpen) return null;
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4",
      role: "dialog",
      "aria-modal": "true",
      "aria-label": "Share artwork"
    },
    /* @__PURE__ */ React.createElement(
      "div",
      {
        className: "absolute inset-0 bg-black/60 backdrop-blur-sm",
        onClick: handleClose,
        "aria-hidden": "true"
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "relative w-full max-w-lg bg-[#0d1829] border border-white/10 rounded-2xl shadow-2xl max-h-[90vh] flex flex-col overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between px-5 py-4 border-b border-white/[0.06]" }, /* @__PURE__ */ React.createElement("h2", { className: "text-sm font-semibold text-white/90" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes mr-2 text-sky-400 opacity-80" }), "Share Artwork to Profile"), /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: handleClose,
        className: "text-slate-500 hover:text-white transition-colors",
        "aria-label": "Close"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark" })
    )), /* @__PURE__ */ React.createElement("div", { className: "flex-1 overflow-y-auto p-5 space-y-4" }, !selected ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "block text-xs font-medium text-slate-400 mb-1.5" }, "Search for an artwork"), /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: inputRef,
        type: "text",
        value: query,
        onChange: (e) => handleSearch(e.target.value),
        placeholder: "Type artwork name…",
        className: "w-full bg-white/5 border border-white/10 rounded-xl pl-9 pr-4 py-2.5 text-sm text-white placeholder-slate-600 focus:outline-none focus:border-sky-500/50 transition-colors"
      }
    ), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass absolute left-3 top-1/2 -translate-y-1/2 text-slate-500 text-xs" }), searching && /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin absolute right-3 top-1/2 -translate-y-1/2 text-slate-500 text-xs" })), results.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-2 rounded-xl border border-white/[0.06] bg-black/20 max-h-56 overflow-y-auto" }, results.map((a) => /* @__PURE__ */ React.createElement(ArtworkResult, { key: a.id, artwork: a, onSelect: (art) => {
      setSelected(art);
      setQuery("");
      setResults([]);
    } }))), query && !searching && results.length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mt-2 text-center py-4" }, "No artworks found.")) : /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "block text-xs font-medium text-slate-400 mb-1.5" }, "Selected Artwork"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3 rounded-xl border border-white/[0.08] bg-black/20 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "w-16 h-14 rounded-lg overflow-hidden shrink-0 bg-white/5" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: selected.thumb_url ?? selected.thumb ?? "",
        alt: selected.title,
        className: "w-full h-full object-cover",
        loading: "lazy"
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/90 truncate" }, selected.title), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-400 mt-0.5" }, "by ", selected.user?.name ?? selected.author?.name ?? selected.author_name ?? "Unknown")), !preselectedArtwork && /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: () => setSelected(null),
        className: "text-slate-500 hover:text-white transition-colors self-start",
        title: "Change artwork"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark text-xs" })
    ))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "block text-xs font-medium text-slate-400 mb-1.5" }, "Commentary ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-600" }, "(optional)")), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: body2,
        onChange: (e) => setBody(e.target.value),
        maxLength: 2e3,
        rows: 3,
        placeholder: "Say something about this artwork…",
        className: "w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white resize-none placeholder-slate-600 focus:outline-none focus:border-sky-500/50 transition-colors"
      }
    ), /* @__PURE__ */ React.createElement("p", { className: "text-right text-[10px] text-slate-600 mt-0.5" }, body2.length, "/2000")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "block text-xs font-medium text-slate-400 mb-1.5" }, "Visibility"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, VISIBILITY_OPTIONS$1.map((v2) => /* @__PURE__ */ React.createElement(
      "button",
      {
        key: v2.value,
        onClick: () => setVisibility(v2.value),
        className: `flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl text-xs font-medium transition-all border ${visibility === v2.value ? "border-sky-500/50 bg-sky-500/10 text-sky-300" : "border-white/10 bg-white/[0.03] text-slate-400 hover:border-white/20 hover:text-white"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${v2.icon} fa-fw` }),
      v2.label
    )))), error && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-400 bg-rose-500/10 border border-rose-500/20 rounded-xl px-3 py-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-exclamation mr-1.5" }), error)), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2 px-5 py-4 border-t border-white/[0.06]" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: handleClose,
        className: "flex-1 px-4 py-2.5 rounded-xl text-sm text-slate-400 hover:text-white hover:bg-white/5 transition-colors"
      },
      "Cancel"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        onClick: handleSubmit,
        disabled: submitting || !selected,
        className: "flex-1 px-4 py-2.5 rounded-xl bg-sky-600 hover:bg-sky-500 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm font-medium transition-colors flex items-center justify-center gap-2"
      },
      submitting ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin" }), " Sharing…") : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes" }), " Share")
    )))
  );
}
const ShareArtworkModal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ShareArtworkModal
}, Symbol.toStringTag, { value: "Module" }));
function TagPeopleModal({ isOpen, onClose, selected = [], onConfirm }) {
  const [query, setQuery] = reactExports.useState("");
  const [results, setResults] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [staged, setStaged] = reactExports.useState(selected);
  const inputRef = reactExports.useRef(null);
  const debounce = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (isOpen) {
      setStaged(selected);
      setQuery("");
      setResults([]);
      setTimeout(() => inputRef.current?.focus(), 80);
    }
  }, [isOpen]);
  const search2 = reactExports.useCallback(async (q2) => {
    if (q2.length < 2) {
      setResults([]);
      return;
    }
    setLoading(true);
    try {
      const { data } = await axios.get("/api/search/users", { params: { q: q2, per_page: 8 } });
      setResults(data.data ?? []);
    } catch {
      setResults([]);
    } finally {
      setLoading(false);
    }
  }, []);
  const handleQueryChange = (e) => {
    const val = e.target.value;
    setQuery(val);
    clearTimeout(debounce.current);
    debounce.current = setTimeout(() => search2(val.replace(/^@/, "")), 300);
  };
  const isSelected = (user) => staged.some((u2) => u2.id === user.id);
  const toggle = (user) => {
    setStaged(
      (prev) => isSelected(user) ? prev.filter((u2) => u2.id !== user.id) : prev.length < 10 ? [...prev, user] : prev
    );
  };
  const handleConfirm = () => {
    onConfirm(staged);
    onClose();
  };
  if (!isOpen) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-50 flex items-center justify-center p-4" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-black/70 backdrop-blur-sm", onClick: onClose }), /* @__PURE__ */ React.createElement("div", { className: "relative w-full max-w-md rounded-2xl border border-white/10 bg-[#0c1525] shadow-2xl overflow-hidden flex flex-col max-h-[80vh]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 px-5 py-4 border-b border-white/[0.07]" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClose,
      className: "w-8 h-8 rounded-full hover:bg-white/10 flex items-center justify-center text-slate-400 hover:text-white transition-colors",
      "aria-label": "Back"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-sm" })
  ), /* @__PURE__ */ React.createElement("h2", { className: "flex-1 text-center text-base font-semibold text-white/90 -ml-8" }, "Tag people"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleConfirm,
      className: "text-sm font-medium text-sky-400 hover:text-sky-300 transition-colors"
    },
    "Done"
  )), /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 border-b border-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 bg-white/[0.06] border border-white/[0.08] rounded-xl px-3 py-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass text-slate-500 text-xs fa-fw" }), /* @__PURE__ */ React.createElement(
    "input",
    {
      ref: inputRef,
      type: "text",
      value: query,
      onChange: handleQueryChange,
      placeholder: "Search users…",
      className: "flex-1 bg-transparent text-sm text-white placeholder-slate-600 focus:outline-none"
    }
  ), loading && /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin text-slate-500 text-xs" }), query && !loading && /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => {
    setQuery("");
    setResults([]);
  }, className: "text-slate-500 hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark text-xs" })))), staged.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 px-4 py-3 border-b border-white/[0.05]" }, staged.map((u2) => /* @__PURE__ */ React.createElement(
    "span",
    {
      key: u2.id,
      className: "flex items-center gap-1.5 px-2.5 py-1 bg-sky-500/15 border border-sky-500/30 rounded-full text-xs text-sky-400"
    },
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: u2.avatar_url ?? "/images/avatar_default.webp",
        alt: "",
        className: "w-4 h-4 rounded-full object-cover"
      }
    ),
    "@",
    u2.username,
    /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => toggle(u2),
        className: "ml-0.5 opacity-60 hover:opacity-100 transition-opacity",
        "aria-label": `Remove @${u2.username}`
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark fa-xs" })
    )
  ))), /* @__PURE__ */ React.createElement("div", { className: "overflow-y-auto flex-1" }, results.length === 0 && query.length >= 2 && !loading && /* @__PURE__ */ React.createElement("p", { className: "px-5 py-8 text-center text-sm text-slate-600" }, 'No users found for "', query, '"'), results.length === 0 && query.length < 2 && /* @__PURE__ */ React.createElement("p", { className: "px-5 py-8 text-center text-sm text-slate-600" }, "Type a name or @username to search"), results.map((u2) => {
    const checked = isSelected(u2);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: u2.id,
        type: "button",
        onClick: () => toggle(u2),
        className: `w-full flex items-center gap-3 px-5 py-3 text-left transition-colors ${checked ? "bg-sky-500/10" : "hover:bg-white/[0.04]"}`
      },
      /* @__PURE__ */ React.createElement(
        "img",
        {
          src: u2.avatar_url ?? "/images/avatar_default.webp",
          alt: u2.username,
          className: "w-10 h-10 rounded-full object-cover ring-1 ring-white/10 shrink-0",
          loading: "lazy"
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/90 truncate" }, u2.name || `@${u2.username}`), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 truncate" }, "@", u2.username)),
      /* @__PURE__ */ React.createElement("div", { className: `w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-colors ${checked ? "bg-sky-500 border-sky-500 text-white" : "border-white/20"}` }, checked && /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check fa-xs" }))
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "px-5 py-3 border-t border-white/[0.07]" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleConfirm,
      className: "w-full py-2.5 rounded-xl bg-sky-600 hover:bg-sky-500 text-white text-sm font-medium transition-colors disabled:opacity-40"
    },
    staged.length === 0 ? "Continue without tagging" : `Tag ${staged.length} ${staged.length === 1 ? "person" : "people"}`
  ))));
}
const VISIBILITY_OPTIONS = [
  { value: "public", icon: "fa-globe", label: "Public" },
  { value: "followers", icon: "fa-user-friends", label: "Followers" },
  { value: "private", icon: "fa-lock", label: "Private" }
];
const URL_RE = /https?:\/\/[^\s\])"'>]{4,}/gi;
function extractFirstUrl(text2) {
  const m2 = text2.match(URL_RE);
  return m2 ? m2[0].replace(/[.,;:!?)]+$/, "") : null;
}
function PostComposer({ user, onPosted }) {
  const [expanded, setExpanded] = reactExports.useState(false);
  const [body2, setBody] = reactExports.useState("");
  const [visibility, setVisibility] = reactExports.useState("public");
  const [submitting, setSubmitting] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(null);
  const [shareModal, setShareModal] = reactExports.useState(false);
  const [linkPreview, setLinkPreview] = reactExports.useState(null);
  const [previewLoading, setPreviewLoading] = reactExports.useState(false);
  const [previewDismissed, setPreviewDismissed] = reactExports.useState(false);
  const [lastPreviewUrl, setLastPreviewUrl] = reactExports.useState(null);
  const [emojiOpen, setEmojiOpen] = reactExports.useState(false);
  const [emojiData, setEmojiData] = reactExports.useState(null);
  const [tagModal, setTagModal] = reactExports.useState(false);
  const [taggedUsers, setTaggedUsers] = reactExports.useState([]);
  const [scheduleOpen, setScheduleOpen] = reactExports.useState(false);
  const [scheduledAt, setScheduledAt] = reactExports.useState("");
  const textareaRef = reactExports.useRef(null);
  const debounceTimer = reactExports.useRef(null);
  const emojiWrapRef = reactExports.useRef(null);
  const openEmojiPicker = reactExports.useCallback(async () => {
    if (!emojiData) {
      const { default: data } = await import("./assets/emoji-data-4xGXbtDn.js");
      setEmojiData(data);
    }
    setEmojiOpen((v2) => !v2);
  }, [emojiData]);
  reactExports.useEffect(() => {
    if (!emojiOpen) return;
    const handler = (e) => {
      if (!isEventWithinNode(e, emojiWrapRef.current)) {
        setEmojiOpen(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [emojiOpen]);
  const insertEmoji = reactExports.useCallback((emoji) => {
    const native = extractNativeEmoji(emoji) || emoji?.shortcodes || "";
    const ta = textareaRef.current;
    if (!ta) {
      setBody((b2) => b2 + native);
      return;
    }
    const start = ta.selectionStart ?? body2.length;
    const end = ta.selectionEnd ?? body2.length;
    const next = body2.slice(0, start) + native + body2.slice(end);
    setBody(next);
    requestAnimationFrame(() => {
      ta.focus();
      const pos = start + native.length;
      ta.setSelectionRange(pos, pos);
    });
    setEmojiOpen(false);
  }, [body2]);
  const handleFocus = () => {
    setExpanded(true);
    setTimeout(() => textareaRef.current?.focus(), 50);
  };
  const fetchLinkPreview = reactExports.useCallback(async (url) => {
    setPreviewLoading(true);
    try {
      const { data } = await axios.get("/api/link-preview", { params: { url } });
      if (data?.url) {
        setLinkPreview(data);
      }
    } catch {
    } finally {
      setPreviewLoading(false);
    }
  }, []);
  const handleBodyChange = (e) => {
    const val = e.target.value;
    setBody(val);
    clearTimeout(debounceTimer.current);
    debounceTimer.current = setTimeout(() => {
      const url = extractFirstUrl(val);
      if (!url || previewDismissed) return;
      if (url === lastPreviewUrl) return;
      setLastPreviewUrl(url);
      setLinkPreview(null);
      fetchLinkPreview(url);
    }, 700);
  };
  const handleDismissPreview = () => {
    setLinkPreview(null);
    setPreviewDismissed(true);
  };
  const resetComposer = () => {
    setBody("");
    setExpanded(false);
    setLinkPreview(null);
    setPreviewLoading(false);
    setPreviewDismissed(false);
    setLastPreviewUrl(null);
    setEmojiOpen(false);
    setTaggedUsers([]);
    setTagModal(false);
    setScheduleOpen(false);
    setScheduledAt("");
  };
  const handleSubmit = async (e) => {
    e?.preventDefault();
    if (!body2.trim()) return;
    setSubmitting(true);
    setError(null);
    try {
      const { data } = await axios.post("/api/posts", {
        type: "text",
        visibility,
        body: body2,
        link_preview: linkPreview ?? void 0,
        tagged_users: taggedUsers.length > 0 ? taggedUsers.map(({ id, username, name: name2 }) => ({ id, username, name: name2 })) : void 0,
        publish_at: scheduledAt || void 0
      });
      onPosted?.(data.post);
      resetComposer();
    } catch (err) {
      setError(err.response?.data?.message ?? "Failed to post.");
    } finally {
      setSubmitting(false);
    }
  };
  const handleShared = (newPost) => {
    onPosted?.(newPost);
    setShareModal(false);
  };
  const showPreview2 = (linkPreview || previewLoading) && !previewDismissed;
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.025] px-5 py-4" }, !expanded ? /* @__PURE__ */ React.createElement(
    "div",
    {
      onClick: handleFocus,
      className: "flex items-center gap-3 cursor-text",
      role: "button",
      tabIndex: 0,
      onKeyDown: (e) => e.key === "Enter" && handleFocus(),
      "aria-label": "Create a post"
    },
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: user.avatar ?? "/images/avatar_default.webp",
        alt: user.name,
        className: "w-9 h-9 rounded-full object-cover ring-1 ring-white/10 shrink-0",
        loading: "lazy"
      }
    ),
    /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500 flex-1 bg-white/[0.04] rounded-xl px-4 py-2.5 hover:bg-white/[0.07] transition-colors" }, "Share an update with your followers.")
  ) : /* @__PURE__ */ React.createElement("form", { onSubmit: handleSubmit, className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("a", { href: `/@${user.username}`, className: "shrink-0", tabIndex: -1 }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: user.avatar ?? "/images/avatar_default.webp",
      alt: user.name,
      className: "w-9 h-9 rounded-full object-cover ring-1 ring-white/10 hover:ring-sky-500/40 transition-all mt-0.5",
      loading: "lazy"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 flex flex-col gap-1.5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1.5" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/@${user.username}`,
      className: "text-sm font-semibold text-white/90 hover:text-sky-400 transition-colors leading-tight",
      tabIndex: -1
    },
    user.name || `@${user.username}`
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500 leading-tight" }, "@", user.username)), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      ref: textareaRef,
      value: body2,
      onChange: handleBodyChange,
      maxLength: 2e3,
      rows: 3,
      placeholder: "Share an update with your followers.",
      autoFocus: true,
      className: "w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white resize-none placeholder-slate-600 focus:outline-none focus:border-sky-500/50 transition-colors"
    }
  ))), taggedUsers.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "pl-12 flex flex-wrap gap-1.5 items-center" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "With:"), taggedUsers.map((u2) => /* @__PURE__ */ React.createElement("span", { key: u2.id, className: "flex items-center gap-1 px-2 py-0.5 bg-sky-500/10 border border-sky-500/20 rounded-full text-xs text-sky-400" }, /* @__PURE__ */ React.createElement("img", { src: u2.avatar_url ?? "/images/avatar_default.webp", alt: "", className: "w-3.5 h-3.5 rounded-full object-cover" }), "@", u2.username, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTaggedUsers((prev) => prev.filter((x2) => x2.id !== u2.id)),
      className: "opacity-60 hover:opacity-100 ml-0.5"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark fa-xs" })
  )))), showPreview2 && /* @__PURE__ */ React.createElement("div", { className: "pl-12" }, /* @__PURE__ */ React.createElement(
    LinkPreviewCard,
    {
      preview: linkPreview,
      loading: previewLoading && !linkPreview,
      onDismiss: handleDismissPreview
    }
  )), scheduleOpen && /* @__PURE__ */ React.createElement("div", { className: "pl-12" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2.5 p-3 rounded-xl bg-violet-500/10 border border-violet-500/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-calendar-plus text-violet-400 text-sm fa-fw shrink-0" }), /* @__PURE__ */ React.createElement("div", { className: "flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "block text-[11px] text-slate-400 mb-1" }, "Publish on"), /* @__PURE__ */ React.createElement(
    DateTimePicker,
    {
      value: scheduledAt,
      onChange: setScheduledAt,
      minDateTime: new Date(Date.now() + 6e4).toISOString().slice(0, 16),
      placeholder: "Pick a publish slot",
      clearable: true,
      className: "border-violet-300/20 bg-violet-500/10"
    }
  ), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-500 mt-1" }, Intl.DateTimeFormat().resolvedOptions().timeZone)), scheduledAt && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setScheduledAt(""),
      className: "text-slate-500 hover:text-slate-300 transition-colors",
      title: "Clear"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-xmark fa-sm" })
  ))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 pl-12" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, VISIBILITY_OPTIONS.map((v2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: v2.value,
      type: "button",
      onClick: () => setVisibility(v2.value),
      title: v2.label,
      className: `flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs transition-all ${visibility === v2.value ? "bg-sky-500/15 text-sky-400 border border-sky-500/30" : "text-slate-500 hover:text-white hover:bg-white/5"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${v2.icon} fa-fw` }),
    visibility === v2.value && /* @__PURE__ */ React.createElement("span", null, v2.label)
  ))), /* @__PURE__ */ React.createElement("div", { ref: emojiWrapRef, className: "relative" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: openEmojiPicker,
      title: "Add emoji",
      className: `flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs transition-all ${emojiOpen ? "bg-amber-500/15 text-amber-400 border border-amber-500/30" : "text-slate-500 hover:text-white hover:bg-white/5"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-face-smile fa-fw" })
  ), emojiOpen && /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-full mb-2 left-0 z-50 shadow-2xl" }, /* @__PURE__ */ React.createElement(reactExports.Suspense, { fallback: /* @__PURE__ */ React.createElement("div", { className: "w-[352px] h-[400px] rounded-2xl bg-[#10192e] border border-white/10 flex items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin text-xl" })) }, emojiData && /* @__PURE__ */ React.createElement(
    EmojiMartPicker,
    {
      data: emojiData,
      onEmojiSelect: insertEmoji,
      theme: "dark",
      set: "native",
      previewPosition: "none",
      skinTonePosition: "search",
      navPosition: "bottom",
      perLine: 9,
      maxFrequentRows: 2
    }
  )))), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTagModal(true),
      title: "Tag people",
      className: `flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs transition-all ${taggedUsers.length > 0 ? "bg-sky-500/15 text-sky-400 border border-sky-500/30" : "text-slate-500 hover:text-white hover:bg-white/5"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-tag fa-fw" }),
    taggedUsers.length > 0 && /* @__PURE__ */ React.createElement("span", null, taggedUsers.length)
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setScheduleOpen((v2) => !v2),
      title: "Schedule post",
      className: `flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-xs transition-all ${scheduleOpen || scheduledAt ? "bg-violet-500/15 text-violet-400 border border-violet-500/30" : "text-slate-500 hover:text-white hover:bg-white/5"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-clock fa-fw" }),
    scheduledAt && /* @__PURE__ */ React.createElement("span", { className: "max-w-[80px] truncate" }, new Date(scheduledAt).toLocaleDateString(void 0, { month: "short", day: "numeric" }))
  ), /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShareModal(true),
      className: "flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs text-slate-400 hover:text-sky-400 hover:bg-sky-500/10 transition-colors",
      title: "Share an artwork"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes fa-fw" }),
    "Share artwork"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: resetComposer,
      className: "px-3 py-1.5 rounded-lg text-xs text-slate-400 hover:text-white hover:bg-white/5 transition-colors"
    },
    "Cancel"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: submitting || !body2.trim(),
      className: `px-4 py-1.5 rounded-xl disabled:opacity-40 disabled:cursor-not-allowed text-white text-xs font-medium transition-colors ${scheduledAt ? "bg-violet-600 hover:bg-violet-500" : "bg-sky-600 hover:bg-sky-500"}`
    },
    submitting ? "Posting…" : scheduledAt ? "Schedule" : "Post"
  ))), body2.length > 1800 && /* @__PURE__ */ React.createElement("p", { className: "text-right text-[10px] text-amber-400/70 pr-1" }, body2.length, "/2000"), error && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-400" }, error))), /* @__PURE__ */ React.createElement(
    ShareArtworkModal,
    {
      isOpen: shareModal,
      onClose: () => setShareModal(false),
      onShared: handleShared
    }
  ), /* @__PURE__ */ React.createElement(
    TagPeopleModal,
    {
      isOpen: tagModal,
      onClose: () => setTagModal(false),
      selected: taggedUsers,
      onConfirm: (users) => {
        setTaggedUsers(users);
        setTagModal(false);
      }
    }
  ));
}
function SuggestedUsersWidget({
  title = "Suggested Users",
  limit = 4,
  isLoggedIn = false,
  excludeUsername = null,
  initialUsers = null
}) {
  const [users, setUsers] = reactExports.useState(Array.isArray(initialUsers) ? initialUsers : []);
  const [loading, setLoading] = reactExports.useState(!Array.isArray(initialUsers) && isLoggedIn);
  reactExports.useEffect(() => {
    if (!isLoggedIn || Array.isArray(initialUsers)) {
      setLoading(false);
      return;
    }
    let cancelled = false;
    axios.get("/api/users/suggestions", { params: { limit } }).then(({ data }) => {
      if (cancelled) return;
      const nextUsers = Array.isArray(data?.data) ? data.data : [];
      setUsers(nextUsers);
    }).catch(() => {
      if (!cancelled) setUsers([]);
    }).finally(() => {
      if (!cancelled) setLoading(false);
    });
    return () => {
      cancelled = true;
    };
  }, [initialUsers, isLoggedIn, limit]);
  const visibleUsers = users.filter((user) => user?.username && user.username !== excludeUsername).slice(0, limit);
  if (!isLoggedIn) return null;
  if (!loading && visibleUsers.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 px-4 py-3 border-b border-white/[0.05]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass text-slate-500 fa-fw text-[13px]" }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-widest text-slate-500" }, title)), /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 space-y-3" }, loading ? [1, 2, 3].map((key) => /* @__PURE__ */ React.createElement("div", { key, className: "animate-pulse flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-10 w-10 rounded-full bg-white/10" }), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "h-2.5 w-24 rounded bg-white/10" }), /* @__PURE__ */ React.createElement("div", { className: "h-2 w-32 rounded bg-white/6" })))) : visibleUsers.map((user) => /* @__PURE__ */ React.createElement("div", { key: user.id, className: "rounded-2xl border border-white/[0.05] bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("a", { href: user.profile_url || `/@${user.username}`, className: "shrink-0" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: user.avatar_url || "/images/avatar_default.webp",
      alt: user.username,
      className: "h-10 w-10 rounded-full object-cover ring-1 ring-white/10",
      loading: "lazy"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("a", { href: user.profile_url || `/@${user.username}`, className: "block truncate text-sm font-semibold text-white/90 hover:text-white" }, user.name || user.username), /* @__PURE__ */ React.createElement("p", { className: "truncate text-xs text-slate-500" }, "@", user.username), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, user.context?.follower_overlap?.label || user.context?.shared_following?.label || user.reason))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-slate-500" }, Number(user.followers_count || 0).toLocaleString(), " followers"), /* @__PURE__ */ React.createElement(
    FollowButton,
    {
      username: user.username,
      initialFollowing: false,
      initialCount: Number(user.followers_count || 0),
      showCount: false,
      sizeClassName: "px-3 py-1.5 text-xs",
      className: "min-w-[110px]"
    }
  ))))));
}
function fmt(n) {
  if (n === null || n === void 0) return "0";
  if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, "") + "M";
  if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, "") + "k";
  return String(n);
}
const SOCIAL_META = {
  twitter: { icon: "fa-brands fa-x-twitter", label: "Twitter / X", prefix: "https://x.com/" },
  instagram: { icon: "fa-brands fa-instagram", label: "Instagram", prefix: "https://instagram.com/" },
  deviantart: { icon: "fa-brands fa-deviantart", label: "DeviantArt", prefix: "https://deviantart.com/" },
  artstation: { icon: "fa-brands fa-artstation", label: "ArtStation", prefix: "https://artstation.com/" },
  behance: { icon: "fa-brands fa-behance", label: "Behance", prefix: "https://behance.net/" },
  website: { icon: "fa-solid fa-globe", label: "Website", prefix: "" },
  youtube: { icon: "fa-brands fa-youtube", label: "YouTube", prefix: "" },
  twitch: { icon: "fa-brands fa-twitch", label: "Twitch", prefix: "" }
};
function SideCard({ title, icon, children, className = "" }) {
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border border-white/[0.07] bg-white/[0.03] overflow-hidden ${className}` }, title && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 px-4 py-3 border-b border-white/[0.05]" }, icon && /* @__PURE__ */ React.createElement("i", { className: `${icon} text-slate-500 fa-fw text-[13px]` }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-widest text-slate-500" }, title)), children);
}
function StatsCard({ stats, followerCount, user, onTabChange }) {
  const items = [
    {
      label: "Uploads",
      value: fmt(stats?.uploads_count ?? 0),
      icon: "fa-solid fa-image",
      color: "text-sky-400",
      tab: "artworks"
    },
    {
      label: "Followers",
      value: fmt(followerCount ?? stats?.followers_count ?? 0),
      icon: "fa-solid fa-user-group",
      color: "text-violet-400",
      tab: null
    },
    {
      label: "Following",
      value: fmt(stats?.following_count ?? 0),
      icon: "fa-solid fa-user-plus",
      color: "text-emerald-400",
      tab: null
    },
    {
      label: "Awards",
      value: fmt(stats?.awards_received_count ?? 0),
      icon: "fa-solid fa-trophy",
      color: "text-amber-400",
      tab: "stats"
    }
  ];
  return /* @__PURE__ */ React.createElement(SideCard, { title: "Stats", icon: "fa-solid fa-chart-simple" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 divide-x divide-y divide-white/[0.05]" }, items.map((item) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: item.label,
      type: "button",
      onClick: () => item.tab && onTabChange?.(item.tab),
      className: `flex flex-col items-center gap-1 py-4 px-3 transition-colors group ${item.tab ? "hover:bg-white/[0.04] cursor-pointer" : "cursor-default"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `${item.icon} ${item.color} text-sm fa-fw mb-0.5 group-hover:scale-110 transition-transform` }),
    /* @__PURE__ */ React.createElement("span", { className: "text-xl font-bold text-white/90 tabular-nums leading-none" }, item.value),
    /* @__PURE__ */ React.createElement("span", { className: "text-[10px] text-slate-500 uppercase tracking-wide" }, item.label)
  ))));
}
function AboutCard({ user, profile, socialLinks, countryName }) {
  const bio = profile?.bio || profile?.about || profile?.description;
  const website = profile?.website || user?.website;
  const joined = user?.created_at ? new Date(user.created_at).toLocaleDateString("en-US", { month: "long", year: "numeric" }) : null;
  const hasSocials = socialLinks && Object.keys(socialLinks).length > 0;
  const hasContent = bio || countryName || website || joined || hasSocials;
  if (!hasContent) return null;
  return /* @__PURE__ */ React.createElement(SideCard, { title: "About", icon: "fa-solid fa-circle-info" }, /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 space-y-3" }, bio && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-300 leading-relaxed line-clamp-4" }, bio), /* @__PURE__ */ React.createElement("div", { className: "space-y-1.5" }, countryName && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[13px] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-location-dot fa-fw text-slate-600 text-xs" }), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Location"), /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, countryName)), joined && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[13px] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days fa-fw text-slate-600 text-xs" }), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Joined"), /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, joined)), website && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-[13px]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link fa-fw text-slate-600 text-xs" }), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Website"), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: website.startsWith("http") ? website : `https://${website}`,
      target: "_blank",
      rel: "noopener noreferrer nofollow",
      className: "text-sky-400/80 hover:text-sky-400 transition-colors truncate max-w-[200px]"
    },
    website.replace(/^https?:\/\//, "")
  ))), hasSocials && /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-1.5 pt-1" }, Object.entries(socialLinks).map(([platform2, link2]) => {
    const meta = SOCIAL_META[platform2] ?? SOCIAL_META.website;
    const url = link2.url || (meta.prefix ? meta.prefix + link2.handle : null);
    if (!url) return null;
    return /* @__PURE__ */ React.createElement(
      "a",
      {
        key: platform2,
        href: url,
        target: "_blank",
        rel: "noopener noreferrer nofollow",
        title: meta.label,
        className: "flex items-center justify-center w-8 h-8 rounded-lg bg-white/5 hover:bg-sky-500/15 text-slate-400 hover:text-sky-400 transition-all border border-white/[0.06] hover:border-sky-500/30"
      },
      /* @__PURE__ */ React.createElement("i", { className: `${meta.icon} text-sm` })
    );
  }))));
}
function RecentFollowersCard({ recentFollowers, followerCount, onTabChange }) {
  const followers = recentFollowers ?? [];
  if (followers.length === 0) return null;
  return /* @__PURE__ */ React.createElement(SideCard, { title: "Recent Followers", icon: "fa-solid fa-user-group" }, /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 space-y-2.5" }, followers.slice(0, 6).map((f2) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: f2.id,
      href: f2.profile_url ?? `/@${f2.username}`,
      className: "flex items-center gap-2.5 group"
    },
    /* @__PURE__ */ React.createElement(
      "img",
      {
        src: f2.avatar_url ?? "/images/avatar_default.webp",
        alt: f2.username,
        className: "w-8 h-8 rounded-full object-cover ring-1 ring-white/10 group-hover:ring-sky-500/40 transition-all shrink-0",
        loading: "lazy"
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[13px] font-medium text-slate-300 group-hover:text-white transition-colors truncate leading-tight" }, f2.name || f2.uname || f2.username), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-600 truncate" }, "@", f2.username))
  )), followerCount > 6 && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onTabChange?.("artworks"),
      className: "w-full text-center text-[12px] text-slate-500 hover:text-sky-400 transition-colors pt-1"
    },
    "View all ",
    fmt(followerCount),
    " followers →"
  )));
}
function TrendingHashtagsCard() {
  const [tags, setTags] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  reactExports.useEffect(() => {
    axios.get("/api/feed/hashtags/trending", { params: { limit: 8 } }).then(({ data }) => setTags(Array.isArray(data.hashtags) ? data.hashtags : [])).catch(() => {
    }).finally(() => setLoading(false));
  }, []);
  if (!loading && tags.length === 0) return null;
  return /* @__PURE__ */ React.createElement(SideCard, { title: "Trending Tags", icon: "fa-solid fa-hashtag" }, /* @__PURE__ */ React.createElement("div", { className: "px-4 py-3 space-y-1" }, loading ? [1, 2, 3, 4].map((i) => /* @__PURE__ */ React.createElement("div", { key: i, className: "animate-pulse flex items-center justify-between py-1.5" }, /* @__PURE__ */ React.createElement("div", { className: "h-2.5 bg-white/10 rounded w-20" }), /* @__PURE__ */ React.createElement("div", { className: "h-2 bg-white/6 rounded w-10" }))) : tags.map((h) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: h.tag,
      href: `/tags/${h.tag}`,
      className: "flex items-center justify-between group py-1.5 px-1 rounded-lg hover:bg-white/[0.04] transition-colors"
    },
    /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-300 group-hover:text-sky-400 transition-colors font-medium" }, "#", h.tag),
    /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-slate-600 tabular-nums" }, h.post_count, " posts")
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between pt-1" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/feed/trending",
      className: "text-[12px] text-sky-500/70 hover:text-sky-400 transition-colors"
    },
    "See trending →"
  ), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/feed/search",
      className: "text-[12px] text-slate-500 hover:text-slate-300 transition-colors"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass mr-1 text-[10px]" }),
    "Search"
  ))));
}
function FeedSidebar({
  user,
  profile,
  stats,
  followerCount,
  recentFollowers,
  suggestedUsers,
  socialLinks,
  countryName,
  isLoggedIn,
  onTabChange
}) {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(
    AboutCard,
    {
      user,
      profile,
      socialLinks,
      countryName
    }
  ), /* @__PURE__ */ React.createElement(
    StatsCard,
    {
      stats,
      followerCount,
      user,
      onTabChange
    }
  ), /* @__PURE__ */ React.createElement(
    RecentFollowersCard,
    {
      recentFollowers,
      followerCount,
      onTabChange
    }
  ), /* @__PURE__ */ React.createElement(
    SuggestedUsersWidget,
    {
      title: "Discover Creators",
      excludeUsername: user?.username,
      isLoggedIn,
      initialUsers: suggestedUsers,
      limit: 4
    }
  ), /* @__PURE__ */ React.createElement(TrendingHashtagsCard, null));
}
function EmptyPostsState({ isOwner, username }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-center justify-center rounded-[28px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-20 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex h-16 w-16 items-center justify-center rounded-3xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-newspaper text-2xl" })), /* @__PURE__ */ React.createElement("p", { className: "mb-1 text-lg font-semibold text-white" }, "No posts yet"), isOwner ? /* @__PURE__ */ React.createElement("p", { className: "max-w-sm text-sm leading-relaxed text-slate-400" }, "Share works in progress, announce releases, or add a bit of personality beyond the gallery.") : /* @__PURE__ */ React.createElement("p", { className: "max-w-sm text-sm leading-relaxed text-slate-400" }, "@", username, " has not published any profile posts yet."));
}
function ErrorPostsState({ onRetry }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-rose-400/20 bg-rose-400/10 px-6 py-12 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-14 w-14 items-center justify-center rounded-2xl border border-rose-300/20 bg-rose-500/10 text-rose-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-triangle-exclamation text-lg" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-lg font-semibold text-white" }, "Posts could not be loaded"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-2 max-w-md text-sm leading-relaxed text-rose-100/80" }, "The profile shell loaded, but the posts feed request failed. Retry without leaving the page."), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onRetry,
      className: "mt-5 inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-white/10 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-white/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-right" }),
    "Retry loading posts"
  ));
}
function TabPosts({
  username,
  isOwner,
  authUser,
  user,
  profile,
  stats,
  followerCount,
  recentFollowers,
  suggestedUsers,
  socialLinks,
  countryName,
  onTabChange
}) {
  const [posts, setPosts] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(true);
  const [page, setPage] = reactExports.useState(1);
  const [hasMore, setHasMore] = reactExports.useState(false);
  const [loaded, setLoaded] = reactExports.useState(false);
  const [error, setError] = reactExports.useState(false);
  React.useEffect(() => {
    fetchFeed(1);
  }, [username]);
  const fetchFeed = async (p = 1) => {
    setLoading(true);
    setError(false);
    try {
      const { data } = await axios.get(`/api/posts/profile/${username}`, { params: { page: p } });
      setPosts((prev) => p === 1 ? data.data : [...prev, ...data.data]);
      setHasMore(data.meta.current_page < data.meta.last_page);
      setPage(p);
    } catch {
      setError(true);
    } finally {
      setLoading(false);
      setLoaded(true);
    }
  };
  const handlePosted = reactExports.useCallback((newPost) => {
    setPosts((prev) => [newPost, ...prev]);
  }, []);
  const handleDeleted = reactExports.useCallback((postId) => {
    setPosts((prev) => prev.filter((p) => p.id !== postId));
  }, []);
  return /* @__PURE__ */ React.createElement("div", { className: "py-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid items-start gap-6 xl:grid-cols-[minmax(0,1fr)_20rem]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-4" }, isOwner && authUser && /* @__PURE__ */ React.createElement("div", { className: "sticky top-24 z-20" }, /* @__PURE__ */ React.createElement(PostComposer, { user: authUser, onPosted: handlePosted })), !loaded && loading && /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, [1, 2, 3].map((i) => /* @__PURE__ */ React.createElement(PostCardSkeleton, { key: i }))), loaded && error && posts.length === 0 && /* @__PURE__ */ React.createElement(ErrorPostsState, { onRetry: () => fetchFeed(1) }), loaded && !loading && !error && posts.length === 0 && /* @__PURE__ */ React.createElement(EmptyPostsState, { isOwner, username }), posts.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, posts.map((post2) => /* @__PURE__ */ React.createElement(
    PostCard$1,
    {
      key: post2.id,
      post: post2,
      isLoggedIn: !!authUser,
      viewerUsername: authUser?.username ?? null,
      onDelete: handleDeleted
    }
  ))), loaded && hasMore && /* @__PURE__ */ React.createElement("div", { className: "flex justify-center py-4" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => fetchFeed(page + 1),
      disabled: loading,
      className: "rounded-2xl border border-white/10 bg-white/[0.04] px-6 py-2.5 text-sm font-medium text-slate-200 transition-colors hover:bg-white/[0.08] disabled:opacity-50"
    },
    loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more posts"
  ))), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24" }, /* @__PURE__ */ React.createElement(
    FeedSidebar,
    {
      user,
      profile,
      stats,
      followerCount,
      recentFollowers,
      suggestedUsers,
      socialLinks,
      countryName,
      isLoggedIn: !!authUser,
      onTabChange
    }
  ))));
}
function TabStories({ stories, username }) {
  const list2 = Array.isArray(stories) ? stories : [];
  if (!list2.length) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.02] px-6 py-12 text-center text-slate-300" }, "No stories published yet.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3" }, list2.map((story) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: story.id,
      href: `/stories/${story.slug}`,
      className: "group overflow-hidden rounded-xl border border-gray-700 bg-gray-800/70 shadow-lg transition duration-200 hover:scale-[1.01] hover:border-sky-500/40"
    },
    story.cover_url ? /* @__PURE__ */ React.createElement("img", { src: story.cover_url, alt: story.title, className: "h-44 w-full object-cover transition-transform duration-300 group-hover:scale-105" }) : /* @__PURE__ */ React.createElement("div", { className: "h-44 w-full bg-gradient-to-br from-gray-900 via-slate-900 to-sky-950" }),
    /* @__PURE__ */ React.createElement("div", { className: "space-y-2 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement(LevelBadge, { level: story.creator_level, rank: story.creator_rank, compact: true }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] uppercase tracking-[0.16em] text-gray-500" }, "Story")), /* @__PURE__ */ React.createElement("h3", { className: "line-clamp-2 text-base font-semibold text-white" }, story.title), /* @__PURE__ */ React.createElement("p", { className: "line-clamp-2 text-xs text-gray-300" }, story.excerpt || ""), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-xs text-gray-400" }, /* @__PURE__ */ React.createElement("span", null, story.reading_time || 1, " min read"), /* @__PURE__ */ React.createElement("span", null, story.views || 0, " views"), /* @__PURE__ */ React.createElement("span", null, story.likes_count || 0, " likes")))
  ))), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: `/stories/creator/${username}`,
      className: "inline-flex rounded-lg border border-sky-400/30 bg-sky-500/10 px-3 py-2 text-sm text-sky-300 transition hover:scale-[1.01] hover:text-sky-200"
    },
    "View all stories"
  ));
}
const TONE_STYLES = {
  sky: "border-sky-300/20 bg-sky-400/10 text-sky-100",
  amber: "border-amber-300/20 bg-amber-400/10 text-amber-100",
  emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
  violet: "border-violet-300/20 bg-violet-400/10 text-violet-100"
};
function StatCard$2({ icon, label, value, tone, hint }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4 shadow-[0_18px_42px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex h-11 w-11 items-center justify-center rounded-2xl border ${TONE_STYLES[tone] || TONE_STYLES.sky}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-sm` })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-2xl font-bold tracking-tight text-white" }, value), hint ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-relaxed text-slate-400" }, hint) : null);
}
function ProfileWorldStatsRow({ summary }) {
  const worldAppearances = summary?.world_appearances || summary?.worlds_joined || 0;
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(
    StatCard$2,
    {
      icon: "fa-globe",
      label: "World Appearances",
      value: worldAppearances,
      tone: "sky",
      hint: summary?.active_year_span?.label ? `Active across ${summary.active_year_span.label}` : "Edition-aware creator history"
    }
  ), /* @__PURE__ */ React.createElement(
    StatCard$2,
    {
      icon: "fa-stars",
      label: "Featured",
      value: summary?.featured_appearances || 0,
      tone: "amber",
      hint: "Editorial features and highlighted placements"
    }
  ), /* @__PURE__ */ React.createElement(
    StatCard$2,
    {
      icon: "fa-trophy",
      label: "Wins / Finalists",
      value: summary?.finalist_winner_appearances || 0,
      tone: "emerald",
      hint: "Higher-tier placements tied to world-linked challenges"
    }
  ), /* @__PURE__ */ React.createElement(
    StatCard$2,
    {
      icon: "fa-bolt",
      label: "Spotlights",
      value: summary?.spotlight_appearances || 0,
      tone: "violet",
      hint: "Editorial spotlight moments across editions"
    }
  ));
}
function toneClasses(tone, isPrimary) {
  const styles2 = {
    emerald: "border-emerald-300/20 bg-emerald-400/12 text-emerald-100",
    violet: "border-violet-300/20 bg-violet-400/12 text-violet-100",
    amber: "border-amber-300/20 bg-amber-400/12 text-amber-100",
    rose: "border-rose-300/20 bg-rose-400/12 text-rose-100",
    sky: "border-sky-300/20 bg-sky-400/12 text-sky-100",
    slate: "border-slate-300/15 bg-slate-300/10 text-slate-200"
  };
  const base = styles2[tone] || styles2.sky;
  return `${base} ${isPrimary ? "shadow-[0_0_22px_rgba(255,255,255,0.05)]" : ""}`.trim();
}
function ProfileWorldRecognitionBadge({ recognition, isPrimary = false }) {
  if (!recognition) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-2 rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] ${toneClasses(recognition.tone, isPrimary)}` }, /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-current opacity-80" }), recognition.label);
}
function formatDate$9(value) {
  if (!value) return null;
  try {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return null;
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  } catch {
    return null;
  }
}
function ProfileWorldHistorySummary({ history: history2 }) {
  const summary = history2?.summary || {};
  const recent = summary?.most_recent_world_activity;
  const recentRecognition = recent?.primary_recognition || (recent?.recognition_label ? { key: String(recent.recognition_label).toLowerCase().replace(/\s+/g, "_"), label: recent.recognition_label, tone: "sky" } : null);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(ProfileWorldStatsRow, { summary }), recent ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_18px_46px_rgba(2,6,23,0.18)] md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Most Recent World Activity"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xl font-semibold tracking-[-0.02em] text-white" }, recent.world_title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2" }, recentRecognition ? /* @__PURE__ */ React.createElement(ProfileWorldRecognitionBadge, { recognition: recentRecognition, isPrimary: true }) : null, formatDate$9(recent.occurred_at) ? /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-400" }, formatDate$9(recent.occurred_at)) : null)), recent.world_url ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: recent.world_url,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-medium text-slate-100 transition-colors hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-xs" }),
    "View world"
  ) : null)) : null);
}
function formatDate$8(value) {
  if (!value) return null;
  try {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return null;
    return date.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
  } catch {
    return null;
  }
}
function ProfileWorldHistoryCard({ entry }) {
  const recognitionBadges = Array.isArray(entry?.recognitions) ? entry.recognitions : [];
  const artwork = entry?.linked_artwork;
  const challenge = entry?.challenge;
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_18px_48px_rgba(2,6,23,0.18)] transition-colors hover:border-white/15 hover:bg-white/[0.055] md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, recognitionBadges.map((recognition, index2) => /* @__PURE__ */ React.createElement(ProfileWorldRecognitionBadge, { key: `${entry.id}-${recognition.key}`, recognition, isPrimary: index2 === 0 }))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-baseline gap-x-3 gap-y-2" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.02em] text-white" }, entry?.world?.title), entry?.world?.edition_year ? /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, "Edition ", entry.world.edition_year) : null, entry?.world?.type_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2.5 py-1 text-[11px] font-medium text-slate-300" }, entry.world.type_label) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-slate-400" }, entry?.world?.family_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group text-[11px] text-slate-500" }), entry.world.family_label) : null, formatDate$8(entry?.occurred_at) ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-calendar text-[11px] text-slate-500" }), formatDate$8(entry.occurred_at)) : null, challenge?.title ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag-checkered text-[11px] text-slate-500" }), challenge.title) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-3" }, entry?.world?.url ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: entry.world.url,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-medium text-slate-100 transition-colors hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-xs" }),
    "View world"
  ) : null, artwork?.url ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artwork.url,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-medium text-slate-100 transition-colors hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-xs" }),
    "View artwork"
  ) : null, challenge?.url ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: challenge.url,
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-medium text-slate-100 transition-colors hover:bg-white/[0.08]"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-xs" }),
    "View challenge"
  ) : null)), /* @__PURE__ */ React.createElement("div", { className: "w-full shrink-0 lg:w-44" }, artwork?.thumbnail_url ? /* @__PURE__ */ React.createElement("a", { href: artwork.url || "#", className: "group block overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-900/60" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: artwork.thumbnail_url,
      alt: artwork.title || entry?.world?.title || "World artwork",
      className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]",
      loading: "lazy"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-medium text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, "Linked artwork"))) : /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[4/3] items-center justify-center rounded-[24px] border border-dashed border-white/12 bg-white/[0.02] text-slate-500" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-xl" }), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs uppercase tracking-[0.18em]" }, "World entry"))))));
}
function ProfileWorldTimelineList({ entries }) {
  const items = Array.isArray(entries) ? entries : [];
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, items.map((entry) => /* @__PURE__ */ React.createElement(ProfileWorldHistoryCard, { key: entry.id, entry })));
}
function EmptyState({ isOwner, hasPrivateContext }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-16 w-16 items-center justify-center rounded-3xl border border-white/10 bg-white/[0.05] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-2xl" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-5 text-xl font-semibold text-white" }, "No public worlds timeline yet"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm leading-relaxed text-slate-400" }, isOwner ? hasPrivateContext ? "Public world history appears here once a live, publicly visible submission or recognized placement is available. Until then, private-only world activity is still tracked for you above." : "Public world history appears here once a live, publicly visible submission or recognized placement is available." : "This creator does not have any public world participation or recognition to show yet."));
}
function OwnerNote({ ownerContext }) {
  if (!ownerContext) {
    return null;
  }
  const details = [
    ownerContext.pending_submissions ? `${ownerContext.pending_submissions} pending submission${ownerContext.pending_submissions === 1 ? "" : "s"}` : null,
    ownerContext.removed_or_blocked_submissions ? `${ownerContext.removed_or_blocked_submissions} removed or blocked item${ownerContext.removed_or_blocked_submissions === 1 ? "" : "s"}` : null,
    ownerContext.hidden_public_entries ? `${ownerContext.hidden_public_entries} recognition${ownerContext.hidden_public_entries === 1 ? "" : "s"} hidden from public view` : null
  ].filter(Boolean);
  if (details.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/15 bg-sky-400/10 px-5 py-4 text-sm text-sky-100" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-300/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-eye text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Private View"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 leading-relaxed text-sky-50/90" }, "Your public worlds timeline stays strict about visibility, but this profile still tracks ", details.join(", "), "."))));
}
function ProfileWorldHistorySection({ history: history2, isOwner }) {
  const entries = Array.isArray(history2?.entries) ? history2.entries : [];
  const highlights = Array.isArray(history2?.highlights) ? history2.highlights : [];
  const highlightIds = new Set(highlights.map((entry) => entry?.id).filter(Boolean));
  const timelineEntries = entries.filter((entry) => !highlightIds.has(entry?.id));
  const hasPrivateContext = Boolean(
    history2?.owner_context?.pending_submissions || history2?.owner_context?.removed_or_blocked_submissions || history2?.owner_context?.hidden_public_entries
  );
  const hasEntries = Boolean(history2?.summary?.available) && entries.length > 0;
  return /* @__PURE__ */ React.createElement("section", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Worlds History"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.02em] text-white md:text-3xl" }, "Recurring worlds, challenge outcomes, and standout editions"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-400" }, "This timeline pulls together edition-aware world participation, featured placements, finalists, winners, and linked challenge results into one creator-facing history layer."))), /* @__PURE__ */ React.createElement(OwnerNote, { ownerContext: isOwner ? history2?.owner_context : null }), hasEntries ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ProfileWorldHistorySummary, { history: history2 }), highlights.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Highlights"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, "The most recent and highest-signal world appearances surface first so recurring recognition reads like a creator recap, not just a raw list.")), /* @__PURE__ */ React.createElement(ProfileWorldTimelineList, { entries: highlights })) : null, timelineEntries.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Full Timeline"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, "Every public world appearance, challenge-linked outcome, and edition-aware placement remains visible here in chronological order.")), /* @__PURE__ */ React.createElement(ProfileWorldTimelineList, { entries: timelineEntries })) : null) : /* @__PURE__ */ React.createElement(EmptyState, { isOwner, hasPrivateContext }));
}
function TabWorlds({ worldHistory, isOwner }) {
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      id: "tabpanel-worlds",
      role: "tabpanel",
      "aria-labelledby": "tab-worlds",
      className: "pt-6"
    },
    /* @__PURE__ */ React.createElement(ProfileWorldHistorySection, { history: worldHistory, isOwner })
  );
}
function GroupProfileSummary({ contributions = [], href = null }) {
  if (!Array.isArray(contributions) || contributions.length === 0) return null;
  const featured = contributions.slice(0, 3);
  return /* @__PURE__ */ React.createElement("section", { className: "mx-auto mt-8 max-w-6xl px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(14,165,233,0.12),transparent_34%),linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-5 shadow-[0_18px_55px_rgba(2,6,23,0.28)] backdrop-blur-xl sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Group footprint"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Collaborative work across public groups"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "See the groups this creator contributes to through releases, credited artworks, and shared publishing activity.")), href ? /* @__PURE__ */ React.createElement("a", { href, className: "text-sm font-semibold text-sky-200 transition hover:text-white" }, "View full contribution history") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-3" }, featured.map((entry) => /* @__PURE__ */ React.createElement("a", { key: entry.group?.slug || entry.group?.id, href: entry.group?.profile_url || "/groups", className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20 hover:bg-black/30" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-white/[0.04]" }, entry.group?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: entry.group.avatar_url, alt: entry.group?.name, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-slate-300" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, entry.group?.name), entry.role?.label ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, entry.role.label) : null, entry.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-300" }, entry.summary) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, entry.trusted ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Trusted contributor", tone: "sky" }) : null, entry.recent_release_titles?.length ? /* @__PURE__ */ React.createElement(GroupBadgePill, { label: "Recent releases", tone: "amber" }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, Number(entry.counts?.artworks || 0).toLocaleString("en-US"), " artworks"), /* @__PURE__ */ React.createElement("span", null, Number(entry.counts?.releases || 0).toLocaleString("en-US"), " releases"), /* @__PURE__ */ React.createElement("span", null, Number(entry.counts?.projects || 0).toLocaleString("en-US"), " projects")))))));
}
const VALID_TABS = ["posts", "artworks", "stories", "achievements", "worlds", "collections", "about", "stats", "favourites", "activity"];
function getInitialTab(initialTab = "posts") {
  if (typeof window === "undefined") {
    return VALID_TABS.includes(initialTab) ? initialTab : "posts";
  }
  try {
    const pathname = window.location.pathname.replace(/\/+$/, "");
    const segments = pathname.split("/").filter(Boolean);
    const lastSegment = segments.at(-1);
    if (VALID_TABS.includes(lastSegment)) {
      return lastSegment;
    }
  } catch {
    return VALID_TABS.includes(initialTab) ? initialTab : "posts";
  }
  return VALID_TABS.includes(initialTab) ? initialTab : "posts";
}
function ProfileShow() {
  const { props } = X$1();
  const {
    user,
    profile,
    artworks,
    featuredArtworks,
    favourites,
    stats,
    socialLinks,
    followerCount,
    recentFollowers,
    followContext,
    followAnalytics,
    suggestedUsers,
    viewerIsFollowing,
    heroBgUrl,
    profileComments,
    creatorStories,
    collections,
    achievements,
    worldRewards,
    worldHistory,
    leaderboardRank,
    groupContributionHistory,
    journey,
    countryName,
    isOwner,
    auth,
    initialTab,
    profileUrl,
    galleryUrl,
    collectionCreateUrl,
    collectionReorderUrl,
    collectionsFeaturedUrl,
    collectionFeatureLimit,
    profileTabUrls,
    seo
  } = props;
  const [activeTab, setActiveTab] = reactExports.useState(() => getInitialTab(initialTab));
  const handleTabChange = reactExports.useCallback((tab2) => {
    if (!VALID_TABS.includes(tab2)) return;
    setActiveTab(tab2);
    try {
      const currentUrl = new URL(window.location.href);
      const targetBase = profileTabUrls?.[tab2] || `${profileUrl || `${window.location.origin}`}/${tab2}`;
      const nextUrl = new URL(targetBase, window.location.origin);
      const sharedPostId = currentUrl.searchParams.get("post");
      if (sharedPostId) {
        nextUrl.searchParams.set("post", sharedPostId);
      }
      window.history.pushState({}, "", nextUrl.toString());
    } catch (_2) {
    }
  }, [profileTabUrls, profileUrl]);
  reactExports.useEffect(() => {
    const onPop = () => setActiveTab(getInitialTab(initialTab));
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, [initialTab]);
  const isLoggedIn = !!auth?.user;
  const artworkList = Array.isArray(artworks) ? artworks : artworks?.data ?? [];
  const artworkNextCursor = artworks?.next_cursor ?? null;
  const favouriteList = Array.isArray(favourites) ? favourites : favourites?.data ?? [];
  const favouriteNextCursor = favourites?.next_cursor ?? null;
  const socialLinksObj = Array.isArray(socialLinks) ? socialLinks.reduce((acc, l3) => {
    acc[l3.platform] = l3;
    return acc;
  }, {}) : socialLinks ?? {};
  const contentShellClassName = activeTab === "artworks" ? "w-full px-4 md:px-6" : activeTab === "posts" || activeTab === "about" ? "mx-auto max-w-7xl px-4 md:px-6" : "max-w-6xl mx-auto px-4";
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[34rem] opacity-90",
      style: {
        background: "radial-gradient(circle at top left, rgba(56,189,248,0.18), transparent 32%), radial-gradient(circle at 82% 10%, rgba(249,115,22,0.16), transparent 28%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #0a1220 100%)"
      }
    }
  ), /* @__PURE__ */ React.createElement(
    "div",
    {
      "aria-hidden": "true",
      className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.06]",
      style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" }
    }
  ), /* @__PURE__ */ React.createElement(
    ProfileHero,
    {
      user,
      profile,
      isOwner,
      viewerIsFollowing,
      followerCount,
      recentFollowers,
      followContext,
      heroBgUrl,
      countryName,
      leaderboardRank,
      extraActions: galleryUrl ? /* @__PURE__ */ React.createElement(
        "a",
        {
          href: galleryUrl,
          className: "inline-flex shrink-0 items-center gap-2 whitespace-nowrap rounded-xl border border-white/15 px-3.5 py-2 text-sm font-medium text-slate-300 transition-all hover:bg-white/5 hover:text-white"
        },
        /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images fa-fw" }),
        "View Gallery"
      ) : null
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(
    ProfileTabs,
    {
      activeTab,
      onTabChange: handleTabChange
    }
  )), /* @__PURE__ */ React.createElement(GroupProfileSummary, { contributions: groupContributionHistory, href: profileTabUrls?.about }), /* @__PURE__ */ React.createElement("div", { className: `${contentShellClassName} pt-6` }, activeTab === "artworks" && /* @__PURE__ */ React.createElement(
    TabArtworks,
    {
      artworks: { data: artworkList, next_cursor: artworkNextCursor },
      featuredArtworks,
      username: user.username || user.name,
      galleryUrl,
      isActive: true
    }
  ), activeTab === "posts" && /* @__PURE__ */ React.createElement(
    TabPosts,
    {
      username: user.username || user.name,
      isOwner,
      authUser: auth?.user ?? null,
      user,
      profile,
      stats,
      followerCount,
      recentFollowers,
      suggestedUsers,
      socialLinks: socialLinksObj,
      countryName,
      profileUrl,
      onTabChange: handleTabChange,
      journey
    }
  ), activeTab === "stories" && /* @__PURE__ */ React.createElement(
    TabStories,
    {
      stories: creatorStories,
      username: user.username || user.name
    }
  ), activeTab === "achievements" && /* @__PURE__ */ React.createElement(TabAchievements, { achievements, worldRewards, worldHistory, onTabChange: handleTabChange }), activeTab === "worlds" && /* @__PURE__ */ React.createElement(TabWorlds, { worldHistory, isOwner }), activeTab === "collections" && /* @__PURE__ */ React.createElement(
    TabCollections,
    {
      collections,
      isOwner,
      createUrl: collectionCreateUrl,
      reorderUrl: collectionReorderUrl,
      featuredUrl: collectionsFeaturedUrl,
      featureLimit: collectionFeatureLimit
    }
  ), activeTab === "about" && /* @__PURE__ */ React.createElement(
    TabAbout,
    {
      user,
      profile,
      stats,
      achievements,
      worldRewards,
      artworks: artworkList,
      creatorStories,
      profileComments,
      socialLinks: socialLinksObj,
      countryName,
      followerCount,
      recentFollowers,
      leaderboardRank,
      groupContributionHistory,
      journey
    }
  ), activeTab === "stats" && /* @__PURE__ */ React.createElement(
    TabStats,
    {
      stats,
      followerCount,
      followAnalytics
    }
  ), activeTab === "favourites" && /* @__PURE__ */ React.createElement(
    TabFavourites,
    {
      favourites: { data: favouriteList, next_cursor: favouriteNextCursor },
      isOwner,
      username: user.username || user.name
    }
  ), activeTab === "activity" && /* @__PURE__ */ React.createElement(
    TabActivity,
    {
      profileComments,
      user,
      isOwner,
      isLoggedIn,
      stats,
      followerCount,
      creatorStories
    }
  ))));
}
const __vite_glob_0_103 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ProfileShow
}, Symbol.toStringTag, { value: "Module" }));
const navItems = [
  { label: "Profile", href: "/dashboard/profile", icon: "fa-solid fa-user" }
  // Future: { label: 'Notifications', href: '/dashboard/notifications', icon: 'fa-solid fa-bell' },
  // Future: { label: 'Privacy',       href: '/dashboard/privacy',       icon: 'fa-solid fa-shield-halved' },
];
function NavLink$1({ item, active, onClick }) {
  return /* @__PURE__ */ React.createElement(
    xe,
    {
      href: item.href,
      onClick,
      className: `flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${active ? "bg-accent/20 text-accent shadow-sm shadow-accent/10" : "text-slate-400 hover:text-white hover:bg-white/5"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }),
    /* @__PURE__ */ React.createElement("span", null, item.label)
  );
}
function SidebarContent({ isActive, onNavigate }) {
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mb-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xs font-semibold uppercase tracking-wider text-slate-500 px-4 mb-2" }, "Settings")), /* @__PURE__ */ React.createElement("nav", { className: "space-y-1 flex-1" }, navItems.map((item) => /* @__PURE__ */ React.createElement(NavLink$1, { key: item.href, item, active: isActive(item.href), onClick: onNavigate }))), /* @__PURE__ */ React.createElement("div", { className: "mt-auto pt-6 space-y-2" }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: "/studio",
      className: "flex items-center gap-2 px-4 py-2 rounded-xl text-sm text-slate-400 hover:text-white hover:bg-white/5 transition-colors",
      onClick: onNavigate
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-palette w-5 text-center" }),
    "Creator Studio"
  )));
}
function SectionSidebar({ sections = [], activeSection, onSectionChange, dirtyMap = {} }) {
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mb-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xs font-semibold uppercase tracking-wider text-slate-500 px-4 mb-2" }, "Settings")), /* @__PURE__ */ React.createElement("nav", { className: "space-y-1 flex-1" }, sections.map((section) => {
    const active = section.key === activeSection;
    const isDirty = !!dirtyMap[section.key];
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: section.key,
        type: "button",
        onClick: () => onSectionChange?.(section.key),
        className: `group relative w-full flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${active ? "bg-accent/20 text-accent shadow-sm shadow-accent/10" : "text-slate-400 hover:text-white hover:bg-white/5"}`
      },
      section.icon ? /* @__PURE__ */ React.createElement("i", { className: `${section.icon} w-5 text-center text-base` }) : null,
      /* @__PURE__ */ React.createElement("span", { className: "flex flex-col items-start gap-0.5" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-2" }, section.label, isDirty && /* @__PURE__ */ React.createElement("span", { className: "inline-block h-1.5 w-1.5 rounded-full bg-amber-400 animate-pulse", title: "Unsaved changes" })), section.description && !active ? /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-normal text-slate-500 leading-tight" }, section.description) : null)
    );
  })));
}
function SettingsLayout({ children, title, sections = null, activeSection = null, onSectionChange = null, dirtyMap = {} }) {
  const { url } = X$1();
  const [mobileOpen, setMobileOpen] = reactExports.useState(false);
  const hasSectionMode = Array.isArray(sections) && sections.length > 0 && typeof onSectionChange === "function";
  const isActive = (href) => url.startsWith(href);
  const currentSection = hasSectionMode ? sections.find((section) => section.key === activeSection) : null;
  return /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-nova-900" }, /* @__PURE__ */ React.createElement("div", { className: "lg:hidden px-4 py-3 border-b border-white/10 bg-nova-900/80 backdrop-blur-xl sticky top-16 z-30" }, hasSectionMode ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "block flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, "Settings section"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      className: "w-full",
      value: activeSection || "",
      onChange: (value) => onSectionChange(value),
      options: sections.map((section) => ({ value: section.key, label: `${section.label}${dirtyMap[section.key] ? " •" : ""}` })),
      searchable: false
    }
  )), dirtyMap[activeSection] ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full bg-amber-400/15 px-2 py-1 text-[10px] font-semibold text-amber-300 border border-amber-400/20" }, "Unsaved") : null) : /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h1", { className: "text-lg font-bold text-white" }, "Settings"), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setMobileOpen(!mobileOpen),
      className: "text-slate-400 hover:text-white p-2",
      "aria-label": "Toggle navigation"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${mobileOpen ? "fa-xmark" : "fa-bars"} text-xl` })
  ))), !hasSectionMode && mobileOpen && /* @__PURE__ */ React.createElement("div", { className: "lg:hidden fixed inset-0 z-40 bg-black/60 backdrop-blur-sm", onClick: () => setMobileOpen(false) }, /* @__PURE__ */ React.createElement(
    "nav",
    {
      className: "absolute left-0 top-0 bottom-0 w-72 bg-nova-900 border-r border-white/10 p-4 pt-20 space-y-1",
      onClick: (e) => e.stopPropagation()
    },
    /* @__PURE__ */ React.createElement(SidebarContent, { isActive, onNavigate: () => setMobileOpen(false) })
  )), /* @__PURE__ */ React.createElement("div", { className: "flex" }, /* @__PURE__ */ React.createElement("aside", { className: "hidden lg:flex flex-col w-64 min-h-[calc(100vh-4rem)] border-r border-white/10 bg-nova-900/60 backdrop-blur-xl p-4 pt-6 sticky top-16 self-start" }, hasSectionMode ? /* @__PURE__ */ React.createElement(SectionSidebar, { sections, activeSection, onSectionChange, dirtyMap }) : /* @__PURE__ */ React.createElement(SidebarContent, { isActive })), /* @__PURE__ */ React.createElement("main", { className: "flex-1 min-w-0 px-4 lg:px-8 pt-4 pb-8 max-w-5xl" }, title && /* @__PURE__ */ React.createElement("div", { className: "mb-6" }, /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white" }, title), currentSection?.description ? /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400 mt-1" }, currentSection.description) : null), children)));
}
const Textarea = reactExports.forwardRef(function Textarea2({ label, error, hint, required, rows = 4, resize = false, id, className = "", ...rest }, ref2) {
  const generatedId = reactExports.useId();
  const labelSlug = typeof label === "string" ? label.toLowerCase().replace(/\s+/g, "-") : null;
  const inputId = id ?? labelSlug ?? `textarea-${generatedId.replace(/[:]/g, "")}`;
  const inputClass = [
    "block w-full rounded-xl border bg-white/[0.06] text-white text-sm",
    "px-3.5 py-2.5 placeholder:text-slate-500",
    "transition-all duration-150",
    "focus:outline-none focus:ring-2 focus:ring-offset-0",
    resize ? "resize-y" : "resize-none",
    error ? "border-red-500/60 focus:border-red-500/70 focus:ring-red-500/40" : "border-white/12 hover:border-white/20 focus:border-accent/50 focus:ring-accent/40",
    "disabled:opacity-50 disabled:cursor-not-allowed",
    className
  ].join(" ");
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1.5" }, label && /* @__PURE__ */ React.createElement("label", { htmlFor: inputId, className: "text-sm font-medium text-white/85" }, label, required && /* @__PURE__ */ React.createElement("span", { className: "text-red-400 ml-1" }, "*")), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      id: inputId,
      ref: ref2,
      rows,
      className: inputClass,
      "aria-invalid": !!error,
      "aria-describedby": error ? `${inputId}-error` : hint ? `${inputId}-hint` : void 0,
      ...rest
    }
  ), error && /* @__PURE__ */ React.createElement("p", { id: `${inputId}-error`, role: "alert", className: "text-xs text-red-400" }, error), !error && hint && /* @__PURE__ */ React.createElement("p", { id: `${inputId}-hint`, className: "text-xs text-slate-500" }, hint));
});
const Radio = reactExports.forwardRef(function Radio2({ label, hint, size = 18, id, className = "", ...rest }, ref2) {
  const dim = typeof size === "number" ? `${size}px` : size;
  const inputId = id ?? (label ? `radio-${label.toLowerCase().replace(/\s+/g, "-")}` : void 0);
  return /* @__PURE__ */ React.createElement("label", { className: "inline-flex items-start gap-2.5 cursor-pointer select-none" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "radio",
      id: inputId,
      ref: ref2,
      className: [
        "shrink-0 cursor-pointer",
        "border border-white/25 bg-white/8",
        "text-accent checked:bg-accent checked:border-accent",
        "transition-colors duration-150",
        "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50 focus-visible:ring-offset-0",
        "disabled:opacity-50 disabled:cursor-not-allowed",
        className
      ].join(" "),
      style: {
        width: dim,
        height: dim,
        minWidth: dim,
        minHeight: dim,
        aspectRatio: "1 / 1",
        marginTop: label ? "1px" : void 0
      },
      ...rest
    }
  ), (label || hint) && /* @__PURE__ */ React.createElement("span", { className: "flex flex-col gap-0.5" }, label && /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/90 leading-snug" }, label), hint && /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, hint)));
});
function RadioGroup({ options = [], value, onChange, name: name2, label, error, direction = "vertical", className = "" }) {
  return /* @__PURE__ */ React.createElement("fieldset", { className: `flex flex-col gap-1.5 ${className}` }, label && /* @__PURE__ */ React.createElement("legend", { className: "text-sm font-medium text-white/85 mb-1" }, label), /* @__PURE__ */ React.createElement("div", { className: `flex gap-3 ${direction === "horizontal" ? "flex-row flex-wrap" : "flex-col"}` }, options.map((opt) => /* @__PURE__ */ React.createElement(
    Radio,
    {
      key: opt.value,
      name: name2,
      value: opt.value,
      checked: value === opt.value,
      onChange: () => onChange(opt.value),
      label: opt.label,
      hint: opt.hint
    }
  ))), error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error));
}
const SETTINGS_SECTIONS = [
  { key: "profile", label: "Profile", icon: "fa-solid fa-user-astronaut", description: "Public identity and avatar." },
  { key: "account", label: "Account", icon: "fa-solid fa-id-badge", description: "Username and email address." },
  { key: "personal", label: "Personal", icon: "fa-solid fa-address-card", description: "Optional personal information." },
  { key: "notifications", label: "Notifications", icon: "fa-solid fa-bell", description: "Manage notification preferences." },
  { key: "content", label: "Content", icon: "fa-solid fa-eye-low-vision", description: "Control mature artwork visibility." },
  { key: "security", label: "Security", icon: "fa-solid fa-shield-halved", description: "Password and account security." },
  { key: "danger", label: "Danger Zone", icon: "fa-solid fa-triangle-exclamation", description: "Destructive account actions." }
];
const MATURE_VISIBILITY_OPTIONS = [
  { value: "hide", label: "Hide mature artworks", hint: "Remove mature artworks from feeds and galleries whenever possible." },
  { value: "blur", label: "Blur mature artworks", hint: "Keep them in listings, but blur thumbnails until you open them." },
  { value: "show", label: "Show mature artworks normally", hint: "Display mature thumbnails without blur in listings." }
];
const MONTHS = [
  { value: "1", label: "January" },
  { value: "2", label: "February" },
  { value: "3", label: "March" },
  { value: "4", label: "April" },
  { value: "5", label: "May" },
  { value: "6", label: "June" },
  { value: "7", label: "July" },
  { value: "8", label: "August" },
  { value: "9", label: "September" },
  { value: "10", label: "October" },
  { value: "11", label: "November" },
  { value: "12", label: "December" }
];
const GENDER_OPTIONS = [
  { value: "m", label: "Male" },
  { value: "f", label: "Female" },
  { value: "x", label: "Prefer not to say" }
];
const AVATAR_POSITION_OPTIONS = [
  { value: "top-left", label: "Top Left" },
  { value: "top", label: "Top" },
  { value: "top-right", label: "Top Right" },
  { value: "left", label: "Left" },
  { value: "center", label: "Center" },
  { value: "right", label: "Right" },
  { value: "bottom-left", label: "Bottom Left" },
  { value: "bottom", label: "Bottom" },
  { value: "bottom-right", label: "Bottom Right" }
];
const USERNAME_REGEX = /^[a-zA-Z0-9_]{3,20}$/;
function getCsrfToken$1() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
async function botHeaders(extra = {}, captcha = {}) {
  const fingerprint = await buildBotFingerprint();
  return {
    ...extra,
    "X-Bot-Fingerprint": fingerprint,
    ...captcha?.token ? { "X-Captcha-Token": captcha.token } : {}
  };
}
function toIsoDate(day, month, year) {
  if (!day || !month || !year) return "";
  return `${String(year).padStart(4, "0")}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
function fromIsoDate(iso) {
  if (!iso || typeof iso !== "string" || !iso.includes("-")) {
    return { day: "", month: "", year: "" };
  }
  const [year, month, day] = iso.split("-");
  return {
    day: String(parseInt(day || "", 10) || ""),
    month: String(parseInt(month || "", 10) || ""),
    year: String(year || "")
  };
}
function equalsObject(a, b2) {
  return JSON.stringify(a) === JSON.stringify(b2);
}
function positionToObjectPosition(position2) {
  const map = {
    "top-left": "0% 0%",
    top: "50% 0%",
    "top-right": "100% 0%",
    left: "0% 50%",
    center: "50% 50%",
    right: "100% 50%",
    "bottom-left": "0% 100%",
    bottom: "50% 100%",
    "bottom-right": "100% 100%"
  };
  return map[position2] || "50% 50%";
}
function SuccessMessage({ text: text2, className = "" }) {
  if (!text2) return null;
  return /* @__PURE__ */ React.createElement("div", { className: `flex items-center gap-2.5 rounded-xl border border-emerald-400/25 bg-emerald-500/10 px-4 py-2.5 text-sm text-emerald-300 animate-in fade-in ${className}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-check shrink-0 text-emerald-400" }), /* @__PURE__ */ React.createElement("span", null, text2));
}
function ErrorMessage({ text: text2, className = "" }) {
  if (!text2) return null;
  return /* @__PURE__ */ React.createElement("div", { className: `flex items-center gap-2.5 rounded-xl border border-red-400/25 bg-red-500/10 px-4 py-2.5 text-sm text-red-300 ${className}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-exclamation shrink-0 text-red-400" }), /* @__PURE__ */ React.createElement("span", null, text2));
}
function SectionCard$1({ title, description, icon, children, actionSlot }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/[0.06] bg-gradient-to-b from-white/[0.04] to-white/[0.02] p-6 shadow-lg shadow-black/10" }, /* @__PURE__ */ React.createElement("header", { className: "flex flex-col gap-4 border-b border-white/[0.06] px-1.5 pb-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, icon ? /* @__PURE__ */ React.createElement("span", { className: "flex h-9 w-9 shrink-0 items-center justify-center self-start rounded-xl bg-accent/10 text-accent md:self-center" }, /* @__PURE__ */ React.createElement("i", { className: `${icon} text-sm` })) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-base font-semibold text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, description) : null)), actionSlot ? /* @__PURE__ */ React.createElement("div", { className: "shrink-0 self-start md:self-center" }, actionSlot) : null), /* @__PURE__ */ React.createElement("div", { className: "px-1.5 pt-5" }, children));
}
function ProfileEdit() {
  const { props } = X$1();
  const {
    user,
    avatarUrl: initialAvatarUrl,
    birthDay,
    birthMonth,
    birthYear,
    countries = [],
    usernameCooldownDays = 30,
    usernameCooldownRemainingDays = 0,
    usernameCooldownActive = false,
    emailLoginUpgradeRequired: initialEmailLoginUpgradeRequired = false,
    forcedSection = null,
    captcha: initialCaptcha = {},
    flash = {}
  } = props;
  toIsoDate(
    birthDay ? parseInt(String(birthDay), 10) : "",
    birthMonth ? parseInt(String(birthMonth), 10) : "",
    birthYear ? String(birthYear) : ""
  );
  const [emailLoginUpgradeRequired, setEmailLoginUpgradeRequired] = reactExports.useState(!!initialEmailLoginUpgradeRequired);
  const [activeSection, setActiveSection] = reactExports.useState(forcedSection || "profile");
  const [profileForm, setProfileForm] = reactExports.useState({
    display_name: user?.name || "",
    website: user?.homepage || "",
    bio: user?.about_me || "",
    signature: user?.signature || "",
    description: user?.description || ""
  });
  const [accountForm, setAccountForm] = reactExports.useState({
    username: user?.username || "",
    email: user?.email || ""
  });
  const [usernameAvailability, setUsernameAvailability] = reactExports.useState({
    status: "idle",
    message: ""
  });
  const [showEmailChangeModal, setShowEmailChangeModal] = reactExports.useState(false);
  const [emailChangeStep, setEmailChangeStep] = reactExports.useState("request");
  const [emailChangeLoading, setEmailChangeLoading] = reactExports.useState(false);
  const [emailChangeForm, setEmailChangeForm] = reactExports.useState({
    new_email: "",
    code: ""
  });
  const [emailChangeError, setEmailChangeError] = reactExports.useState("");
  const [emailChangeInfo, setEmailChangeInfo] = reactExports.useState("");
  const [personalForm, setPersonalForm] = reactExports.useState(() => {
    const fromUser = fromIsoDate(user?.birthday || "");
    const fromProps = {
      day: birthDay ? String(parseInt(String(birthDay), 10) || "") : "",
      month: birthMonth ? String(parseInt(String(birthMonth), 10) || "") : "",
      year: birthYear ? String(birthYear) : ""
    };
    return {
      day: fromUser.day || fromProps.day || "",
      month: fromUser.month || fromProps.month || "",
      year: fromUser.year || fromProps.year || "",
      gender: String(user?.gender || "").toLowerCase() || "",
      country_id: user?.country_id ? String(user.country_id) : ""
    };
  });
  const [notificationForm, setNotificationForm] = reactExports.useState({
    email_notifications: !!user?.email_notifications,
    upload_notifications: !!user?.upload_notifications,
    follower_notifications: !!user?.follower_notifications,
    comment_notifications: !!user?.comment_notifications,
    newsletter: !!user?.newsletter
  });
  const [contentForm, setContentForm] = reactExports.useState({
    mature_content_visibility: user?.mature_content_visibility || "blur",
    mature_content_warning_enabled: user?.mature_content_warning_enabled !== false
  });
  const [securityForm, setSecurityForm] = reactExports.useState({
    current_password: "",
    new_password: "",
    new_password_confirmation: ""
  });
  const [savingSection, setSavingSection] = reactExports.useState("");
  const [savedMessage, setSavedMessage] = reactExports.useState({ section: "", text: "" });
  const [errorsBySection, setErrorsBySection] = reactExports.useState({
    profile: {},
    account: {},
    personal: {},
    notifications: {},
    content: {},
    security: {}
  });
  const [captchaState, setCaptchaState] = reactExports.useState({
    required: !!flash?.botCaptchaRequired,
    section: "",
    token: "",
    message: "",
    nonce: 0,
    provider: initialCaptcha?.provider || "",
    siteKey: initialCaptcha?.siteKey || "",
    inputName: initialCaptcha?.inputName || "cf-turnstile-response",
    scriptUrl: initialCaptcha?.scriptUrl || ""
  });
  const [avatarUrl, setAvatarUrl] = reactExports.useState(initialAvatarUrl || "");
  const [avatarFile, setAvatarFile] = reactExports.useState(null);
  const [avatarPosition, setAvatarPosition] = reactExports.useState("center");
  const [dragActive, setDragActive] = reactExports.useState(false);
  const [removeAvatar, setRemoveAvatar] = reactExports.useState(false);
  const avatarInputRef = reactExports.useRef(null);
  const [showDeleteModal, setShowDeleteModal] = reactExports.useState(false);
  const [deletePassword, setDeletePassword] = reactExports.useState("");
  const [deleteError, setDeleteError] = reactExports.useState("");
  const [deleting, setDeleting] = reactExports.useState(false);
  const settingsSections = reactExports.useMemo(() => {
    if (!emailLoginUpgradeRequired) {
      return SETTINGS_SECTIONS;
    }
    return SETTINGS_SECTIONS.filter((section) => section.key === "account");
  }, [emailLoginUpgradeRequired]);
  const initialRef = reactExports.useRef({
    profileForm,
    accountForm,
    personalForm,
    notificationForm,
    contentForm,
    avatarUrl: initialAvatarUrl || ""
  });
  const dirtyMap = reactExports.useMemo(() => {
    return {
      profile: !equalsObject(profileForm, initialRef.current.profileForm) || !!avatarFile || avatarFile && avatarPosition !== "center" || removeAvatar || avatarUrl !== initialRef.current.avatarUrl,
      account: !equalsObject(accountForm, initialRef.current.accountForm),
      personal: !equalsObject(personalForm, initialRef.current.personalForm),
      notifications: !equalsObject(notificationForm, initialRef.current.notificationForm),
      content: !equalsObject(contentForm, initialRef.current.contentForm),
      security: !!securityForm.current_password || !!securityForm.new_password || !!securityForm.new_password_confirmation,
      danger: false
    };
  }, [profileForm, accountForm, personalForm, notificationForm, contentForm, securityForm, avatarFile, avatarPosition, removeAvatar, avatarUrl]);
  const hasUnsavedChanges = reactExports.useMemo(
    () => Object.entries(dirtyMap).some(([key, dirty]) => key !== "danger" && dirty),
    [dirtyMap]
  );
  reactExports.useEffect(() => {
    const beforeUnload = (event) => {
      if (!hasUnsavedChanges) return;
      event.preventDefault();
      event.returnValue = "";
    };
    window.addEventListener("beforeunload", beforeUnload);
    return () => window.removeEventListener("beforeunload", beforeUnload);
  }, [hasUnsavedChanges]);
  reactExports.useEffect(() => {
    if (!emailLoginUpgradeRequired) {
      return;
    }
    setActiveSection("account");
  }, [emailLoginUpgradeRequired]);
  reactExports.useEffect(() => {
    if (usernameCooldownActive) {
      setUsernameAvailability({ status: "idle", message: "" });
      return;
    }
    if (emailLoginUpgradeRequired) {
      setUsernameAvailability({ status: "idle", message: "" });
      return;
    }
    const candidate = String(accountForm.username || "").trim().toLowerCase();
    const current = String(initialRef.current.accountForm.username || "").trim().toLowerCase();
    if (!candidate || candidate === current) {
      setUsernameAvailability({ status: "idle", message: "" });
      return;
    }
    if (!USERNAME_REGEX.test(candidate)) {
      setUsernameAvailability({ status: "invalid", message: "Use 3-20 letters, numbers, or underscores." });
      return;
    }
    setUsernameAvailability({ status: "checking", message: "Checking availability..." });
    const controller = new AbortController();
    const timeout = window.setTimeout(async () => {
      try {
        const response = await fetch(`/api/username/check?username=${encodeURIComponent(candidate)}`, {
          credentials: "same-origin",
          headers: { Accept: "application/json" },
          signal: controller.signal
        });
        const payload = await response.json().catch(() => ({}));
        if (!response.ok) {
          const msg = payload?.errors?.username?.[0] || "Username is not available.";
          setUsernameAvailability({ status: "invalid", message: msg });
          return;
        }
        if (payload.available) {
          setUsernameAvailability({ status: "available", message: "Username is available." });
          return;
        }
        setUsernameAvailability({ status: "taken", message: "Username is already taken." });
      } catch (error) {
        if (error?.name !== "AbortError") {
          setUsernameAvailability({ status: "invalid", message: "Unable to check username right now." });
        }
      }
    }, 300);
    return () => {
      controller.abort();
      window.clearTimeout(timeout);
    };
  }, [accountForm.username, usernameCooldownActive, emailLoginUpgradeRequired]);
  const openEmailChangeModal = () => {
    setShowEmailChangeModal(true);
    setEmailChangeStep("request");
    setEmailChangeError("");
    setEmailChangeInfo("");
    setEmailChangeForm({ new_email: "", code: "" });
  };
  const closeEmailChangeModal = () => {
    if (emailChangeLoading) return;
    setShowEmailChangeModal(false);
    setEmailChangeStep("request");
    setEmailChangeError("");
    setEmailChangeInfo("");
    setEmailChangeForm({ new_email: "", code: "" });
  };
  const countryOptions = (countries || []).map((c) => ({
    value: String(c.id || ""),
    label: c.name || "",
    iso2: c.iso2 || "",
    flagEmoji: c.flag_emoji || "",
    flagPath: c.flag_path || "",
    group: c.is_featured ? "Featured" : "All countries"
  }));
  const yearOptions = reactExports.useMemo(() => {
    const current = (/* @__PURE__ */ new Date()).getFullYear();
    return Array.from({ length: 100 }, (_2, index2) => {
      const year = String(current - index2);
      return { value: year, label: year };
    });
  }, []);
  const dayOptions = reactExports.useMemo(
    () => Array.from({ length: 31 }, (_2, i) => ({ value: String(i + 1), label: String(i + 1) })),
    []
  );
  const clearSectionStatus = (section) => {
    setSavedMessage((prev) => prev.section === section ? { section: "", text: "" } : prev);
    setErrorsBySection((prev) => ({ ...prev, [section]: {} }));
  };
  const resetCaptchaState = () => {
    setCaptchaState((prev) => ({
      ...prev,
      required: false,
      section: "",
      token: "",
      message: "",
      nonce: prev.nonce + 1
    }));
  };
  const captureCaptchaRequirement = (section, payload = {}) => {
    const requiresCaptcha = !!(payload?.requires_captcha || payload?.requiresCaptcha);
    if (!requiresCaptcha) {
      return false;
    }
    const nextCaptcha = payload?.captcha || {};
    const message = payload?.errors?.captcha?.[0] || payload?.message || "Complete the captcha challenge to continue.";
    setCaptchaState((prev) => ({
      required: true,
      section,
      token: "",
      message,
      nonce: prev.nonce + 1,
      provider: nextCaptcha.provider || payload?.captcha_provider || prev.provider || initialCaptcha?.provider || "turnstile",
      siteKey: nextCaptcha.siteKey || payload?.captcha_site_key || prev.siteKey || initialCaptcha?.siteKey || "",
      inputName: nextCaptcha.inputName || payload?.captcha_input || prev.inputName || initialCaptcha?.inputName || "cf-turnstile-response",
      scriptUrl: nextCaptcha.scriptUrl || payload?.captcha_script_url || prev.scriptUrl || initialCaptcha?.scriptUrl || ""
    }));
    updateSectionErrors(section, {
      _general: [message],
      captcha: [message]
    });
    return true;
  };
  const applyCaptchaPayload = (payload = {}) => {
    if (!captchaState.required || !captchaState.inputName) {
      return payload;
    }
    return {
      ...payload,
      [captchaState.inputName]: captchaState.token || ""
    };
  };
  const applyCaptchaFormData = (formData) => {
    if (captchaState.required && captchaState.inputName) {
      formData.set(captchaState.inputName, captchaState.token || "");
    }
  };
  const renderCaptchaChallenge = (section, placement = "section") => {
    if (!captchaState.required || !captchaState.siteKey || activeSection !== section) {
      return null;
    }
    if (section === "account" && showEmailChangeModal && placement !== "modal") {
      return null;
    }
    if (section === "account" && !showEmailChangeModal && placement === "modal") {
      return null;
    }
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-amber-400/20 bg-amber-500/10 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-sm text-amber-100" }, captchaState.message || "Complete the captcha challenge to continue."), /* @__PURE__ */ React.createElement(
      TurnstileField,
      {
        key: `${section}-${placement}-${captchaState.nonce}`,
        provider: captchaState.provider,
        siteKey: captchaState.siteKey,
        scriptUrl: captchaState.scriptUrl,
        onToken: (token) => setCaptchaState((prev) => ({ ...prev, token })),
        className: "rounded-lg border border-white/10 bg-black/20 p-3"
      }
    ));
  };
  const switchSection = (nextSection) => {
    if (emailLoginUpgradeRequired && nextSection !== "account") {
      return;
    }
    if (activeSection === nextSection) return;
    if (dirtyMap[activeSection]) {
      const shouldContinue = window.confirm("You have unsaved changes in this section. Leave without saving?");
      if (!shouldContinue) return;
    }
    setActiveSection(nextSection);
  };
  const handleAvatarSelect = (file) => {
    if (!file) return;
    if (!file.type.startsWith("image/")) return;
    setAvatarFile(file);
    setRemoveAvatar(false);
    setAvatarUrl(URL.createObjectURL(file));
    clearSectionStatus("profile");
  };
  const dragHandler = (event) => {
    event.preventDefault();
    event.stopPropagation();
  };
  const handleDrop = (event) => {
    dragHandler(event);
    setDragActive(false);
    const file = event.dataTransfer?.files?.[0];
    if (file) handleAvatarSelect(file);
  };
  const updateSectionErrors = (section, errors = {}) => {
    setErrorsBySection((prev) => ({ ...prev, [section]: errors }));
  };
  const saveProfileSection = async (event) => {
    event.preventDefault();
    setSavingSection("profile");
    clearSectionStatus("profile");
    try {
      const formData = new FormData();
      formData.append("display_name", profileForm.display_name || "");
      formData.append("website", profileForm.website || "");
      formData.append("bio", profileForm.bio || "");
      formData.append("signature", profileForm.signature || "");
      formData.append("description", profileForm.description || "");
      formData.append("remove_avatar", removeAvatar ? "1" : "0");
      formData.append("avatar_position", avatarPosition);
      if (avatarFile) {
        formData.append("avatar", avatarFile);
      }
      applyCaptchaFormData(formData);
      const response = await fetch("/settings/profile/update", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: formData
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("profile", payload)) {
          return;
        }
        updateSectionErrors("profile", payload.errors || { _general: [payload.message || "Unable to save profile section."] });
        return;
      }
      const nextAvatarUrl = payload.avatarUrl || avatarUrl || initialAvatarUrl;
      initialRef.current.profileForm = { ...profileForm };
      initialRef.current.avatarUrl = nextAvatarUrl || "";
      setAvatarUrl(nextAvatarUrl || "");
      setAvatarFile(null);
      setAvatarPosition("center");
      setRemoveAvatar(false);
      resetCaptchaState();
      setSavedMessage({ section: "profile", text: payload.message || "Profile updated successfully." });
    } catch (error) {
      updateSectionErrors("profile", { _general: ["Request failed. Please try again."] });
    } finally {
      setSavingSection("");
    }
  };
  const saveAccountSection = async (event) => {
    event.preventDefault();
    if (emailLoginUpgradeRequired) {
      return;
    }
    if (usernameCooldownActive && accountForm.username !== initialRef.current.accountForm.username) {
      updateSectionErrors("account", {
        username: [`Username can be changed again in ${usernameCooldownRemainingDays} days.`]
      });
      return;
    }
    setSavingSection("account");
    clearSectionStatus("account");
    try {
      const response = await fetch("/settings/account/username", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({ username: accountForm.username, homepage_url: "" }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("account", payload)) {
          return;
        }
        updateSectionErrors("account", payload.errors || { _general: [payload.message || "Unable to save account section."] });
        return;
      }
      initialRef.current.accountForm = { ...accountForm };
      resetCaptchaState();
      setSavedMessage({ section: "account", text: payload.message || "Account updated successfully." });
    } catch (error) {
      updateSectionErrors("account", { _general: ["Request failed. Please try again."] });
    } finally {
      setSavingSection("");
    }
  };
  const requestEmailChange = async () => {
    setEmailChangeLoading(true);
    setEmailChangeError("");
    setEmailChangeInfo("");
    try {
      const response = await fetch("/settings/email/request", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({ new_email: emailChangeForm.new_email, homepage_url: "" }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("account", payload)) {
          setEmailChangeError(payload?.errors?.captcha?.[0] || payload?.message || "Complete the captcha challenge to continue.");
          return;
        }
        setEmailChangeError(payload?.errors?.new_email?.[0] || payload?.message || "Unable to request email change.");
        return;
      }
      setEmailChangeStep("verify");
      resetCaptchaState();
      setEmailChangeInfo(payload.message || "Verification code sent to your new email address.");
    } catch (error) {
      setEmailChangeError("Request failed. Please try again.");
    } finally {
      setEmailChangeLoading(false);
    }
  };
  const verifyEmailChange = async () => {
    setEmailChangeLoading(true);
    setEmailChangeError("");
    setEmailChangeInfo("");
    try {
      const response = await fetch("/settings/email/verify", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({ code: emailChangeForm.code, homepage_url: "" }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("account", payload)) {
          setEmailChangeError(payload?.errors?.captcha?.[0] || payload?.message || "Complete the captcha challenge to continue.");
          return;
        }
        setEmailChangeError(payload?.errors?.code?.[0] || payload?.message || "Verification failed.");
        return;
      }
      const nextEmail = payload.email || emailChangeForm.new_email;
      setAccountForm((prev) => ({ ...prev, email: nextEmail }));
      initialRef.current.accountForm = { ...initialRef.current.accountForm, email: nextEmail };
      setEmailLoginUpgradeRequired(false);
      setShowEmailChangeModal(false);
      setEmailChangeStep("request");
      setEmailChangeForm({ new_email: "", code: "" });
      resetCaptchaState();
      setSavedMessage({ section: "account", text: payload.message || "Email updated successfully." });
    } catch (error) {
      setEmailChangeError("Request failed. Please try again.");
    } finally {
      setEmailChangeLoading(false);
    }
  };
  const savePersonalSection = async (event) => {
    event.preventDefault();
    setSavingSection("personal");
    clearSectionStatus("personal");
    try {
      const response = await fetch("/settings/personal/update", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({
          birthday: toIsoDate(personalForm.day, personalForm.month, personalForm.year) || null,
          gender: personalForm.gender || null,
          country_id: personalForm.country_id || null,
          homepage_url: ""
        }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("personal", payload)) {
          return;
        }
        updateSectionErrors("personal", payload.errors || { _general: [payload.message || "Unable to save personal details."] });
        return;
      }
      initialRef.current.personalForm = { ...personalForm };
      resetCaptchaState();
      setSavedMessage({ section: "personal", text: payload.message || "Personal details saved successfully." });
    } catch (error) {
      updateSectionErrors("personal", { _general: ["Request failed. Please try again."] });
    } finally {
      setSavingSection("");
    }
  };
  const saveNotificationsSection = async (event) => {
    event.preventDefault();
    setSavingSection("notifications");
    clearSectionStatus("notifications");
    try {
      const response = await fetch("/settings/notifications/update", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({ ...notificationForm, homepage_url: "" }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("notifications", payload)) {
          return;
        }
        updateSectionErrors("notifications", payload.errors || { _general: [payload.message || "Unable to save notifications."] });
        return;
      }
      initialRef.current.notificationForm = { ...notificationForm };
      resetCaptchaState();
      setSavedMessage({ section: "notifications", text: payload.message || "Notification settings saved successfully." });
    } catch (error) {
      updateSectionErrors("notifications", { _general: ["Request failed. Please try again."] });
    } finally {
      setSavingSection("");
    }
  };
  const saveContentSection = async (event) => {
    event.preventDefault();
    setSavingSection("content");
    clearSectionStatus("content");
    try {
      const response = await fetch("/settings/content/update", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({ ...contentForm, homepage_url: "" }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("content", payload)) {
          return;
        }
        updateSectionErrors("content", payload.errors || { _general: [payload.message || "Unable to save content settings."] });
        return;
      }
      initialRef.current.contentForm = { ...contentForm };
      resetCaptchaState();
      setSavedMessage({ section: "content", text: payload.message || "Content settings saved successfully." });
    } catch (error) {
      updateSectionErrors("content", { _general: ["Request failed. Please try again."] });
    } finally {
      setSavingSection("");
    }
  };
  const saveSecuritySection = async (event) => {
    event.preventDefault();
    setSavingSection("security");
    clearSectionStatus("security");
    try {
      const response = await fetch("/settings/security/password", {
        method: "POST",
        credentials: "same-origin",
        headers: await botHeaders({
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        }, captchaState),
        body: JSON.stringify(applyCaptchaPayload({ ...securityForm, homepage_url: "" }))
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        if (captureCaptchaRequirement("security", payload)) {
          return;
        }
        updateSectionErrors("security", payload.errors || { _general: [payload.message || "Unable to update password."] });
        return;
      }
      setSecurityForm({
        current_password: "",
        new_password: "",
        new_password_confirmation: ""
      });
      resetCaptchaState();
      setSavedMessage({ section: "security", text: payload.message || "Password updated successfully." });
    } catch (error) {
      updateSectionErrors("security", { _general: ["Request failed. Please try again."] });
    } finally {
      setSavingSection("");
    }
  };
  const handleDeleteAccount = async () => {
    setDeleting(true);
    setDeleteError("");
    try {
      const response = await fetch("/profile", {
        method: "DELETE",
        credentials: "same-origin",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          "X-CSRF-TOKEN": getCsrfToken$1()
        },
        body: JSON.stringify({ password: deletePassword })
      });
      if (response.ok || response.status === 302) {
        window.location.href = "/";
        return;
      }
      const payload = await response.json().catch(() => ({}));
      setDeleteError(payload.errors?.password?.[0] || payload.message || "Deletion failed.");
    } catch (error) {
      setDeleteError("Request failed.");
    } finally {
      setDeleting(false);
    }
  };
  reactExports.useEffect(() => {
    if (!savedMessage.text) return;
    const timer = window.setTimeout(() => {
      setSavedMessage({ section: "", text: "" });
    }, 4e3);
    return () => window.clearTimeout(timer);
  }, [savedMessage]);
  const sectionSaved = savedMessage.section === activeSection ? savedMessage.text : "";
  return /* @__PURE__ */ React.createElement(
    SettingsLayout,
    {
      title: "Settings",
      sections: settingsSections,
      activeSection,
      onSectionChange: switchSection,
      dirtyMap
    },
    /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, activeSection === "profile" ? /* @__PURE__ */ React.createElement("form", { className: "space-y-4", onSubmit: saveProfileSection }, /* @__PURE__ */ React.createElement(
      SectionCard$1,
      {
        title: "Profile",
        icon: "fa-solid fa-user-astronaut",
        description: "Manage your public identity and profile presentation.",
        actionSlot: /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "accent", size: "sm", loading: savingSection === "profile" }, "Save Profile")
      },
      /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 lg:grid-cols-[260px,1fr]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement(
        "div",
        {
          className: `group relative rounded-2xl border border-white/10 bg-black/20 p-5 transition-colors duration-200 ${dragActive ? "border-accent/50 bg-accent/5" : ""}`,
          onDragEnter: (e) => {
            dragHandler(e);
            setDragActive(true);
          },
          onDragLeave: (e) => {
            dragHandler(e);
            setDragActive(false);
          },
          onDragOver: dragHandler,
          onDrop: handleDrop
        },
        /* @__PURE__ */ React.createElement("div", { className: "relative mx-auto", style: { width: 144, height: 144 } }, /* @__PURE__ */ React.createElement(
          "div",
          {
            className: "overflow-hidden rounded-full border-2 border-white/10 bg-white/5 shadow-lg shadow-black/20",
            style: { width: 144, height: 144, minWidth: 144, minHeight: 144 }
          },
          avatarUrl ? /* @__PURE__ */ React.createElement(
            "img",
            {
              src: avatarUrl,
              alt: "Avatar preview",
              className: "block h-full w-full object-cover object-center",
              style: { aspectRatio: "1 / 1", objectPosition: positionToObjectPosition(avatarPosition) }
            }
          ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full flex-col items-center justify-center gap-1 text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-camera text-xl" }), /* @__PURE__ */ React.createElement("span", { className: "text-[11px]" }, "No avatar"))
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => avatarInputRef.current?.click(),
            className: "absolute inset-0 flex cursor-pointer flex-col items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-opacity duration-200 hover:opacity-100 focus-visible:opacity-100",
            "aria-label": "Upload avatar"
          },
          /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-camera-retro text-lg" }),
          /* @__PURE__ */ React.createElement("span", { className: "mt-1 text-xs font-medium" }, "Change")
        )),
        /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-center text-xs text-slate-500" }, "256 × 256 recommended · JPG, PNG, WEBP"),
        /* @__PURE__ */ React.createElement(
          "input",
          {
            ref: avatarInputRef,
            type: "file",
            className: "hidden",
            accept: "image/jpeg,image/png,image/webp",
            onChange: (e) => handleAvatarSelect(e.target.files?.[0])
          }
        ),
        /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-center gap-2" }, /* @__PURE__ */ React.createElement(
          Button$1,
          {
            type: "button",
            size: "xs",
            variant: "secondary",
            onClick: () => avatarInputRef.current?.click(),
            leftIcon: /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-from-bracket text-[10px]" })
          },
          "Upload"
        ), avatarUrl ? /* @__PURE__ */ React.createElement(
          Button$1,
          {
            type: "button",
            size: "xs",
            variant: "ghost",
            onClick: () => {
              setAvatarFile(null);
              setRemoveAvatar(true);
              setAvatarUrl("");
            },
            leftIcon: /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can text-[10px]" })
          },
          "Remove"
        ) : null)
      ), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-black/20 p-3" }, /* @__PURE__ */ React.createElement(
        NovaSelect,
        {
          label: "Avatar crop position",
          placeholder: "Select crop position",
          value: avatarPosition,
          onChange: (nextValue) => {
            setAvatarPosition(nextValue);
            clearSectionStatus("profile");
          },
          options: AVATAR_POSITION_OPTIONS,
          searchable: false,
          hint: "Applies when saving a newly selected avatar"
        }
      ))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(ErrorMessage, { text: errorsBySection.profile._general?.[0] }), /* @__PURE__ */ React.createElement(SuccessMessage, { text: sectionSaved }), /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Display Name",
          value: profileForm.display_name,
          onChange: (e) => {
            setProfileForm((prev) => ({ ...prev, display_name: e.target.value }));
            clearSectionStatus("profile");
          },
          error: errorsBySection.profile.display_name?.[0],
          maxLength: 60,
          required: true
        }
      ), /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Website",
          value: profileForm.website,
          onChange: (e) => {
            setProfileForm((prev) => ({ ...prev, website: e.target.value }));
            clearSectionStatus("profile");
          },
          placeholder: "https://",
          error: errorsBySection.profile.website?.[0]
        }
      ), /* @__PURE__ */ React.createElement(
        Textarea,
        {
          label: "Bio",
          value: profileForm.bio,
          onChange: (e) => {
            setProfileForm((prev) => ({ ...prev, bio: e.target.value }));
            clearSectionStatus("profile");
          },
          rows: 4,
          maxLength: 200,
          error: errorsBySection.profile.bio?.[0],
          hint: `${(profileForm.bio || "").length}/200`
        }
      ), /* @__PURE__ */ React.createElement(
        Textarea,
        {
          label: "Signature",
          value: profileForm.signature,
          onChange: (e) => {
            setProfileForm((prev) => ({ ...prev, signature: e.target.value }));
            clearSectionStatus("profile");
          },
          rows: 3,
          error: errorsBySection.profile.signature?.[0]
        }
      ), /* @__PURE__ */ React.createElement(
        Textarea,
        {
          label: "Description",
          value: profileForm.description,
          onChange: (e) => {
            setProfileForm((prev) => ({ ...prev, description: e.target.value }));
            clearSectionStatus("profile");
          },
          rows: 3,
          error: errorsBySection.profile.description?.[0]
        }
      ), renderCaptchaChallenge("profile")))
    )) : null, activeSection === "account" ? /* @__PURE__ */ React.createElement("form", { className: "space-y-4", onSubmit: saveAccountSection }, /* @__PURE__ */ React.createElement(
      SectionCard$1,
      {
        title: emailLoginUpgradeRequired ? "Finish Email Upgrade" : "Account",
        icon: "fa-solid fa-id-badge",
        description: emailLoginUpgradeRequired ? "Add and verify a real email address. Once completed, email becomes your only login identifier." : "Update your core account identity details.",
        actionSlot: !emailLoginUpgradeRequired ? /* @__PURE__ */ React.createElement(
          Button$1,
          {
            type: "submit",
            variant: "accent",
            size: "sm",
            loading: savingSection === "account",
            disabled: usernameCooldownActive
          },
          "Save Username"
        ) : null
      },
      /* @__PURE__ */ React.createElement(ErrorMessage, { text: errorsBySection.account._general?.[0], className: "mb-4" }),
      /* @__PURE__ */ React.createElement(SuccessMessage, { text: sectionSaved, className: "mb-4" }),
      emailLoginUpgradeRequired ? /* @__PURE__ */ React.createElement("div", { className: "mb-4 rounded-2xl border border-amber-400/30 bg-amber-500/10 p-4 text-sm text-amber-100" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-envelope-circle-check mt-0.5 shrink-0 text-amber-300" }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-amber-200" }, "Email upgrade required"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-amber-100/90" }, "This account was migrated without a real email address. Add a valid email, enter the verification code, and future sign-ins will use email only.")))) : null,
      /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Username",
          value: accountForm.username,
          onChange: (e) => {
            setAccountForm((prev) => ({ ...prev, username: e.target.value }));
            clearSectionStatus("account");
          },
          disabled: emailLoginUpgradeRequired || usernameCooldownActive,
          error: errorsBySection.account.username?.[0],
          hint: emailLoginUpgradeRequired ? "Username login is temporary. Complete the email upgrade to switch this account to email-only sign-in." : usernameCooldownActive ? `Username can be changed again in ${usernameCooldownRemainingDays} days.` : "Allowed: letters, numbers, underscores (3-20).",
          required: true
        }
      ), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs uppercase tracking-wide text-slate-400" }, emailLoginUpgradeRequired ? "Primary Login Email" : "Current Email"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm font-medium text-white" }, accountForm.email || "No email set"), emailLoginUpgradeRequired ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-slate-400" }, "The current value is temporary. Replace it with a real email address to finish the upgrade.") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement(Button$1, { type: "button", variant: emailLoginUpgradeRequired ? "accent" : "secondary", size: "sm", onClick: openEmailChangeModal }, emailLoginUpgradeRequired ? "Add Primary Email" : "Change Email")))),
      !emailLoginUpgradeRequired && usernameAvailability.status !== "idle" ? /* @__PURE__ */ React.createElement(
        "p",
        {
          className: `mt-4 flex items-center gap-2 rounded-xl border px-3 py-2 text-xs ${usernameAvailability.status === "available" ? "border-emerald-400/30 bg-emerald-500/10 text-emerald-300" : usernameAvailability.status === "checking" ? "border-sky-400/30 bg-sky-500/10 text-sky-300" : "border-red-400/30 bg-red-500/10 text-red-300"}`
        },
        /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${usernameAvailability.status === "available" ? "fa-circle-check" : usernameAvailability.status === "checking" ? "fa-spinner fa-spin" : "fa-circle-xmark"} shrink-0` }),
        usernameAvailability.message
      ) : null,
      !emailLoginUpgradeRequired ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 flex items-center gap-2 rounded-xl border border-white/[0.06] bg-white/[0.02] px-3 py-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-clock shrink-0 text-slate-500" }), "You can change your username once every ", usernameCooldownDays, " days.") : null,
      renderCaptchaChallenge("account")
    )) : null, activeSection === "personal" ? /* @__PURE__ */ React.createElement("form", { className: "space-y-4", onSubmit: savePersonalSection }, /* @__PURE__ */ React.createElement(
      SectionCard$1,
      {
        title: "Personal Details",
        icon: "fa-solid fa-address-card",
        description: "Optional information shown only when you decide to provide it.",
        actionSlot: /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "accent", size: "sm", loading: savingSection === "personal" }, "Save Personal Details")
      },
      /* @__PURE__ */ React.createElement(ErrorMessage, { text: errorsBySection.personal._general?.[0], className: "mb-4" }),
      /* @__PURE__ */ React.createElement(SuccessMessage, { text: sectionSaved, className: "mb-4" }),
      /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-1.5 block text-sm font-medium text-white/85" }, "Birthday"), /* @__PURE__ */ React.createElement("div", { className: "grid max-w-lg grid-cols-3 gap-3" }, /* @__PURE__ */ React.createElement(
        NovaSelect,
        {
          placeholder: "Day",
          value: personalForm.day,
          onChange: (nextValue) => {
            setPersonalForm((prev) => ({ ...prev, day: nextValue ?? "" }));
            clearSectionStatus("personal");
          },
          options: dayOptions,
          searchable: false
        }
      ), /* @__PURE__ */ React.createElement(
        NovaSelect,
        {
          placeholder: "Month",
          value: personalForm.month,
          onChange: (nextValue) => {
            setPersonalForm((prev) => ({ ...prev, month: nextValue ?? "" }));
            clearSectionStatus("personal");
          },
          options: MONTHS,
          searchable: false
        }
      ), /* @__PURE__ */ React.createElement(
        NovaSelect,
        {
          placeholder: "Year",
          value: personalForm.year,
          onChange: (nextValue) => {
            setPersonalForm((prev) => ({ ...prev, year: nextValue ?? "" }));
            clearSectionStatus("personal");
          },
          options: yearOptions,
          searchable: false
        }
      )), errorsBySection.personal.birthday?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-red-300" }, errorsBySection.personal.birthday[0]) : null), /* @__PURE__ */ React.createElement(
        RadioGroup,
        {
          label: "Gender",
          name: "gender",
          options: GENDER_OPTIONS,
          value: personalForm.gender,
          onChange: (value) => {
            setPersonalForm((prev) => ({ ...prev, gender: value }));
            clearSectionStatus("personal");
          },
          direction: "horizontal",
          error: errorsBySection.personal.gender?.[0]
        }
      ), countryOptions.length > 0 ? /* @__PURE__ */ React.createElement(
        NovaSelect,
        {
          label: "Country",
          value: personalForm.country_id || null,
          onChange: (value) => {
            setPersonalForm((prev) => ({ ...prev, country_id: value ? String(value) : "" }));
            clearSectionStatus("personal");
          },
          options: countryOptions,
          placeholder: "Choose country",
          clearable: true,
          error: errorsBySection.personal.country_id?.[0] || errorsBySection.personal.country?.[0],
          hint: "Search by country name or ISO code.",
          renderOption: (option) => /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-center gap-2" }, option.flagPath ? /* @__PURE__ */ React.createElement(
            "img",
            {
              src: option.flagPath,
              alt: "",
              className: "h-4 w-6 rounded-sm object-cover",
              onError: (event) => {
                event.currentTarget.style.display = "none";
              }
            }
          ) : option.flagEmoji ? /* @__PURE__ */ React.createElement("span", null, option.flagEmoji) : null, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, option.label), option.iso2 ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 text-[11px] uppercase text-slate-500" }, option.iso2) : null)
        }
      ) : /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-400" }, "Country list is currently unavailable."), renderCaptchaChallenge("personal"))
    )) : null, activeSection === "notifications" ? /* @__PURE__ */ React.createElement("form", { className: "space-y-4", onSubmit: saveNotificationsSection }, /* @__PURE__ */ React.createElement(
      SectionCard$1,
      {
        title: "Notifications",
        icon: "fa-solid fa-bell",
        description: "Choose how and when Skinbase should notify you.",
        actionSlot: /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "accent", size: "sm", loading: savingSection === "notifications" }, "Save Notification Settings")
      },
      /* @__PURE__ */ React.createElement(ErrorMessage, { text: errorsBySection.notifications._general?.[0], className: "mb-4" }),
      /* @__PURE__ */ React.createElement(SuccessMessage, { text: sectionSaved, className: "mb-4" }),
      /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, [
        ["email_notifications", "Email notifications", "General email alerts for account activity.", "fa-solid fa-envelope"],
        ["upload_notifications", "Upload notifications", "Notify me when followed creators upload.", "fa-solid fa-cloud-arrow-up"],
        ["follower_notifications", "Follower notifications", "Notify me when someone follows me.", "fa-solid fa-user-plus"],
        ["comment_notifications", "Comment notifications", "Notify me about comments on my content.", "fa-solid fa-comment-dots"],
        ["newsletter", "Newsletter", "Receive occasional community and product updates.", "fa-solid fa-newspaper"]
      ].map(([field, label, hint, icon]) => /* @__PURE__ */ React.createElement("div", { key: field, className: "flex items-center gap-3 rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3 transition-colors hover:bg-white/[0.04]" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/[0.06] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `${icon} text-xs` })), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/90" }, label), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, hint)), /* @__PURE__ */ React.createElement(
        Checkbox,
        {
          checked: !!notificationForm[field],
          onChange: (e) => {
            setNotificationForm((prev) => ({ ...prev, [field]: e.target.checked }));
            clearSectionStatus("notifications");
          },
          "aria-label": label,
          variant: "accent",
          size: 20
        }
      ))), renderCaptchaChallenge("notifications"))
    )) : null, activeSection === "content" ? /* @__PURE__ */ React.createElement("form", { className: "space-y-4", onSubmit: saveContentSection }, /* @__PURE__ */ React.createElement(
      SectionCard$1,
      {
        title: "Content Preferences",
        icon: "fa-solid fa-eye-low-vision",
        description: "Decide how mature artworks should appear in listings and artwork detail pages.",
        actionSlot: /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "accent", size: "sm", loading: savingSection === "content" }, "Save Content Settings")
      },
      /* @__PURE__ */ React.createElement(ErrorMessage, { text: errorsBySection.content._general?.[0], className: "mb-4" }),
      /* @__PURE__ */ React.createElement(SuccessMessage, { text: sectionSaved, className: "mb-4" }),
      /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-1.5 block text-sm font-medium text-white/85" }, "Mature artwork visibility"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, MATURE_VISIBILITY_OPTIONS.map((option) => {
        const isActive = contentForm.mature_content_visibility === option.value;
        return /* @__PURE__ */ React.createElement(
          "button",
          {
            key: option.value,
            type: "button",
            onClick: () => {
              setContentForm((prev) => ({ ...prev, mature_content_visibility: option.value }));
              clearSectionStatus("content");
            },
            className: `rounded-2xl border px-4 py-3 text-left transition ${isActive ? "border-amber-300/50 bg-amber-400/10 text-white shadow-[0_0_0_1px_rgba(251,191,36,0.15)]" : "border-white/[0.08] bg-white/[0.02] text-slate-300 hover:bg-white/[0.04]"}`
          },
          /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg ${isActive ? "bg-amber-300/15 text-amber-200" : "bg-white/[0.06] text-slate-400"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${option.value === "hide" ? "fa-eye-slash" : option.value === "blur" ? "fa-droplet-slash" : "fa-eye"}` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium" }, option.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, option.hint)))
        );
      })), errorsBySection.content.mature_content_visibility?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-red-300" }, errorsBySection.content.mature_content_visibility[0]) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3 transition-colors hover:bg-white/[0.04]" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-white/[0.06] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-triangle-exclamation text-xs" })), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white/90" }, "Show warning before opening mature artwork pages"), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Display an interstitial on artwork detail pages before revealing mature media.")), /* @__PURE__ */ React.createElement(
        Checkbox,
        {
          checked: !!contentForm.mature_content_warning_enabled,
          onChange: (e) => {
            setContentForm((prev) => ({ ...prev, mature_content_warning_enabled: e.target.checked }));
            clearSectionStatus("content");
          },
          "aria-label": "Show warning before opening mature artwork pages",
          variant: "accent",
          size: 20
        }
      )), errorsBySection.content.mature_content_warning_enabled?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-red-300" }, errorsBySection.content.mature_content_warning_enabled[0]) : null, renderCaptchaChallenge("content"))
    )) : null, activeSection === "security" ? /* @__PURE__ */ React.createElement("form", { className: "space-y-4", onSubmit: saveSecuritySection }, /* @__PURE__ */ React.createElement(
      SectionCard$1,
      {
        title: "Security",
        icon: "fa-solid fa-shield-halved",
        description: "Update password. Additional security controls can be added here later.",
        actionSlot: /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "accent", size: "sm", loading: savingSection === "security" }, "Update Password")
      },
      /* @__PURE__ */ React.createElement(ErrorMessage, { text: errorsBySection.security._general?.[0], className: "mb-4" }),
      /* @__PURE__ */ React.createElement(SuccessMessage, { text: sectionSaved, className: "mb-4" }),
      /* @__PURE__ */ React.createElement("div", { className: "grid max-w-2xl gap-4" }, /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Current Password",
          type: "password",
          value: securityForm.current_password,
          onChange: (e) => {
            setSecurityForm((prev) => ({ ...prev, current_password: e.target.value }));
            clearSectionStatus("security");
          },
          error: errorsBySection.security.current_password?.[0],
          autoComplete: "current-password"
        }
      ), /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "New Password",
          type: "password",
          value: securityForm.new_password,
          onChange: (e) => {
            setSecurityForm((prev) => ({ ...prev, new_password: e.target.value }));
            clearSectionStatus("security");
          },
          error: errorsBySection.security.new_password?.[0],
          hint: "Minimum 8 characters",
          autoComplete: "new-password"
        }
      ), /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Confirm Password",
          type: "password",
          value: securityForm.new_password_confirmation,
          onChange: (e) => {
            setSecurityForm((prev) => ({ ...prev, new_password_confirmation: e.target.value }));
            clearSectionStatus("security");
          },
          error: errorsBySection.security.new_password_confirmation?.[0],
          autoComplete: "new-password"
        }
      ), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/[0.06] bg-white/[0.02] p-4" }, /* @__PURE__ */ React.createElement("p", { className: "flex items-center gap-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-lock text-slate-500" }), "Coming soon: Two-factor authentication, active sessions, and login history.")), renderCaptchaChallenge("security"))
    )) : null, activeSection === "danger" ? /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-red-500/20 bg-gradient-to-b from-red-500/[0.06] to-red-500/[0.02] p-6 shadow-lg shadow-red-900/10" }, /* @__PURE__ */ React.createElement("header", { className: "flex flex-col gap-3 border-b border-red-500/10 pb-4 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-red-500/15 text-red-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-triangle-exclamation text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-base font-semibold text-red-300" }, "Danger Zone"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-red-400/70" }, "These actions are permanent and cannot be undone.")))), /* @__PURE__ */ React.createElement("div", { className: "pt-5" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-red-500/15 bg-red-500/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-medium text-white" }, "Delete account"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, "Permanently removes your artworks, comments, followers, and all profile data.")), /* @__PURE__ */ React.createElement(Button$1, { variant: "danger", size: "sm", onClick: () => setShowDeleteModal(true) }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can mr-1.5 text-xs" }), "Delete Account"))))) : null),
    /* @__PURE__ */ React.createElement(
      Modal,
      {
        open: showEmailChangeModal,
        onClose: closeEmailChangeModal,
        title: emailLoginUpgradeRequired ? "Finish Email Upgrade" : "Change Email",
        size: "sm",
        closeOnBackdrop: !emailLoginUpgradeRequired,
        footer: /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-2" }, !emailLoginUpgradeRequired ? /* @__PURE__ */ React.createElement(Button$1, { type: "button", variant: "ghost", size: "sm", onClick: closeEmailChangeModal, disabled: emailChangeLoading }, "Cancel") : null, emailChangeStep === "request" ? /* @__PURE__ */ React.createElement(
          Button$1,
          {
            type: "button",
            variant: "accent",
            size: "sm",
            loading: emailChangeLoading,
            onClick: requestEmailChange
          },
          "Send Code"
        ) : /* @__PURE__ */ React.createElement(
          Button$1,
          {
            type: "button",
            variant: "accent",
            size: "sm",
            loading: emailChangeLoading,
            onClick: verifyEmailChange
          },
          "Verify and Update"
        ))
      },
      /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, emailLoginUpgradeRequired ? /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-sky-400/30 bg-sky-500/10 px-3 py-2 text-sm text-sky-200" }, "Add the email address you want to use for future sign-ins, then enter the verification code we send there.") : null, emailChangeError ? /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-red-400/30 bg-red-500/10 px-3 py-2 text-sm text-red-300" }, emailChangeError) : null, emailChangeInfo ? /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-emerald-400/30 bg-emerald-500/10 px-3 py-2 text-sm text-emerald-300" }, emailChangeInfo) : null, renderCaptchaChallenge("account", "modal"), emailChangeStep === "request" ? /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Enter new email address",
          type: "email",
          value: emailChangeForm.new_email,
          onChange: (e) => setEmailChangeForm((prev) => ({ ...prev, new_email: e.target.value })),
          autoComplete: "email",
          required: true
        }
      ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-300" }, "Enter the 6-digit verification code sent to ", emailChangeForm.new_email, "."), /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Verification Code",
          value: emailChangeForm.code,
          onChange: (e) => setEmailChangeForm((prev) => ({ ...prev, code: e.target.value })),
          inputMode: "numeric",
          maxLength: 6,
          required: true
        }
      )))
    ),
    /* @__PURE__ */ React.createElement(
      Modal,
      {
        open: showDeleteModal,
        onClose: () => setShowDeleteModal(false),
        title: "Delete Account",
        size: "sm",
        footer: /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-2" }, /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "sm", onClick: () => setShowDeleteModal(false) }, "Cancel"), /* @__PURE__ */ React.createElement(Button$1, { variant: "danger", size: "sm", loading: deleting, onClick: handleDeleteAccount }, "Permanently Delete"))
      },
      /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-300" }, "Confirm your password to permanently delete your account."), /* @__PURE__ */ React.createElement(
        TextInput,
        {
          label: "Password",
          type: "password",
          value: deletePassword,
          onChange: (e) => setDeletePassword(e.target.value),
          error: deleteError,
          autoComplete: "current-password"
        }
      ))
    )
  );
}
const __vite_glob_0_104 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: ProfileEdit
}, Symbol.toStringTag, { value: "Module" }));
function csrfToken() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function studioSurface(pathname = window.location.pathname) {
  return String(pathname || "/studio").split("?")[0] || "/studio";
}
function studioModule(pathname = window.location.pathname) {
  const segments = studioSurface(pathname).split("/").filter(Boolean);
  if (segments[0] !== "studio") {
    return null;
  }
  return segments[1] || "overview";
}
async function trackStudioEvent(eventType, payload = {}) {
  try {
    await fetch("/api/studio/events", {
      method: "POST",
      credentials: "same-origin",
      keepalive: true,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": csrfToken(),
        "X-Requested-With": "XMLHttpRequest"
      },
      body: JSON.stringify({
        event_type: eventType,
        ...payload
      })
    });
  } catch {
  }
}
const baseNavGroups = [
  {
    label: "Creator Studio",
    items: [
      { label: "Overview", href: "/studio", icon: "fa-solid fa-chart-line" },
      { label: "Search", href: "/studio/search", icon: "fa-solid fa-magnifying-glass" },
      { label: "Groups", href: "/studio/groups", icon: "fa-solid fa-people-group" }
    ]
  },
  {
    label: "Create",
    items: [
      { label: "New Artwork", href: "/upload", icon: "fa-solid fa-cloud-arrow-up" },
      { label: "Upload Queue", href: "/studio/upload-queue", icon: "fa-solid fa-layer-group" },
      { label: "New Card", href: "/studio/cards/create", icon: "fa-solid fa-id-card" },
      { label: "New Story", href: "/studio/stories/create", icon: "fa-solid fa-feather-pointed", fullLoad: true },
      { label: "New Collection", href: "/settings/collections/create", icon: "fa-solid fa-layer-group" }
    ]
  },
  {
    label: "Content",
    items: [
      { label: "All Content", href: "/studio/content", icon: "fa-solid fa-table-cells-large" },
      { label: "Artworks", href: "/studio/artworks", icon: "fa-solid fa-images" },
      { label: "Cards", href: "/studio/cards", icon: "fa-solid fa-id-card" },
      { label: "Collections", href: "/studio/collections", icon: "fa-solid fa-layer-group" },
      { label: "Stories", href: "/studio/stories", icon: "fa-solid fa-feather-pointed" }
    ]
  },
  {
    label: "Library",
    items: [
      { label: "Drafts", href: "/studio/drafts", icon: "fa-solid fa-file-pen" },
      { label: "Upload Queue", href: "/studio/upload-queue", icon: "fa-solid fa-list-check" },
      { label: "Scheduled", href: "/studio/scheduled", icon: "fa-solid fa-calendar-days" },
      { label: "Calendar", href: "/studio/calendar", icon: "fa-solid fa-calendar-days" },
      { label: "Archived", href: "/studio/archived", icon: "fa-solid fa-box-archive" },
      { label: "Assets", href: "/studio/assets", icon: "fa-solid fa-photo-film" }
    ]
  },
  {
    label: "Engagement",
    items: [
      { label: "Inbox", href: "/studio/inbox", icon: "fa-solid fa-inbox" },
      { label: "Activity", href: "/studio/activity", icon: "fa-solid fa-bell" },
      { label: "Comments", href: "/studio/comments", icon: "fa-solid fa-comments" },
      { label: "Followers", href: "/studio/followers", icon: "fa-solid fa-user-group" },
      { label: "Challenges", href: "/studio/challenges", icon: "fa-solid fa-trophy" }
    ]
  },
  {
    label: "Insights",
    items: [
      { label: "Analytics", href: "/studio/analytics", icon: "fa-solid fa-chart-pie" },
      { label: "Growth", href: "/studio/growth", icon: "fa-solid fa-chart-line" }
    ]
  },
  {
    label: "Creator",
    items: [
      { label: "Profile", href: "/studio/profile", icon: "fa-solid fa-id-card" },
      { label: "Featured Content", href: "/studio/featured", icon: "fa-solid fa-wand-magic-sparkles" },
      { label: "Preferences", href: "/studio/preferences", icon: "fa-solid fa-sliders" },
      { label: "Studio Settings", href: "/studio/settings", icon: "fa-solid fa-gear" }
    ]
  }
];
const baseQuickCreateItems = [
  { label: "Artwork", href: "/upload", icon: "fa-solid fa-cloud-arrow-up" },
  { label: "Card", href: "/studio/cards/create", icon: "fa-solid fa-id-card" },
  { label: "Story", href: "/studio/stories/create", icon: "fa-solid fa-feather-pointed", fullLoad: true },
  { label: "Collection", href: "/settings/collections/create", icon: "fa-solid fa-layer-group" }
];
const STUDIO_CONTEXT_STORAGE_KEY = "sb.studio.last-context";
const RESTORABLE_STUDIO_PATHS = ["/studio", "/studio/artworks", "/studio/collections", "/studio/settings"];
function supportsStudioContextRestore(pathname) {
  return RESTORABLE_STUDIO_PATHS.includes(pathname);
}
function studioRouteKeyForPath(pathname) {
  if (pathname === "/studio/artworks" || pathname.endsWith("/artworks")) return "studio_artworks_url";
  if (pathname === "/studio/collections" || pathname.endsWith("/collections")) return "studio_collections_url";
  if (pathname === "/studio/settings" || pathname.endsWith("/settings")) return "studio_settings_url";
  if (pathname.endsWith("/members")) return "studio_members_url";
  if (pathname.endsWith("/invitations")) return "studio_invitations_url";
  return "studio_url";
}
function nestedRouteKeyFor(topLevelRouteKey) {
  return topLevelRouteKey.replace(/_url$/, "");
}
function groupStudioUrlForPath(group, pathname) {
  if (!group) return "/studio";
  const routeKey = studioRouteKeyForPath(pathname);
  const nestedRouteKey = nestedRouteKeyFor(routeKey);
  return group[routeKey] || group.urls?.[nestedRouteKey] || group.studio_url || group.urls?.studio || "/studio";
}
function personalStudioUrlForPath(pathname) {
  if (pathname === "/studio/artworks" || pathname.endsWith("/artworks")) return "/studio/artworks";
  if (pathname === "/studio/collections" || pathname.endsWith("/collections")) return "/studio/collections";
  if (pathname === "/studio/settings" || pathname.endsWith("/settings")) return "/studio/settings";
  return "/studio";
}
function persistStudioContext(slug) {
  if (typeof window === "undefined") return;
  try {
    window.sessionStorage.setItem(STUDIO_CONTEXT_STORAGE_KEY, slug || "");
  } catch {
  }
}
function readPersistedStudioContext() {
  if (typeof window === "undefined") return null;
  try {
    return window.sessionStorage.getItem(STUDIO_CONTEXT_STORAGE_KEY);
  } catch {
    return null;
  }
}
function navigateToStudioUrl(targetUrl) {
  if (typeof window === "undefined" || !targetUrl) return;
  if (typeof window.location?.assign === "function") {
    window.location.assign(targetUrl);
    return;
  }
  window.location.href = targetUrl;
}
function NavLink({ item, active }) {
  const className = `flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${active ? "bg-accent/20 text-accent shadow-sm shadow-accent/10" : "text-slate-400 hover:text-white hover:bg-white/5"}`;
  if (item.fullLoad) {
    return /* @__PURE__ */ React.createElement("a", { href: item.href, className }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }), /* @__PURE__ */ React.createElement("span", null, item.label));
  }
  return /* @__PURE__ */ React.createElement(
    xe,
    {
      href: item.href,
      className
    },
    /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }),
    /* @__PURE__ */ React.createElement("span", null, item.label)
  );
}
function studioContextSummary(option) {
  if (!option) return "";
  if (option.kind === "personal") return option.description || "Your creator workspace";
  return [option.roleLabel, option.description].filter(Boolean).join(" · ");
}
function studioContextInitials(label) {
  const initials = String(label || "").split(/\s+/).filter(Boolean).slice(0, 2).map((segment) => segment.charAt(0).toUpperCase()).join("");
  return initials || "SB";
}
function StudioContextAvatar({ option, size = "md" }) {
  const sizeClass2 = size === "lg" ? "h-11 w-11 text-sm" : "h-9 w-9 text-xs";
  if (option?.avatarUrl) {
    return /* @__PURE__ */ React.createElement(
      "img",
      {
        src: option.avatarUrl,
        alt: option.label,
        className: `${sizeClass2} rounded-2xl object-cover ring-1 ring-white/10 shadow-[0_10px_24px_rgba(15,23,42,0.25)]`
      }
    );
  }
  const toneClass = option?.kind === "personal" ? "border-sky-300/25 bg-sky-300/12 text-sky-100" : "border-amber-300/20 bg-amber-300/10 text-amber-100";
  return /* @__PURE__ */ React.createElement("span", { className: `${sizeClass2} inline-flex items-center justify-center rounded-2xl border font-semibold uppercase tracking-[0.16em] ${toneClass}` }, option?.kind === "personal" ? /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-[12px]" }) : studioContextInitials(option?.label));
}
function StudioContextOptionContent({ option, expanded = false }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-3" }, /* @__PURE__ */ React.createElement(StudioContextAvatar, { option, size: expanded ? "lg" : "md" }), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: `truncate font-semibold ${expanded ? "text-[15px]" : "text-sm"} text-white` }, option.label), /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs text-slate-400" }, studioContextSummary(option))), expanded && option.kind === "group" && option.status ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, String(option.status).replace(/_/g, " ")) : null);
}
function buildStudioContextOptions(currentGroup, studioGroups, userLabel, userAvatarUrl) {
  return [
    {
      value: "",
      label: "Personal studio",
      description: userLabel,
      avatarUrl: userAvatarUrl || null,
      group: "Workspace",
      kind: "personal"
    },
    ...studioGroups.map((group) => ({
      value: group.slug,
      label: group.name,
      description: Number(group.artworks_count || 0) > 0 ? `${Number(group.artworks_count || 0).toLocaleString()} artwork${Number(group.artworks_count || 0) === 1 ? "" : "s"}` : "Group workspace",
      roleLabel: group.role_label || "Member",
      status: group.status,
      avatarUrl: group.avatar_url || null,
      group: "Groups",
      kind: "group",
      isCurrent: currentGroup?.slug === group.slug
    }))
  ];
}
function StudioLayout({ children, title, subtitle, actions }) {
  const { url, props } = X$1();
  const [mobileOpen, setMobileOpen] = reactExports.useState(false);
  const [createOpen, setCreateOpen] = reactExports.useState(false);
  const pathname = url.split("?")[0];
  const pageTitle = title ? `${title} — Creator Studio` : "Creator Studio";
  const pageDescription = subtitle || "Manage your creator workspace from one shared Creator Studio surface.";
  const pageSeo = {
    title: pageTitle,
    description: pageDescription,
    robots: "noindex,nofollow"
  };
  const studioGroups = Array.isArray(props.studio_groups) ? props.studio_groups : [];
  const currentGroup = props.studioGroup || null;
  const userLabel = props.auth?.user?.name || props.auth?.user?.username || "Your creator workspace";
  const userAvatarUrl = props.auth?.user?.avatar_url || null;
  const canManageNews = Boolean(props.auth?.user?.is_admin || props.auth?.user?.is_moderator);
  const canManageWorlds = canManageNews;
  const isStaff = Boolean(props.auth?.user?.is_staff);
  const studioContextOptions = buildStudioContextOptions(currentGroup, studioGroups, userLabel, userAvatarUrl);
  const navGroups = baseNavGroups.map((group) => {
    if (!canManageNews && !canManageWorlds || group.label !== "Content") {
      return group;
    }
    const extraItems = [];
    if (canManageNews) {
      extraItems.push({ label: "News", href: "/studio/news", icon: "fa-solid fa-newspaper" });
    }
    if (canManageWorlds) {
      extraItems.push({ label: "Worlds", href: "/studio/worlds", icon: "fa-solid fa-globe" });
    }
    return {
      ...group,
      items: [...group.items, ...extraItems]
    };
  });
  const quickCreatePool = [...baseQuickCreateItems];
  if (canManageNews) {
    quickCreatePool.push({ label: "News Article", href: "/studio/news/create", icon: "fa-solid fa-newspaper" });
  }
  if (canManageWorlds) {
    quickCreatePool.push({ label: "World", href: "/studio/worlds/create", icon: "fa-solid fa-globe" });
  }
  const quickCreateItems = quickCreatePool.map((item) => {
    if (currentGroup?.urls && item.label === "Artwork") {
      return { ...item, href: currentGroup.urls?.studio_artworks ? `/upload?group=${currentGroup.slug}` : item.href };
    }
    if (currentGroup?.urls && item.label === "Collection") {
      return { ...item, href: `/settings/collections/create?group=${currentGroup.slug}` };
    }
    return item;
  });
  reactExports.useEffect(() => {
    const moduleKey = studioModule(pathname);
    const surface = studioSurface(pathname);
    trackStudioEvent("studio_opened", {
      surface,
      module: moduleKey
    });
    trackStudioEvent("studio_module_opened", {
      surface,
      module: moduleKey
    });
  }, [pathname]);
  reactExports.useEffect(() => {
    if (!currentGroup?.slug) return;
    persistStudioContext(currentGroup.slug);
  }, [currentGroup?.slug]);
  reactExports.useEffect(() => {
    if (currentGroup || !supportsStudioContextRestore(pathname)) return;
    const storedSlug = readPersistedStudioContext();
    if (!storedSlug) return;
    const nextGroup = studioGroups.find((group) => group.slug === storedSlug);
    if (!nextGroup) {
      persistStudioContext("");
      return;
    }
    const targetUrl = groupStudioUrlForPath(nextGroup, pathname);
    if (targetUrl && targetUrl !== pathname) {
      navigateToStudioUrl(targetUrl);
    }
  }, [currentGroup, pathname, studioGroups]);
  const isActive = (href) => {
    if (href === "/studio") return pathname === "/studio";
    return pathname.startsWith(href);
  };
  const handleQuickCreateClick = (item) => {
    trackStudioEvent("studio_quick_create_used", {
      surface: studioSurface(pathname),
      module: item.label.toLowerCase(),
      meta: {
        href: item.href,
        label: item.label
      }
    });
  };
  const handleContextChange = (nextSlug) => {
    persistStudioContext(nextSlug);
    const nextGroup = studioGroups.find((group) => group.slug === nextSlug);
    const targetUrl = nextGroup ? groupStudioUrlForPath(nextGroup, pathname) : personalStudioUrlForPath(pathname);
    if (targetUrl !== pathname) {
      navigateToStudioUrl(targetUrl);
    }
  };
  return /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.12),_transparent_30%),radial-gradient(circle_at_bottom_right,_rgba(34,197,94,0.12),_transparent_35%),linear-gradient(180deg,_#06101d_0%,_#020617_45%,_#02040a_100%)]" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: pageSeo }), /* @__PURE__ */ React.createElement("div", { className: "sticky top-16 z-30 border-b border-white/10 bg-slate-950/80 backdrop-blur-xl lg:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between px-4 py-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/70" }, "Creator Studio"), /* @__PURE__ */ React.createElement("h1", { className: "text-lg font-bold text-white" }, title || "Creator Studio")), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: () => setMobileOpen(!mobileOpen),
      className: "rounded-full border border-white/10 p-2 text-slate-400 hover:text-white",
      "aria-label": "Toggle navigation"
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${mobileOpen ? "fa-xmark" : "fa-bars"} text-xl` })
  ))), mobileOpen && /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden", onClick: () => setMobileOpen(false) }, /* @__PURE__ */ React.createElement(
    "nav",
    {
      className: "absolute left-0 top-0 bottom-0 w-80 overflow-y-auto border-r border-white/10 bg-slate-950 p-4 pt-20",
      onClick: (event) => event.stopPropagation()
    },
    /* @__PURE__ */ React.createElement(
      StudioSidebarContent,
      {
        currentGroup,
        studioGroups,
        studioContextOptions,
        navGroups,
        quickCreateItems,
        isActive,
        isStaff,
        onNavigate: () => setMobileOpen(false),
        onQuickCreate: handleQuickCreateClick,
        onContextChange: handleContextChange
      }
    )
  )), /* @__PURE__ */ React.createElement("div", { className: "flex" }, /* @__PURE__ */ React.createElement("aside", { className: "sticky top-16 hidden min-h-[calc(100vh-4rem)] w-72 self-start border-r border-white/10 bg-slate-950/55 p-4 pt-6 backdrop-blur-xl lg:flex lg:flex-col" }, /* @__PURE__ */ React.createElement(
    StudioSidebarContent,
    {
      currentGroup,
      studioGroups,
      studioContextOptions,
      navGroups,
      quickCreateItems,
      isActive,
      isStaff,
      onQuickCreate: handleQuickCreateClick,
      onContextChange: handleContextChange
    }
  )), /* @__PURE__ */ React.createElement("main", { className: "min-w-0 flex-1 px-4 pb-10 pt-4 lg:px-8 lg:pt-6" }, /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.12),_transparent_28%),radial-gradient(circle_at_bottom_right,_rgba(56,189,248,0.12),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.84),_rgba(2,6,23,0.95))] p-5 shadow-[0_22px_70px_rgba(2,6,23,0.32)] lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/70" }, "Creator Studio"), title && /* @__PURE__ */ React.createElement("h1", { className: "mt-2 text-3xl font-semibold text-white lg:text-4xl" }, title), subtitle && /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-6 text-slate-300" }, subtitle), currentGroup ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Group context: ", currentGroup.name) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 lg:justify-end" }, studioGroups.length > 0 ? /* @__PURE__ */ React.createElement(ContextSwitcher, { currentGroup, studioContextOptions, onContextChange: handleContextChange }) : null, actions, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setCreateOpen((current) => !current),
      className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }),
    "Create New"
  ), createOpen && /* @__PURE__ */ React.createElement("div", { className: "absolute right-0 top-[calc(100%+0.75rem)] z-20 min-w-[220px] rounded-[24px] border border-white/10 bg-slate-950/95 p-2 shadow-[0_18px_40px_rgba(2,6,23,0.5)] backdrop-blur-xl" }, quickCreateItems.map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.href,
      href: item.href,
      onClick: () => handleQuickCreateClick(item),
      className: "flex items-center gap-3 rounded-2xl px-4 py-3 text-sm text-slate-200 transition hover:bg-white/[0.06] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-sky-200` }),
    /* @__PURE__ */ React.createElement("span", null, "New ", item.label)
  ))))))), children)));
}
function ContextSwitcher({ currentGroup, studioContextOptions, onContextChange }) {
  return /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-3 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.88),rgba(7,14,28,0.94))] p-2 pr-3 text-sm text-slate-200 shadow-[0_18px_40px_rgba(2,6,23,0.24)]" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-11 w-11 items-center justify-center rounded-[20px] border border-sky-300/14 bg-sky-300/10 text-sky-100 shadow-[inset_0_1px_0_rgba(255,255,255,0.05)]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-sm" })), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: currentGroup?.slug || "",
      onChange: (value) => onContextChange?.(value),
      options: studioContextOptions,
      searchable: true,
      searchPlaceholder: "Search studios or groups…",
      renderOption: (option) => /* @__PURE__ */ React.createElement(StudioContextOptionContent, { option, expanded: true }),
      renderValue: (option) => /* @__PURE__ */ React.createElement(StudioContextOptionContent, { option }),
      className: "min-w-[280px] border-white/10 bg-white/[0.03] shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] hover:border-white/20"
    }
  ));
}
function StudioSidebarContent({ currentGroup, studioContextOptions, navGroups, quickCreateItems, isActive, isStaff, onNavigate, onQuickCreate, onContextChange }) {
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-[26px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Skinbase Nova"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Creator Studio"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Create, manage, and grow from one modular workspace built for every creator surface."), studioContextOptions.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-black/20 p-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Context"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: currentGroup?.slug || "",
      onChange: (value) => onContextChange?.(value),
      className: "mt-2",
      options: studioContextOptions,
      searchable: true,
      searchPlaceholder: "Search studios or groups…",
      renderOption: (option) => /* @__PURE__ */ React.createElement(StudioContextOptionContent, { option, expanded: true }),
      renderValue: (option) => /* @__PURE__ */ React.createElement(StudioContextOptionContent, { option })
    }
  )) : null), /* @__PURE__ */ React.createElement("nav", { className: "flex-1 space-y-5", onClick: onNavigate }, navGroups.map((group) => /* @__PURE__ */ React.createElement("div", { key: group.label }, /* @__PURE__ */ React.createElement("h3", { className: "mb-2 px-3 text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "space-y-1" }, group.items.map((item) => /* @__PURE__ */ React.createElement(NavLink, { key: item.href, item, active: isActive(item.href) }))))), isStaff && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "mb-2 px-3 text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-500/70" }, "Administration"), /* @__PURE__ */ React.createElement("div", { className: "space-y-1" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: "/moderation",
      className: "flex items-center gap-3 rounded-xl px-4 py-2.5 text-sm font-medium text-rose-300/70 transition hover:bg-rose-500/10 hover:text-rose-300"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-halved w-5 text-center text-base" }),
    /* @__PURE__ */ React.createElement("span", null, "Admin Panel")
  )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-[linear-gradient(135deg,_rgba(15,23,42,0.95),_rgba(12,74,110,0.4))] p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, "Quick create"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-2" }, quickCreateItems.map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.href,
      href: item.href,
      className: "inline-flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-100 transition hover:border-white/20 hover:bg-white/[0.06]",
      onClick: () => {
        onQuickCreate?.(item);
        onNavigate?.();
      }
    },
    /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-sky-200` }),
    /* @__PURE__ */ React.createElement("span", null, "New ", item.label)
  )))));
}
async function requestJson$7(url, method = "POST") {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed");
  }
  return payload;
}
function formatDate$7(value) {
  if (!value) return "Unknown";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unknown";
  return date.toLocaleString(void 0, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
}
function StudioActivity() {
  const { props } = X$1();
  const listing = props.listing || {};
  const filters = listing.filters || {};
  const items = listing.items || [];
  const meta = listing.meta || {};
  const summary = listing.summary || {};
  const typeOptions = listing.type_options || [];
  const moduleOptions = listing.module_options || [];
  const endpoints = props.endpoints || {};
  const [marking, setMarking] = reactExports.useState(false);
  const updateFilters = (patch2) => {
    const next = { ...filters, ...patch2 };
    if (patch2.page == null) next.page = 1;
    trackStudioEvent("studio_activity_opened", {
      surface: studioSurface(),
      module: "activity",
      meta: patch2
    });
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  const markAllRead = async () => {
    setMarking(true);
    try {
      await requestJson$7(endpoints.markAllRead);
      At.reload({ only: ["listing"] });
    } catch (error) {
      window.alert(error?.message || "Unable to mark activity as read.");
    } finally {
      setMarking(false);
    }
  };
  return /* @__PURE__ */ React.createElement(
    StudioLayout,
    {
      title: props.title,
      subtitle: props.description,
      actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: markAllRead, disabled: marking, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check-double" }), marking ? "Updating..." : "Mark all read")
    },
    /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "New since last read"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.new_items || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Unread notifications"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.unread_notifications || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Last inbox reset"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, summary.last_read_at ? formatDate$7(summary.last_read_at) : "Not yet"))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search activity"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Message, actor, or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "all", onChange: (val) => updateFilters({ type: val }), options: typeOptions, searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Content type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: moduleOptions, searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateFilters({ q: "", type: "all", module: "all" }), className: "w-full rounded-2xl border border-white/10 px-4 py-3 text-sm text-slate-200" }, "Reset")))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: `rounded-[28px] border p-5 ${item.is_new ? "border-sky-300/25 bg-sky-300/10" : "border-white/10 bg-white/[0.03]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-4" }, item.actor?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.actor.avatar_url, alt: item.actor.name || "Activity actor", className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-black/20 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bell" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, item.module_label), /* @__PURE__ */ React.createElement("span", null, formatDate$7(item.created_at)), item.is_new && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-300/20 px-2 py-1 text-sky-100" }, "New")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-3 text-sm text-slate-400" }, item.actor?.name && /* @__PURE__ */ React.createElement("span", null, item.actor.name), /* @__PURE__ */ React.createElement("a", { href: item.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-slate-200" }, "Open")))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No activity matches this filter.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Previous"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next")))
  );
}
const __vite_glob_0_105 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioActivity
}, Symbol.toStringTag, { value: "Module" }));
const kpiItems$2 = [
  { key: "views", label: "Views", icon: "fa-eye", color: "text-emerald-400", bg: "bg-emerald-500/10" },
  { key: "appreciation", label: "Reactions", icon: "fa-heart", color: "text-pink-400", bg: "bg-pink-500/10" },
  { key: "shares", label: "Shares", icon: "fa-share-nodes", color: "text-amber-400", bg: "bg-amber-500/10" },
  { key: "saves", label: "Saves", icon: "fa-bookmark", color: "text-purple-400", bg: "bg-purple-500/10" },
  { key: "comments", label: "Comments", icon: "fa-comment", color: "text-blue-400", bg: "bg-blue-500/10" },
  { key: "followers", label: "Followers", icon: "fa-user-group", color: "text-cyan-300", bg: "bg-cyan-400/10" }
];
const rangeOptions$1 = [7, 14, 30, 60, 90];
function formatShortDate$1(value) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString(void 0, { month: "short", day: "numeric" });
}
function TrendChart({ title, subtitle, points, colorClass, fillClass, icon }) {
  const normalizedPoints = Array.isArray(points) ? points : [];
  const values = normalizedPoints.map((point2) => Number(point2.value || 0));
  const maxValue = Math.max(...values, 1);
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle)), /* @__PURE__ */ React.createElement("div", { className: `flex h-11 w-11 items-center justify-center rounded-2xl ${fillClass} ${colorClass}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon}` }))), normalizedPoints.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex h-52 items-center justify-center rounded-[22px] border border-dashed border-white/10 bg-black/20 px-6 text-sm text-slate-400" }, "No analytics points are available for this time window yet.") : /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex h-52 items-end gap-2" }, normalizedPoints.map((point2) => {
    const height = `${Math.max(8, Math.round(Number(point2.value || 0) / maxValue * 100))}%`;
    return /* @__PURE__ */ React.createElement("div", { key: point2.date, className: "flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-medium text-slate-500" }, Number(point2.value || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "flex w-full flex-1 items-end rounded-t-[18px] bg-white/[0.03] px-[2px]" }, /* @__PURE__ */ React.createElement("div", { className: `w-full rounded-t-[16px] ${fillClass}`, style: { height } })), /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.14em] text-slate-500" }, formatShortDate$1(point2.date)));
  })));
}
function StudioAnalytics() {
  const { props } = X$1();
  const {
    totals,
    topContent,
    moduleBreakdown,
    recentComments,
    publishingTimeline,
    viewsTrend,
    engagementTrend,
    comparison,
    insightBlocks,
    rangeDays
  } = props;
  const updateRange = (days) => {
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: "analytics",
      meta: {
        range_days: days
      }
    });
    At.get(window.location.pathname, { range_days: days }, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: "Analytics", subtitle: "Cross-module insights for the whole creator workspace, not just artwork uploads." }, /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),radial-gradient(circle_at_bottom_right,_rgba(244,114,182,0.12),_transparent_40%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 shadow-[0_22px_60px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Analytics window"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Performance over the last ", rangeDays || 30, " days"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, "This view compares module output, shows views and engagement trends over time, and keeps publishing rhythm in the same window.")), /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-white/10 bg-black/20 p-1" }, rangeOptions$1.map((days) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: days,
      type: "button",
      onClick: () => updateRange(days),
      className: `rounded-full px-4 py-2 text-sm font-semibold transition ${Number(rangeDays || 30) === days ? "bg-white text-slate-950" : "text-slate-300 hover:text-white"}`
    },
    days,
    "d"
  ))))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 xl:grid-cols-6" }, kpiItems$2.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 mb-3" }, /* @__PURE__ */ React.createElement("div", { className: `w-10 h-10 rounded-xl ${item.bg} flex items-center justify-center ${item.color}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon}` })), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-medium text-slate-400 uppercase tracking-wider leading-tight" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-3xl font-bold text-white tabular-nums" }, (totals?.[item.key] ?? 0).toLocaleString())))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(
    TrendChart,
    {
      title: "Views over time",
      subtitle: "Cross-module reach across the current analytics window.",
      points: viewsTrend,
      colorClass: "text-emerald-300",
      fillClass: "bg-emerald-400/60",
      icon: "fa-eye"
    }
  ), /* @__PURE__ */ React.createElement(
    TrendChart,
    {
      title: "Engagement over time",
      subtitle: "Combined engagement score so you can see momentum shifts, not just raw traffic.",
      points: engagementTrend,
      colorClass: "text-pink-300",
      fillClass: "bg-pink-400/60",
      icon: "fa-bolt"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Module breakdown"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (moduleBreakdown || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, Number(item.count || 0).toLocaleString(), " items"))), /* @__PURE__ */ React.createElement("a", { href: item.index_url, className: "text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3 text-sm text-slate-400 md:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.views || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Reactions"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.appreciation || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.comments || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Shares"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.shares || 0).toLocaleString()))))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Publishing rhythm"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (publishingTimeline || []).map((point2) => /* @__PURE__ */ React.createElement("div", { key: point2.date }, /* @__PURE__ */ React.createElement("div", { className: "mb-1 flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, new Date(point2.date).toLocaleDateString(void 0, { month: "short", day: "numeric" })), /* @__PURE__ */ React.createElement("span", null, point2.count)), /* @__PURE__ */ React.createElement("div", { className: "h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-sky-300/60", style: { width: `${Math.min(100, point2.count * 18)}%` } }))))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Module comparison"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Last ", rangeDays || 30, " days")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, (comparison || []).map((item) => {
    const viewMax = Math.max(...(comparison || []).map((entry) => Number(entry.views || 0)), 1);
    const engagementMax = Math.max(...(comparison || []).map((entry) => Number(entry.engagement || 0)), 1);
    return /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, Number(item.published_count || 0).toLocaleString(), " published"))), /* @__PURE__ */ React.createElement("a", { href: moduleBreakdown?.find((entry) => entry.key === item.key)?.index_url, className: "text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Views"), /* @__PURE__ */ React.createElement("span", null, Number(item.views || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-emerald-400/60", style: { width: `${Math.max(4, Math.round(Number(item.views || 0) / viewMax * 100))}%` } }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Engagement"), /* @__PURE__ */ React.createElement("span", null, Number(item.engagement || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-pink-400/60", style: { width: `${Math.max(4, Math.round(Number(item.engagement || 0) / engagementMax * 100))}%` } })))));
  }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Readable insights"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-400" }, (insightBlocks || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.key, href: item.href, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl bg-white/[0.04] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: item.icon })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("span", { className: "mt-3 inline-flex items-center gap-2 text-sm font-medium text-sky-100" }, item.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Top content"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/5 text-left text-[11px] uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Module"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Title"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4 text-right" }, "Views"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4 text-right" }, "Reactions"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4 text-right" }, "Comments"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 text-right" }, "Open"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/5" }, (topContent || []).map((item) => /* @__PURE__ */ React.createElement("tr", { key: item.id }, /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-slate-300" }, item.module_label), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-white" }, item.title), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-right text-slate-300" }, Number(item.metrics?.views || 0).toLocaleString()), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-right text-slate-300" }, Number(item.metrics?.appreciation || 0).toLocaleString()), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-right text-slate-300" }, Number(item.metrics?.comments || 0).toLocaleString()), /* @__PURE__ */ React.createElement("td", { className: "py-3 text-right" }, /* @__PURE__ */ React.createElement("a", { href: item.analytics_url || item.view_url, className: "text-sky-100" }, "Open")))))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (recentComments || []).map((comment) => /* @__PURE__ */ React.createElement("article", { key: comment.id, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, comment.module_label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white" }, comment.author_name, " on ", comment.item_title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, comment.body)))))));
}
const __vite_glob_0_106 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioAnalytics
}, Symbol.toStringTag, { value: "Module" }));
function ConfirmDangerModal({ open, onClose, onConfirm, title, message, confirmText = "DELETE" }) {
  const [input, setInput] = reactExports.useState("");
  const inputRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (open) {
      setInput("");
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [open]);
  if (!open) return null;
  const canConfirm = input === confirmText;
  const handleKeyDown2 = (e) => {
    if (e.key === "Escape") onClose();
    if (e.key === "Enter" && canConfirm) onConfirm();
  };
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-[60] flex items-center justify-center p-4", onKeyDown: handleKeyDown2 }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-black/70 backdrop-blur-sm", onClick: onClose }), /* @__PURE__ */ React.createElement("div", { className: "relative w-full max-w-md bg-nova-900 border border-red-500/30 rounded-2xl shadow-2xl shadow-red-500/10 p-6 space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-triangle-exclamation text-red-400" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-bold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400 mt-1" }, message))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "text-xs font-medium text-slate-400 mb-1.5 block" }, "Type ", /* @__PURE__ */ React.createElement("span", { className: "text-red-400 font-mono" }, confirmText), " to confirm"), /* @__PURE__ */ React.createElement(
    "input",
    {
      ref: inputRef,
      type: "text",
      value: input,
      onChange: (e) => setInput(e.target.value),
      className: "w-full px-3 py-2.5 rounded-xl bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:ring-2 focus:ring-red-500/50 font-mono",
      placeholder: confirmText
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-2 pt-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: onClose,
      className: "px-4 py-2 rounded-xl text-sm text-slate-400 hover:text-white hover:bg-white/5 transition-all"
    },
    "Cancel"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      onClick: onConfirm,
      disabled: !canConfirm,
      className: `px-5 py-2 rounded-xl text-sm font-semibold transition-all ${canConfirm ? "bg-red-600 hover:bg-red-700 text-white" : "bg-white/5 text-slate-500 cursor-not-allowed"}`
    },
    "Delete permanently"
  ))));
}
function formatDate$6(value) {
  if (!value) return "Unscheduled";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unscheduled";
  return date.toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
}
function metricValue$1(item, key) {
  return Number(item?.metrics?.[key] ?? 0).toLocaleString();
}
function readinessClasses(readiness) {
  if (!readiness) return "border-white/15 bg-white/5 text-slate-300";
  if (readiness.can_publish && readiness.score >= readiness.max) return "border-emerald-400/30 bg-emerald-400/10 text-emerald-100";
  if (readiness.can_publish) return "border-sky-400/30 bg-sky-400/10 text-sky-100";
  return "border-amber-400/30 bg-amber-400/10 text-amber-100";
}
function statusClasses$1(status2) {
  switch (status2) {
    case "published":
      return "border-emerald-400/30 bg-emerald-400/10 text-emerald-200";
    case "draft":
    case "pending_review":
      return "border-amber-400/30 bg-amber-400/10 text-amber-100";
    case "scheduled":
    case "processing":
      return "border-sky-400/30 bg-sky-400/10 text-sky-100";
    case "archived":
    case "hidden":
    case "rejected":
      return "border-white/15 bg-white/5 text-slate-300";
    default:
      return "border-white/15 bg-white/5 text-slate-200";
  }
}
function itemReadiness(item) {
  if (item?.status === "published") return null;
  return item?.workflow?.readiness ?? null;
}
function buildPaginationPages$1(current, last) {
  if (last <= 1) return [1];
  if (last <= 7) {
    return Array.from({ length: last }, (_2, index2) => index2 + 1);
  }
  const pages2 = /* @__PURE__ */ new Set([1, 2, current - 1, current, current + 1, last - 1, last]);
  const sorted = [...pages2].filter((page) => page >= 1 && page <= last).sort((left, right) => left - right);
  const result = [];
  for (let index2 = 0; index2 < sorted.length; index2 += 1) {
    if (index2 > 0 && sorted[index2] - sorted[index2 - 1] > 1) {
      result.push("ellipsis");
    }
    result.push(sorted[index2]);
  }
  return result;
}
function bulkErrorMessage(payload, fallback = "Bulk action failed.") {
  if (Array.isArray(payload?.errors) && payload.errors.length > 0) {
    return payload.errors[0];
  }
  return payload?.message || payload?.error || payload?.errors?.confirm?.[0] || payload?.errors?.action?.[0] || fallback;
}
function stripHtml$2(value) {
  if (typeof value !== "string") return "";
  return value.replace(/<[^>]*>/g, "").trim();
}
function ActionLink({ href, icon, label, onClick }) {
  if (!href) return null;
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href,
      onClick,
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5 text-xs font-medium text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06]"
    },
    /* @__PURE__ */ React.createElement("i", { className: `${icon} text-[11px]` }),
    /* @__PURE__ */ React.createElement("span", null, label)
  );
}
function RequestActionButton({ action, onExecute, busyKey }) {
  if (!action || action.type !== "request") return null;
  const isBusy = busyKey === `${action.key}:${action.url}`;
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onExecute(action),
      disabled: isBusy,
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5 text-xs font-medium text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("i", { className: `${action.icon} text-[11px]` }),
    /* @__PURE__ */ React.createElement("span", null, isBusy ? "Working..." : action.label)
  );
}
function PreviewLink({ item }) {
  if (!item?.preview_url) return null;
  return /* @__PURE__ */ React.createElement(ActionLink, { href: item.preview_url, icon: "fa-solid fa-eye", label: "Preview" });
}
function GridCard({ item, onExecuteAction, busyKey }) {
  const readiness = itemReadiness(item);
  const handleEditClick = () => {
    trackStudioEvent("studio_item_edited", {
      surface: studioSurface(),
      module: item.module,
      item_module: item.module,
      item_id: item.numeric_id,
      meta: {
        action: "edit"
      }
    });
  };
  return /* @__PURE__ */ React.createElement("article", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-white/[0.03] shadow-[0_18px_50px_rgba(3,7,18,0.22)] transition hover:-translate-y-0.5 hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[1.15/1] overflow-hidden bg-slate-950/70" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.18),_transparent_55%),linear-gradient(135deg,_rgba(15,23,42,0.9),_rgba(2,6,23,0.95))] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `${item.module_icon} text-3xl` })), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 inline-flex items-center gap-2 rounded-full border border-black/10 bg-black/45 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white backdrop-blur-md" }, /* @__PURE__ */ React.createElement("i", { className: `${item.module_icon} text-[10px]` }), /* @__PURE__ */ React.createElement("span", null, item.module_label))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h3", { className: "truncate text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm text-slate-400" }, item.subtitle || item.visibility || "Untitled metadata")), /* @__PURE__ */ React.createElement("span", { className: `inline-flex shrink-0 items-center rounded-full border px-2.5 py-1 text-[11px] font-medium capitalize ${statusClasses$1(item.status)}` }, String(item.status || "unknown").replace("_", " "))), readiness && /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-medium ${readinessClasses(readiness)}` }, readiness.label), item.workflow.is_stale_draft && /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-400/30 bg-amber-400/10 px-2.5 py-1 text-[11px] font-medium text-amber-100" }, "Stale draft"), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-500" }, readiness.score, "/", readiness.max, " ready")), /* @__PURE__ */ React.createElement("p", { className: "line-clamp-2 min-h-[2.5rem] text-sm text-slate-300/90" }, stripHtml$2(item.description) || "No description yet."), Array.isArray(readiness?.missing) && readiness.missing.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/5 bg-slate-950/35 p-3 text-xs text-slate-400" }, readiness.missing.slice(0, 2).join(" • ")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-2 rounded-2xl border border-white/5 bg-slate-950/40 p-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.16em]" }, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, metricValue$1(item, "views"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.16em]" }, "Reactions"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, metricValue$1(item, "appreciation"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.16em]" }, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, metricValue$1(item, "comments")))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Updated ", formatDate$6(item.updated_at)), item.published_at && /* @__PURE__ */ React.createElement("span", null, "Published ", formatDate$6(item.published_at))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(ActionLink, { href: item.edit_url || item.manage_url, icon: "fa-solid fa-pen-to-square", label: "Edit", onClick: handleEditClick }), /* @__PURE__ */ React.createElement(PreviewLink, { item }), /* @__PURE__ */ React.createElement(ActionLink, { href: item.analytics_url, icon: "fa-solid fa-chart-line", label: "Analytics" }), /* @__PURE__ */ React.createElement(ActionLink, { href: item.view_url, icon: "fa-solid fa-arrow-up-right-from-square", label: "Open" }), (item.actions || []).map((action) => /* @__PURE__ */ React.createElement(RequestActionButton, { key: `${item.id}-${action.key}`, action: { ...action, item_id: item.numeric_id, item_module: item.module }, onExecute: onExecuteAction, busyKey }))), Array.isArray(item.workflow?.cross_module_actions) && item.workflow.cross_module_actions.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 border-t border-white/5 pt-3" }, item.workflow.cross_module_actions.slice(0, 2).map((action) => /* @__PURE__ */ React.createElement(ActionLink, { key: `${item.id}-${action.label}`, href: action.href, icon: action.icon, label: action.label })))));
}
function ListRow$1({ item, onExecuteAction, busyKey }) {
  const readiness = itemReadiness(item);
  const handleEditClick = () => {
    trackStudioEvent("studio_item_edited", {
      surface: studioSurface(),
      module: item.module,
      item_module: item.module,
      item_id: item.numeric_id,
      meta: {
        action: "edit"
      }
    });
  };
  return /* @__PURE__ */ React.createElement("article", { className: "grid gap-4 rounded-[24px] border border-white/10 bg-white/[0.03] p-4 transition hover:border-white/20 md:grid-cols-[120px_minmax(0,1fr)_auto] md:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "h-24 overflow-hidden rounded-2xl bg-slate-950/60" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: `${item.module_icon} text-2xl` }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: `${item.module_icon} text-[10px]` }), item.module_label), /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-medium capitalize ${statusClasses$1(item.status)}` }, String(item.status || "unknown").replace("_", " "))), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 truncate text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, item.subtitle || item.visibility || "Untitled metadata"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 line-clamp-2 text-sm text-slate-300/90" }, stripHtml$2(item.description) || "No description yet."), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, readiness && /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-medium ${readinessClasses(readiness)}` }, readiness.label), item.workflow?.is_stale_draft && /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-400/30 bg-amber-400/10 px-2.5 py-1 text-[11px] font-medium text-amber-100" }, "Stale draft")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-4 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, metricValue$1(item, "views"), " views"), /* @__PURE__ */ React.createElement("span", null, metricValue$1(item, "appreciation"), " reactions"), /* @__PURE__ */ React.createElement("span", null, metricValue$1(item, "comments"), " comments"), /* @__PURE__ */ React.createElement("span", null, "Updated ", formatDate$6(item.updated_at))), Array.isArray(readiness?.missing) && readiness.missing.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, readiness.missing.slice(0, 2).join(" • "))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 md:justify-end" }, /* @__PURE__ */ React.createElement(ActionLink, { href: item.edit_url || item.manage_url, icon: "fa-solid fa-pen-to-square", label: "Edit", onClick: handleEditClick }), /* @__PURE__ */ React.createElement(PreviewLink, { item }), /* @__PURE__ */ React.createElement(ActionLink, { href: item.analytics_url, icon: "fa-solid fa-chart-line", label: "Analytics" }), /* @__PURE__ */ React.createElement(ActionLink, { href: item.view_url, icon: "fa-solid fa-arrow-up-right-from-square", label: "Open" }), (item.actions || []).map((action) => /* @__PURE__ */ React.createElement(RequestActionButton, { key: `${item.id}-${action.key}`, action: { ...action, item_id: item.numeric_id, item_module: item.module }, onExecute: onExecuteAction, busyKey })), (item.workflow?.cross_module_actions || []).slice(0, 2).map((action) => /* @__PURE__ */ React.createElement(ActionLink, { key: `${item.id}-${action.label}`, href: action.href, icon: action.icon, label: action.label }))));
}
function materializeFilter(filter2, pendingFilters) {
  if (filter2?.key !== "category") {
    return filter2;
  }
  const selectedContentType = pendingFilters?.content_type || "all";
  const options = Array.isArray(filter2.options) ? filter2.options.filter((option) => option.value === "all" || selectedContentType === "all" || option.content_type_slug === selectedContentType) : filter2.options;
  return {
    ...filter2,
    options
  };
}
function selectOptions(options = []) {
  return options.map((option) => ({
    value: option.value,
    label: option.label,
    group: option.group,
    disabled: option.disabled,
    icon: option.icon
  }));
}
function FilterField({ label, children }) {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), children);
}
function AdvancedFilterControl({ filter: filter2, onChange, value }) {
  const controlValue = value ?? filter2.value;
  if (filter2.type === "select") {
    const options = selectOptions(filter2.options || []);
    const searchable = filter2.searchable ?? options.length > 8;
    return /* @__PURE__ */ React.createElement(FilterField, { label: filter2.label }, /* @__PURE__ */ React.createElement(
      NovaSelect,
      {
        id: `studio-filter-${filter2.key}`,
        options,
        value: controlValue || "all",
        onChange: (nextValue) => onChange(filter2.key, nextValue ?? "all"),
        placeholder: filter2.label,
        searchable
      }
    ));
  }
  return /* @__PURE__ */ React.createElement(FilterField, { label: filter2.label }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: controlValue || "",
      onChange: (event) => onChange(filter2.key, event.target.value),
      placeholder: filter2.placeholder || filter2.label,
      className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-sky-300/40 focus:bg-black/30"
    }
  ));
}
function StudioContentBrowser({
  listing,
  quickCreate = [],
  hideModuleFilter = false,
  hideBucketFilter = false,
  defaultSort = "updated_desc",
  sortStorageKey = null,
  emptyTitle = "Nothing here yet",
  emptyBody = "Try adjusting filters or create something new."
}) {
  const [viewMode, setViewMode] = reactExports.useState("grid");
  const [busyKey, setBusyKey] = reactExports.useState(null);
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [bulkBusy, setBulkBusy] = reactExports.useState(false);
  const [optimisticRemovedIds, setOptimisticRemovedIds] = reactExports.useState([]);
  const [pendingFilters, setPendingFilters] = reactExports.useState({
    q: "",
    bucket: "all",
    sort: defaultSort,
    content_type: "all",
    category: "all",
    tag: ""
  });
  const [deleteDialog, setDeleteDialog] = reactExports.useState({
    open: false,
    title: "",
    message: "",
    target: null
  });
  const filters = listing?.filters || {};
  const items = listing?.items || [];
  const meta = listing?.meta || {};
  const advancedFilters = listing?.advanced_filters || [];
  const visibleItems = items.filter((item) => !optimisticRemovedIds.includes(Number(item.numeric_id)));
  const currentModule = filters.module || listing?.module || items[0]?.module || null;
  const visibleQuickCreate = hideModuleFilter && currentModule && currentModule !== "all" ? quickCreate.filter((action) => action.key === currentModule) : quickCreate;
  const supportsArtworkBulk = currentModule === "artworks" && items.every((item) => item.module === "artworks");
  const selectableIds = supportsArtworkBulk ? visibleItems.map((item) => Number(item.numeric_id)).filter((value) => Number.isInteger(value) && value > 0) : [];
  const allVisibleSelected = selectableIds.length > 0 && selectableIds.every((id) => selectedIds.includes(id));
  const selectedOnPage = selectedIds.filter((id) => selectableIds.includes(id));
  const visibleTotal = Math.max(0, Number(meta.total || 0) - optimisticRemovedIds.length);
  const currentPage = Math.max(1, Number(meta.current_page || 1));
  const lastPage = Math.max(1, Number(meta.last_page || 1));
  const perPage = Math.max(1, Number(meta.per_page || visibleItems.length || 24));
  const rangeStart = visibleTotal === 0 ? 0 : (currentPage - 1) * perPage + 1;
  const rangeEnd = visibleTotal === 0 ? 0 : Math.min(visibleTotal, rangeStart + Math.max(visibleItems.length, 1) - 1);
  const paginationPages = buildPaginationPages$1(currentPage, lastPage);
  const filterControlCount = 1 + (hideModuleFilter ? 0 : 1) + (hideBucketFilter ? 0 : 1) + 1 + advancedFilters.length + 1;
  const filterGridClass = filterControlCount <= 4 ? "xl:grid-cols-4" : filterControlCount === 5 ? "xl:grid-cols-5" : filterControlCount === 6 ? "xl:grid-cols-6" : "xl:grid-cols-6 2xl:grid-cols-7";
  reactExports.useEffect(() => {
    const stored = window.localStorage.getItem("studio-content-view");
    if (stored === "grid" || stored === "list" || stored === "table") {
      setViewMode(stored);
      return;
    }
    if (listing?.default_view === "grid" || listing?.default_view === "list" || listing?.default_view === "table") {
      setViewMode(listing.default_view);
    }
  }, [listing?.default_view]);
  reactExports.useEffect(() => {
    setSelectedIds((current) => current.filter((id) => selectableIds.includes(id)));
  }, [visibleItems, supportsArtworkBulk]);
  reactExports.useEffect(() => {
    setOptimisticRemovedIds([]);
  }, [items]);
  reactExports.useEffect(() => {
    setPendingFilters({
      q: filters.q || "",
      bucket: filters.bucket || "all",
      sort: filters.sort || defaultSort,
      content_type: filters.content_type || "all",
      category: filters.category || "all",
      tag: filters.tag || ""
    });
  }, [filters.q, filters.bucket, filters.sort, filters.content_type, filters.category, filters.tag, defaultSort]);
  reactExports.useEffect(() => {
    if (!sortStorageKey) {
      return;
    }
    const params = new URLSearchParams(window.location.search);
    if (params.has("sort")) {
      return;
    }
    const storedSort = window.localStorage.getItem(sortStorageKey);
    const sortOptions = new Set((listing?.sort_options || []).map((option) => option.value));
    const activeSort = filters.sort || defaultSort;
    if (!storedSort || !sortOptions.has(storedSort) || storedSort === activeSort) {
      return;
    }
    At.get(window.location.pathname, {
      ...filters,
      sort: storedSort,
      page: 1
    }, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  }, [sortStorageKey, listing?.sort_options, filters, defaultSort]);
  const updateQuery = (patch2) => {
    const next = {
      ...filters,
      ...patch2
    };
    if (patch2.page == null) {
      next.page = 1;
    }
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: filters.module || listing?.module || null,
      meta: {
        patch: patch2
      }
    });
    if (sortStorageKey && typeof next.sort === "string" && next.sort !== "") {
      window.localStorage.setItem(sortStorageKey, next.sort);
    }
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  const updateView = (nextMode) => {
    setViewMode(nextMode);
    window.localStorage.setItem("studio-content-view", nextMode);
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: filters.module || listing?.module || null,
      meta: {
        view_mode: nextMode
      }
    });
  };
  const setPendingFilter = (key, value) => {
    setPendingFilters((current) => {
      if (key === "content_type") {
        return {
          ...current,
          content_type: value,
          category: "all"
        };
      }
      return {
        ...current,
        [key]: value
      };
    });
  };
  const submitSearch = () => {
    updateQuery({
      q: pendingFilters.q,
      bucket: pendingFilters.bucket,
      sort: pendingFilters.sort,
      content_type: pendingFilters.content_type,
      category: pendingFilters.category,
      tag: pendingFilters.tag
    });
  };
  const addOptimisticallyRemovedIds = (ids) => {
    setOptimisticRemovedIds((current) => Array.from(/* @__PURE__ */ new Set([
      ...current,
      ...ids.map((value) => Number(value)).filter((value) => Number.isInteger(value) && value > 0)
    ])));
  };
  const toggleSelected = (numericId) => {
    setSelectedIds((current) => current.includes(numericId) ? current.filter((id) => id !== numericId) : [...current, numericId]);
  };
  const toggleSelectAllVisible = () => {
    if (!supportsArtworkBulk || selectableIds.length === 0) {
      return;
    }
    setSelectedIds((current) => {
      if (allVisibleSelected) {
        return current.filter((id) => !selectableIds.includes(id));
      }
      return Array.from(/* @__PURE__ */ new Set([...current, ...selectableIds]));
    });
  };
  const executeBulkAction = async (actionKey) => {
    if (!supportsArtworkBulk || selectedIds.length === 0 || bulkBusy) {
      return;
    }
    const labels = {
      publish: "publish",
      unpublish: "move to draft",
      archive: "archive",
      unarchive: "restore",
      delete: "delete permanently"
    };
    if (actionKey === "delete") {
      setDeleteDialog({
        open: true,
        title: `Delete ${selectedIds.length} artwork${selectedIds.length === 1 ? "" : "s"}?`,
        message: "This permanently removes the selected artworks. This cannot be undone.",
        target: {
          kind: "bulk",
          actionKey,
          ids: [...selectedIds]
        }
      });
      return;
    }
    if (!window.confirm(`Are you sure you want to ${labels[actionKey] || actionKey} ${selectedIds.length} artwork${selectedIds.length === 1 ? "" : "s"}?`)) {
      return;
    }
    setBulkBusy(true);
    try {
      const response = await fetch("/api/studio/artworks/bulk", {
        method: "POST",
        credentials: "same-origin",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
          "X-Requested-With": "XMLHttpRequest"
        },
        body: JSON.stringify({
          action: actionKey,
          artwork_ids: selectedIds
        })
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(bulkErrorMessage(payload));
      }
      trackStudioEvent("studio_filter_used", {
        surface: studioSurface(),
        module: "artworks",
        meta: {
          bulk_action: actionKey,
          count: selectedIds.length
        }
      });
      setSelectedIds([]);
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Bulk action failed.");
    } finally {
      setBulkBusy(false);
    }
  };
  const closeDeleteDialog = () => {
    setDeleteDialog({
      open: false,
      title: "",
      message: "",
      target: null
    });
  };
  const confirmDeleteDialog = async () => {
    const target = deleteDialog.target;
    if (!target) {
      closeDeleteDialog();
      return;
    }
    if (target.kind === "bulk") {
      setBulkBusy(true);
      try {
        const response = await fetch("/api/studio/artworks/bulk", {
          method: "POST",
          credentials: "same-origin",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
            "X-Requested-With": "XMLHttpRequest"
          },
          body: JSON.stringify({
            action: "delete",
            artwork_ids: target.ids,
            confirm: "DELETE"
          })
        });
        const payload = await response.json().catch(() => ({}));
        if (!response.ok) {
          throw new Error(bulkErrorMessage(payload));
        }
        trackStudioEvent("studio_filter_used", {
          surface: studioSurface(),
          module: "artworks",
          meta: {
            bulk_action: "delete",
            count: target.ids.length
          }
        });
        addOptimisticallyRemovedIds(target.ids);
        setSelectedIds([]);
        closeDeleteDialog();
        At.reload({ preserveScroll: true, preserveState: true });
      } catch (error) {
        window.alert(error?.message || "Bulk action failed.");
      } finally {
        setBulkBusy(false);
      }
      return;
    }
    if (target.kind === "single") {
      const action = target.action;
      const requestKey = `${action.key}:${action.url}`;
      setBusyKey(requestKey);
      try {
        const response = await fetch(action.url, {
          method: String(action.method || "post").toUpperCase(),
          credentials: "same-origin",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
            "X-Requested-With": "XMLHttpRequest"
          },
          body: action.payload ? JSON.stringify(action.payload) : void 0
        });
        const payload = await response.json().catch(() => ({}));
        if (!response.ok) {
          throw new Error(payload?.message || payload?.error || "Request failed");
        }
        addOptimisticallyRemovedIds(action.payload?.artwork_ids || []);
        closeDeleteDialog();
        if (action.redirect_pattern && payload?.data?.id) {
          window.location.assign(action.redirect_pattern.replace("__ID__", String(payload.data.id)));
          return;
        }
        if (payload?.redirect) {
          window.location.assign(payload.redirect);
          return;
        }
        At.reload({ preserveScroll: true, preserveState: true });
      } catch (error) {
        window.alert(error?.message || "Action failed.");
      } finally {
        setBusyKey(null);
      }
    }
  };
  const executeAction = async (action) => {
    if (!action?.url || action.type !== "request") {
      return;
    }
    if (action.key === "delete") {
      setDeleteDialog({
        open: true,
        title: "Delete artwork permanently?",
        message: action.confirm || "This artwork will be permanently removed and cannot be restored.",
        target: {
          kind: "single",
          action
        }
      });
      return;
    }
    if (action.confirm && !window.confirm(action.confirm)) {
      return;
    }
    const requestKey = `${action.key}:${action.url}`;
    setBusyKey(requestKey);
    try {
      const response = await fetch(action.url, {
        method: String(action.method || "post").toUpperCase(),
        credentials: "same-origin",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
          "X-Requested-With": "XMLHttpRequest"
        },
        body: action.payload ? JSON.stringify(action.payload) : void 0
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(payload?.message || payload?.error || "Request failed");
      }
      if (action.key === "archive") {
        trackStudioEvent("studio_item_archived", {
          surface: studioSurface(),
          module: filters.module || null,
          item_module: action.item_module || null,
          item_id: action.item_id || null,
          meta: {
            action: action.key,
            url: action.url
          }
        });
      }
      if (action.key === "restore") {
        trackStudioEvent("studio_item_restored", {
          surface: studioSurface(),
          module: filters.module || null,
          item_module: action.item_module || null,
          item_id: action.item_id || null,
          meta: {
            action: action.key,
            url: action.url
          }
        });
      }
      if (action.redirect_pattern && payload?.data?.id) {
        window.location.assign(action.redirect_pattern.replace("__ID__", String(payload.data.id)));
        return;
      }
      if (payload?.redirect) {
        window.location.assign(payload.redirect);
        return;
      }
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Action failed.");
    } finally {
      setBusyKey(null);
    }
  };
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.12),_transparent_35%),radial-gradient(circle_at_bottom_right,_rgba(56,189,248,0.12),_transparent_40%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 shadow-[0_22px_60px_rgba(2,6,23,0.28)] lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end" }, /* @__PURE__ */ React.createElement("div", { className: `grid gap-3 md:grid-cols-2 ${filterGridClass}` }, /* @__PURE__ */ React.createElement(FilterField, { label: "Search" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: pendingFilters.q,
      onChange: (event) => setPendingFilter("q", event.target.value),
      placeholder: "Title, description, module",
      className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none transition placeholder:text-slate-500 focus:border-sky-300/40 focus:bg-black/30"
    }
  )), !hideModuleFilter && /* @__PURE__ */ React.createElement(FilterField, { label: "Module" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      id: "studio-filter-module",
      options: selectOptions(listing?.module_options || []),
      value: filters.module || "all",
      onChange: (nextValue) => updateQuery({ module: nextValue ?? "all" }),
      placeholder: "All content",
      searchable: false
    }
  )), !hideBucketFilter && /* @__PURE__ */ React.createElement(FilterField, { label: "Status" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      id: "studio-filter-status",
      options: selectOptions(listing?.bucket_options || []),
      value: pendingFilters.bucket,
      onChange: (nextValue) => setPendingFilter("bucket", nextValue ?? "all"),
      placeholder: "All",
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement(FilterField, { label: "Sort" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      id: "studio-filter-sort",
      options: selectOptions(listing?.sort_options || []),
      value: pendingFilters.sort,
      onChange: (nextValue) => setPendingFilter("sort", nextValue ?? defaultSort),
      placeholder: "Recently updated",
      searchable: false
    }
  )), advancedFilters.map((filter2) => {
    const resolvedFilter = materializeFilter(filter2, pendingFilters);
    return /* @__PURE__ */ React.createElement(
      AdvancedFilterControl,
      {
        key: filter2.key,
        filter: resolvedFilter,
        value: filter2.key === "content_type" || filter2.key === "category" || filter2.key === "tag" ? pendingFilters[filter2.key] : void 0,
        onChange: (key, value) => {
          if (key === "content_type" || key === "category" || key === "tag") {
            setPendingFilter(key, value);
            return;
          }
          updateQuery({ [key]: value });
        }
      }
    );
  }), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: submitSearch,
      className: "inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-300/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-magnifying-glass" }),
    /* @__PURE__ */ React.createElement("span", null, "Search")
  ))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-white/10 bg-black/20 p-1" }, [
    { value: "grid", icon: "fa-solid fa-table-cells-large", label: "Grid view" },
    { value: "list", icon: "fa-solid fa-list", label: "List view" },
    { value: "table", icon: "fa-solid fa-table-list", label: "Table view" }
  ].map((option) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: option.value,
      type: "button",
      onClick: () => updateView(option.value),
      className: `inline-flex items-center gap-2 rounded-full px-3 py-2 text-xs font-semibold transition ${viewMode === option.value ? "bg-white text-slate-950" : "text-slate-300 hover:text-white"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: option.icon }),
    /* @__PURE__ */ React.createElement("span", { className: "hidden sm:inline" }, option.label)
  ))), visibleQuickCreate.map((action) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: action.key,
      href: action.url,
      onClick: () => trackStudioEvent("studio_quick_create_used", {
        surface: studioSurface(),
        module: action.key,
        meta: {
          href: action.url,
          label: action.label
        }
      }),
      className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15"
    },
    /* @__PURE__ */ React.createElement("i", { className: action.icon }),
    /* @__PURE__ */ React.createElement("span", null, "New ", action.label)
  ))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Showing ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, visibleItems.length), " of ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, visibleTotal.toLocaleString()), " items"), /* @__PURE__ */ React.createElement("p", null, "Page ", currentPage, " of ", lastPage)), viewMode === "table" && supportsArtworkBulk && /* @__PURE__ */ React.createElement("section", { className: "flex flex-wrap items-center justify-between gap-3 rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: allVisibleSelected,
      onChange: toggleSelectAllVisible,
      label: "Select page"
    }
  )), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, selectedIds.length > 0 ? `${selectedIds.length} selected` : "Select artworks to run bulk actions")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, [
    { key: "publish", label: "Publish", icon: "fa-solid fa-rocket" },
    { key: "unpublish", label: "Draft", icon: "fa-solid fa-file-pen" },
    { key: "archive", label: "Archive", icon: "fa-solid fa-box-archive" },
    { key: "unarchive", label: "Restore", icon: "fa-solid fa-rotate-left" },
    { key: "delete", label: "Delete", icon: "fa-solid fa-trash" }
  ].map((action) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: action.key,
      type: "button",
      disabled: selectedIds.length === 0 || bulkBusy,
      onClick: () => executeBulkAction(action.key),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-black/20 px-3 py-2 text-xs font-semibold text-slate-200 transition hover:border-white/20 hover:bg-black/30 disabled:cursor-not-allowed disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("i", { className: action.icon }),
    /* @__PURE__ */ React.createElement("span", null, bulkBusy ? "Working..." : action.label)
  )))), visibleItems.length > 0 ? viewMode === "grid" ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4" }, visibleItems.map((item) => /* @__PURE__ */ React.createElement(GridCard, { key: item.id, item, onExecuteAction: executeAction, busyKey }))) : viewMode === "list" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, visibleItems.map((item) => /* @__PURE__ */ React.createElement(ListRow$1, { key: item.id, item, onExecuteAction: executeAction, busyKey }))) : /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/10 text-left text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("thead", { className: "bg-black/20 text-[11px] uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("tr", null, supportsArtworkBulk && /* @__PURE__ */ React.createElement("th", { scope: "col", className: "w-12 px-4 py-3" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: allVisibleSelected,
      onChange: toggleSelectAllVisible,
      "aria-label": "Select all artworks on this page"
    }
  )), /* @__PURE__ */ React.createElement("th", { scope: "col", className: "px-4 py-3" }, "Item"), /* @__PURE__ */ React.createElement("th", { scope: "col", className: "px-4 py-3" }, "Status"), /* @__PURE__ */ React.createElement("th", { scope: "col", className: "px-4 py-3" }, "Category"), /* @__PURE__ */ React.createElement("th", { scope: "col", className: "px-4 py-3" }, "Updated"), /* @__PURE__ */ React.createElement("th", { scope: "col", className: "px-4 py-3" }, "Stats"), /* @__PURE__ */ React.createElement("th", { scope: "col", className: "px-4 py-3" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/5" }, visibleItems.map((item) => {
    const isSelected = selectedOnPage.includes(Number(item.numeric_id));
    return /* @__PURE__ */ React.createElement("tr", { key: item.id, className: "align-top transition hover:bg-white/[0.03]" }, supportsArtworkBulk && /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement(
      Checkbox,
      {
        checked: isSelected,
        onChange: () => toggleSelected(Number(item.numeric_id)),
        "aria-label": `Select ${item.title}`
      }
    )), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-[280px] items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-16 w-16 shrink-0 overflow-hidden rounded-2xl bg-slate-950/60" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: `${item.module_icon} text-lg` }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: `${item.module_icon} text-[10px]` }), item.module_label), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "#", item.numeric_id)), /* @__PURE__ */ React.createElement("div", { className: "mt-2 truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, item.subtitle || item.visibility || "Untitled metadata"), Array.isArray(item.taxonomies?.tags) && item.taxonomies.tags.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-1.5" }, item.taxonomies.tags.slice(0, 3).map((tag) => /* @__PURE__ */ React.createElement("span", { key: `${item.id}-${tag.slug}`, className: "rounded-full border border-white/10 px-2 py-1 text-[10px] text-slate-400" }, tag.name)))))), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-medium capitalize ${statusClasses$1(item.status)}` }, String(item.status || "unknown").replace("_", " ")), itemReadiness(item) && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-medium ${readinessClasses(itemReadiness(item))}` }, itemReadiness(item).label)))), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, item.subtitle || item.taxonomies?.categories?.[0]?.name || "Uncategorized"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.visibility || "private")), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, "Updated ", formatDate$6(item.updated_at)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Created ", formatDate$6(item.created_at)), item.published_at && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Published ", formatDate$6(item.published_at))), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, metricValue$1(item, "views"), " views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, metricValue$1(item, "appreciation"), " reactions"), /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, metricValue$1(item, "comments"), " comments")), /* @__PURE__ */ React.createElement("td", { className: "px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-[220px] flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(ActionLink, { href: item.edit_url || item.manage_url, icon: "fa-solid fa-pen-to-square", label: "Edit" }), /* @__PURE__ */ React.createElement(PreviewLink, { item }), /* @__PURE__ */ React.createElement(ActionLink, { href: item.view_url, icon: "fa-solid fa-arrow-up-right-from-square", label: "Open" }), (item.actions || []).slice(0, 2).map((action) => /* @__PURE__ */ React.createElement(RequestActionButton, { key: `${item.id}-${action.key}`, action: { ...action, item_id: item.numeric_id, item_module: item.module }, onExecute: executeAction, busyKey })))));
  }))))) : /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-dashed border-white/15 bg-white/[0.02] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, emptyTitle), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm text-slate-400" }, emptyBody)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.2em] text-slate-500" }, "Creator Studio"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, visibleTotal > 0 ? /* @__PURE__ */ React.createElement(React.Fragment, null, "Showing ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, rangeStart.toLocaleString(), "-", rangeEnd.toLocaleString()), " of ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, visibleTotal.toLocaleString())) : "No items to display")), lastPage > 1 && /* @__PURE__ */ React.createElement("nav", { "aria-label": "Studio pagination", className: "flex flex-col gap-3 lg:items-end" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: currentPage <= 1,
      onClick: () => updateQuery({ page: 1 }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-slate-300 transition hover:border-white/20 hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-angles-left" }),
    /* @__PURE__ */ React.createElement("span", { className: "hidden sm:inline" }, "First")
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: currentPage <= 1,
      onClick: () => updateQuery({ page: Math.max(1, currentPage - 1) }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-slate-300 transition hover:border-white/20 hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }),
    /* @__PURE__ */ React.createElement("span", null, "Previous")
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-1.5" }, paginationPages.map((page, index2) => page === "ellipsis" ? /* @__PURE__ */ React.createElement("span", { key: `ellipsis-${index2}`, className: "inline-flex h-10 min-w-[2.5rem] items-center justify-center text-xs font-semibold uppercase tracking-[0.16em] text-slate-500" }, "...") : /* @__PURE__ */ React.createElement(
    "button",
    {
      key: page,
      type: "button",
      "aria-current": page === currentPage ? "page" : void 0,
      onClick: () => updateQuery({ page }),
      className: `inline-flex h-10 min-w-[2.5rem] items-center justify-center rounded-2xl border px-3 text-sm font-semibold transition ${page === currentPage ? "border-sky-400/30 bg-sky-300/15 text-white shadow-[0_10px_24px_rgba(14,165,233,0.16)]" : "border-white/10 text-slate-300 hover:border-white/20 hover:bg-white/[0.04]"}`
    },
    page
  ))), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: currentPage >= lastPage,
      onClick: () => updateQuery({ page: currentPage + 1 }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-slate-300 transition hover:border-white/20 hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("span", null, "Next"),
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: currentPage >= lastPage,
      onClick: () => updateQuery({ page: lastPage }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-slate-300 transition hover:border-white/20 hover:bg-white/[0.04] disabled:cursor-not-allowed disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("span", { className: "hidden sm:inline" }, "Last"),
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-angles-right" })
  )), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Jump by page number or use first/last for longer queues.")))), /* @__PURE__ */ React.createElement(
    ConfirmDangerModal,
    {
      open: deleteDialog.open,
      onClose: closeDeleteDialog,
      onConfirm: confirmDeleteDialog,
      title: deleteDialog.title,
      message: deleteDialog.message,
      confirmText: "DELETE"
    }
  ));
}
function StudioArchived() {
  const { props } = X$1();
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      hideBucketFilter: true,
      emptyTitle: "No archived content",
      emptyBody: "Nothing is currently hidden or archived across your creator modules."
    }
  ));
}
const __vite_glob_0_107 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioArchived
}, Symbol.toStringTag, { value: "Module" }));
const kpiItems$1 = [
  { key: "views", label: "Views", icon: "fa-eye", color: "text-emerald-400" },
  { key: "favourites", label: "Favourites", icon: "fa-heart", color: "text-pink-400" },
  { key: "shares", label: "Shares", icon: "fa-share-nodes", color: "text-amber-400" },
  { key: "comments", label: "Comments", icon: "fa-comment", color: "text-blue-400" },
  { key: "downloads", label: "Downloads", icon: "fa-download", color: "text-purple-400" }
];
const metricCards = [
  { key: "ranking_score", label: "Ranking Score", icon: "fa-trophy", color: "text-yellow-400" },
  { key: "heat_score", label: "Heat Score", icon: "fa-fire", color: "text-orange-400" },
  { key: "engagement_velocity", label: "Engagement Velocity", icon: "fa-bolt", color: "text-cyan-400" }
];
function StudioArtworkAnalytics() {
  const { props } = X$1();
  const { artwork, analytics } = props;
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: `Analytics: ${artwork?.title || "Artwork"}` }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: "/studio/artworks",
      className: "inline-flex items-center gap-2 text-sm text-slate-400 hover:text-white mb-6 transition-colors"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }),
    "Back to Artworks"
  ), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 mb-8 bg-nova-900/60 border border-white/10 rounded-2xl p-4" }, artwork?.thumb_url && /* @__PURE__ */ React.createElement(
    "img",
    {
      src: artwork.thumb_url,
      alt: artwork.title,
      className: "w-20 h-20 rounded-xl object-cover bg-nova-800"
    }
  ), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-bold text-white" }, artwork?.title), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mt-1" }, "/", artwork?.slug))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4 mb-8" }, kpiItems$1.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "bg-nova-900/60 border border-white/10 rounded-2xl p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-2" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} ${item.color}` }), /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium text-slate-400 uppercase tracking-wider" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-2xl font-bold text-white tabular-nums" }, (analytics?.[item.key] ?? 0).toLocaleString())))), /* @__PURE__ */ React.createElement("h3", { className: "text-base font-bold text-white mb-4" }, "Performance Metrics"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8" }, metricCards.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "bg-nova-900/60 border border-white/10 rounded-2xl p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-3" }, /* @__PURE__ */ React.createElement("div", { className: `w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center ${item.color}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} text-lg` })), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-slate-300" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-3xl font-bold text-white tabular-nums" }, (analytics?.[item.key] ?? 0).toFixed(1))))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "bg-nova-900/40 border border-white/10 rounded-2xl p-6" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white mb-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-line mr-2 text-slate-500" }), "Traffic Sources"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-pie text-3xl text-slate-700 mb-3" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Coming soon"), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1" }, "Traffic source tracking is on the roadmap")))), /* @__PURE__ */ React.createElement("div", { className: "bg-nova-900/40 border border-white/10 rounded-2xl p-6" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white mb-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-from-square mr-2 text-slate-500" }), "Shares by Platform"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes text-3xl text-slate-700 mb-3" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Coming soon"), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1" }, "Per-platform breakdown coming in a future update")))), /* @__PURE__ */ React.createElement("div", { className: "bg-nova-900/40 border border-white/10 rounded-2xl p-6 lg:col-span-2" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white mb-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy mr-2 text-slate-500" }), "Ranking History"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-area text-3xl text-slate-700 mb-3" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Coming soon"), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1" }, "Historical ranking data will be tracked in a future update"))))));
}
const __vite_glob_0_108 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioArtworkAnalytics
}, Symbol.toStringTag, { value: "Module" }));
function ToolbarButton({ title, onClick, children, className = "" }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      title,
      onMouseDown: (event) => {
        event.preventDefault();
        onClick?.();
      },
      className: [
        "inline-flex h-8 min-w-8 items-center justify-center rounded-md px-2 text-xs font-semibold text-white/60 transition",
        "hover:bg-white/10 hover:text-white",
        className
      ].join(" ")
    },
    children
  );
}
function UploadDescriptionEditor({ id, value, onChange, placeholder, error, rows = 8 }) {
  const [tab2, setTab] = reactExports.useState("write");
  const textareaRef = reactExports.useRef(null);
  const focusTextarea = reactExports.useCallback(() => {
    requestAnimationFrame(() => {
      textareaRef.current?.focus();
    });
  }, []);
  const wrapSelection = reactExports.useCallback((before, after, placeholderText = "text") => {
    const textarea = textareaRef.current;
    if (!textarea) return;
    const current = String(value || "");
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selected = current.slice(start, end);
    const replacement = `${before}${selected || placeholderText}${after}`;
    const next = current.slice(0, start) + replacement + current.slice(end);
    onChange?.(next);
    requestAnimationFrame(() => {
      textarea.focus();
      if (selected) {
        textarea.selectionStart = start + replacement.length;
        textarea.selectionEnd = start + replacement.length;
      } else {
        textarea.selectionStart = start + before.length;
        textarea.selectionEnd = start + before.length + placeholderText.length;
      }
    });
  }, [onChange, value]);
  const prefixLines = reactExports.useCallback((prefix) => {
    const textarea = textareaRef.current;
    if (!textarea) return;
    const current = String(value || "");
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selected = current.slice(start, end);
    const fallback = prefix.endsWith(". ") ? `${prefix}item` : `${prefix}item`;
    const source = selected || fallback;
    const nextBlock = source.split("\n").map((line) => `${prefix}${line}`).join("\n");
    const next = current.slice(0, start) + nextBlock + current.slice(end);
    onChange?.(next);
    requestAnimationFrame(() => {
      textarea.focus();
      textarea.selectionStart = start;
      textarea.selectionEnd = start + nextBlock.length;
    });
  }, [onChange, value]);
  const insertLink = reactExports.useCallback(() => {
    const textarea = textareaRef.current;
    if (!textarea) return;
    const current = String(value || "");
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selected = current.slice(start, end);
    const replacement = selected && /^https?:\/\//i.test(selected) ? `[link](${selected})` : `[link](https://)`;
    const next = current.slice(0, start) + replacement + current.slice(end);
    onChange?.(next);
    requestAnimationFrame(() => {
      textarea.focus();
      if (selected && /^https?:\/\//i.test(selected)) {
        textarea.selectionStart = start + 1;
        textarea.selectionEnd = start + 5;
      } else {
        const urlStart = start + replacement.indexOf("https://");
        textarea.selectionStart = urlStart;
        textarea.selectionEnd = urlStart + "https://".length;
      }
    });
  }, [onChange, value]);
  const insertAtCursor = reactExports.useCallback((text2) => {
    const textarea = textareaRef.current;
    if (!textarea) {
      onChange?.(`${String(value || "")}${text2}`);
      return;
    }
    const current = String(value || "");
    const start = textarea.selectionStart ?? current.length;
    const end = textarea.selectionEnd ?? current.length;
    const next = current.slice(0, start) + text2 + current.slice(end);
    onChange?.(next);
    requestAnimationFrame(() => {
      textarea.focus();
      textarea.selectionStart = start + text2.length;
      textarea.selectionEnd = start + text2.length;
    });
  }, [onChange, value]);
  const handleKeyDown2 = reactExports.useCallback((event) => {
    const withModifier = event.ctrlKey || event.metaKey;
    if (!withModifier) return;
    switch (event.key.toLowerCase()) {
      case "b":
        event.preventDefault();
        wrapSelection("**", "**");
        break;
      case "i":
        event.preventDefault();
        wrapSelection("*", "*");
        break;
      case "k":
        event.preventDefault();
        insertLink();
        break;
      case "e":
        event.preventDefault();
        wrapSelection("`", "`");
        break;
    }
  }, [insertLink, wrapSelection]);
  const previewValue = String(value || "").trim();
  return /* @__PURE__ */ React.createElement("div", { className: `overflow-hidden rounded-xl border bg-white/10 ${error ? "border-red-300/60" : "border-white/15"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/10 px-2 py-1.5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTab("write"),
      className: `rounded-md px-2.5 py-1 text-xs font-medium transition ${tab2 === "write" ? "bg-white/12 text-white" : "text-white/55 hover:text-white/80"}`
    },
    "Write"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setTab("preview"),
      className: `rounded-md px-2.5 py-1 text-xs font-medium transition ${tab2 === "preview" ? "bg-white/12 text-white" : "text-white/55 hover:text-white/80"}`
    },
    "Preview"
  )), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-white/40" }, "Safe formatting only")), tab2 === "write" && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-1 border-b border-white/10 px-2 py-1" }, /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, "B"), /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, "I"), /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, "</>"), /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Link (Ctrl+K)", onClick: insertLink }, "Link"), /* @__PURE__ */ React.createElement("span", { className: "mx-1 h-4 w-px bg-white/10", "aria-hidden": "true" }), /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Bulleted list", onClick: () => prefixLines("- ") }, "List"), /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Numbered list", onClick: () => prefixLines("1. ") }, "1."), /* @__PURE__ */ React.createElement(ToolbarButton, { title: "Quote", onClick: () => prefixLines("> ") }, "Quote"), /* @__PURE__ */ React.createElement("span", { className: "mx-1 h-4 w-px bg-white/10", "aria-hidden": "true" }), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: insertAtCursor, className: "h-8 w-8 rounded-md text-white/60 hover:bg-white/10 hover:text-white" })), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      id,
      ref: textareaRef,
      value,
      onChange: (event) => onChange?.(event.target.value),
      onKeyDown: handleKeyDown2,
      rows,
      className: "w-full resize-y bg-transparent px-3 py-3 text-sm text-white placeholder-white/45 focus:outline-none",
      placeholder
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-2 px-3 pb-2 text-[11px] text-white/45" }, /* @__PURE__ */ React.createElement("span", null, "Supports bold, italic, code, links, lists, quotes, and emoji."), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: focusTextarea, className: "text-white/50 transition hover:text-white/80" }, "Continue editing"))), tab2 === "preview" && /* @__PURE__ */ React.createElement("div", { className: "min-h-[188px] px-3 py-3" }, previewValue ? /* @__PURE__ */ React.createElement("div", { className: "prose prose-invert prose-sm max-w-none text-white/85 [&_a]:text-sky-300 [&_a]:no-underline hover:[&_a]:underline [&_blockquote]:border-l-2 [&_blockquote]:border-white/20 [&_blockquote]:pl-3 [&_code]:rounded [&_code]:bg-white/10 [&_code]:px-1 [&_code]:py-0.5 [&_ul]:pl-4 [&_ol]:pl-4" }, /* @__PURE__ */ React.createElement(
    Markdown,
    {
      allowedElements: ["p", "strong", "em", "a", "code", "pre", "ul", "ol", "li", "blockquote", "br"],
      unwrapDisallowed: true,
      components: {
        a: ({ href, children }) => /* @__PURE__ */ React.createElement("a", { href, target: "_blank", rel: "noopener noreferrer nofollow" }, children)
      }
    },
    previewValue
  )) : /* @__PURE__ */ React.createElement("p", { className: "text-sm italic text-white/35" }, "Nothing to preview yet.")));
}
function FormField({ label, required, error, hint, htmlFor, children, className = "" }) {
  return /* @__PURE__ */ React.createElement("div", { className: `flex flex-col gap-1.5 ${className}` }, label && /* @__PURE__ */ React.createElement(
    "label",
    {
      htmlFor,
      className: "text-sm font-medium text-white/85 select-none"
    },
    label,
    required && /* @__PURE__ */ React.createElement("span", { className: "text-red-400 ml-1" }, "*")
  ), children, error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error), !error && hint && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, hint));
}
const sizeMap = {
  sm: { track: "w-8  h-4", thumb: "w-3  h-3", translate: "translate-x-4", offset: "translate-x-0.5" },
  md: { track: "w-10 h-5", thumb: "w-3.5 h-3.5", translate: "translate-x-5", offset: "translate-x-[3px]" },
  lg: { track: "w-12 h-6", thumb: "w-4.5 h-4.5", translate: "translate-x-6", offset: "translate-x-[3px]" }
};
const variantMap = {
  accent: "bg-accent",
  emerald: "bg-emerald-500",
  sky: "bg-sky-500"
};
const Toggle = reactExports.forwardRef(function Toggle2({ checked = false, onChange, label, hint, size = "md", variant = "accent", id, disabled = false, className = "" }, ref2) {
  const s2 = sizeMap[size] ?? sizeMap.md;
  const vClass = variantMap[variant] ?? variantMap.accent;
  const inputId = id ?? (label ? `toggle-${label.toLowerCase().replace(/\s+/g, "-")}` : void 0);
  return /* @__PURE__ */ React.createElement(
    "label",
    {
      className: [
        "inline-flex items-start gap-3 cursor-pointer select-none",
        disabled ? "opacity-50 cursor-not-allowed pointer-events-none" : "",
        className
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "checkbox",
        id: inputId,
        ref: ref2,
        checked,
        onChange,
        disabled,
        className: "sr-only",
        role: "switch",
        "aria-checked": checked
      }
    ),
    /* @__PURE__ */ React.createElement(
      "span",
      {
        className: [
          "relative inline-flex shrink-0 rounded-full transition-colors duration-200 mt-px",
          s2.track,
          checked ? vClass : "bg-white/15",
          "focus-within:ring-2 focus-within:ring-accent/50 focus-within:ring-offset-0"
        ].join(" "),
        "aria-hidden": "true"
      },
      /* @__PURE__ */ React.createElement(
        "span",
        {
          className: [
            "absolute top-1/2 -translate-y-1/2 rounded-full bg-white shadow transition-transform duration-200",
            s2.thumb,
            checked ? s2.translate : s2.offset
          ].join(" ")
        }
      )
    ),
    (label || hint) && /* @__PURE__ */ React.createElement("span", { className: "flex flex-col gap-0.5" }, label && /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/90 leading-snug" }, label), hint && /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, hint))
  );
});
const FALLBACK_MAX_USER_TAGS = 30;
function getMaxUserTags() {
  if (typeof window === "undefined") return FALLBACK_MAX_USER_TAGS;
  const value = Number(window.SKINBASE_LIMITS?.tags?.max_user_tags);
  return Number.isInteger(value) && value > 0 ? value : FALLBACK_MAX_USER_TAGS;
}
const DEBOUNCE_MS$1 = 250;
const MAX_RESULTS = 30;
const MIN_LENGTH = 2;
const MAX_LENGTH = 32;
function normalizeSlug(raw) {
  return String(raw ?? "").trim().toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9_-]/g, "").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, "").slice(0, MAX_LENGTH);
}
function parseTagList$1(input) {
  if (Array.isArray(input)) return input;
  if (typeof input !== "string") return [];
  return input.split(/[\n,]+/).map((item) => item.trim()).filter(Boolean);
}
function analyzePastedTags$1(rawText, selectedSlugs, maxTags) {
  const parts = parseTagList$1(rawText);
  const itemsToAdd = [];
  const skippedDuplicates = [];
  const skippedInvalid = [];
  const skippedOverflow = [];
  for (const part of parts) {
    const name2 = String(part ?? "").trim();
    const slug = normalizeSlug(name2);
    if (!slug || slug.length < MIN_LENGTH || slug.length > MAX_LENGTH) {
      skippedInvalid.push(name2);
      continue;
    }
    if (selectedSlugs.includes(slug) || itemsToAdd.some((item) => item.slug === slug)) {
      skippedDuplicates.push(slug);
      continue;
    }
    if (selectedSlugs.length + itemsToAdd.length >= maxTags) {
      skippedOverflow.push(slug);
      continue;
    }
    itemsToAdd.push({ slug, name: name2 });
  }
  return {
    parsedCount: parts.length,
    itemsToAdd,
    nextSlugs: [...selectedSlugs, ...itemsToAdd.map((item) => item.slug)],
    skippedDuplicates,
    skippedInvalid,
    skippedOverflow
  };
}
function toListItem(item) {
  if (!item) return null;
  if (typeof item === "string") {
    const slug2 = normalizeSlug(item);
    return slug2 ? { key: slug2, slug: slug2, name: slug2, usageCount: null, recentClicks: 0, isAi: false } : null;
  }
  const slug = normalizeSlug(item.slug || item.tag || item.name || "");
  if (!slug) return null;
  const usageCount = Number(item.usage_count);
  const recentClicks = Number(item.recent_clicks);
  return {
    key: String(item.id ?? slug),
    slug,
    name: item.name || item.tag || item.slug || slug,
    usageCount: Number.isFinite(usageCount) ? usageCount : null,
    recentClicks: Number.isFinite(recentClicks) ? recentClicks : 0,
    isAi: Boolean(item.is_ai || item.source === "ai")
  };
}
function SearchInput$1({ value, onChange, onKeyDown, onPaste, inputRef, disabled, hint }) {
  return /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      ref: inputRef,
      type: "text",
      value,
      onChange: (e) => onChange(e.target.value),
      onKeyDown,
      onPaste,
      disabled,
      className: "w-full rounded-xl border border-white/10 bg-white/5 py-2.5 pl-3 pr-9 text-sm text-white placeholder:text-white/40 focus:border-accent/50 focus:outline-none focus:ring-2 focus:ring-accent/30 disabled:cursor-not-allowed disabled:opacity-60",
      placeholder: hint || "Search or add tags…",
      "aria-label": "Search or add tags",
      autoComplete: "off",
      spellCheck: false
    }
  ), /* @__PURE__ */ React.createElement(
    "svg",
    {
      className: "pointer-events-none absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-white/35",
      viewBox: "0 0 20 20",
      fill: "currentColor",
      "aria-hidden": "true"
    },
    /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M12.9 14.32a8 8 0 111.414-1.414l4.387 4.387-1.414 1.414-4.387-4.387zM8 14A6 6 0 108 2a6 6 0 000 12z", clipRule: "evenodd" })
  ));
}
function SelectedChips({ slugs, names, onRemove, disabled }) {
  if (slugs.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-1.5" }, slugs.map((slug) => /* @__PURE__ */ React.createElement(
    "span",
    {
      key: slug,
      className: "inline-flex items-center gap-1 rounded-lg bg-accent/20 px-2.5 py-1 text-xs font-medium text-accent"
    },
    names[slug] || slug,
    /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => onRemove(slug),
        disabled,
        className: "ml-0.5 flex h-4 w-4 items-center justify-center rounded-full hover:bg-white/15 disabled:cursor-not-allowed",
        "aria-label": `Remove tag ${names[slug] || slug}`
      },
      /* @__PURE__ */ React.createElement("svg", { className: "h-2.5 w-2.5", viewBox: "0 0 10 10", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M6.414 5l2.293-2.293a1 1 0 00-1.414-1.414L5 3.586 2.707 1.293A1 1 0 001.293 2.707L3.586 5 1.293 7.293a1 1 0 101.414 1.414L5 6.414l2.293 2.293a1 1 0 001.414-1.414L6.414 5z" }))
    )
  )));
}
function AddNewRow({ label, onAdd, disabled }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onAdd,
      disabled,
      className: "flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-sm text-sky-300 transition-all hover:bg-sky-400/10 disabled:cursor-not-allowed disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 shrink-0", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "2", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", d: "M8 3v10M3 8h10" })),
    /* @__PURE__ */ React.createElement("span", null, "Add ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold" }, '"', label, '"'))
  );
}
function ListRow({ item, isSelected, onToggle, disabled }) {
  const detailLabel = item.recentClicks > 0 ? `${item.recentClicks.toLocaleString()} recent clicks` : typeof item.usageCount === "number" ? `${item.usageCount.toLocaleString()} uses` : null;
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onToggle(item),
      disabled,
      className: `flex w-full items-center justify-between rounded-lg px-3 py-2 text-sm transition-all disabled:cursor-not-allowed ${isSelected ? "bg-accent/12 text-accent" : "text-slate-300 hover:bg-white/6 hover:text-white"}`
    },
    /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-center gap-2.5" }, isSelected ? /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 shrink-0 text-accent", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M8 16A8 8 0 108 0a8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L7 8.586 5.707 7.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z", clipRule: "evenodd" })) : /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 shrink-0 text-white/30", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("circle", { cx: "8", cy: "8", r: "6.25" })), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.name), item.isAi && /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-purple-400/40 bg-purple-400/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-purple-200" }, "AI")),
    detailLabel && /* @__PURE__ */ React.createElement("span", { className: "ml-3 shrink-0 text-[11px] text-white/40" }, detailLabel)
  );
}
function PastedTagsDialog$1({ open, preview, maxTags, onClose, onConfirm }) {
  const backdropRef = reactExports.useRef(null);
  const cancelButtonRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const timeoutId = window.setTimeout(() => cancelButtonRef.current?.focus(), 60);
    return () => window.clearTimeout(timeoutId);
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open || !preview) return null;
  const duplicateCount = preview.skippedDuplicates.length;
  const invalidCount = preview.skippedInvalid.length;
  const overflowCount = preview.skippedOverflow.length;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "dialog",
          "aria-modal": "true",
          "aria-labelledby": "tag-picker-paste-title",
          className: "w-full max-w-lg overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]"
        },
        /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Tag Import"), /* @__PURE__ */ React.createElement("h3", { id: "tag-picker-paste-title", className: "mt-2 text-lg font-semibold text-white" }, "Add ", preview.itemsToAdd.length, " pasted tag", preview.itemsToAdd.length === 1 ? "" : "s", "?"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Parsed ", preview.parsedCount, " item", preview.parsedCount === 1 ? "" : "s", " from your paste. Confirm before applying them.")),
        /* @__PURE__ */ React.createElement("div", { className: "space-y-4 px-6 py-5" }, overflowCount > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-amber-300/25 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "Only ", preview.itemsToAdd.length, " tag", preview.itemsToAdd.length === 1 ? "" : "s", " can be added because the limit is ", maxTags, ". ", overflowCount, " pasted tag", overflowCount === 1 ? "" : "s", " will be skipped."), (duplicateCount > 0 || invalidCount > 0) && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-white/70" }, duplicateCount > 0 ? `${duplicateCount} duplicate tag${duplicateCount === 1 ? "" : "s"} ignored.` : "", duplicateCount > 0 && invalidCount > 0 ? " " : "", invalidCount > 0 ? `${invalidCount} invalid tag${invalidCount === 1 ? "" : "s"} ignored.` : ""), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-xs font-semibold uppercase tracking-[0.18em] text-white/40" }, "Tags to add"), /* @__PURE__ */ React.createElement("div", { className: "max-h-56 overflow-auto rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, preview.itemsToAdd.map((item) => /* @__PURE__ */ React.createElement(
          "span",
          {
            key: item.slug,
            className: "inline-flex items-center rounded-full border border-sky-300/25 bg-sky-400/10 px-3 py-1.5 text-xs font-medium text-sky-100"
          },
          item.name
        )))))),
        /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement(
          "button",
          {
            ref: cancelButtonRef,
            type: "button",
            onClick: () => onClose?.(),
            className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/20"
          },
          "Cancel"
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onConfirm?.(),
            className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/40"
          },
          "Add tags"
        ))
      )
    ),
    document.body
  );
}
function TagPicker({
  value = [],
  onChange,
  suggestedTags = [],
  disabled = false,
  maxTags = getMaxUserTags(),
  searchEndpoint = "/api/tags/search",
  popularEndpoint = "/api/tags/popular",
  placeholder,
  error
}) {
  const selectedSlugs = reactExports.useMemo(
    () => Array.from(new Set((Array.isArray(value) ? value : []).map(normalizeSlug).filter(Boolean))),
    [value]
  );
  const [query, setQuery] = reactExports.useState("");
  const [results, setResults] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [fetchError, setFetchError] = reactExports.useState(false);
  const [inputError, setInputError] = reactExports.useState("");
  const [pastePreview, setPastePreview] = reactExports.useState(null);
  const [nameMap, setNameMap] = reactExports.useState({});
  const updateNameMap = reactExports.useCallback((items) => {
    setNameMap((prev) => {
      const next = { ...prev };
      items.forEach((item) => {
        if (item?.slug && item.name) next[item.slug] = item.name;
      });
      return next;
    });
  }, []);
  const abortRef = reactExports.useRef(null);
  const timerRef = reactExports.useRef(null);
  const inputRef = reactExports.useRef(null);
  const cacheRef = reactExports.useRef(/* @__PURE__ */ new Map());
  const aiItems = reactExports.useMemo(() => {
    return (Array.isArray(suggestedTags) ? suggestedTags : []).map(toListItem).filter(Boolean).map((item) => ({ ...item, isAi: true }));
  }, [suggestedTags]);
  const fetchTags = reactExports.useCallback(async (q2) => {
    const cacheKey = q2.trim() || "__popular__";
    if (cacheRef.current.has(cacheKey)) {
      setResults(cacheRef.current.get(cacheKey));
      setFetchError(false);
      return;
    }
    if (abortRef.current) abortRef.current.abort();
    abortRef.current = new AbortController();
    setLoading(true);
    setFetchError(false);
    try {
      const url = q2.trim() ? `${searchEndpoint}?q=${encodeURIComponent(q2.trim())}` : popularEndpoint;
      const res = await window.axios.get(url, { signal: abortRef.current.signal });
      const raw = res?.data?.data || res?.data || [];
      const items = (Array.isArray(raw) ? raw : []).map(toListItem).filter(Boolean).slice(0, MAX_RESULTS);
      cacheRef.current.set(cacheKey, items);
      setResults(items);
      updateNameMap(items);
    } catch (err) {
      if (err?.code === "ERR_CANCELED" || abortRef.current?.signal?.aborted) return;
      setFetchError(true);
      setResults([]);
    } finally {
      if (!abortRef.current?.signal?.aborted) setLoading(false);
    }
  }, [searchEndpoint, popularEndpoint, updateNameMap]);
  reactExports.useEffect(() => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => fetchTags(query), query ? DEBOUNCE_MS$1 : 0);
    return () => clearTimeout(timerRef.current);
  }, [query, fetchTags]);
  reactExports.useEffect(() => () => {
    abortRef.current?.abort();
  }, []);
  reactExports.useEffect(() => {
    updateNameMap(aiItems);
  }, [aiItems, updateNameMap]);
  const addTag = reactExports.useCallback((rawSlug, displayName) => {
    const slug = normalizeSlug(rawSlug);
    if (!slug) return;
    if (slug.length < MIN_LENGTH) {
      setInputError(`Too short (min ${MIN_LENGTH} chars)`);
      return;
    }
    if (selectedSlugs.includes(slug)) {
      setInputError("Already added");
      return;
    }
    if (selectedSlugs.length >= maxTags) {
      setInputError("Maximum tags reached");
      return;
    }
    setInputError("");
    updateNameMap([{ slug, name: displayName || rawSlug }]);
    onChange?.([...selectedSlugs, slug]);
    setQuery("");
  }, [selectedSlugs, maxTags, onChange, updateNameMap]);
  const toggleTag = reactExports.useCallback((item) => {
    if (selectedSlugs.includes(item.slug)) {
      onChange?.(selectedSlugs.filter((s2) => s2 !== item.slug));
    } else {
      addTag(item.slug, item.name);
    }
  }, [selectedSlugs, addTag, onChange]);
  const removeTag = reactExports.useCallback((slug) => {
    setInputError("");
    onChange?.(selectedSlugs.filter((s2) => s2 !== slug));
  }, [selectedSlugs, onChange]);
  const closePastePreview = reactExports.useCallback(() => {
    setPastePreview(null);
  }, []);
  const confirmPastePreview = reactExports.useCallback(() => {
    if (!pastePreview) return;
    updateNameMap(pastePreview.itemsToAdd);
    onChange?.(pastePreview.nextSlugs);
    setQuery("");
    setInputError("");
    setPastePreview(null);
  }, [onChange, pastePreview, updateNameMap]);
  const handleKeyDown2 = reactExports.useCallback((e) => {
    const commit = e.key === "Enter" || e.key === "," || e.key === "Tab";
    if (!commit) return;
    if (e.key === "Backspace" && query === "" && selectedSlugs.length > 0) {
      removeTag(selectedSlugs[selectedSlugs.length - 1]);
      return;
    }
    const candidate = query.trim().replace(/,$/, "");
    if (!candidate) return;
    e.preventDefault();
    addTag(candidate, candidate);
  }, [query, selectedSlugs, addTag, removeTag]);
  const handlePaste = reactExports.useCallback((event) => {
    const raw = event.clipboardData?.getData("text");
    if (!raw) return;
    const parts = parseTagList$1(raw);
    if (parts.length <= 1) return;
    event.preventDefault();
    const preview = analyzePastedTags$1(raw, selectedSlugs, maxTags);
    if (preview.itemsToAdd.length === 0) {
      if (selectedSlugs.length >= maxTags || preview.skippedOverflow.length > 0) {
        setInputError("Maximum tags reached");
      } else {
        setInputError("No new tags found in pasted text");
      }
      return;
    }
    setInputError("");
    setPastePreview(preview);
  }, [maxTags, selectedSlugs]);
  const querySlug = normalizeSlug(query);
  const showAddNew = Boolean(
    query.trim() && querySlug.length >= MIN_LENGTH && !results.some((r) => r.slug === querySlug) && !selectedSlugs.includes(querySlug)
  );
  const displayList = reactExports.useMemo(() => {
    const seen = /* @__PURE__ */ new Set();
    const merged = [];
    if (!query.trim()) {
      aiItems.forEach((item) => {
        if (!seen.has(item.slug)) {
          seen.add(item.slug);
          merged.push(item);
        }
      });
    }
    results.forEach((item) => {
      if (!seen.has(item.slug)) {
        seen.add(item.slug);
        merged.push(item);
      }
    });
    return merged;
  }, [aiItems, results, query]);
  const atMax = selectedSlugs.length >= maxTags;
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3", "data-testid": "tag-picker-root" }, /* @__PURE__ */ React.createElement(
    SearchInput$1,
    {
      value: query,
      onChange: (v2) => {
        setQuery(v2);
        setInputError("");
      },
      onKeyDown: handleKeyDown2,
      onPaste: handlePaste,
      inputRef,
      disabled,
      hint: placeholder
    }
  ), inputError && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-red-300", role: "alert" }, inputError), /* @__PURE__ */ React.createElement(
    SelectedChips,
    {
      slugs: selectedSlugs,
      names: nameMap,
      onRemove: removeTag,
      disabled
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "max-h-52 overflow-y-auto rounded-xl border border-white/8 bg-white/[0.02] p-1 sb-scrollbar" }, loading && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-5" }, /* @__PURE__ */ React.createElement("div", { className: "h-5 w-5 animate-spin rounded-full border-2 border-accent/30 border-t-accent" })), !loading && fetchError && /* @__PURE__ */ React.createElement("p", { className: "py-4 text-center text-xs text-amber-300/80" }, "Tag search unavailable"), !loading && showAddNew && /* @__PURE__ */ React.createElement(
    AddNewRow,
    {
      label: query.trim(),
      onAdd: () => addTag(query.trim(), query.trim()),
      disabled: disabled || atMax
    }
  ), !loading && !fetchError && displayList.length === 0 && !showAddNew && /* @__PURE__ */ React.createElement("p", { className: "py-4 text-center text-sm text-white/40" }, query ? "No tags found — press Enter to add" : "Type to search or add tags"), !loading && !fetchError && displayList.map((item) => /* @__PURE__ */ React.createElement(
    ListRow,
    {
      key: item.key,
      item,
      isSelected: selectedSlugs.includes(item.slug),
      onToggle: toggleTag,
      disabled: disabled || atMax && !selectedSlugs.includes(item.slug)
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-white/45" }, /* @__PURE__ */ React.createElement("span", null, selectedSlugs.length, "/", maxTags, " tags selected"), atMax ? /* @__PURE__ */ React.createElement("span", { className: "text-amber-300/80" }, "Maximum tags reached") : /* @__PURE__ */ React.createElement("span", { className: "text-white/30" }, "Enter, comma or Tab to add. Paste a comma-separated list to review multiple tags.")), error && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-red-300" }, error), /* @__PURE__ */ React.createElement(
    PastedTagsDialog$1,
    {
      open: Boolean(pastePreview),
      preview: pastePreview,
      maxTags,
      onClose: closePastePreview,
      onConfirm: confirmPastePreview
    }
  ));
}
function toLocalDateTimeString(isoString, tz) {
  if (!isoString) return { date: "", time: "" };
  try {
    const d2 = new Date(isoString);
    const opts = { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" };
    const dateStr = new Intl.DateTimeFormat("en-CA", opts).format(d2);
    const timeStr = new Intl.DateTimeFormat("en-GB", {
      timeZone: tz,
      hour: "2-digit",
      minute: "2-digit",
      hour12: false
    }).format(d2);
    return { date: dateStr, time: timeStr };
  } catch {
    return { date: "", time: "" };
  }
}
function formatPreviewLabel(isoString, tz) {
  if (!isoString) return null;
  try {
    return new Intl.DateTimeFormat("en-GB", {
      timeZone: tz,
      weekday: "short",
      day: "numeric",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
      timeZoneName: "short"
    }).format(new Date(isoString));
  } catch {
    return isoString;
  }
}
function localToUtcIso(dateStr, timeStr, tz) {
  if (!dateStr || !timeStr) return null;
  try {
    const dtStr = `${dateStr}T${timeStr}:00`;
    const local = new Date(
      new Date(dtStr).toLocaleString("en-US", { timeZone: tz })
    );
    const utcOffset = new Date(dtStr) - local;
    const utcDate = new Date(new Date(dtStr).getTime() + utcOffset);
    return utcDate.toISOString();
  } catch {
    return null;
  }
}
const MIN_FUTURE_MS = 5 * 60 * 1e3;
function SchedulePublishPicker({
  mode = "now",
  scheduledAt = null,
  timezone = Intl.DateTimeFormat().resolvedOptions().timeZone,
  onModeChange,
  onScheduleAt,
  disabled = false
}) {
  const initial = reactExports.useMemo(
    () => toLocalDateTimeString(scheduledAt, timezone),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  );
  const [localDateTime, setLocalDateTime] = reactExports.useState(initial.date && initial.time ? `${initial.date}T${initial.time}` : "");
  const [error, setError] = reactExports.useState("");
  const minScheduleLocalDateTime = (() => {
    const next = toLocalDateTimeString(new Date(Date.now() + MIN_FUTURE_MS).toISOString(), timezone);
    return next.date && next.time ? `${next.date}T${next.time}` : "";
  })();
  const validate = reactExports.useCallback(
    (value) => {
      const [datePart = "", timePart = ""] = String(value || "").split("T");
      if (!datePart || !timePart) return "Date and time are required.";
      const iso = localToUtcIso(datePart, timePart.slice(0, 5), timezone);
      if (!iso) return "Invalid date or time.";
      const target = new Date(iso);
      if (Number.isNaN(target.getTime())) return "Invalid date or time.";
      if (target.getTime() - Date.now() < MIN_FUTURE_MS) {
        return "Scheduled time must be at least 5 minutes in the future.";
      }
      return "";
    },
    [timezone]
  );
  reactExports.useEffect(() => {
    const next = toLocalDateTimeString(scheduledAt, timezone);
    setLocalDateTime(next.date && next.time ? `${next.date}T${next.time}` : "");
  }, [scheduledAt, timezone]);
  reactExports.useEffect(() => {
    if (mode !== "schedule") {
      setError("");
      return;
    }
    if (!localDateTime) {
      setError("");
      onScheduleAt?.(null);
      return;
    }
    const err = validate(localDateTime);
    setError(err);
    if (!err) {
      const [datePart = "", timePart = ""] = localDateTime.split("T");
      onScheduleAt?.(localToUtcIso(datePart, timePart.slice(0, 5), timezone));
    } else {
      onScheduleAt?.(null);
    }
  }, [localDateTime, mode, timezone]);
  const previewLabel = reactExports.useMemo(() => {
    if (mode !== "schedule" || error) return null;
    const [datePart = "", timePart = ""] = localDateTime.split("T");
    const iso = localToUtcIso(datePart, timePart.slice(0, 5), timezone);
    return formatPreviewLabel(iso, timezone);
  }, [mode, error, localDateTime, timezone]);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-2", role: "group", "aria-label": "Publish mode" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled,
      onClick: () => {
        onModeChange?.("now");
        setError("");
      },
      className: [
        "flex-1 rounded-lg border py-2 text-sm transition",
        mode === "now" ? "border-sky-300/60 bg-sky-500/25 text-white" : "border-white/15 bg-white/6 text-white/60 hover:bg-white/10",
        disabled ? "cursor-not-allowed opacity-50" : ""
      ].join(" "),
      "aria-pressed": mode === "now"
    },
    "Publish now"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled,
      onClick: () => onModeChange?.("schedule"),
      className: [
        "flex-1 rounded-lg border py-2 text-sm transition",
        mode === "schedule" ? "border-sky-300/60 bg-sky-500/25 text-white" : "border-white/15 bg-white/6 text-white/60 hover:bg-white/10",
        disabled ? "cursor-not-allowed opacity-50" : ""
      ].join(" "),
      "aria-pressed": mode === "schedule"
    },
    "Schedule"
  )), mode === "schedule" && /* @__PURE__ */ React.createElement("div", { className: "space-y-2 rounded-xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement(
    DateTimePicker,
    {
      id: "schedule-datetime",
      label: "Release date and time",
      value: localDateTime,
      onChange: setLocalDateTime,
      placeholder: "Pick a release slot",
      disabled,
      minDateTime: minScheduleLocalDateTime,
      clearable: true,
      hint: `Timezone: ${timezone}`,
      error
    }
  ), previewLabel && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-emerald-300/80" }, "Will publish on: ", /* @__PURE__ */ React.createElement("span", { className: "font-medium" }, previewLabel))));
}
function SelectedArtworkCard({ artwork, onClear, disabled = false }) {
  if (!artwork) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-sky-300/20 bg-sky-400/[0.08] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-4" }, artwork.thumbnail ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumbnail, alt: artwork.title, className: "h-20 w-20 rounded-[22px] object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-20 w-20 items-center justify-center rounded-[22px] border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Linked original"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 truncate text-lg font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap items-center gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, artwork.publisher || "Artist"), artwork.year ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, artwork.year) : null, artwork.content_type ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, artwork.content_type) : null))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, artwork.url ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: artwork.url,
      target: "_blank",
      rel: "noreferrer",
      className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
    },
    "Open public",
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-500" })
  ) : null, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onClear,
      disabled,
      className: "inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:cursor-not-allowed disabled:opacity-60"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link-slash" }),
    "Remove link"
  ))));
}
function ArtworkEvolutionSearchPicker({ artworkId, selected, onSelect, disabled = false }) {
  const [query, setQuery] = reactExports.useState("");
  const [options, setOptions] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (!artworkId) return void 0;
    const controller = new AbortController();
    const handle = window.setTimeout(async () => {
      setLoading(true);
      try {
        const response = await fetch(`/api/studio/artworks/${artworkId}/evolution-options?search=${encodeURIComponent(query)}`, {
          headers: { Accept: "application/json" },
          credentials: "same-origin",
          signal: controller.signal
        });
        if (!response.ok) {
          setOptions([]);
          return;
        }
        const data = await response.json();
        setOptions(Array.isArray(data.data) ? data.data : []);
      } catch (error) {
        if (error?.name !== "AbortError") {
          setOptions([]);
        }
      } finally {
        setLoading(false);
      }
    }, query.trim() === "" ? 0 : 220);
    return () => {
      controller.abort();
      window.clearTimeout(handle);
    };
  }, [artworkId, query]);
  const visibleOptions = options.filter((option) => Number(option.id) !== Number(selected?.id));
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(SelectedArtworkCard, { artwork: selected, onClear: () => onSelect(null), disabled }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-end" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Search your manageable artworks"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: query,
      onChange: (event) => setQuery(event.target.value),
      placeholder: "Search by title, slug, creator, or group",
      disabled,
      className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35 disabled:cursor-not-allowed disabled:opacity-60"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, loading ? "Searching…" : `${visibleOptions.length} result${visibleOptions.length === 1 ? "" : "s"}`)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-relaxed text-slate-400" }, "Start with your own published artworks. Group-published pieces appear too when you can publish artworks for that group. Results are ranked by visual similarity when the vector index is available."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, visibleOptions.length ? visibleOptions.map((option) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: option.id,
      type: "button",
      onClick: () => onSelect(option),
      disabled,
      className: "flex w-full flex-col gap-4 rounded-[24px] border border-white/10 bg-white/[0.04] p-4 text-left transition hover:border-white/20 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-60 md:flex-row md:items-center md:justify-between"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-center gap-4" }, option.thumbnail ? /* @__PURE__ */ React.createElement("img", { src: option.thumbnail, alt: option.title, className: "h-16 w-16 rounded-[18px] object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center rounded-[18px] border border-white/10 bg-white/[0.05] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, option.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap items-center gap-2 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, option.publisher || "Artist"), option.year ? /* @__PURE__ */ React.createElement("span", null, option.year) : null, option.category ? /* @__PURE__ */ React.createElement("span", null, option.category) : null, typeof option.similarity_score === "number" ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, Math.round(option.similarity_score * 100), "% similar") : null))),
    /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 self-start rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 md:self-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link" }), "Link older version")
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.02] px-5 py-10 text-center text-sm text-slate-300" }, loading ? "Searching artworks…" : "No manageable published artworks matched this search yet."))));
}
function metaItems(world) {
  return [
    world?.promotion_window_label || world?.timeframe_label,
    Number(world?.live_submission_count || 0) > 0 ? `${Number(world.live_submission_count)} live submissions` : null,
    Number(world?.relation_count || 0) > 0 ? `${Number(world.relation_count)} curated links` : null,
    world?.theme?.label || world?.type || null
  ].filter(Boolean);
}
function WorldCampaignMeta({ world, className = "" }) {
  const items = metaItems(world);
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: `flex flex-wrap gap-2 text-xs text-slate-200/75 ${className}`.trim() }, items.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-white/12 bg-black/25 px-3 py-1.5" }, item)));
}
function UploadWorldHighlightCard({ world, sourceSurface = "", sourceDetail = "" }) {
  const cardRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!sourceSurface || !world?.id || typeof window === "undefined") {
      return void 0;
    }
    const node2 = cardRef.current;
    if (!node2) {
      return void 0;
    }
    if (typeof window.IntersectionObserver !== "function") {
      trackWorldSourceImpression({
        worldId: world.id,
        worldTitle: world.title,
        sourceSurface,
        sourceDetail,
        sectionKey: "upload_highlight"
      });
      return void 0;
    }
    const observer = new window.IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting || entry.intersectionRatio < 0.5) {
          return;
        }
        trackWorldSourceImpression({
          worldId: world.id,
          worldTitle: world.title,
          sourceSurface,
          sourceDetail,
          sectionKey: "upload_highlight"
        });
        observer.disconnect();
      });
    }, { threshold: [0.5] });
    observer.observe(node2);
    return () => observer.disconnect();
  }, [sourceDetail, sourceSurface, world?.id, world?.title]);
  if (!world) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { ref: cardRef, className: "overflow-hidden rounded-[24px] border border-emerald-300/20 bg-[linear-gradient(135deg,rgba(16,185,129,0.14),rgba(15,23,42,0.84))] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[9rem_minmax(0,1fr)] md:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "h-28 overflow-hidden rounded-[20px] border border-white/12 bg-slate-950/80" }, world.teaser_image_url || world.cover_url ? /* @__PURE__ */ React.createElement("img", { src: world.teaser_image_url || world.cover_url, alt: world.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe" }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-100/80" }, "Upload spotlight"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), world.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.campaign_label, tone: "slate" } }) : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-xl font-semibold tracking-[-0.03em] text-white" }, world.teaser_title || world.title), world.teaser_title && world.teaser_title !== world.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-white/55" }, world.title) : null, world.teaser_summary || world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-200/85" }, world.teaser_summary || world.summary) : null, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world, className: "mt-4" }))));
}
function modeTone(mode) {
  switch (mode) {
    case "manual_approval":
      return "border-sky-300/30 bg-sky-400/10 text-sky-100";
    case "auto_add":
      return "border-emerald-300/30 bg-emerald-400/10 text-emerald-100";
    default:
      return "border-white/10 bg-white/[0.04] text-slate-300";
  }
}
function dateBadgeLabel(item) {
  const timeframe = String(item?.timeframe_label || "").trim();
  const submissionWindow = String(item?.submission_window_label || "").trim();
  if (timeframe && submissionWindow) {
    return timeframe === submissionWindow ? timeframe : `${submissionWindow} • ${timeframe}`;
  }
  return submissionWindow || timeframe || "";
}
function WorldSubmissionSelector({
  title = "Add to Worlds",
  description = "Attach this artwork to active worlds while keeping community participation separate from curated editorial relations.",
  options = [],
  emptyMessage = "No worlds are currently open for creator participation.",
  onToggle,
  onNoteChange,
  className = "",
  analyticsContext = null
}) {
  const items = Array.isArray(options) ? options : [];
  const highlightedWorld = items.find((item) => item.is_active_campaign && item.is_accepting_submissions);
  const itemRefs = reactExports.useRef(/* @__PURE__ */ new Map());
  reactExports.useEffect(() => {
    if (!analyticsContext?.sourceSurface || typeof window === "undefined") {
      return void 0;
    }
    const refs = Array.from(itemRefs.current.entries());
    if (refs.length === 0) {
      return void 0;
    }
    if (typeof window.IntersectionObserver !== "function") {
      refs.forEach(([worldId]) => {
        const item = items.find((candidate) => Number(candidate.id) === Number(worldId));
        if (!item) {
          return;
        }
        trackWorldSourceImpression({
          worldId: item.id,
          worldTitle: item.title || item.teaser_title || "",
          sourceSurface: analyticsContext.sourceSurface,
          sourceDetail: analyticsContext.sourceDetail ? `${analyticsContext.sourceDetail}:selector` : "selector",
          sectionKey: "community_submissions"
        });
      });
      return void 0;
    }
    const observer = new window.IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting || entry.intersectionRatio < 0.35) {
          return;
        }
        const worldId = Number(entry.target.getAttribute("data-world-id") || 0);
        const item = items.find((candidate) => Number(candidate.id) === worldId);
        if (!item) {
          return;
        }
        trackWorldSourceImpression({
          worldId: item.id,
          worldTitle: item.title || item.teaser_title || "",
          sourceSurface: analyticsContext.sourceSurface,
          sourceDetail: analyticsContext.sourceDetail ? `${analyticsContext.sourceDetail}:selector` : "selector",
          sectionKey: "community_submissions"
        });
        observer.unobserve(entry.target);
      });
    }, { threshold: [0.35] });
    refs.forEach(([, node2]) => {
      if (node2) {
        observer.observe(node2);
      }
    });
    return () => observer.disconnect();
  }, [analyticsContext?.sourceDetail, analyticsContext?.sourceSurface, items]);
  return /* @__PURE__ */ React.createElement("section", { className: `rounded-[28px] border border-white/10 bg-white/[0.03] p-5 ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-3xl text-sm leading-6 text-slate-400" }, description)), /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-slate-500" }, items.filter((item) => item.selected).length, " selected")), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement(
    UploadWorldHighlightCard,
    {
      world: highlightedWorld,
      sourceSurface: analyticsContext?.sourceSurface || "",
      sourceDetail: analyticsContext?.sourceDetail ? `${analyticsContext.sourceDetail}:highlight` : "highlight"
    }
  )), items.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, emptyMessage) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3" }, items.map((item) => {
    const checked = Boolean(item.selected);
    const locked = Boolean(item.selection_locked);
    const combinedDateLabel = dateBadgeLabel(item);
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: item.id,
        ref: (node2) => {
          if (node2) {
            itemRefs.current.set(item.id, node2);
          } else {
            itemRefs.current.delete(item.id);
          }
        },
        "data-world-id": item.id,
        className: `overflow-hidden rounded-[24px] border transition-colors ${checked ? "border-sky-300/25 bg-sky-400/[0.07]" : "border-white/10 bg-black/20"}`
      },
      /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => {
            if (locked) {
              return;
            }
            if (!checked && analyticsContext?.sourceSurface) {
              trackWorldAnalytics("world_submission_started", {
                world_id: item.id,
                source_surface: analyticsContext.sourceSurface,
                source_detail: analyticsContext.sourceDetail || "",
                section_key: "community_submissions",
                entity_type: "world",
                entity_id: item.id,
                entity_title: item.title || ""
              });
            }
            onToggle?.(item.id);
          },
          disabled: locked,
          className: "flex w-full items-center gap-4 p-4 text-left disabled:cursor-not-allowed"
        },
        /* @__PURE__ */ React.createElement("div", { className: "h-12 w-12 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-950/80" }, item.cover_url ? /* @__PURE__ */ React.createElement("img", { src: item.cover_url, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_48%),linear-gradient(135deg,_rgba(15,23,42,0.96),_rgba(2,6,23,0.96))] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-globe text-sm" }))),
        /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-1.5" }, (Array.isArray(item.status_badges) ? item.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: `${item.id}-${badge.label}`, badge })), item.participation_mode_label ? /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${modeTone(item.participation_mode)}` }, item.participation_mode_label) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate text-sm font-semibold text-white" }, item.teaser_title || item.title), item.tagline ? /* @__PURE__ */ React.createElement("div", { className: "truncate text-[11px] uppercase tracking-[0.14em] text-slate-500" }, item.tagline) : null),
        /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs ${checked ? "border-sky-300/40 bg-sky-400/20 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-500"}` }, checked ? /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check text-[10px]" }) : null)
      ),
      checked ? /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/10 px-4 pb-4 pt-4" }, item.teaser_summary || item.summary ? /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-300" }, item.teaser_summary || item.summary) : null, combinedDateLabel || item.promotion_window_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-xs text-slate-300" }, combinedDateLabel ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, combinedDateLabel) : null, item.promotion_window_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, item.promotion_window_label) : null, item.can_resubmit ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/25 bg-amber-400/10 px-3 py-1 text-amber-100" }, "Can re-add") : null) : null, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world: item, className: "mt-3" }), item.submission_guidelines ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "World guidelines"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, item.submission_guidelines)) : null, item.selection_locked_reason ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-400" }, item.selection_locked_reason) : null, item.reviewer_note ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Moderator note"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 leading-6" }, item.reviewer_note)) : null, item.submission_note_enabled ? /* @__PURE__ */ React.createElement("label", { className: "mt-3 grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Creator note ", /* @__PURE__ */ React.createElement("span", { className: "normal-case tracking-normal text-slate-600" }, "(optional)")), /* @__PURE__ */ React.createElement(
        "textarea",
        {
          rows: 3,
          value: item.note || "",
          onChange: (event) => onNoteChange?.(item.id, event.target.value),
          disabled: locked,
          placeholder: "Context for world moderators: fit, angle, or why this artwork belongs here.",
          className: "nova-scrollbar rounded-[20px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none placeholder:text-slate-600 disabled:cursor-not-allowed disabled:opacity-60"
        }
      )) : null) : null
    );
  })));
}
const HTML_TAG_RE = /<[a-z][^>]*>/i;
const MAX_CONTENT_LENGTH = 1e4;
function decodeHtmlEntities(value) {
  const decoded = String(value || "");
  if (typeof document === "undefined") {
    return decoded.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'");
  }
  const textarea = document.createElement("textarea");
  textarea.innerHTML = decoded;
  return textarea.value;
}
function stripResidualTags(value) {
  return String(value || "").replace(/<[^>]+>/g, "");
}
function normalizeMarkdownLiteContent(value) {
  const raw = String(value || "");
  const trimmed = raw.trim();
  if (!trimmed || !HTML_TAG_RE.test(trimmed)) {
    return raw;
  }
  const normalized = raw.replace(/<\s*a[^>]*href=(['"])(.*?)\1[^>]*>([\s\S]*?)<\s*\/a\s*>/gi, (_2, __, href, label) => {
    const text2 = stripResidualTags(label).trim() || href;
    return `[${text2}](${href})`;
  }).replace(/<\s*(strong|b)(?:\s+[^>]*)?>([\s\S]*?)<\s*\/\s*\1\s*>/gi, (_2, __, text2) => `**${stripResidualTags(text2)}**`).replace(/<\s*(em|i)(?:\s+[^>]*)?>([\s\S]*?)<\s*\/\s*\1\s*>/gi, (_2, __, text2) => `*${stripResidualTags(text2)}*`).replace(/<\s*code(?:\s+[^>]*)?>([\s\S]*?)<\s*\/code\s*>/gi, (_2, text2) => `\`${stripResidualTags(text2)}\``).replace(/<\s*br\s*\/?>/gi, "\n").replace(/<\s*\/p\s*>/gi, "\n\n").replace(/<\s*p(?:\s+[^>]*)?>/gi, "").replace(/<\s*li(?:\s+[^>]*)?>([\s\S]*?)<\s*\/li\s*>/gi, (_2, text2) => `- ${stripResidualTags(text2).trim()}
`).replace(/<\s*\/ul\s*>|<\s*\/ol\s*>/gi, "\n").replace(/<\s*(ul|ol)(?:\s+[^>]*)?>/gi, "").replace(/<\s*blockquote(?:\s+[^>]*)?>([\s\S]*?)<\s*\/blockquote\s*>/gi, (_2, text2) => {
    const lines = stripResidualTags(text2).split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => `> ${line}`);
    return `${lines.join("\n")}

`;
  }).replace(/<[^>]+>/g, "");
  return decodeHtmlEntities(normalized).replace(/\r\n?/g, "\n").replace(/[\t ]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
}
function validateMarkdownLiteContent(value) {
  const raw = String(value || "");
  const trimmed = raw.trim();
  if (!trimmed) return [];
  const errors = [];
  if (trimmed.length > MAX_CONTENT_LENGTH) {
    errors.push("Content exceeds maximum length of 10,000 characters.");
  }
  if (HTML_TAG_RE.test(trimmed)) {
    errors.push("HTML tags are not allowed. Use Markdown formatting instead.");
  }
  const emojiCount = countEmoji(trimmed);
  if (emojiCount > FLOOD_COUNT_THRESHOLD) {
    errors.push("Too many emoji. Please limit emoji usage.");
  }
  if (emojiCount > 5 && trimmed.length > 0 && emojiCount / trimmed.length > FLOOD_DENSITY_THRESHOLD) {
    errors.push("Content is mostly emoji. Please add some text.");
  }
  return errors;
}
const TABS = [
  { id: "details", label: "Details", icon: "fa-solid fa-pen-fancy" },
  { id: "media", label: "Media", icon: "fa-solid fa-photo-film" },
  { id: "evolution", label: "Evolution", icon: "fa-solid fa-code-branch" },
  { id: "tags", label: "Tags", icon: "fa-solid fa-tags" },
  { id: "worlds", label: "Worlds", icon: "fa-solid fa-globe" },
  { id: "taxonomy", label: "Category", icon: "fa-solid fa-palette" },
  { id: "visibility", label: "Visibility", icon: "fa-solid fa-eye" },
  { id: "ai", label: "AI Assist", icon: "fa-solid fa-wand-magic-sparkles" }
];
function getCsrfToken() {
  return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "";
}
function formatBytes$1(bytes) {
  if (!bytes) return "—";
  if (bytes < 1024) return bytes + " B";
  if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
  return (bytes / 1048576).toFixed(1) + " MB";
}
function resolveFileExtension(fileName, fallbackExt = "") {
  const normalizedFallback = String(fallbackExt || "").trim().replace(/^\./, "").toLowerCase();
  const normalizedName = String(fileName || "").trim();
  const fromName = normalizedName.includes(".") ? normalizedName.split(".").pop()?.trim().toLowerCase() : "";
  return fromName || normalizedFallback;
}
function isArchiveArtwork(fileName, mimeType, fileExt) {
  const extension2 = resolveFileExtension(fileName, fileExt);
  if (["zip", "rar", "7z", "tar", "gz"].includes(extension2)) return true;
  const normalizedMime = String(mimeType || "").toLowerCase();
  return normalizedMime.includes("zip") || normalizedMime.includes("rar") || normalizedMime.includes("7z") || normalizedMime.includes("tar") || normalizedMime.includes("gzip");
}
function formatSchedulePreview(value, timezone) {
  if (!value) return "Pick a date and time";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Pick a date and time";
  try {
    return new Intl.DateTimeFormat(void 0, {
      dateStyle: "medium",
      timeStyle: "short",
      timeZone: timezone || void 0
    }).format(date);
  } catch {
    return date.toLocaleString();
  }
}
function formatReleaseCountdown$1(value, nowMs = Date.now()) {
  if (!value) return "";
  const releaseDate = new Date(value);
  if (Number.isNaN(releaseDate.getTime())) return "";
  const remainingMs = releaseDate.getTime() - nowMs;
  if (remainingMs <= 0) {
    return "Releasing now";
  }
  const totalSeconds = Math.floor(remainingMs / 1e3);
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor(totalSeconds % 86400 / 3600);
  const minutes = Math.floor(totalSeconds % 3600 / 60);
  const seconds = totalSeconds % 60;
  const parts = [];
  if (days > 0) parts.push(`${days}d`);
  if (days > 0 || hours > 0) parts.push(`${hours}h`);
  if (days > 0 || hours > 0 || minutes > 0) parts.push(`${minutes}m`);
  if (days === 0) parts.push(`${seconds}s`);
  return `In ${parts.join(" ")}`;
}
function getContentTypeVisualKey$1(slug) {
  const map = { skins: "skins", wallpapers: "wallpapers", photography: "photography", other: "other", members: "members" };
  return map[slug] || "other";
}
function buildCategoryTree$1(contentTypes) {
  return (contentTypes || []).map((ct) => ({
    ...ct,
    rootCategories: (ct.categories || ct.root_categories || []).map((rc) => ({
      ...rc,
      children: rc.children || []
    }))
  }));
}
function nextSourceForManualEdit(currentSource) {
  if (currentSource === "ai_applied" || currentSource === "ai_generated") return "mixed";
  if (currentSource === "mixed") return "mixed";
  return "manual";
}
function statusTone$2(status2) {
  switch (status2) {
    case "ready":
      return "border-emerald-400/30 bg-emerald-400/10 text-emerald-200";
    case "queued":
    case "processing":
      return "border-sky-400/30 bg-sky-400/10 text-sky-200";
    case "failed":
      return "border-red-400/30 bg-red-400/10 text-red-200";
    default:
      return "border-white/10 bg-white/[0.04] text-slate-300";
  }
}
function statusLabel(status2) {
  switch (status2) {
    case "queued":
      return "Queued";
    case "processing":
      return "Processing";
    case "ready":
      return "Ready";
    case "failed":
      return "Failed";
    case "pending":
      return "Pending";
    default:
      return "Not analyzed";
  }
}
function visibilityLabel(value) {
  switch (value) {
    case "unlisted":
      return "Unlisted";
    case "private":
      return "Private";
    default:
      return "Public";
  }
}
function normalizeContributorCredits$1(contributorIds = [], contributorCredits = {}) {
  const normalized = {};
  const ids = Array.isArray(contributorIds) ? contributorIds.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0) : [];
  ids.forEach((id) => {
    const current = contributorCredits?.[id] || contributorCredits?.[String(id)] || {};
    normalized[id] = {
      creditRole: typeof current.creditRole === "string" ? current.creditRole : "",
      isPrimary: Boolean(current.isPrimary)
    };
  });
  const leadIds = Object.entries(normalized).filter(([, value]) => value.isPrimary).map(([id]) => Number(id));
  if (leadIds.length > 1) {
    leadIds.slice(1).forEach((id) => {
      normalized[id] = {
        ...normalized[id],
        isPrimary: false
      };
    });
  }
  return normalized;
}
function mapContributorCredits(contributorCredits = []) {
  return (Array.isArray(contributorCredits) ? contributorCredits : []).reduce((accumulator, contributor) => {
    const userId = Number(contributor?.user_id);
    if (!Number.isFinite(userId) || userId <= 0) return accumulator;
    accumulator[userId] = {
      creditRole: typeof contributor?.credit_role === "string" ? contributor.credit_role : "",
      isPrimary: Boolean(contributor?.is_primary)
    };
    return accumulator;
  }, {});
}
function normalizeWorldSubmissionOptions(options = []) {
  return (Array.isArray(options) ? options : []).map((world) => ({
    ...world,
    selected: Boolean(world?.selected),
    note: typeof world?.note === "string" ? world.note : ""
  }));
}
function Section({ children, className = "", id = void 0 }) {
  return /* @__PURE__ */ React.createElement("section", { id, className: `scroll-mt-24 bg-nova-900/60 border border-white/10 rounded-2xl p-6 ${className}` }, children);
}
function SectionTitle({ icon, children }) {
  return /* @__PURE__ */ React.createElement("h3", { className: "flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-slate-400 mb-4" }, icon && /* @__PURE__ */ React.createElement("i", { className: `${icon} text-accent/70 text-[11px]` }), children);
}
function InlineAiButton({ children, onClick, disabled = false, loading = false }) {
  return /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick,
      disabled,
      className: "inline-flex items-center gap-1 rounded-full border border-sky-400/20 bg-sky-400/10 px-2.5 py-1 text-[11px] font-semibold text-sky-200 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("span", null, loading ? "..." : "✦"),
    /* @__PURE__ */ React.createElement("span", null, children)
  );
}
function FieldLabel({ label, actionLabel, onAction, disabled = false, loading = false }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement(InlineAiButton, { onClick: onAction, disabled, loading }, actionLabel));
}
function RightRailCard({ title, children, className = "" }) {
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(148,163,184,0.16),_rgba(15,23,42,0.92)_62%)] p-4 ${className}` }, /* @__PURE__ */ React.createElement("h3", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, children));
}
function StudioArtworkEdit() {
  const { props } = X$1();
  const { artwork, contentTypes: rawContentTypes } = props;
  const groupOptions = Array.isArray(props.groupOptions) ? props.groupOptions : [];
  const evolutionRelationTypes = Array.isArray(props.evolutionRelationTypes) ? props.evolutionRelationTypes : [];
  const initialEvolutionRelation = artwork?.evolution_relation || null;
  const contributorOptionsByGroup = props.contributorOptionsByGroup && typeof props.contributorOptionsByGroup === "object" ? props.contributorOptionsByGroup : {};
  const initialWorldSubmissionOptions = Array.isArray(props.worldSubmissionOptions) ? props.worldSubmissionOptions : [];
  const contentTypes = reactExports.useMemo(() => buildCategoryTree$1(rawContentTypes || []), [rawContentTypes]);
  const [contentTypeId, setContentTypeId] = reactExports.useState(artwork?.content_type_id || null);
  const [categoryId, setCategoryId] = reactExports.useState(artwork?.parent_category_id || null);
  const [subCategoryId, setSubCategoryId] = reactExports.useState(artwork?.sub_category_id || null);
  const [title, setTitle] = reactExports.useState(artwork?.title || "");
  const [description, setDescription] = reactExports.useState(() => normalizeMarkdownLiteContent(artwork?.description || ""));
  const [tagSlugs, setTagSlugs] = reactExports.useState(() => (artwork?.tags || []).map((t) => t.slug || t.name));
  const [visibility, setVisibility] = reactExports.useState(artwork?.visibility || (artwork?.is_public ? "public" : "private"));
  const [publishMode, setPublishMode] = reactExports.useState(artwork?.publish_mode || (artwork?.artwork_status === "scheduled" ? "schedule" : "now"));
  const [scheduledAt, setScheduledAt] = reactExports.useState(artwork?.publish_at || null);
  const [groupSlug, setGroupSlug] = reactExports.useState(artwork?.group_slug || "");
  const [primaryAuthorUserId, setPrimaryAuthorUserId] = reactExports.useState(artwork?.primary_author_user_id || null);
  const [contributorUserIds, setContributorUserIds] = reactExports.useState(() => Array.isArray(artwork?.contributor_user_ids) ? artwork.contributor_user_ids.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0) : []);
  const [contributorCredits, setContributorCredits] = reactExports.useState(() => normalizeContributorCredits$1(artwork?.contributor_user_ids || [], mapContributorCredits(artwork?.contributor_credits || [])));
  const [worldSubmissionOptions, setWorldSubmissionOptions] = reactExports.useState(() => normalizeWorldSubmissionOptions(initialWorldSubmissionOptions));
  const [titleSource, setTitleSource] = reactExports.useState(artwork?.title_source || "manual");
  const [descriptionSource, setDescriptionSource] = reactExports.useState(artwork?.description_source || "manual");
  const [tagsSource, setTagsSource] = reactExports.useState(artwork?.tags_source || "manual");
  const [categorySource, setCategorySource] = reactExports.useState(artwork?.category_source || "manual");
  const [evolutionTarget, setEvolutionTarget] = reactExports.useState(initialEvolutionRelation?.target_artwork || null);
  const [evolutionRelationType, setEvolutionRelationType] = reactExports.useState(initialEvolutionRelation?.relation_type || evolutionRelationTypes[0]?.value || "remake_of");
  const [evolutionNote, setEvolutionNote] = reactExports.useState(initialEvolutionRelation?.note || "");
  const [saving, setSaving] = reactExports.useState(false);
  const [saved, setSaved] = reactExports.useState(false);
  const [errors, setErrors] = reactExports.useState({});
  const [aiData, setAiData] = reactExports.useState(null);
  const [aiLoading, setAiLoading] = reactExports.useState(false);
  const [aiAction, setAiAction] = reactExports.useState("");
  const [aiDirect, setAiDirect] = reactExports.useState(false);
  const [isAiPanelOpen, setIsAiPanelOpen] = reactExports.useState(true);
  const [selectedAiTags, setSelectedAiTags] = reactExports.useState([]);
  const [activeTab, setActiveTab] = reactExports.useState("details");
  const [isCategoryChooserOpen, setIsCategoryChooserOpen] = reactExports.useState(() => !artwork?.parent_category_id);
  const [nowMs, setNowMs] = reactExports.useState(() => Date.now());
  const userTimezone = reactExports.useMemo(() => artwork?.artwork_timezone || Intl.DateTimeFormat().resolvedOptions().timeZone, [artwork?.artwork_timezone]);
  const fileInputRef = reactExports.useRef(null);
  const [replacing, setReplacing] = reactExports.useState(false);
  const [thumbUrl, setThumbUrl] = reactExports.useState(artwork?.thumb_url_lg || artwork?.thumb_url || null);
  const downloadUrl = artwork?.download_url || (artwork?.id ? `/download/artwork/${artwork.id}` : null);
  const [selectedMediaId, setSelectedMediaId] = reactExports.useState("cover");
  const [fileExt, setFileExt] = reactExports.useState(artwork?.file_ext || "");
  const [mimeType, setMimeType] = reactExports.useState(artwork?.mime_type || "");
  const [hasArchiveFile, setHasArchiveFile] = reactExports.useState(Boolean(artwork?.has_archive_file));
  const [artworkScreenshots, setArtworkScreenshots] = reactExports.useState(() => Array.isArray(artwork?.screenshots) ? artwork.screenshots : []);
  const [fileMeta, setFileMeta] = reactExports.useState({
    name: artwork?.file_name || "—",
    size: artwork?.file_size || 0,
    width: artwork?.width || 0,
    height: artwork?.height || 0
  });
  const [versionCount, setVersionCount] = reactExports.useState(artwork?.version_count ?? 1);
  const [requiresReapproval, setRequiresReapproval] = reactExports.useState(artwork?.requires_reapproval ?? false);
  const [changeNote, setChangeNote] = reactExports.useState("");
  const [showChangeNote, setShowChangeNote] = reactExports.useState(false);
  const [showHistory, setShowHistory] = reactExports.useState(false);
  const [historyData, setHistoryData] = reactExports.useState(null);
  const [historyLoading, setHistoryLoading] = reactExports.useState(false);
  const [restoring, setRestoring] = reactExports.useState(null);
  const [archiveRevisionSaving, setArchiveRevisionSaving] = reactExports.useState(false);
  const [archiveRevisionError, setArchiveRevisionError] = reactExports.useState("");
  const [archiveCoverFile, setArchiveCoverFile] = reactExports.useState(null);
  const [archiveCoverPreview, setArchiveCoverPreview] = reactExports.useState(null);
  const [archivePackageFile, setArchivePackageFile] = reactExports.useState(null);
  const [archiveExtraScreenshots, setArchiveExtraScreenshots] = reactExports.useState([]);
  const [archiveExtraPreviews, setArchiveExtraPreviews] = reactExports.useState([]);
  const [replaceShots, setReplaceShots] = reactExports.useState({});
  const [replaceShotPreviews, setReplaceShotPreviews] = reactExports.useState({});
  const [removedShots, setRemovedShots] = reactExports.useState({});
  const [pendingReplaceFile, setPendingReplaceFile] = reactExports.useState(null);
  const [pendingReplacePreview, setPendingReplacePreview] = reactExports.useState(null);
  const [dragOverZone, setDragOverZone] = reactExports.useState(null);
  const screenshotItems = artworkScreenshots;
  const activeScreenshotCount = screenshotItems.filter((_2, index2) => !removedShots[index2]).length;
  const currentFileExt = resolveFileExtension(fileMeta.name, fileExt);
  const archiveArtwork = hasArchiveFile || isArchiveArtwork(fileMeta.name, mimeType, fileExt);
  const quickReplaceSupported = !archiveArtwork;
  const mediaItems = reactExports.useMemo(() => {
    const coverItem = {
      id: "cover",
      label: archiveArtwork ? "Cover preview" : "Main artwork",
      url: thumbUrl,
      width: fileMeta.width || 0,
      height: fileMeta.height || 0
    };
    const screenshotMedia = screenshotItems.map((item, index2) => ({
      id: item.id || `shot-${index2 + 1}`,
      label: item.label || `Screenshot ${index2 + 1}`,
      url: item.thumb_url || item.url || null,
      width: 0,
      height: 0
    }));
    return [coverItem, ...screenshotMedia].filter((item) => Boolean(item.url));
  }, [archiveArtwork, fileMeta.height, fileMeta.width, screenshotItems, thumbUrl]);
  const activeMedia = mediaItems.find((item) => item.id === selectedMediaId) || mediaItems[0] || null;
  const activeMediaLabel = activeMedia?.label || (archiveArtwork ? "Cover preview" : "Main artwork");
  const selectedCT = contentTypes.find((ct) => ct.id === contentTypeId) || null;
  const rootCategories = selectedCT?.rootCategories || [];
  const selectedRoot = rootCategories.find((c) => c.id === categoryId) || null;
  const subCategories = selectedRoot?.children || [];
  const selectedGroupOption = reactExports.useMemo(() => groupOptions.find((group) => String(group.slug || "") === String(groupSlug || "")) || null, [groupOptions, groupSlug]);
  const currentContributorOptions = reactExports.useMemo(() => {
    const selectedSlug = String(groupSlug || "");
    return Array.isArray(contributorOptionsByGroup?.[selectedSlug]) ? contributorOptionsByGroup[selectedSlug] : [];
  }, [contributorOptionsByGroup, groupSlug]);
  const aiStatus = aiData?.status || artwork?.ai_status || "not_analyzed";
  const aiSuggestedTags = reactExports.useMemo(() => (aiData?.tag_suggestions || []).map((item) => item.tag).filter(Boolean), [aiData]);
  const selectedLeafCategoryId = subCategoryId || categoryId || null;
  const visibilitySummary = publishMode === "schedule" ? `Scheduled as ${visibilityLabel(visibility)}` : visibilityLabel(visibility);
  const selectedSubCategory = subCategoryId ? subCategories.find((item) => item.id === subCategoryId) || null : null;
  const heroMeta = [
    selectedCT?.name || "No content type",
    selectedRoot?.name || "No root category",
    selectedSubCategory?.name || null
  ].filter(Boolean);
  const categoryPreviewSummary = [selectedCT?.name, selectedRoot?.name, selectedSubCategory?.name].filter(Boolean).join(" / ") || "Choose a category path";
  const visibilityPreviewHint = publishMode === "schedule" ? "Hidden until the scheduled publish time." : visibility === "private" ? "Draft-only visibility." : visibility === "unlisted" ? "Accessible by direct link." : "Visible to everyone immediately.";
  const hasScheduledRelease = publishMode === "schedule" && Boolean(scheduledAt);
  const schedulePreviewSummary = hasScheduledRelease ? formatReleaseCountdown$1(scheduledAt, nowMs) : "";
  const schedulePreviewHint = hasScheduledRelease ? formatSchedulePreview(scheduledAt, userTimezone) : "";
  const publishingIdentityOptions = reactExports.useMemo(() => {
    const personalOption = {
      value: "",
      label: "Personal profile",
      icon: /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-[11px] text-sky-200", "aria-hidden": "true" }),
      contextLabel: "Publish under your own creator identity"
    };
    const groupItems = groupOptions.map((group) => ({
      value: group.slug,
      label: group.name,
      icon: /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-users text-[11px] text-violet-200", "aria-hidden": "true" }),
      contextLabel: "Publish under the shared group identity"
    }));
    return [personalOption, ...groupItems];
  }, [groupOptions]);
  const primaryAuthorOptions = reactExports.useMemo(() => currentContributorOptions.map((user) => ({
    value: Number(user.id),
    label: user.name || user.username,
    username: user.username,
    avatarUrl: user.avatar_url || null
  })), [currentContributorOptions]);
  const selectedEvolutionType = evolutionRelationTypes.find((option) => String(option.value) === String(evolutionRelationType)) || evolutionRelationTypes[0] || null;
  const handleContentTypeChange = (id) => {
    setContentTypeId(id);
    setCategoryId(null);
    setSubCategoryId(null);
    setIsCategoryChooserOpen(true);
    setCategorySource((current) => nextSourceForManualEdit(current));
  };
  const handleCategoryChange = (id) => {
    setCategoryId(id);
    setSubCategoryId(null);
    setIsCategoryChooserOpen(false);
    setCategorySource((current) => nextSourceForManualEdit(current));
  };
  const handleSubCategoryChange = (id) => {
    setSubCategoryId(id);
    setCategorySource((current) => nextSourceForManualEdit(current));
  };
  const handleTitleChange = (e) => {
    setTitle(e.target.value);
    setTitleSource((current) => nextSourceForManualEdit(current));
  };
  const handleDescriptionChange = (value) => {
    setDescription(value);
    setDescriptionSource((current) => nextSourceForManualEdit(current));
  };
  const handleTagChange = (nextTags) => {
    setTagSlugs(nextTags);
    setTagsSource((current) => nextSourceForManualEdit(current));
  };
  const loadAiData = reactExports.useCallback(async (silent = false) => {
    if (!artwork?.id) return;
    if (!silent) setAiLoading(true);
    try {
      const res = await fetch(`/api/studio/artworks/${artwork.id}/ai`, {
        headers: { Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin"
      });
      if (!res.ok) return;
      const data = await res.json();
      setAiData(data.data || null);
      setSelectedAiTags((data.data?.tag_suggestions || []).map((item) => item.tag).filter(Boolean));
    } catch (err) {
      console.error("AI assist load failed:", err);
    } finally {
      if (!silent) setAiLoading(false);
    }
  }, [artwork?.id]);
  const syncCurrentPayload = reactExports.useCallback((current) => {
    if (!current) return;
    setTitle(current.title || "");
    setDescription(normalizeMarkdownLiteContent(current.description || ""));
    setTagSlugs(Array.isArray(current.tags) ? current.tags : []);
    setContentTypeId(current.content_type_id || null);
    setCategoryId(current.category_id || null);
    setSubCategoryId(null);
    setTitleSource(current.sources?.title || "manual");
    setDescriptionSource(current.sources?.description || "manual");
    setTagsSource(current.sources?.tags || "manual");
    setCategorySource(current.sources?.category || "manual");
  }, []);
  const trackAiEvent = reactExports.useCallback(async (eventType, meta = {}) => {
    if (!artwork?.id) return;
    try {
      await fetch(`/api/studio/artworks/${artwork.id}/ai/events`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin",
        body: JSON.stringify({ event_type: eventType, meta })
      });
    } catch (err) {
      console.error("AI event track failed:", err);
    }
  }, [artwork?.id]);
  const triggerAi = reactExports.useCallback(async (action = "analyze", options = {}) => {
    if (!artwork?.id) return;
    setAiAction(action);
    try {
      const direct = typeof options.direct === "boolean" ? options.direct : aiDirect;
      const intent = options.intent || "analyze";
      const requestBody = { direct, intent };
      const res = await fetch(`/api/studio/artworks/${artwork.id}/ai/${action}`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin",
        body: JSON.stringify(requestBody)
      });
      if (res.ok) {
        const data = await res.json();
        if (direct && data?.data) {
          setAiData(data.data);
        } else {
          await loadAiData(true);
        }
      }
    } catch (err) {
      console.error("AI assist request failed:", err);
    } finally {
      setAiAction("");
    }
  }, [aiDirect, artwork?.id, loadAiData]);
  const persistAiAction = reactExports.useCallback(async (payload) => {
    if (!artwork?.id) return;
    setAiAction("apply");
    try {
      const res = await fetch(`/api/studio/artworks/${artwork.id}/ai/apply`, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin",
        body: JSON.stringify(payload)
      });
      if (res.ok) {
        const data = await res.json();
        if (data?.data) {
          setAiData(data.data);
          syncCurrentPayload(data.data.current);
          setSelectedAiTags((data.data.tag_suggestions || []).map((item) => item.tag).filter(Boolean));
        } else {
          await loadAiData(true);
        }
      }
    } catch (err) {
      console.error("AI assist apply failed:", err);
    } finally {
      setAiAction("");
    }
  }, [artwork?.id, loadAiData, syncCurrentPayload]);
  const copyText = reactExports.useCallback(async (value) => {
    if (!value) return;
    try {
      await window.navigator?.clipboard?.writeText(value);
      trackAiEvent("suggestion_copied", { length: value.length });
    } catch (err) {
      console.error("Clipboard write failed:", err);
    }
  }, [trackAiEvent]);
  const applyTitleSuggestion = reactExports.useCallback((value, mode = "replace") => {
    persistAiAction({ title: value, title_mode: mode });
  }, [persistAiAction]);
  const applyDescriptionSuggestion = reactExports.useCallback((value, mode = "replace") => {
    persistAiAction({ description: value, description_mode: mode });
  }, [persistAiAction]);
  const applyTagSuggestions = reactExports.useCallback((values, mode = "add") => {
    const normalized = Array.isArray(values) ? values.filter(Boolean) : [];
    if (normalized.length === 0) return;
    persistAiAction({ tags: normalized, tag_mode: mode });
  }, [persistAiAction]);
  const applyCategorySuggestion = reactExports.useCallback((suggestion, mode = "both") => {
    if (!suggestion) return;
    const payload = {};
    if (mode === "content_type" || mode === "both") {
      payload.content_type_id = suggestion.content_type_id || suggestion.id || null;
    }
    if (mode === "category" || mode === "both") {
      payload.category_id = suggestion.root_category_id || suggestion.id || null;
    }
    persistAiAction(payload);
  }, [persistAiAction]);
  const toggleSuggestedTag = reactExports.useCallback((tag) => {
    if (!tag) return;
    setSelectedAiTags((current) => current.includes(tag) ? current.filter((item) => item !== tag) : [...current, tag]);
  }, []);
  const handleImproveAll = reactExports.useCallback(() => {
    if (aiStatus !== "ready") {
      triggerAi("analyze", { intent: "analyze" });
      return;
    }
    const bestTitle = aiData?.title_suggestions?.[0]?.text;
    const bestDescription = aiData?.description_suggestions?.find((item) => item.variant === "normal")?.text || aiData?.description_suggestions?.[0]?.text;
    const bestCategory = aiData?.category;
    const payload = {};
    if (bestTitle) {
      payload.title = bestTitle;
      payload.title_mode = "replace";
    }
    if (bestDescription) {
      payload.description = bestDescription;
      payload.description_mode = "replace";
    }
    if (aiSuggestedTags.length > 0) {
      payload.tags = aiSuggestedTags;
      payload.tag_mode = "add";
    }
    if (bestCategory?.content_type_id) {
      payload.content_type_id = bestCategory.content_type_id;
    }
    if (bestCategory?.root_category_id || bestCategory?.id) {
      payload.category_id = bestCategory.root_category_id || bestCategory.id;
    }
    if (Object.keys(payload).length > 0) {
      persistAiAction(payload);
    }
    trackAiEvent("improve_all_applied", {
      applied_title: Boolean(bestTitle),
      applied_description: Boolean(bestDescription),
      applied_tags: aiSuggestedTags.length > 0,
      applied_category: Boolean(bestCategory)
    });
  }, [aiData, aiStatus, aiSuggestedTags, persistAiAction, trackAiEvent, triggerAi]);
  const requestAiIntent = reactExports.useCallback((intent, action = null) => {
    const nextAction = action || (aiStatus === "ready" ? "regenerate" : "analyze");
    trackAiEvent("intent_requested", { intent, action: nextAction });
    triggerAi(nextAction, { intent });
  }, [aiStatus, trackAiEvent, triggerAi]);
  const toggleAiPanel = reactExports.useCallback(() => {
    setIsAiPanelOpen((current) => {
      const next = !current;
      trackAiEvent("panel_toggled", { open: next });
      return next;
    });
  }, [trackAiEvent]);
  reactExports.useEffect(() => {
    loadAiData();
  }, [loadAiData]);
  reactExports.useEffect(() => {
    if (aiStatus !== "queued" && aiStatus !== "processing") return void 0;
    const timer = window.setInterval(() => loadAiData(true), 4e3);
    return () => window.clearInterval(timer);
  }, [aiStatus, loadAiData]);
  reactExports.useEffect(() => {
    if (!hasScheduledRelease) return void 0;
    const timer = window.setInterval(() => {
      setNowMs(Date.now());
    }, 1e3);
    return () => window.clearInterval(timer);
  }, [hasScheduledRelease]);
  reactExports.useEffect(() => {
    const selectedSlug = String(groupSlug || "");
    if (!selectedSlug) {
      if (primaryAuthorUserId || contributorUserIds.length > 0 || Object.keys(contributorCredits || {}).length > 0) {
        setPrimaryAuthorUserId(null);
        setContributorUserIds([]);
        setContributorCredits({});
      }
      return;
    }
    const validGroup = groupOptions.some((group) => String(group.slug || "") === selectedSlug);
    if (!validGroup) {
      setGroupSlug("");
      setPrimaryAuthorUserId(null);
      setContributorUserIds([]);
      setContributorCredits({});
      return;
    }
    const validContributorIds = currentContributorOptions.map((user) => Number(user.id)).filter((id) => Number.isFinite(id) && id > 0);
    const nextPrimaryAuthorId = validContributorIds.includes(Number(primaryAuthorUserId)) ? Number(primaryAuthorUserId) : validContributorIds[0] || null;
    const nextContributorIds = contributorUserIds.map((id) => Number(id)).filter((id) => validContributorIds.includes(id) && id !== nextPrimaryAuthorId);
    const nextContributorCredits = normalizeContributorCredits$1(nextContributorIds, contributorCredits);
    const primaryChanged = (primaryAuthorUserId ? Number(primaryAuthorUserId) : null) !== nextPrimaryAuthorId;
    const contributorsChanged = nextContributorIds.length !== contributorUserIds.length || nextContributorIds.some((id, index2) => id !== contributorUserIds[index2]);
    const contributorCreditsChanged = JSON.stringify(nextContributorCredits) !== JSON.stringify(normalizeContributorCredits$1(contributorUserIds, contributorCredits));
    if (primaryChanged) setPrimaryAuthorUserId(nextPrimaryAuthorId);
    if (contributorsChanged) setContributorUserIds(nextContributorIds);
    if (contributorCreditsChanged) setContributorCredits(nextContributorCredits);
  }, [groupSlug, groupOptions, currentContributorOptions, primaryAuthorUserId, contributorUserIds, contributorCredits]);
  const handleSave = reactExports.useCallback(async () => {
    setSaving(true);
    setSaved(false);
    setErrors({});
    try {
      const payload = {
        title,
        description,
        visibility,
        mode: publishMode,
        publish_at: publishMode === "schedule" ? scheduledAt : null,
        timezone: userTimezone,
        group: groupSlug || null,
        primary_author_user_id: groupSlug ? primaryAuthorUserId : null,
        contributor_user_ids: groupSlug ? contributorUserIds : [],
        contributor_credits: groupSlug ? contributorUserIds.map((id) => ({
          user_id: id,
          credit_role: contributorCredits?.[id]?.creditRole?.trim() ? contributorCredits[id].creditRole.trim() : null,
          is_primary: Boolean(contributorCredits?.[id]?.isPrimary)
        })) : [],
        content_type_id: contentTypeId,
        category_id: selectedLeafCategoryId,
        tags: tagSlugs,
        title_source: titleSource,
        description_source: descriptionSource,
        tags_source: tagsSource,
        category_source: categorySource,
        world_submissions: worldSubmissionOptions.filter((world) => Boolean(world?.selected)).map((world) => ({
          world_id: Number(world.id),
          note: typeof world.note === "string" ? world.note : "",
          source_surface: "navigation"
        })).filter((entry) => Number.isFinite(entry.world_id) && entry.world_id > 0),
        evolution_target_artwork_id: evolutionTarget?.id || null,
        evolution_relation_type: evolutionTarget ? evolutionRelationType : null,
        evolution_note: evolutionTarget ? evolutionNote : null
      };
      const res = await fetch(`/api/studio/artworks/${artwork.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json", Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin",
        body: JSON.stringify(payload)
      });
      if (res.ok) {
        const data = await res.json();
        const updatedArtwork = data?.artwork || null;
        const updatedEvolutionRelation = data?.evolution_relation || updatedArtwork?.evolution_relation || null;
        if (updatedArtwork) {
          setVisibility(updatedArtwork.visibility || visibility);
          setPublishMode(updatedArtwork.publish_mode || "now");
          setScheduledAt(updatedArtwork.publish_at || null);
          setGroupSlug(updatedArtwork.group_slug || "");
          setPrimaryAuthorUserId(updatedArtwork.primary_author_user_id || null);
          setContributorUserIds(Array.isArray(updatedArtwork.contributor_user_ids) ? updatedArtwork.contributor_user_ids.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0) : []);
          setContributorCredits(normalizeContributorCredits$1(updatedArtwork.contributor_user_ids || [], mapContributorCredits(updatedArtwork.contributor_credits || [])));
        }
        if (Array.isArray(data?.world_submission_options)) {
          setWorldSubmissionOptions(normalizeWorldSubmissionOptions(data.world_submission_options));
        }
        setEvolutionTarget(updatedEvolutionRelation?.target_artwork || null);
        setEvolutionRelationType(updatedEvolutionRelation?.relation_type || evolutionRelationTypes[0]?.value || "remake_of");
        setEvolutionNote(updatedEvolutionRelation?.note || "");
        setSaved(true);
        setTimeout(() => setSaved(false), 3e3);
      } else {
        const data = await res.json();
        if (data.errors) setErrors(data.errors);
      }
    } catch (err) {
      console.error("Save failed:", err);
    } finally {
      setSaving(false);
    }
  }, [title, description, visibility, publishMode, scheduledAt, userTimezone, groupSlug, primaryAuthorUserId, contributorUserIds, contributorCredits, contentTypeId, selectedLeafCategoryId, tagSlugs, titleSource, descriptionSource, tagsSource, categorySource, worldSubmissionOptions, evolutionTarget, evolutionRelationType, evolutionNote, artwork?.id, evolutionRelationTypes]);
  const handleFileReplace = async (file) => {
    if (!file) return;
    setReplacing(true);
    try {
      const fd = new FormData();
      fd.append("file", file);
      if (changeNote.trim()) fd.append("change_note", changeNote.trim());
      const res = await fetch(`/api/studio/artworks/${artwork.id}/replace-file`, {
        method: "POST",
        headers: { Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin",
        body: fd
      });
      const data = await res.json();
      if (res.ok && data.thumb_url) {
        syncMediaPayload(data, { fallbackName: file.name, fallbackSize: file.size });
        if (data.version_number) setVersionCount(data.version_number);
        if (typeof data.requires_reapproval !== "undefined") setRequiresReapproval(data.requires_reapproval);
        setChangeNote("");
        setShowChangeNote(false);
        if (pendingReplacePreview) {
          URL.revokeObjectURL(pendingReplacePreview);
          setPendingReplacePreview(null);
        }
        setPendingReplaceFile(null);
      } else {
        alert(data.error || "File replacement failed.");
      }
    } catch (err) {
      console.error("File replace failed:", err);
    } finally {
      setReplacing(false);
      if (fileInputRef.current) fileInputRef.current.value = "";
    }
  };
  const loadVersionHistory = async () => {
    setHistoryLoading(true);
    setShowHistory(true);
    try {
      const res = await fetch(`/api/studio/artworks/${artwork.id}/versions`, {
        headers: { Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin"
      });
      setHistoryData(await res.json());
    } catch (err) {
      console.error("Failed to load version history:", err);
    } finally {
      setHistoryLoading(false);
    }
  };
  const handleRestoreVersion = async (versionId) => {
    if (!window.confirm("Restore this version? A copy will become the new current version.")) return;
    setRestoring(versionId);
    try {
      const res = await fetch(`/api/studio/artworks/${artwork.id}/restore/${versionId}`, {
        method: "POST",
        headers: { Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin"
      });
      const data = await res.json();
      if (res.ok && data.success) {
        syncMediaPayload(data);
        if (data.version_number) setVersionCount(data.version_number);
        setShowHistory(false);
      } else {
        alert(data.error || "Restore failed.");
      }
    } catch (err) {
      console.error("Restore failed:", err);
    } finally {
      setRestoring(null);
    }
  };
  const syncMediaPayload = reactExports.useCallback((payload, options = {}) => {
    const fallbackName = typeof options.fallbackName === "string" ? options.fallbackName : null;
    const fallbackSize = Number.isFinite(options.fallbackSize) ? Number(options.fallbackSize) : null;
    if (payload?.thumb_url) {
      setThumbUrl(payload.thumb_url_lg || payload.thumb_url);
    }
    setSelectedMediaId("cover");
    setFileMeta({
      name: payload?.file_name || fallbackName || "—",
      size: typeof payload?.file_size === "number" ? payload.file_size : fallbackSize ?? 0,
      width: payload?.width || 0,
      height: payload?.height || 0
    });
    if (typeof payload?.file_ext === "string") setFileExt(payload.file_ext);
    if (typeof payload?.mime_type === "string") setMimeType(payload.mime_type);
    if (typeof payload?.has_archive_file !== "undefined") setHasArchiveFile(Boolean(payload.has_archive_file));
    if (Array.isArray(payload?.screenshots)) setArtworkScreenshots(payload.screenshots);
  }, []);
  const resetArchiveRevisionState = reactExports.useCallback(() => {
    setArchiveRevisionError("");
    if (archiveCoverPreview) URL.revokeObjectURL(archiveCoverPreview);
    setArchiveCoverFile(null);
    setArchiveCoverPreview(null);
    setArchivePackageFile(null);
    setArchiveExtraScreenshots([]);
    archiveExtraPreviews.forEach((url) => URL.revokeObjectURL(url));
    setArchiveExtraPreviews([]);
    Object.values(replaceShotPreviews).forEach((url) => URL.revokeObjectURL(url));
    setReplaceShots({});
    setReplaceShotPreviews({});
    setRemovedShots({});
  }, [archiveCoverPreview, archiveExtraPreviews, replaceShotPreviews]);
  const handleArchiveRevisionSubmit = async () => {
    const hasReplaceShots = Object.values(replaceShots).some(Boolean);
    const hasRemovedShots = Object.values(removedShots).some(Boolean);
    if (!archiveCoverFile && !archivePackageFile && archiveExtraScreenshots.length === 0 && !hasReplaceShots && !hasRemovedShots) {
      setArchiveRevisionError("Choose a new cover screenshot, a new archive file, or extra screenshots first.");
      return;
    }
    setArchiveRevisionSaving(true);
    setArchiveRevisionError("");
    try {
      const fd = new FormData();
      if (archiveCoverFile) fd.append("cover_file", archiveCoverFile);
      if (archivePackageFile) fd.append("archive_file", archivePackageFile);
      archiveExtraScreenshots.forEach((file) => fd.append("screenshot_files[]", file));
      Object.entries(replaceShots).forEach(([idx, file]) => {
        if (file) fd.append(`replace_shots[${idx}]`, file);
      });
      Object.entries(removedShots).forEach(([idx, removed]) => {
        if (removed) fd.append("remove_shots[]", idx);
      });
      if (changeNote.trim()) fd.append("change_note", changeNote.trim());
      const res = await fetch(`/api/studio/artworks/${artwork.id}/revise-media`, {
        method: "POST",
        headers: { Accept: "application/json", "X-CSRF-TOKEN": getCsrfToken() },
        credentials: "same-origin",
        body: fd
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        setArchiveRevisionError(data.error || "Archive revision failed.");
        return;
      }
      syncMediaPayload(data);
      if (data.version_number) setVersionCount(data.version_number);
      if (typeof data.requires_reapproval !== "undefined") setRequiresReapproval(data.requires_reapproval);
      setShowChangeNote(false);
      setChangeNote("");
      resetArchiveRevisionState();
    } catch (err) {
      console.error("Archive revision failed:", err);
      setArchiveRevisionError("Archive revision failed.");
    } finally {
      setArchiveRevisionSaving(false);
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: "Edit Artwork" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4 mb-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 min-w-0" }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: "/studio/artworks",
      className: "flex items-center justify-center w-9 h-9 rounded-xl border border-white/10 text-slate-400 hover:text-white hover:bg-white/5 transition-all shrink-0",
      "aria-label": "Back to artworks"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M10 3L5 8l5 5", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }))
  ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h1", { className: "text-lg font-bold text-white truncate" }, title || "Untitled artwork"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap items-center gap-2 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Editing"), /* @__PURE__ */ React.createElement("span", { className: "h-1 w-1 rounded-full bg-slate-600" }), /* @__PURE__ */ React.createElement("span", { className: publishMode === "schedule" ? "text-sky-300" : visibility === "private" ? "text-amber-400" : "text-emerald-400" }, visibilitySummary), heroMeta.map((item) => /* @__PURE__ */ React.createElement(React.Fragment, { key: item }, /* @__PURE__ */ React.createElement("span", { className: "h-1 w-1 rounded-full bg-slate-600" }), /* @__PURE__ */ React.createElement("span", null, item))))))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-6 items-start xl:grid-cols-[300px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 xl:sticky xl:top-6 xl:max-h-[calc(100vh-48px)] xl:overflow-y-auto xl:overscroll-contain xl:pr-1 nova-scrollbar" }, /* @__PURE__ */ React.createElement(Section, { className: "overflow-hidden" }, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-image" }, "Media"), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.14),_transparent_54%),linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-3 shadow-[0_20px_60px_rgba(2,8,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[22px] border border-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-10 flex items-start justify-between gap-2 p-3" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-black/45 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-white/75" }, archiveArtwork ? "Archive package" : "Single image"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-accent/20 bg-accent/12 px-2.5 py-1 text-[10px] font-semibold text-accent" }, "v", versionCount)), /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[4/5] min-h-[280px]" }, activeMedia?.url ? /* @__PURE__ */ React.createElement(
    "img",
    {
      src: activeMedia.url,
      alt: title || "Artwork preview",
      className: "h-full w-full object-cover"
    }
  ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }), /* @__PURE__ */ React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5", fill: "currentColor" }), /* @__PURE__ */ React.createElement("path", { d: "M21 15l-5-5L5 21" }))), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/85 via-black/45 to-transparent p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/50" }, activeMediaLabel), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-semibold text-white", title: fileMeta.name }, fileMeta.name), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2 text-[11px] text-white/65" }, currentFileExt && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/10 px-2 py-0.5 uppercase tracking-[0.14em] text-white/70" }, currentFileExt), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("span", null, screenshotItems.length, " screenshot", screenshotItems.length !== 1 ? "s" : ""), fileMeta.width > 0 && /* @__PURE__ */ React.createElement("span", null, fileMeta.width, " × ", fileMeta.height))), replacing && /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 z-20 flex items-center justify-center bg-black/60" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-full border border-white/10 bg-black/55 px-4 py-2 text-xs text-white/80 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "h-5 w-5 rounded-full border-2 border-accent/30 border-t-accent animate-spin" }), "Uploading new revision…"))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[11px] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Size"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatBytes$1(fileMeta.size))), downloadUrl ? /* @__PURE__ */ React.createElement(
    "a",
    {
      href: downloadUrl,
      "aria-label": "Download artwork",
      title: "Download artwork",
      className: "inline-flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-emerald-400/25 bg-emerald-400/10 text-emerald-200 transition hover:bg-emerald-400/15 hover:text-white"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M8.75 1.5a.75.75 0 00-1.5 0v6.19L5.53 5.97a.75.75 0 10-1.06 1.06l3 3a.75.75 0 001.06 0l3-3a.75.75 0 10-1.06-1.06L8.75 7.69V1.5z" }), /* @__PURE__ */ React.createElement("path", { d: "M2.5 10.75A.75.75 0 013.25 10h9.5a.75.75 0 010 1.5h-9.5a.75.75 0 01-.75-.75z" }), /* @__PURE__ */ React.createElement("path", { d: "M2 12.5A1.5 1.5 0 013.5 11h9a1.5 1.5 0 011.5 1.5v1A1.5 1.5 0 0112.5 15h-9A1.5 1.5 0 012 13.5v-1z" }))
  ) : null), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setActiveTab("media"),
      className: "group flex w-full items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-left transition hover:border-white/20 hover:bg-white/[0.05]"
    },
    /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition group-hover:border-accent/30 group-hover:bg-accent/10 group-hover:text-accent" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-photo-film text-[13px]", "aria-hidden": "true" })),
    /* @__PURE__ */ React.createElement("span", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Media"), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-sm font-medium text-white" }, archiveArtwork ? "Manage package and screenshots" : "Replace image and manage screenshots")),
    /* @__PURE__ */ React.createElement("span", { className: "pt-0.5 text-slate-600 transition group-hover:text-slate-300", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-right text-[11px]" }))
  ))), /* @__PURE__ */ React.createElement(Section, { className: "space-y-3" }, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-layer-group" }, "Publishing Snapshot"), [
    {
      id: "taxonomy",
      label: "Category",
      value: categoryPreviewSummary,
      hint: categorySource === "manual" ? "Manual category path" : `Source: ${String(categorySource).replace(/_/g, " ")}`,
      icon: "fa-solid fa-palette"
    },
    {
      id: "visibility",
      label: "Visibility",
      value: visibilitySummary,
      hint: visibilityPreviewHint,
      icon: "fa-solid fa-eye"
    },
    hasScheduledRelease ? {
      id: "visibility",
      label: "Scheduler",
      value: schedulePreviewSummary,
      hint: schedulePreviewHint,
      icon: "fa-regular fa-clock"
    } : null
  ].filter(Boolean).map((item) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${item.label}-${item.id}`,
      type: "button",
      onClick: () => setActiveTab(item.id),
      className: "group flex w-full items-start gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-left transition hover:border-white/20 hover:bg-white/[0.05]"
    },
    /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition group-hover:border-accent/30 group-hover:bg-accent/10 group-hover:text-accent" }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} text-[13px]`, "aria-hidden": "true" })),
    /* @__PURE__ */ React.createElement("span", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, item.label), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block truncate text-sm font-medium text-white", title: item.value }, item.value), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs text-slate-500" }, item.hint)),
    /* @__PURE__ */ React.createElement("span", { className: "pt-1 text-slate-600 transition group-hover:text-slate-300", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-right text-[11px]" }))
  ))), /* @__PURE__ */ React.createElement(Section, { className: "py-3 px-4" }, /* @__PURE__ */ React.createElement(
    xe,
    {
      href: `/studio/artworks/${artwork?.id}/analytics`,
      className: "flex items-center gap-3 py-2 text-sm text-slate-400 hover:text-white transition-colors group"
    },
    /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-center w-8 h-8 rounded-lg bg-white/5 group-hover:bg-accent/15 transition-colors" }, /* @__PURE__ */ React.createElement("svg", { width: "14", height: "14", viewBox: "0 0 16 16", fill: "currentColor", className: "text-slate-500 group-hover:text-accent transition-colors", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M1 11a1 1 0 011-1h2a1 1 0 011 1v3a1 1 0 01-1 1H2a1 1 0 01-1-1v-3zm5-4a1 1 0 011-1h2a1 1 0 011 1v7a1 1 0 01-1 1H7a1 1 0 01-1-1V7zm5-5a1 1 0 011-1h2a1 1 0 011 1v12a1 1 0 01-1 1h-2a1 1 0 01-1-1V2z" }))),
    "View Analytics"
  ))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col min-h-0" }, /* @__PURE__ */ React.createElement("div", { className: "sticky top-0 z-30 bg-nova-900/95 backdrop-blur-md flex items-stretch border-b border-white/10 mb-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center overflow-x-auto flex-1 min-w-0" }, TABS.map((tab2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: tab2.id,
      type: "button",
      onClick: () => setActiveTab(tab2.id),
      className: [
        "relative flex items-center gap-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors",
        activeTab === tab2.id ? "text-white after:absolute after:bottom-0 after:left-0 after:right-0 after:h-[2px] after:bg-accent after:rounded-t-full" : "text-slate-400 hover:text-slate-200"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("i", { className: `${tab2.icon} text-[11px]`, "aria-hidden": "true" }),
    tab2.label,
    tab2.id === "evolution" && evolutionTarget && /* @__PURE__ */ React.createElement("span", { className: "h-1.5 w-1.5 rounded-full bg-sky-400" }),
    tab2.id === "ai" && aiStatus !== "not_analyzed" && /* @__PURE__ */ React.createElement("span", { className: `h-1.5 w-1.5 rounded-full ${aiStatus === "ready" ? "bg-emerald-400" : aiStatus === "failed" ? "bg-red-400" : "bg-sky-400"}` })
  ))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 px-3 flex-shrink-0" }, saved && /* @__PURE__ */ React.createElement("span", { className: "text-xs text-emerald-400 flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M8 16A8 8 0 108 0a8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L7 8.586 5.707 7.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z", clipRule: "evenodd" })), "Saved"), /* @__PURE__ */ React.createElement(Button$1, { variant: "accent", size: "xs", loading: saving, onClick: handleSave }, "Save"))), activeTab === "taxonomy" && /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(Section, { id: "taxonomy", className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-palette" }, "Category"), /* @__PURE__ */ React.createElement("p", { className: "-mt-2 text-sm text-slate-400" }, "Pick a content type from the left, then choose the best category path on the right. The layout keeps the hierarchy visible instead of stretching into one long wall of chips.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, selectedCT?.name || "Unset")), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-1.5 text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Path"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, selectedRoot?.name || "Choose category")))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 xl:grid-cols-[280px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.02))] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h4", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Content types"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-500" }, "Start here")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[11px] text-slate-400" }, contentTypes.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, contentTypes.map((ct) => {
    const isActive = contentTypeId === ct.id;
    const visualKey = getContentTypeVisualKey$1(ct.slug);
    const categoryCount = ct.rootCategories?.length || 0;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: ct.id,
        type: "button",
        onClick: () => handleContentTypeChange(ct.id),
        className: [
          "group flex w-full items-center gap-3 rounded-2xl border px-3 py-3 text-left transition-all",
          isActive ? "border-emerald-400/40 bg-emerald-400/10 shadow-[0_0_0_1px_rgba(52,211,153,0.18)]" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: `flex h-12 w-12 items-center justify-center rounded-2xl border ${isActive ? "border-emerald-400/30 bg-emerald-400/10" : "border-white/10 bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement(
        "img",
        {
          src: `/gfx/mascot_${visualKey}.webp`,
          alt: "",
          className: "h-8 w-8 object-contain",
          onError: (e) => {
            e.target.style.display = "none";
          }
        }
      )),
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: `text-sm font-semibold ${isActive ? "text-emerald-200" : "text-white"}` }, ct.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-slate-500" }, categoryCount, " ", categoryCount === 1 ? "category" : "categories")),
      /* @__PURE__ */ React.createElement("div", { className: `text-xs ${isActive ? "text-emerald-300" : "text-slate-500 group-hover:text-slate-300"}` }, isActive ? "Selected" : "Open")
    );
  }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(14,165,233,0.08),_rgba(15,23,36,0.92)_52%)] p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h4", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Category path"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Choose the main branch first, then refine with a subcategory when needed.")), /* @__PURE__ */ React.createElement(InlineAiButton, { onClick: () => requestAiIntent("category"), disabled: aiAction !== "", loading: aiAction === "analyze" || aiAction === "regenerate" }, "Category")), !selectedCT && /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-dashed border-white/12 bg-white/[0.02] px-5 py-10 text-center" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-medium text-white" }, "Select a content type first"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-500" }, "Once you choose the content type, the matching category tree will appear here.")), selectedCT && /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-400/20 bg-emerald-400/10 px-2.5 py-1 text-emerald-200" }, selectedCT.name), /* @__PURE__ */ React.createElement("span", null, "contains ", rootCategories.length, " top-level ", rootCategories.length === 1 ? "category" : "categories")), selectedRoot && !isCategoryChooserOpen && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-purple-400/25 bg-purple-400/[0.08] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-purple-200/80" }, "Selected category"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, selectedRoot.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, subCategories.length > 0 ? `Next step: choose one of the ${subCategories.length} subcategories below.` : "This category is complete. No subcategory is required.")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setIsCategoryChooserOpen(true),
      className: "inline-flex items-center justify-center rounded-xl border border-white/10 bg-white/[0.05] px-3 py-2 text-sm font-medium text-slate-200 transition hover:border-white/20 hover:bg-white/[0.08] hover:text-white"
    },
    "Change"
  ))), (!selectedRoot || isCategoryChooserOpen) && /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-2" }, rootCategories.map((cat) => {
    const isActive = categoryId === cat.id;
    const childCount = cat.children?.length || 0;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: cat.id,
        type: "button",
        onClick: () => handleCategoryChange(cat.id),
        className: [
          "rounded-2xl border px-4 py-4 text-left transition-all",
          isActive ? "border-purple-400/40 bg-purple-400/12 shadow-[0_0_0_1px_rgba(192,132,252,0.15)]" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: `text-sm font-semibold ${isActive ? "text-purple-200" : "text-white"}` }, cat.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-slate-500" }, childCount > 0 ? `${childCount} subcategories available` : "Standalone category")), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2 py-1 text-[11px] ${isActive ? "bg-purple-300/15 text-purple-200" : "bg-white/[0.05] text-slate-500"}` }, isActive ? "Selected" : "Choose"))
    );
  })), selectedRoot && subCategories.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-cyan-400/15 bg-cyan-400/[0.05] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h5", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-cyan-200/80" }, "Subcategories"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Refine ", /* @__PURE__ */ React.createElement("span", { className: "text-white" }, selectedRoot.name), " with one more level.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-cyan-400/20 bg-cyan-400/10 px-2 py-1 text-[11px] text-cyan-200" }, subCategories.length)), !subCategoryId && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-xl border border-amber-400/20 bg-amber-400/10 px-3 py-2 text-sm text-amber-100" }, "Subcategory still needs to be selected."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2.5" }, subCategories.map((sub) => {
    const isActive = subCategoryId === sub.id;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: sub.id,
        type: "button",
        onClick: () => handleSubCategoryChange(sub.id),
        className: [
          "rounded-xl border px-3 py-2 text-xs font-medium transition-all",
          isActive ? "border-cyan-400/40 bg-cyan-400/15 text-cyan-200" : "border-white/10 bg-white/[0.04] text-slate-300 hover:border-white/20 hover:text-white"
        ].join(" ")
      },
      sub.name
    );
  }))), selectedRoot && subCategories.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "text-white font-medium" }, selectedRoot.name), " does not have subcategories. Selecting it is enough.")), errors.category_id && /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs text-red-400" }, errors.category_id[0]))))), activeTab === "details" && /* @__PURE__ */ React.createElement(Section, { id: "details", className: "space-y-5" }, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-pen-fancy" }, "Details"), /* @__PURE__ */ React.createElement(
    TextInput,
    {
      label: /* @__PURE__ */ React.createElement(FieldLabel, { label: /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1" }, "Title ", /* @__PURE__ */ React.createElement("span", { className: "text-red-400" }, "*")), actionLabel: "Title", onAction: () => requestAiIntent("title"), disabled: aiAction !== "", loading: aiAction === "analyze" || aiAction === "regenerate" }),
      value: title,
      onChange: handleTitleChange,
      placeholder: "Give your artwork a title",
      error: errors.title?.[0]
    }
  ), /* @__PURE__ */ React.createElement(FormField, { label: /* @__PURE__ */ React.createElement(FieldLabel, { label: "Description", actionLabel: "Description", onAction: () => requestAiIntent("description"), disabled: aiAction !== "", loading: aiAction === "analyze" || aiAction === "regenerate" }), htmlFor: "artwork-description" }, /* @__PURE__ */ React.createElement(
    UploadDescriptionEditor,
    {
      id: "artwork-description",
      value: description,
      onChange: handleDescriptionChange,
      placeholder: "Describe your artwork, tools, inspiration…",
      error: errors.description?.[0],
      rows: 10
    }
  )), /* @__PURE__ */ React.createElement(Section, { className: "space-y-5 border-white/8 bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-users" }, "Attribution"), /* @__PURE__ */ React.createElement("p", { className: "-mt-2 text-sm text-slate-400" }, "Switch between personal and group context, then maintain primary author and contributor credits without leaving the edit screen.")), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${groupSlug ? "border-sky-300/20 bg-sky-300/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-300"}` }, selectedGroupOption ? `Group: ${selectedGroupOption.name}` : "Personal publish")), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Publishing identity",
      value: groupSlug || "",
      onChange: (nextValue) => setGroupSlug(String(nextValue || "")),
      options: publishingIdentityOptions,
      searchable: false,
      placeholder: "Choose publishing identity",
      error: errors.group?.[0],
      hint: selectedGroupOption ? "The artwork will be publicly published under the selected group while authorship stays editable below." : "Personal publishing keeps the artwork under your own creator profile.",
      className: "mt-2 bg-black/20",
      renderOption: (option) => /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.04]" }, option.icon), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block truncate font-medium text-white" }, option.label), /* @__PURE__ */ React.createElement("span", { className: "block truncate text-[11px] text-slate-500" }, option.contextLabel)))
    }
  ), groupSlug ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Primary author",
      value: primaryAuthorUserId || null,
      onChange: (nextValue) => setPrimaryAuthorUserId(nextValue ? Number(nextValue) : null),
      options: primaryAuthorOptions,
      placeholder: "Choose primary author",
      searchable: primaryAuthorOptions.length > 6,
      error: errors.primary_author_user_id?.[0],
      hint: "Primary author remains the lead creator shown on the public artwork page.",
      className: "mt-2 bg-black/20",
      renderOption: (option) => /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-center gap-3" }, option.avatarUrl ? /* @__PURE__ */ React.createElement("img", { src: option.avatarUrl, alt: "", className: "h-7 w-7 shrink-0 rounded-full object-cover" }) : /* @__PURE__ */ React.createElement("span", { className: "flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-[11px]", "aria-hidden": "true" })), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block truncate font-medium text-white" }, option.label), option.username ? /* @__PURE__ */ React.createElement("span", { className: "block truncate text-[11px] text-slate-500" }, "@", option.username) : null))
    }
  )), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/90" }, "Contributors"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "Optional")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 grid gap-2" }, currentContributorOptions.filter((user) => Number(user.id) !== Number(primaryAuthorUserId)).map((user) => {
    const active = contributorUserIds.some((id) => Number(id) === Number(user.id));
    const creditMeta = contributorCredits?.[user.id] || contributorCredits?.[String(user.id)] || { creditRole: "", isPrimary: false };
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: user.id,
        className: [
          "rounded-2xl border px-3 py-3 transition",
          active ? "border-sky-300/30 bg-sky-300/10 text-white" : "border-white/10 bg-white/[0.03] text-slate-200 hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, user.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: user.avatar_url, alt: user.name || user.username, className: "h-10 w-10 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold" }, user.name || user.username), /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs text-slate-400" }, "@", user.username)), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => {
            setContributorUserIds((current) => {
              const nextIds = new Set(current.map((id) => Number(id)).filter((id) => id !== Number(primaryAuthorUserId)));
              if (nextIds.has(Number(user.id))) {
                nextIds.delete(Number(user.id));
              } else {
                nextIds.add(Number(user.id));
              }
              const normalizedIds = Array.from(nextIds);
              setContributorCredits((currentCredits) => normalizeContributorCredits$1(normalizedIds, currentCredits));
              return normalizedIds;
            });
          },
          className: [
            "inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold transition",
            active ? "border-sky-300/40 bg-sky-300/20 text-sky-50" : "border-white/10 bg-white/[0.03] text-white/70 hover:border-white/20 hover:text-white"
          ].join(" ")
        },
        /* @__PURE__ */ React.createElement("span", { className: ["inline-flex h-4 w-4 items-center justify-center rounded-full border text-[10px]", active ? "border-sky-300/40 bg-sky-300/20 text-sky-50" : "border-white/10 bg-white/[0.03] text-white/35"].join(" ") }, active ? "✓" : ""),
        active ? "Added" : "Add credit"
      )),
      active ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium uppercase tracking-[0.16em] text-slate-300" }, "Credit role"), /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "text",
          value: creditMeta.creditRole || "",
          onChange: (event) => setContributorCredits((current) => ({
            ...normalizeContributorCredits$1(contributorUserIds, current),
            [Number(user.id)]: {
              ...normalizeContributorCredits$1(contributorUserIds, current)[Number(user.id)] || { isPrimary: false },
              creditRole: event.target.value
            }
          })),
          placeholder: "Colorist, concept support, layout...",
          className: "mt-2 w-full rounded-xl border border-white/15 bg-black/20 px-3 py-3 text-sm text-white outline-none transition focus:border-sky-300/40"
        }
      )), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => setContributorCredits((current) => {
            const nextCredits = normalizeContributorCredits$1(contributorUserIds, current);
            contributorUserIds.forEach((id) => {
              nextCredits[id] = {
                ...nextCredits[id] || { creditRole: "" },
                isPrimary: id === Number(user.id)
              };
            });
            return nextCredits;
          }),
          className: [
            "inline-flex items-center justify-center rounded-xl border px-3 py-3 text-sm font-medium transition",
            creditMeta.isPrimary ? "border-emerald-300/35 bg-emerald-400/12 text-emerald-100" : "border-white/10 bg-white/[0.03] text-slate-200 hover:border-white/20 hover:bg-white/[0.06] hover:text-white"
          ].join(" ")
        },
        creditMeta.isPrimary ? "Lead support" : "Set lead support"
      )) : null
    );
  })), errors.contributor_credits?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-red-400" }, errors.contributor_credits[0]) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-400" }, "Personal publishing uses your own creator profile as the primary author automatically."))), activeTab === "media" && /* @__PURE__ */ React.createElement(Section, { id: "media", className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-photo-film" }, "Media & Revisions"), /* @__PURE__ */ React.createElement("p", { className: "-mt-2 text-sm text-slate-400" }, quickReplaceSupported ? "Drop or upload a new image, then add or manage up to 4 extra screenshots in the same media workspace." : "Replace the archive package, update the cover screenshot, or add / replace screenshots — saved together as one revision.")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: loadVersionHistory,
      className: "inline-flex shrink-0 items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-[11px] font-semibold text-slate-300 transition hover:border-accent/30 hover:bg-accent/10 hover:text-accent"
    },
    /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M8 3.5a4.5 4.5 0 00-4.04 2.51.75.75 0 01-1.34-.67A6 6 0 1114 8a.75.75 0 01-1.5 0A4.5 4.5 0 008 3.5z", clipRule: "evenodd" }), /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M4.75.75a.75.75 0 00-.75.75v3.5c0 .414.336.75.75.75h3.5a.75.75 0 000-1.5H5.5V1.5a.75.75 0 00-.75-.75z", clipRule: "evenodd" })),
    "History"
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-12 w-12 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, thumbUrl && /* @__PURE__ */ React.createElement("img", { src: thumbUrl, alt: "", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-semibold text-white", title: fileMeta.name }, fileMeta.name || "Artwork file"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-1.5" }, currentFileExt && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] uppercase tracking-[0.12em] text-white/55" }, currentFileExt), fileMeta.width > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, fileMeta.width, " × ", fileMeta.height), fileMeta.size > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, formatBytes$1(fileMeta.size)), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, screenshotItems.length, " screenshot", screenshotItems.length !== 1 ? "s" : ""))), /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold text-slate-400" }, "v", versionCount)), requiresReapproval && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "Visual changes on this artwork require a new moderation pass."), quickReplaceSupported && (() => {
    const zone = "single-replace";
    const isDragging = dragOverZone === zone;
    const stageFile = (file) => {
      if (!file || !file.type.startsWith("image/")) return;
      if (pendingReplacePreview) URL.revokeObjectURL(pendingReplacePreview);
      setPendingReplaceFile(file);
      setPendingReplacePreview(URL.createObjectURL(file));
    };
    return /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Replace image"), /* @__PURE__ */ React.createElement(
      "div",
      {
        className: [
          "relative overflow-hidden rounded-2xl border-2 border-dashed transition",
          isDragging ? "border-sky-400/60 bg-sky-400/10" : "border-white/15 bg-white/[0.02]"
        ].join(" "),
        onDragOver: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragEnter: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragLeave: () => setDragOverZone(null),
        onDrop: (e) => {
          e.preventDefault();
          setDragOverZone(null);
          stageFile(e.dataTransfer.files?.[0]);
        }
      },
      pendingReplacePreview ? /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-24 w-24 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement("img", { src: pendingReplacePreview, alt: "Preview", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 py-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "Ready to upload"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-medium text-white" }, pendingReplaceFile?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$1(pendingReplaceFile?.size)), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          className: "mt-3 text-xs text-slate-400 hover:text-white transition-colors",
          onClick: () => {
            URL.revokeObjectURL(pendingReplacePreview);
            setPendingReplacePreview(null);
            setPendingReplaceFile(null);
          }
        },
        "✕ Remove"
      ))) : /* @__PURE__ */ React.createElement("label", { className: "flex cursor-pointer flex-col items-center justify-center gap-3 p-10 text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-12 w-12 items-center justify-center rounded-full border border-white/10 bg-white/[0.05] text-slate-400" }, /* @__PURE__ */ React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5" }))), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-slate-300" }, "Drop image here or ", /* @__PURE__ */ React.createElement("span", { className: "text-sky-300" }, "browse")), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "JPG · PNG · WEBP · TIFF — any resolution"), /* @__PURE__ */ React.createElement(
        "input",
        {
          ref: fileInputRef,
          type: "file",
          className: "hidden",
          accept: "image/*",
          onChange: (e) => stageFile(e.target.files?.[0])
        }
      )),
      replacing && /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 flex flex-col items-center justify-center gap-3 rounded-2xl bg-black/65 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "h-8 w-8 rounded-full border-2 border-accent/30 border-t-accent animate-spin" }), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-300" }, "Uploading revision…"))
    ), /* @__PURE__ */ React.createElement(
      TextInput,
      {
        value: changeNote,
        onChange: (e) => setChangeNote(e.target.value),
        placeholder: "Change note for this revision… (optional)",
        size: "sm"
      }
    ), pendingReplaceFile && /* @__PURE__ */ React.createElement("div", { className: "flex justify-end" }, /* @__PURE__ */ React.createElement(
      Button$1,
      {
        variant: "accent",
        size: "sm",
        loading: replacing,
        onClick: () => handleFileReplace(pendingReplaceFile)
      },
      replacing ? "Uploading…" : "Upload new version"
    )));
  })(), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, archiveArtwork ? "Revise archive media" : "Additional screenshots"), archiveRevisionError && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-red-400/20 bg-red-500/10 px-4 py-3 text-sm text-red-200" }, archiveRevisionError), archiveArtwork && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-400" }, "Cover screenshot"), (() => {
    const zone = "archive-cover";
    const isDragging = dragOverZone === zone;
    const stageFile = (file) => {
      if (!file || !file.type.startsWith("image/")) return;
      if (archiveCoverPreview) URL.revokeObjectURL(archiveCoverPreview);
      setArchiveCoverFile(file);
      setArchiveCoverPreview(URL.createObjectURL(file));
    };
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        className: [
          "relative overflow-hidden rounded-2xl border-2 border-dashed transition",
          isDragging ? "border-sky-400/60 bg-sky-400/10" : "border-white/15 bg-white/[0.02]"
        ].join(" "),
        onDragOver: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragEnter: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragLeave: () => setDragOverZone(null),
        onDrop: (e) => {
          e.preventDefault();
          setDragOverZone(null);
          stageFile(e.dataTransfer.files?.[0]);
        }
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-20 w-20 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, archiveCoverPreview ? /* @__PURE__ */ React.createElement("img", { src: archiveCoverPreview, alt: "New cover", className: "h-full w-full object-cover" }) : thumbUrl ? /* @__PURE__ */ React.createElement("img", { src: thumbUrl, alt: "Current cover", className: "h-full w-full object-cover opacity-60" }) : null), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 py-1" }, archiveCoverFile ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "New cover staged"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-medium text-white" }, archiveCoverFile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$1(archiveCoverFile.size)), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          className: "mt-2 text-xs text-slate-400 hover:text-white transition-colors",
          onClick: () => {
            URL.revokeObjectURL(archiveCoverPreview);
            setArchiveCoverFile(null);
            setArchiveCoverPreview(null);
          }
        },
        "✕ Remove"
      )) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-500" }, "Current cover"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, "Drop a new image or click to browse."), /* @__PURE__ */ React.createElement("label", { className: "mt-2 inline-flex cursor-pointer items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold text-slate-300 transition hover:bg-white/[0.08] hover:text-white" }, /* @__PURE__ */ React.createElement("svg", { width: "11", height: "11", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M2.75 14A1.75 1.75 0 011 12.25V9.5a.75.75 0 011.5 0v2.75c0 .138.112.25.25.25h10.5a.25.25 0 00.25-.25V9.5a.75.75 0 011.5 0v2.75A1.75 1.75 0 0113.25 14H2.75z" }), /* @__PURE__ */ React.createElement("path", { d: "M11.78 5.22a.75.75 0 00-1.06 0L8.75 7.19V1.75a.75.75 0 00-1.5 0v5.44L5.28 5.22a.75.75 0 00-1.06 1.06l3.25 3.25a.75.75 0 001.06 0l3.25-3.25a.75.75 0 000-1.06z" })), "Replace cover", /* @__PURE__ */ React.createElement("input", { type: "file", className: "hidden", accept: "image/*", onChange: (e) => stageFile(e.target.files?.[0]) })))))
    );
  })()), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-400" }, "Archive package"), (() => {
    const zone = "archive-pkg";
    const isDragging = dragOverZone === zone;
    const stageFile = (file) => {
      if (!file) return;
      setArchivePackageFile(file);
    };
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        className: [
          "rounded-2xl border-2 border-dashed transition",
          isDragging ? "border-sky-400/60 bg-sky-400/10" : "border-white/15 bg-white/[0.02]"
        ].join(" "),
        onDragOver: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragEnter: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragLeave: () => setDragOverZone(null),
        onDrop: (e) => {
          e.preventDefault();
          setDragOverZone(null);
          stageFile(e.dataTransfer.files?.[0]);
        }
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 px-4 py-4" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-400" }, /* @__PURE__ */ React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" }))), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, archivePackageFile ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "New package staged"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-sm font-medium text-white" }, archivePackageFile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$1(archivePackageFile.size))) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-500" }, "Current package"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-sm text-slate-300" }, fileMeta.name || "—"))), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-col gap-2" }, archivePackageFile ? /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          className: "text-xs text-slate-400 hover:text-white transition-colors",
          onClick: () => setArchivePackageFile(null)
        },
        "✕ Remove"
      ) : /* @__PURE__ */ React.createElement("label", { className: "inline-flex cursor-pointer items-center gap-1.5 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold text-slate-300 transition hover:bg-white/[0.08] hover:text-white" }, /* @__PURE__ */ React.createElement("svg", { width: "11", height: "11", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M2.75 14A1.75 1.75 0 011 12.25V9.5a.75.75 0 011.5 0v2.75c0 .138.112.25.25.25h10.5a.25.25 0 00.25-.25V9.5a.75.75 0 011.5 0v2.75A1.75 1.75 0 0113.25 14H2.75z" }), /* @__PURE__ */ React.createElement("path", { d: "M11.78 5.22a.75.75 0 00-1.06 0L8.75 7.19V1.75a.75.75 0 00-1.5 0v5.44L5.28 5.22a.75.75 0 00-1.06 1.06l3.25 3.25a.75.75 0 001.06 0l3.25-3.25a.75.75 0 000-1.06z" })), "Replace", /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "file",
          className: "hidden",
          accept: ".zip,.rar,.7z,.tar,.gz,application/zip,application/x-zip-compressed,application/x-rar-compressed,application/vnd.rar,application/x-7z-compressed,application/x-tar,application/gzip",
          onChange: (e) => stageFile(e.target.files?.[0])
        }
      ))))
    );
  })())), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-400" }, "Screenshots ", /* @__PURE__ */ React.createElement("span", { className: "ml-1 font-normal text-slate-500" }, "(", activeScreenshotCount, " active / ", screenshotItems.length, " existing)")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3 sm:grid-cols-4" }, screenshotItems.map((shot, i) => {
    const shotZone = `replace-shot-${i}`;
    const isDragging = dragOverZone === shotZone;
    const pendingPreview = replaceShotPreviews[i];
    const pendingFile = replaceShots[i];
    const isRemoved = Boolean(removedShots[i]);
    const stageShot = (file) => {
      if (!file || !file.type.startsWith("image/")) return;
      if (pendingPreview) URL.revokeObjectURL(pendingPreview);
      setRemovedShots((prev) => {
        const next = { ...prev };
        delete next[i];
        return next;
      });
      setReplaceShots((prev) => ({ ...prev, [i]: file }));
      setReplaceShotPreviews((prev) => ({ ...prev, [i]: URL.createObjectURL(file) }));
    };
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: shot.id || `shot-${i}`,
        className: [
          "relative overflow-hidden rounded-2xl border-2 border-dashed transition",
          isDragging ? "border-sky-400/60 bg-sky-400/10" : "border-white/10 bg-white/[0.02]"
        ].join(" "),
        onDragOver: (e) => {
          e.preventDefault();
          setDragOverZone(shotZone);
        },
        onDragEnter: (e) => {
          e.preventDefault();
          setDragOverZone(shotZone);
        },
        onDragLeave: () => setDragOverZone(null),
        onDrop: (e) => {
          e.preventDefault();
          setDragOverZone(null);
          stageShot(e.dataTransfer.files?.[0]);
        }
      },
      /* @__PURE__ */ React.createElement("div", { className: "aspect-square overflow-hidden bg-black/25" }, /* @__PURE__ */ React.createElement(
        "img",
        {
          src: pendingPreview || shot.thumb_url || shot.url,
          alt: shot.label || `Screenshot ${i + 1}`,
          className: [
            "h-full w-full object-cover transition-opacity",
            isRemoved ? "opacity-25 grayscale" : "opacity-100"
          ].join(" ")
        }
      ), pendingPreview && /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 flex items-center justify-center gap-1 bg-emerald-500/80 py-1 text-[10px] font-semibold text-white" }, "New"), isRemoved && /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 flex items-center justify-center gap-1 bg-red-500/85 py-1 text-[10px] font-semibold text-white" }, "Disabled for next save")),
      /* @__PURE__ */ React.createElement("div", { className: "space-y-1 p-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-1" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] text-slate-500" }, "Shot ", i + 1), pendingFile ? /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          className: "text-[10px] text-slate-400 hover:text-white transition-colors",
          onClick: () => {
            URL.revokeObjectURL(pendingPreview);
            setReplaceShots((prev) => {
              const n = { ...prev };
              delete n[i];
              return n;
            });
            setReplaceShotPreviews((prev) => {
              const n = { ...prev };
              delete n[i];
              return n;
            });
          }
        },
        "Undo replace"
      ) : isRemoved ? /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          className: "text-[10px] text-emerald-300 hover:text-white transition-colors",
          onClick: () => setRemovedShots((prev) => {
            const next = { ...prev };
            delete next[i];
            return next;
          })
        },
        "Re-enable"
      ) : /* @__PURE__ */ React.createElement("label", { className: "cursor-pointer text-[10px] font-semibold text-sky-300 hover:text-white transition-colors" }, "Replace", /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "file",
          className: "hidden",
          accept: "image/*",
          onChange: (e) => stageShot(e.target.files?.[0])
        }
      ))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "truncate text-[10px] text-slate-600" }, pendingFile ? pendingFile.name : shot.label || `Screenshot ${i + 1}`), !pendingFile && !isRemoved && /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          className: "text-[10px] text-red-300 hover:text-white transition-colors",
          onClick: () => setRemovedShots((prev) => ({ ...prev, [i]: true }))
        },
        "Delete"
      )))
    );
  }))), activeScreenshotCount < 4 && /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-400" }, "Add screenshots ", /* @__PURE__ */ React.createElement("span", { className: "ml-1 font-normal text-slate-500" }, "(up to ", 4 - activeScreenshotCount, " more)")), (() => {
    const zone = "archive-extra-shots";
    const isDragging = dragOverZone === zone;
    const availableSlots = Math.max(0, 4 - activeScreenshotCount);
    const stageFiles = (files) => {
      const imageFiles = Array.from(files).filter((f2) => f2.type.startsWith("image/")).slice(0, availableSlots);
      archiveExtraPreviews.forEach((url) => URL.revokeObjectURL(url));
      setArchiveExtraScreenshots(imageFiles);
      setArchiveExtraPreviews(imageFiles.map((f2) => URL.createObjectURL(f2)));
    };
    return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
      "div",
      {
        className: [
          "rounded-2xl border-2 border-dashed transition",
          isDragging ? "border-sky-400/60 bg-sky-400/10" : "border-white/15 bg-white/[0.02]"
        ].join(" "),
        onDragOver: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragEnter: (e) => {
          e.preventDefault();
          setDragOverZone(zone);
        },
        onDragLeave: () => setDragOverZone(null),
        onDrop: (e) => {
          e.preventDefault();
          setDragOverZone(null);
          stageFiles(e.dataTransfer.files);
        }
      },
      /* @__PURE__ */ React.createElement("label", { className: "flex cursor-pointer flex-col items-center justify-center gap-2 py-6 text-center" }, /* @__PURE__ */ React.createElement("svg", { width: "20", height: "20", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", className: "text-slate-500", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M12 4.5v15m7.5-7.5h-15" })), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-slate-300" }, "Drop images here or ", /* @__PURE__ */ React.createElement("span", { className: "text-sky-300" }, "browse")), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "Select up to ", availableSlots, " image", availableSlots !== 1 ? "s" : ""), /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "file",
          className: "hidden",
          accept: "image/*",
          multiple: true,
          onChange: (e) => stageFiles(e.target.files)
        }
      ))
    ), archiveExtraPreviews.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-4 gap-2" }, archiveExtraPreviews.map((url, i) => /* @__PURE__ */ React.createElement("div", { key: url, className: "relative overflow-hidden rounded-xl border border-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square" }, /* @__PURE__ */ React.createElement("img", { src: url, alt: `New ${i + 1}`, className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        "aria-label": "Remove",
        className: "absolute right-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-black/70 text-[10px] text-white hover:bg-red-500/80 transition-colors",
        onClick: () => {
          URL.revokeObjectURL(url);
          const next = archiveExtraScreenshots.filter((_2, j2) => j2 !== i);
          const nextPrev = archiveExtraPreviews.filter((_2, j2) => j2 !== i);
          setArchiveExtraScreenshots(next);
          setArchiveExtraPreviews(nextPrev);
        }
      },
      "✕"
    )))));
  })()), /* @__PURE__ */ React.createElement(
    TextInput,
    {
      value: changeNote,
      onChange: (e) => setChangeNote(e.target.value),
      placeholder: archiveArtwork ? "Describe what changed in this revision… (optional)" : "Describe the screenshot update… (optional)",
      size: "sm"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex justify-end" }, /* @__PURE__ */ React.createElement(
    Button$1,
    {
      variant: "accent",
      size: "sm",
      loading: archiveRevisionSaving,
      onClick: handleArchiveRevisionSubmit
    },
    archiveRevisionSaving ? "Saving revision…" : "Save revision"
  )))), activeTab === "evolution" && /* @__PURE__ */ React.createElement(Section, { id: "evolution", className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-code-branch" }, "Artwork Evolution"), /* @__PURE__ */ React.createElement("p", { className: "-mt-2 text-sm text-slate-400" }, "Connect this piece to an older public original so the artwork page can tell a clear Then & Now story in both directions.")), /* @__PURE__ */ React.createElement("div", { className: `inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] ${evolutionTarget ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-300"}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sparkles text-[10px]", "aria-hidden": "true" }), evolutionTarget ? selectedEvolutionType?.short_label || "Linked" : "No original linked")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(320px,0.8fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(
    ArtworkEvolutionSearchPicker,
    {
      artworkId: artwork?.id,
      selected: evolutionTarget,
      onSelect: (option) => setEvolutionTarget(option),
      disabled: saving
    }
  ), errors.evolution_target_artwork_id?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "text-sm text-red-400" }, errors.evolution_target_artwork_id[0]) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement(RightRailCard, { title: "Relation settings" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Story type"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: evolutionRelationType,
      onChange: (value) => setEvolutionRelationType(value),
      disabled: saving || !evolutionTarget,
      className: "mt-2",
      options: evolutionRelationTypes.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), errors.evolution_relation_type?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "text-sm text-red-400" }, errors.evolution_relation_type[0]) : null, /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Creator note"), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: evolutionNote,
      onChange: (event) => setEvolutionNote(event.target.value),
      placeholder: "Optional context for viewers: what changed, what you learned, why this version matters...",
      disabled: saving || !evolutionTarget,
      rows: 6,
      className: "mt-2 w-full rounded-[24px] border border-white/10 bg-[#0d1726] px-4 py-3 text-sm leading-6 text-white outline-none transition focus:border-sky-300/35 disabled:cursor-not-allowed disabled:opacity-60"
    }
  )), errors.evolution_note?.[0] ? /* @__PURE__ */ React.createElement("p", { className: "text-sm text-red-400" }, errors.evolution_note[0]) : null)), /* @__PURE__ */ React.createElement(RightRailCard, { title: "Public behavior" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("p", null, "The newer artwork gets the main comparison panel. The older artwork gets an updated-version card pointing back here."), /* @__PURE__ */ React.createElement("p", null, "Only published public artworks can be linked, and the original has to be older than the piece you are editing."), /* @__PURE__ */ React.createElement("p", null, evolutionTarget ? `Current target: ${evolutionTarget.title}` : "Pick an older artwork first to unlock relation type and note settings.")))))), activeTab === "ai" && /* @__PURE__ */ React.createElement(Section, { id: "ai-assist", className: "space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-wand-magic-sparkles" }, "AI Assist"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Review-only suggestions built from the current artwork image. Nothing is written to the artwork until you apply it.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 self-start" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold ${statusTone$2(aiStatus)}` }, /* @__PURE__ */ React.createElement("span", { className: `h-2 w-2 rounded-full ${aiStatus === "ready" ? "bg-emerald-300" : aiStatus === "failed" ? "bg-red-300" : aiStatus === "queued" || aiStatus === "processing" ? "bg-sky-300" : "bg-slate-400"}` }), /* @__PURE__ */ React.createElement("span", null, statusLabel(aiStatus))), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: toggleAiPanel,
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-slate-300 transition hover:bg-white/[0.08] hover:text-white"
    },
    /* @__PURE__ */ React.createElement("span", null, isAiPanelOpen ? "Collapse" : "Expand")
  ))), isAiPanelOpen && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Button$1, { variant: "secondary", size: "xs", onClick: () => requestAiIntent("analyze", "analyze"), loading: aiAction === "analyze" }, aiDirect ? "Analyze now" : "Analyze artwork"), /* @__PURE__ */ React.createElement(Button$1, { variant: "secondary", size: "xs", onClick: handleImproveAll }, "Improve all"), /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "xs", onClick: () => requestAiIntent("title") }, "Generate title"), /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "xs", onClick: () => requestAiIntent("description") }, "Generate description"), /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "xs", onClick: () => requestAiIntent("tags") }, "Suggest tags"), /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "xs", onClick: () => requestAiIntent("category") }, "Suggest category"), /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "xs", onClick: () => requestAiIntent("similar") }, "Find similar"), /* @__PURE__ */ React.createElement(Button$1, { variant: "ghost", size: "xs", onClick: () => requestAiIntent("analyze", "regenerate"), loading: aiAction === "regenerate" }, "Refresh suggestions")), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement(
    Toggle,
    {
      checked: aiDirect,
      onChange: (event) => setAiDirect(event.target.checked),
      label: "Run AI directly",
      hint: "Optional. When enabled, AI analysis runs inline and returns suggestions immediately instead of going through the queue.",
      size: "sm",
      variant: "sky",
      disabled: aiAction !== ""
    }
  )), aiLoading && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "h-4 w-4 rounded-full border-2 border-sky-400/20 border-t-sky-300 animate-spin" }), /* @__PURE__ */ React.createElement("span", null, "Loading AI assist data…")), aiData?.error_message && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-red-400/20 bg-red-400/10 px-4 py-3 text-sm text-red-100" }, aiData.error_message), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Title suggestions"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => requestAiIntent("title", "regenerate"), className: "text-xs text-slate-400 transition hover:text-white" }, "Regenerate")), (aiData?.title_suggestions || []).length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "Analyze the artwork to generate title ideas."), (aiData?.title_suggestions || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.text, className: "rounded-xl border border-white/10 bg-white/[0.04] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-medium text-white" }, item.text), typeof item.confidence === "number" && /* @__PURE__ */ React.createElement("div", { className: "text-[11px] text-slate-500" }, "Confidence ", Math.round(item.confidence * 100), "%")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap justify-end gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyTitleSuggestion(item.text, "replace"), className: "text-xs text-sky-200 transition hover:text-white" }, "Replace"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyTitleSuggestion(item.text, "insert"), className: "text-xs text-slate-300 transition hover:text-white" }, "Insert"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => copyText(item.text), className: "text-xs text-slate-400 transition hover:text-white" }, "Copy")))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Description suggestions"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => requestAiIntent("description", "regenerate"), className: "text-xs text-slate-400 transition hover:text-white" }, "Regenerate")), (aiData?.description_suggestions || []).length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "AI descriptions appear here after analysis."), (aiData?.description_suggestions || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.variant}-${item.text}`, className: "rounded-xl border border-white/10 bg-white/[0.04] p-3 space-y-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, item.variant), typeof item.confidence === "number" && /* @__PURE__ */ React.createElement("div", { className: "text-[11px] text-slate-500" }, Math.round(item.confidence * 100), "%")), /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-200" }, item.text), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyDescriptionSuggestion(item.text, "replace"), className: "text-xs text-sky-200 transition hover:text-white" }, "Replace"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyDescriptionSuggestion(item.text, "append"), className: "text-xs text-slate-300 transition hover:text-white" }, "Append"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => copyText(item.text), className: "text-xs text-slate-400 transition hover:text-white" }, "Copy"))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Tag suggestions"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => requestAiIntent("tags", "regenerate"), className: "text-xs text-slate-400 transition hover:text-white" }, "Regenerate")), (aiData?.tag_suggestions || []).length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "Suggested tags, confidence, and quick-apply actions appear here."), (aiData?.tag_suggestions || []).length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (aiData?.tag_suggestions || []).map((item) => {
    const isApplied = tagSlugs.includes(item.tag);
    const isSelected = selectedAiTags.includes(item.tag);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: item.tag,
        type: "button",
        onClick: () => toggleSuggestedTag(item.tag),
        className: `rounded-full border px-3 py-1 text-xs font-semibold transition ${isSelected ? "border-emerald-400/30 bg-emerald-400/10 text-emerald-200" : isApplied ? "border-white/20 bg-white/[0.08] text-white" : "border-sky-400/20 bg-sky-400/10 text-sky-200 hover:bg-sky-400/15"}`
      },
      isSelected ? "✓" : isApplied ? "•" : "+",
      " ",
      item.tag,
      typeof item.confidence === "number" && /* @__PURE__ */ React.createElement("span", { className: "ml-1 text-[10px] text-white/60" }, Math.round(item.confidence * 100), "%")
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyTagSuggestions(selectedAiTags, "add"), className: "text-xs text-sky-200 transition hover:text-white" }, "Add selected"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyTagSuggestions(aiSuggestedTags, "add"), className: "text-xs text-slate-300 transition hover:text-white" }, "Add all"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyTagSuggestions(aiSuggestedTags, "remove"), className: "text-xs text-slate-400 transition hover:text-white" }, "Remove suggested")))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Category suggestions"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => requestAiIntent("category", "regenerate"), className: "text-xs text-slate-400 transition hover:text-white" }, "Regenerate")), !aiData?.content_type && !aiData?.category && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "AI content-type and category candidates appear here after analysis."), aiData?.content_type && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Suggested content type"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white" }, aiData.content_type.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyCategorySuggestion(aiData.category || { content_type_id: aiData.content_type.id }, "content_type"), className: "text-xs text-sky-200 transition hover:text-white" }, "Apply content type"))), aiData?.category && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] p-3 space-y-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Suggested category"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white" }, aiData.category.label)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyCategorySuggestion(aiData.category, "category"), className: "text-xs text-sky-200 transition hover:text-white" }, "Apply category"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyCategorySuggestion(aiData.category, "both"), className: "text-xs text-slate-300 transition hover:text-white" }, "Apply both")), (aiData.category.alternatives || []).length > 0 && /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, aiData.category.alternatives.map((item) => /* @__PURE__ */ React.createElement("button", { key: item.id, type: "button", onClick: () => applyCategorySuggestion(item, "both"), className: "rounded-full border border-white/10 bg-white/[0.03] px-3 py-1 text-xs text-slate-300 transition hover:text-white" }, item.label)))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Similar / duplicate candidates"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => requestAiIntent("similar", "regenerate"), className: "text-xs text-slate-400 transition hover:text-white" }, "Refresh")), (aiData?.similar_candidates || []).length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "Possible duplicates or visually similar artworks will appear here."), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, (aiData?.similar_candidates || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.artwork_id, className: "rounded-xl border border-white/10 bg-white/[0.04] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden rounded-lg bg-white/5" }, item.thumbnail_url ? /* @__PURE__ */ React.createElement("img", { src: item.thumbnail_url, alt: item.title || "Similar artwork", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-xs text-slate-500" }, "No preview")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-medium text-white" }, item.title || `Artwork #${item.artwork_id}`), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] text-slate-500" }, "#", item.artwork_id, " · ", item.match_type, " · ", typeof item.score === "number" ? `${Math.round(item.score * 100)}%` : "n/a"), item.owner && /* @__PURE__ */ React.createElement("div", { className: "text-[11px] text-slate-500" }, item.owner), item.review_state && /* @__PURE__ */ React.createElement("div", { className: "text-[11px] text-emerald-300 uppercase tracking-[0.18em]" }, item.review_state)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, item.url && /* @__PURE__ */ React.createElement("a", { href: item.url, target: "_blank", rel: "noreferrer", onClick: () => trackAiEvent("duplicate_candidate_viewed", { candidate_artwork_id: item.artwork_id, match_type: item.match_type }), className: "text-xs text-sky-200 transition hover:text-white" }, "Open"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => persistAiAction({ similar_actions: [{ artwork_id: item.artwork_id, state: "ignored" }] }), className: "text-xs text-slate-300 transition hover:text-white" }, "Ignore"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => persistAiAction({ similar_actions: [{ artwork_id: item.artwork_id, state: "reviewed" }] }), className: "text-xs text-slate-400 transition hover:text-white" }, "Mark as reviewed")))))))), activeTab === "tags" && /* @__PURE__ */ React.createElement(Section, { id: "tags", className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-tags" }, "Tags"), /* @__PURE__ */ React.createElement(InlineAiButton, { onClick: () => requestAiIntent("tags"), disabled: aiAction !== "", loading: aiAction === "analyze" || aiAction === "regenerate" }, "Tags")), /* @__PURE__ */ React.createElement(
    TagPicker,
    {
      value: tagSlugs,
      onChange: handleTagChange,
      suggestedTags: aiSuggestedTags,
      searchEndpoint: "/api/studio/tags/search",
      popularEndpoint: "/api/studio/tags/search",
      error: errors.tags?.[0]
    }
  )), activeTab === "worlds" && /* @__PURE__ */ React.createElement(
    WorldSubmissionSelector,
    {
      title: "Add to Worlds",
      description: "Attach this artwork to active worlds for creator participation. These remain separate from moderator-curated world relations and keep their own review state.",
      options: worldSubmissionOptions,
      emptyMessage: "No worlds are currently open for creator participation, and this artwork has no existing world history yet.",
      onToggle: (worldId) => setWorldSubmissionOptions((current) => current.map((world) => Number(world.id) === Number(worldId) && !world.selection_locked ? { ...world, selected: !world.selected } : world)),
      onNoteChange: (worldId, note) => setWorldSubmissionOptions((current) => current.map((world) => Number(world.id) === Number(worldId) ? { ...world, note } : world)),
      analyticsContext: { sourceSurface: "navigation", sourceDetail: "studio_artwork_edit" }
    }
  ), activeTab === "visibility" && /* @__PURE__ */ React.createElement(Section, { id: "visibility", className: "space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-1" }, /* @__PURE__ */ React.createElement(SectionTitle, { icon: "fa-solid fa-eye" }, "Visibility"), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 -mt-2" }, "Match the same publish options used during upload, including unlisted access and scheduled publishing.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, [
    { value: "public", label: "Public", hint: "Visible to everyone" },
    { value: "unlisted", label: "Unlisted", hint: "Available by direct link" },
    { value: "private", label: "Private", hint: "Keep as draft visibility" }
  ].map((option) => {
    const active = visibility === option.value;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => setVisibility(option.value),
        className: [
          "flex items-start justify-between gap-3 rounded-2xl border px-4 py-4 text-left transition",
          active ? "border-sky-300/30 bg-sky-400/10 text-white" : "border-white/10 bg-white/[0.03] text-white/75 hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-white/50" }, option.hint)),
      /* @__PURE__ */ React.createElement("span", { className: [
        "mt-0.5 inline-flex h-5 w-5 items-center justify-center rounded-full border text-[10px]",
        active ? "border-sky-300/40 bg-sky-400/20 text-sky-100" : "border-white/10 bg-white/5 text-white/35"
      ].join(" ") }, active ? "✓" : "")
    );
  })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement(
    SchedulePublishPicker,
    {
      mode: publishMode,
      scheduledAt,
      timezone: userTimezone,
      onModeChange: setPublishMode,
      onScheduleAt: setScheduledAt,
      disabled: saving
    }
  ), errors.publish_at?.[0] && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-red-400" }, errors.publish_at[0]), errors.visibility?.[0] && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-red-400" }, errors.visibility[0]), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-slate-500" }, publishMode === "schedule" ? "Scheduled artworks stay hidden until the selected time." : visibility === "private" ? "Private keeps the artwork hidden from public views." : visibility === "unlisted" ? "Unlisted keeps the artwork accessible but not broadly surfaced." : "Public makes the artwork visible immediately."))))), /* @__PURE__ */ React.createElement(
    Modal,
    {
      open: showHistory,
      onClose: () => setShowHistory(false),
      title: "Version History",
      size: "lg",
      footer: /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mr-auto" }, "Restoring creates a new version — nothing is deleted.")
    },
    historyLoading && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-12" }, /* @__PURE__ */ React.createElement("div", { className: "w-6 h-6 border-2 border-accent/30 border-t-accent rounded-full animate-spin" })),
    !historyLoading && historyData && /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, historyData.versions.map((v2) => /* @__PURE__ */ React.createElement(
      "div",
      {
        key: v2.id,
        className: [
          "rounded-xl border p-4 transition-all",
          v2.is_current ? "border-accent/40 bg-accent/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-1" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold text-white" }, "v", v2.version_number), v2.is_current && /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-accent/20 text-accent border border-accent/30" }, "Current")), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-400" }, v2.created_at ? new Date(v2.created_at).toLocaleString() : ""), v2.width && /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-400" }, v2.width, " × ", v2.height, " px · ", formatBytes$1(v2.file_size)), v2.change_note && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-300 mt-1 italic" }, "“", v2.change_note, "”")), !v2.is_current && /* @__PURE__ */ React.createElement(
        Button$1,
        {
          variant: "ghost",
          size: "xs",
          loading: restoring === v2.id,
          onClick: () => handleRestoreVersion(v2.id)
        },
        "Restore"
      ))
    )), historyData.versions.length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 text-center py-8" }, "No version history yet."))
  ));
}
const __vite_glob_0_109 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioArtworkEdit
}, Symbol.toStringTag, { value: "Module" }));
function SummaryCard$3({ label, value, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm" }, label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(value || 0).toLocaleString()));
}
function StudioArtworks() {
  const { props } = X$1();
  const summary = props.summary || {};
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-4" }, /* @__PURE__ */ React.createElement(SummaryCard$3, { label: "Artworks", value: summary.count, icon: "fa-solid fa-images" }), /* @__PURE__ */ React.createElement(SummaryCard$3, { label: "Drafts", value: summary.draft_count, icon: "fa-solid fa-file-pen" }), /* @__PURE__ */ React.createElement(SummaryCard$3, { label: "Published", value: summary.published_count, icon: "fa-solid fa-rocket" }), /* @__PURE__ */ React.createElement("a", { href: "/upload", className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Upload artwork"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6" }, "Start a new visual upload flow without leaving Creator Studio."))), /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      hideModuleFilter: true,
      defaultSort: "published_desc",
      sortStorageKey: "studio-artworks-sort"
    }
  ));
}
const __vite_glob_0_110 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioArtworks
}, Symbol.toStringTag, { value: "Module" }));
function formatDate$5(value) {
  if (!value) return "Unknown";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unknown";
  return date.toLocaleDateString(void 0, { month: "short", day: "numeric", year: "numeric" });
}
function StudioAssets() {
  const { props } = X$1();
  const assets = props.assets || {};
  const items = assets.items || [];
  const summary = assets.summary || [];
  const highlights = assets.highlights || {};
  const filters = assets.filters || {};
  const meta = assets.meta || {};
  const typeOptions = assets.type_options || [];
  const sourceOptions = assets.source_options || [];
  const sortOptions = assets.sort_options || [];
  const trackReuse = (asset, destination) => {
    trackStudioEvent("studio_asset_reused", {
      surface: studioSurface(),
      module: "assets",
      item_module: asset.source_key || "assets",
      item_id: asset.numeric_id,
      meta: {
        asset_id: asset.id,
        asset_type: asset.type,
        destination
      }
    });
  };
  const updateFilters = (patch2) => {
    const next = {
      ...filters,
      ...patch2
    };
    if (patch2.page == null) {
      next.page = 1;
    }
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: "assets",
      meta: patch2
    });
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),radial-gradient(circle_at_bottom_right,_rgba(34,197,94,0.12),_transparent_40%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 shadow-[0_22px_60px_rgba(2,6,23,0.28)] lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 xl:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Search assets"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: filters.q || "",
      onChange: (event) => updateFilters({ q: event.target.value }),
      placeholder: "Title, source, or description",
      className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.type || "all",
      onChange: (value) => updateFilters({ type: value }),
      options: typeOptions.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Source"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.source || "all",
      onChange: (value) => updateFilters({ source: value }),
      options: sourceOptions.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Sort"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.sort || "recent",
      onChange: (value) => updateFilters({ sort: value }),
      options: sortOptions.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Library volume"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(meta.total || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "creator assets available")))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-5" }, summary.map((item) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: item.key,
      type: "button",
      onClick: () => updateFilters({ type: item.key }),
      className: `rounded-[24px] border p-5 text-left transition ${filters.type === item.key ? "border-sky-300/25 bg-sky-300/10" : "border-white/10 bg-white/[0.03] hover:border-white/20"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium" }, item.label)), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, Number(item.count || 0).toLocaleString()))
  ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Showing ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, items.length), " of ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(meta.total || 0).toLocaleString()), " assets"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => updateFilters({ type: "all", source: "all", sort: "recent", q: "" }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-slate-200"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left" }),
    "Reset filters"
  )), items.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mt-6 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, items.map((asset) => /* @__PURE__ */ React.createElement("article", { key: asset.id, className: "overflow-hidden rounded-[26px] border border-white/10 bg-white/[0.03] shadow-[0_18px_50px_rgba(3,7,18,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[1.15/1] overflow-hidden bg-slate-950/70" }, asset.image_url ? /* @__PURE__ */ React.createElement("img", { src: asset.image_url, alt: asset.title, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-photo-film text-2xl" })), /* @__PURE__ */ React.createElement("div", { className: "absolute left-4 top-4 inline-flex items-center gap-2 rounded-full border border-black/10 bg-black/45 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white backdrop-blur-md" }, /* @__PURE__ */ React.createElement("span", null, asset.type_label))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 p-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, asset.source_label), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 truncate text-lg font-semibold text-white" }, asset.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 line-clamp-2 text-sm leading-6 text-slate-400" }, asset.description)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-4 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Used ", Number(asset.usage_count || 0).toLocaleString(), " times"), /* @__PURE__ */ React.createElement("span", null, "Updated ", formatDate$5(asset.created_at))), (asset.usage_references || []).length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-xs text-slate-400" }, (asset.usage_references || []).slice(0, 2).map((reference) => /* @__PURE__ */ React.createElement("a", { key: `${asset.id}-${reference.href}`, href: reference.href, className: "rounded-full border border-white/10 px-2.5 py-1 transition hover:border-white/20 hover:text-white" }, reference.label))) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: asset.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square" }), "Manage"), /* @__PURE__ */ React.createElement("a", { href: asset.view_url, onClick: () => trackReuse(asset, asset.view_url), className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-repeat" }), "Reuse")))))) : /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[28px] border border-dashed border-white/15 bg-white/[0.02] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, "No assets match this view"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm text-slate-400" }, "Try another asset type or a broader search term. This library includes card backgrounds, story covers, collection covers, artwork previews, and profile branding."))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent uploads"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (highlights.recent_uploads || []).slice(0, 5).map((asset) => /* @__PURE__ */ React.createElement("a", { key: `${asset.id}-recent`, href: asset.manage_url, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 p-3" }, asset.image_url ? /* @__PURE__ */ React.createElement("img", { src: asset.image_url, alt: asset.title, className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-white/5 text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-photo-film" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, asset.title), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, asset.type_label)))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Most reused"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (highlights.most_used || []).slice(0, 5).map((asset) => /* @__PURE__ */ React.createElement("a", { key: `${asset.id}-used`, href: asset.manage_url, className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-black/20 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, asset.title), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, asset.source_label)), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, Number(asset.usage_count || 0).toLocaleString()))))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: (meta.current_page || 1) <= 1,
      onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }),
    "Previous"
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.2em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: (meta.current_page || 1) >= (meta.last_page || 1),
      onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40"
    },
    "Next",
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })
  ))));
}
const __vite_glob_0_111 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioAssets
}, Symbol.toStringTag, { value: "Module" }));
function formatScheduledDate(value, options = {}) {
  if (!value) return "Not scheduled";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Not scheduled";
  try {
    return date.toLocaleString(void 0, {
      month: "short",
      day: "numeric",
      ...options.includeYear === false ? {} : { year: "numeric" },
      hour: "numeric",
      minute: "2-digit",
      ...options.timeZone ? { timeZone: options.timeZone } : {}
    });
  } catch {
    return date.toLocaleString();
  }
}
function formatReleaseCountdown(value, nowMs = Date.now()) {
  if (!value) return "Not scheduled";
  const releaseDate = new Date(value);
  if (Number.isNaN(releaseDate.getTime())) return "Not scheduled";
  const remainingMs = releaseDate.getTime() - nowMs;
  if (remainingMs <= 0) {
    return "Releasing now";
  }
  const totalSeconds = Math.floor(remainingMs / 1e3);
  const days = Math.floor(totalSeconds / 86400);
  const hours = Math.floor(totalSeconds % 86400 / 3600);
  const minutes = Math.floor(totalSeconds % 3600 / 60);
  const seconds = totalSeconds % 60;
  const parts = [];
  if (days > 0) parts.push(`${days}d`);
  if (days > 0 || hours > 0) parts.push(`${hours}h`);
  if (days > 0 || hours > 0 || minutes > 0) parts.push(`${minutes}m`);
  if (days === 0) parts.push(`${seconds}s`);
  return `In ${parts.join(" ")}`;
}
function parseFocusDate(value) {
  if (!value) return /* @__PURE__ */ new Date();
  const parsed = /* @__PURE__ */ new Date(`${value}T12:00:00`);
  return Number.isNaN(parsed.getTime()) ? /* @__PURE__ */ new Date() : parsed;
}
function toFocusDateValue(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
function shiftFocusDate(value, view, direction) {
  const next = new Date(parseFocusDate(value));
  if (view === "week") {
    next.setDate(next.getDate() + direction * 7);
    return toFocusDateValue(next);
  }
  const originalDay = next.getDate();
  next.setDate(1);
  next.setMonth(next.getMonth() + direction);
  const lastDayOfMonth = new Date(next.getFullYear(), next.getMonth() + 1, 0).getDate();
  next.setDate(Math.min(originalDay, lastDayOfMonth));
  return toFocusDateValue(next);
}
function itemHref(item) {
  return item.edit_url || item.manage_url || item.preview_url || item.view_url || "#";
}
function CalendarThumb({ item, className = "h-full w-full", showTime = false }) {
  return /* @__PURE__ */ React.createElement("a", { href: itemHref(item), className: `group relative block overflow-hidden rounded-2xl border border-white/10 bg-slate-950/80 ${className}` }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title || "", className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center bg-[linear-gradient(135deg,rgba(14,165,233,0.2),rgba(15,23,42,0.95))] text-[10px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, item.module_label || "Item"), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-slate-950 via-slate-950/70 to-transparent p-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-[11px] font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex items-center justify-between gap-2 text-[10px] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.module_label), showTime && item.scheduled_at ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 text-sky-200" }, formatScheduledDate(item.scheduled_at)) : null)));
}
function CalendarInlineItem({ item, showTime = true }) {
  return /* @__PURE__ */ React.createElement("a", { href: itemHref(item), className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 p-2.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-11 w-11 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-slate-950/80" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title || "", className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center bg-[linear-gradient(135deg,rgba(14,165,233,0.2),rgba(15,23,42,0.95))] text-[9px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, String(item.module_label || "Item").slice(0, 3))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex items-center gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.module_label), showTime && item.scheduled_at ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 text-sky-200" }, formatScheduledDate(item.scheduled_at)) : null)));
}
function CalendarDayModal({ day, busyKey, endpoints, onAction, onClose, nowMs }) {
  if (!day) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-50 flex items-end justify-center bg-slate-950/70 p-3 backdrop-blur-sm md:items-center md:p-6", role: "dialog", "aria-modal": "true", "aria-label": `Scheduled items for ${day.label || day.date}` }, /* @__PURE__ */ React.createElement("button", { type: "button", "aria-label": "Close day details", className: "absolute inset-0 cursor-default", onClick: onClose }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 flex max-h-[90vh] w-full max-w-3xl flex-col overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_30%),linear-gradient(180deg,_rgba(15,23,42,0.98),_rgba(2,6,23,0.98))] shadow-2xl shadow-black/40" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4 border-b border-white/10 px-5 py-4 md:px-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Day queue"), /* @__PURE__ */ React.createElement("h3", { className: "mt-1 text-xl font-semibold text-white" }, day.label || day.date), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, Number(day.count || 0).toLocaleString(), " scheduled item", Number(day.count || 0) === 1 ? "" : "s")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Close")), /* @__PURE__ */ React.createElement("div", { className: "overflow-y-auto px-5 py-4 md:px-6 md:py-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, (day.detail_items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("a", { href: itemHref(item), className: "group block" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-36 overflow-hidden border-b border-white/10 bg-slate-950/80" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title || "", className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.03]", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center bg-[linear-gradient(135deg,rgba(14,165,233,0.2),rgba(15,23,42,0.95))] text-sm font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, item.module_label || "Item"), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-slate-950 via-slate-950/75 to-transparent p-3" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-center justify-between gap-2 text-[11px] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.module_label), item.scheduled_at ? /* @__PURE__ */ React.createElement("span", { className: "shrink-0 text-sky-200" }, formatScheduledDate(item.scheduled_at)) : null)))), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-medium text-sky-200" }, formatReleaseCountdown(item.scheduled_at, nowMs)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.subtitle || item.workflow?.readiness?.label || "Scheduled item"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyKey === `publish:${item.id}`, onClick: () => onAction(endpoints.publishNowPattern, item, "publish"), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs text-sky-100 disabled:opacity-50" }, "Publish now"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyKey === `unschedule:${item.id}`, onClick: () => onAction(endpoints.unschedulePattern, item, "unschedule"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200 disabled:opacity-50" }, "Unschedule"), /* @__PURE__ */ React.createElement("a", { href: itemHref(item), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/5" }, "Open")))))))));
}
function CalendarMonthDay({ day, onOpenDetail }) {
  const items = day.items || [];
  const overflowCount = Number(day.overflow_count || Math.max(0, Number(day.count || 0) - items.length));
  const hasItems = items.length > 0;
  return /* @__PURE__ */ React.createElement(
    "div",
    {
      className: `min-h-[156px] rounded-[22px] border p-3 ${day.is_current_month ? "border-white/10 bg-black/20" : "border-white/5 bg-black/10"}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `text-sm font-semibold ${day.is_current_month ? "text-white" : "text-slate-500"}` }, day.day), hasItems ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onOpenDetail(day), className: "rounded-full border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-300 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, day.count) : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, day.count)),
    hasItems ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, items.length === 1 ? /* @__PURE__ */ React.createElement(CalendarThumb, { item: items[0], className: "h-[92px]" }) : /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-2" }, items.map((item) => /* @__PURE__ */ React.createElement(CalendarThumb, { key: item.id, item, className: "h-[58px]" }))), overflowCount > 0 ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onOpenDetail(day), className: "w-full rounded-xl border border-dashed border-white/10 px-2.5 py-1.5 text-left text-[11px] font-medium text-slate-300 transition hover:border-sky-300/20 hover:bg-sky-300/5 hover:text-sky-100" }, "+", overflowCount, " more scheduled") : null) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-dashed border-white/10 px-3 py-6 text-center text-[11px] uppercase tracking-[0.18em] text-slate-600" }, "Quiet day")
  );
}
async function requestJson$6(url, method = "POST") {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) throw new Error(payload?.message || "Request failed");
  return payload;
}
function StudioCalendar() {
  const { props } = X$1();
  const calendar = props.calendar || {};
  const filters = calendar.filters || {};
  const summary = calendar.summary || {};
  const currentView = filters.view || "month";
  const [busyKey, setBusyKey] = reactExports.useState(null);
  const [nowMs, setNowMs] = reactExports.useState(() => Date.now());
  const [selectedDay, setSelectedDay] = reactExports.useState(null);
  const updateFilters = (patch2) => {
    setSelectedDay(null);
    const next = { ...filters, ...patch2 };
    trackStudioEvent("studio_scheduled_opened", {
      surface: studioSurface(),
      module: next.module,
      meta: patch2
    });
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  const shiftCalendar = (direction) => {
    updateFilters({ focus_date: shiftFocusDate(filters.focus_date, currentView, direction) });
  };
  const resetCalendarFocus = () => {
    updateFilters({ focus_date: toFocusDateValue(/* @__PURE__ */ new Date()) });
  };
  const runAction = async (pattern, item, key) => {
    const url = String(pattern || "").replace("__MODULE__", item.module).replace("__ID__", String(item.numeric_id));
    setBusyKey(`${key}:${item.id}`);
    try {
      await requestJson$6(url);
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to update schedule.");
    } finally {
      setBusyKey(null);
    }
  };
  reactExports.useEffect(() => {
    const hasTimedEntries = Boolean(summary.next_publish_at) || (calendar.scheduled_items || []).some((item) => Boolean(item.scheduled_at));
    if (!hasTimedEntries) return void 0;
    const timer = window.setInterval(() => {
      setNowMs(Date.now());
    }, 1e3);
    return () => window.clearInterval(timer);
  }, [calendar.scheduled_items, summary.next_publish_at]);
  reactExports.useEffect(() => {
    if (!selectedDay?.date) return;
    const nextSelectedDay = (calendar.month?.days || []).find((day) => day.date === selectedDay.date) || null;
    setSelectedDay(nextSelectedDay);
  }, [calendar.month?.days, selectedDay?.date]);
  reactExports.useEffect(() => {
    if (!selectedDay) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        setSelectedDay(null);
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [selectedDay]);
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Scheduled"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.scheduled_total || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Unscheduled"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.unscheduled_total || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Overloaded days"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.overloaded_days || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Next publish"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, formatReleaseCountdown(summary.next_publish_at, nowMs)), summary.next_publish_at && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, formatScheduledDate(summary.next_publish_at)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 xl:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search planning queue"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Title or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "View"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.view || "month", onChange: (val) => updateFilters({ view: val }), options: calendar.view_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: calendar.module_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Queue"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.status || "scheduled", onChange: (val) => updateFilters({ status: val }), options: calendar.status_options || [], searchable: false })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, filters.view === "week" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, calendar.week?.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Week planning")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(-1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Prev week"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetCalendarFocus, className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Today"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Next week"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-7" }, (calendar.week?.days || []).map((day) => /* @__PURE__ */ React.createElement("div", { key: day.date, className: "rounded-[22px] border border-white/10 bg-black/20 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, day.label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, day.items.length > 0 ? day.items.map((item) => /* @__PURE__ */ React.createElement(CalendarInlineItem, { key: item.id, item })) : /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "No scheduled items")))))) : filters.view === "agenda" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Agenda"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, (calendar.agenda || []).map((group) => /* @__PURE__ */ React.createElement("div", { key: group.date, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, group.count, " items")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, group.items.map((item) => /* @__PURE__ */ React.createElement(CalendarInlineItem, { key: item.id, item }))))))) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, calendar.month?.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Month planning")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(-1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Prev month"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetCalendarFocus, className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Today"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Next month"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-7 gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((label) => /* @__PURE__ */ React.createElement("div", { key: label, className: "px-2 py-1" }, label))), /* @__PURE__ */ React.createElement("div", { className: "mt-2 grid grid-cols-7 gap-2" }, (calendar.month?.days || []).map((day) => /* @__PURE__ */ React.createElement(CalendarMonthDay, { key: day.date, day, onOpenDetail: setSelectedDay }))))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Coverage gaps"), /* @__PURE__ */ React.createElement("a", { href: "/studio/drafts", className: "text-sm font-medium text-sky-100" }, "Open drafts")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (calendar.gaps || []).length > 0 ? (calendar.gaps || []).map((gap) => /* @__PURE__ */ React.createElement("div", { key: gap.date, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, gap.label)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/15 px-4 py-8 text-sm text-slate-500" }, "No empty days in the next two weeks."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Unscheduled queue"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, (calendar.unscheduled_items || []).length)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (calendar.unscheduled_items || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label, " · ", item.workflow?.readiness?.label || "Needs review"))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Upcoming actions"), /* @__PURE__ */ React.createElement("a", { href: "/studio/scheduled", className: "text-sm font-medium text-sky-100" }, "Open list")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (calendar.scheduled_items || []).slice(0, 5).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs font-medium text-sky-200" }, formatReleaseCountdown(item.scheduled_at, nowMs)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, formatScheduledDate(item.scheduled_at)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyKey === `publish:${item.id}`, onClick: () => runAction(props.endpoints.publishNowPattern, item, "publish"), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs text-sky-100 disabled:opacity-50" }, "Publish now"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyKey === `unschedule:${item.id}`, onClick: () => runAction(props.endpoints.unschedulePattern, item, "unschedule"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200 disabled:opacity-50" }, "Unschedule")))))))), /* @__PURE__ */ React.createElement(CalendarDayModal, { day: selectedDay, busyKey, endpoints: props.endpoints, onAction: runAction, onClose: () => setSelectedDay(null), nowMs })));
}
const __vite_glob_0_112 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioCalendar
}, Symbol.toStringTag, { value: "Module" }));
const kpiItems = [
  { key: "views", label: "Views", icon: "fa-eye", color: "text-emerald-400" },
  { key: "likes", label: "Likes", icon: "fa-heart", color: "text-pink-400" },
  { key: "saves", label: "Saves", icon: "fa-bookmark", color: "text-amber-400" },
  { key: "remixes", label: "Remixes", icon: "fa-code-branch", color: "text-cyan-400" },
  { key: "comments", label: "Comments", icon: "fa-comment", color: "text-blue-400" },
  { key: "challenge_entries", label: "Challenges", icon: "fa-trophy", color: "text-violet-400" }
];
const secondaryItems = [
  { key: "favorites", label: "Favorites", icon: "fa-star" },
  { key: "shares", label: "Shares", icon: "fa-share-nodes" },
  { key: "downloads", label: "Downloads", icon: "fa-download" }
];
function StudioCardAnalytics() {
  const { props } = X$1();
  const { card, analytics } = props;
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: `Analytics: ${card?.title || "Nova Card"}` }, /* @__PURE__ */ React.createElement(xe, { href: "/studio/cards", className: "mb-6 inline-flex items-center gap-2 text-sm text-slate-400 transition-colors hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }), "Back to Cards"), /* @__PURE__ */ React.createElement("div", { className: "mb-8 flex items-center gap-4 rounded-2xl border border-white/10 bg-nova-900/60 p-4" }, card?.preview_url ? /* @__PURE__ */ React.createElement("img", { src: card.preview_url, alt: card.title, className: "h-20 w-20 rounded-xl object-cover bg-nova-800" }) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-bold text-white" }, card?.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-500" }, "/", card?.slug), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.18em] text-slate-400" }, card?.status, " • ", card?.visibility))), /* @__PURE__ */ React.createElement("div", { className: "mb-8 grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-6" }, kpiItems.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-2xl border border-white/10 bg-nova-900/60 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} ${item.color}` }), /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium uppercase tracking-wider text-slate-400" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-2xl font-bold tabular-nums text-white" }, (analytics?.[item.key] ?? 0).toLocaleString())))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-nova-900/40 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.18em] text-slate-300" }, "Ranking signals"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-400" }, "Trending score"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-bold tabular-nums text-white" }, Number(analytics?.trending_score ?? 0).toFixed(2))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-400" }, "Last engaged"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-white" }, analytics?.last_engaged_at || "No activity yet")))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-nova-900/40 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.18em] text-slate-300" }, "Secondary metrics"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, secondaryItems.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} text-slate-500` }), item.label), /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tabular-nums text-white" }, (analytics?.[item.key] ?? 0).toLocaleString())))))));
}
const __vite_glob_0_113 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioCardAnalytics
}, Symbol.toStringTag, { value: "Module" }));
function NovaCardTemplatePicker({ templates = [], selectedId = null, onSelect }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, templates.map((template) => {
    const active = Number(selectedId) === Number(template.id);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: template.id,
        type: "button",
        onClick: () => onSelect?.(template),
        className: `rounded-[24px] border p-4 text-left transition ${active ? "border-sky-300/35 bg-sky-400/10 text-white" : "border-white/10 bg-white/[0.03] text-slate-200 hover:border-white/20 hover:bg-white/[0.05]"}`
      },
      /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Template"),
      /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold tracking-[-0.03em]" }, template.name),
      template.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, template.description) : null,
      /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, (template.supported_formats || []).map((format) => /* @__PURE__ */ React.createElement("span", { key: `${template.id}-${format}`, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, format)))
    );
  }));
}
function NovaCardGradientPicker({ gradients = [], selectedKey = null, onSelect }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2" }, gradients.map((gradient) => {
    const active = selectedKey === gradient.key;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: gradient.key,
        type: "button",
        onClick: () => onSelect?.(gradient),
        className: `overflow-hidden rounded-[22px] border text-left transition ${active ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}`
      },
      /* @__PURE__ */ React.createElement("div", { className: "h-20 w-full", style: { background: `linear-gradient(135deg, ${gradient.colors?.[0] || "#0f172a"}, ${gradient.colors?.[1] || "#1d4ed8"})` } }),
      /* @__PURE__ */ React.createElement("div", { className: "p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, gradient.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] uppercase tracking-[0.18em] text-slate-400" }, gradient.key))
    );
  }));
}
function NovaCardFontPicker({ fonts = [], selectedKey = null, onSelect }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, fonts.map((font) => {
    const active = selectedKey === font.key;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: font.key,
        type: "button",
        onClick: () => onSelect?.(font),
        className: `rounded-[22px] border p-4 text-left transition ${active ? "border-sky-300/35 bg-sky-400/12 ring-1 ring-sky-400/20 text-white" : "border-white/10 bg-white/[0.03] text-slate-200 hover:border-white/20 hover:bg-white/[0.05]"}`
      },
      /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500 mb-2" }, font.label),
      /* @__PURE__ */ React.createElement("div", { className: "text-[1.65rem] font-semibold leading-tight text-white", style: { fontFamily: font.family, fontWeight: font.weight || 600 } }, "The quick brown fox"),
      /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-400 leading-relaxed", style: { fontFamily: font.family } }, font.recommended_use),
      active && /* @__PURE__ */ React.createElement("div", { className: "mt-2 inline-flex items-center gap-1 rounded-full border border-sky-400/25 bg-sky-500/10 px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.2em] text-sky-300" }, "Active")
    );
  }));
}
const styles = {
  idle: "border-white/10 bg-white/[0.04] text-slate-300",
  saving: "border-sky-300/20 bg-sky-400/10 text-sky-100",
  saved: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
  error: "border-rose-300/20 bg-rose-400/10 text-rose-100"
};
function NovaCardAutosaveIndicator({ status: status2 = "idle", message = "" }) {
  return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] ${styles[status2] || styles.idle}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${status2 === "saving" ? "fa-rotate fa-spin" : status2 === "saved" ? "fa-check" : status2 === "error" ? "fa-triangle-exclamation" : "fa-cloud"}` }), message || (status2 === "saving" ? "Saving" : status2 === "saved" ? "Saved" : status2 === "error" ? "Failed" : "Draft"));
}
const TYPE_LABELS = {
  style: "Style",
  layout: "Layout",
  background: "Background",
  typography: "Typography",
  starter: "Starter"
};
const TYPE_ICONS = {
  style: "fa-palette",
  layout: "fa-table-columns",
  background: "fa-image",
  typography: "fa-font",
  starter: "fa-star"
};
function PresetCard({ preset, onApply, onDelete, applying }) {
  return /* @__PURE__ */ React.createElement("div", { className: "group relative flex items-center gap-3 rounded-[18px] border border-white/10 bg-white/[0.03] px-3.5 py-3 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: applying,
      onClick: () => onApply(preset),
      className: "flex flex-1 items-center gap-3 text-left"
    },
    /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/[0.06] text-sky-300 text-xs" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${TYPE_ICONS[preset.preset_type] || "fa-sparkles"}` })),
    /* @__PURE__ */ React.createElement("span", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block truncate text-sm font-semibold text-white" }, preset.name), /* @__PURE__ */ React.createElement("span", { className: "block text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, TYPE_LABELS[preset.preset_type] || preset.preset_type, preset.is_default ? " · Default" : "")),
    applying ? /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate fa-spin text-sky-300 text-xs" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chevron-right text-slate-500 text-xs opacity-0 transition group-hover:opacity-100" })
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onDelete(preset),
      className: "ml-1 rounded-full p-1.5 text-slate-500 opacity-0 transition hover:text-rose-400 group-hover:opacity-100",
      title: "Delete preset"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash-can text-xs" })
  ));
}
function NovaCardPresetPicker({
  presets = {},
  endpoints = {},
  cardId = null,
  onApplyPatch,
  onPresetsChange,
  activeType = null
}) {
  const [selectedType, setSelectedType] = React.useState(activeType || "style");
  const [applyingId, setApplyingId] = React.useState(null);
  const [capturing, setCapturing] = React.useState(false);
  const [captureName, setCaptureName] = React.useState("");
  const [captureType, setCaptureType] = React.useState("style");
  const [showCaptureForm, setShowCaptureForm] = React.useState(false);
  const [error, setError] = React.useState(null);
  const typeKeys = Object.keys(TYPE_LABELS);
  const listedPresets = Array.isArray(presets[selectedType]) ? presets[selectedType] : [];
  async function handleApply(preset) {
    if (!cardId || !endpoints.presetApplyPattern) return;
    const url = endpoints.presetApplyPattern.replace("__PRESET__", preset.id).replace("__CARD__", cardId);
    setApplyingId(preset.id);
    setError(null);
    try {
      const res = await fetch(url, {
        method: "GET",
        headers: { "X-Requested-With": "XMLHttpRequest", Accept: "application/json" }
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.message || "Failed to apply preset");
      if (data?.project_patch && onApplyPatch) {
        onApplyPatch(data.project_patch);
      }
    } catch (err) {
      setError(err.message || "Failed to apply preset");
    } finally {
      setApplyingId(null);
    }
  }
  async function handleDelete(preset) {
    if (!endpoints.presetDestroyPattern) return;
    const url = endpoints.presetDestroyPattern.replace("__PRESET__", preset.id);
    if (!window.confirm(`Delete preset "${preset.name}"?`)) return;
    try {
      const csrfToken2 = document.querySelector('meta[name="csrf-token"]')?.content || "";
      const res = await fetch(url, {
        method: "DELETE",
        headers: {
          "X-Requested-With": "XMLHttpRequest",
          Accept: "application/json",
          "X-CSRF-TOKEN": csrfToken2
        }
      });
      if (!res.ok) throw new Error("Failed to delete preset");
      onPresetsChange?.();
    } catch (err) {
      setError(err.message || "Failed to delete preset");
    }
  }
  async function handleCapture(e) {
    e.preventDefault();
    if (!cardId || !endpoints.capturePresetPattern || !captureName.trim()) return;
    const url = endpoints.capturePresetPattern.replace("__CARD__", cardId);
    setCapturing(true);
    setError(null);
    try {
      const csrfToken2 = document.querySelector('meta[name="csrf-token"]')?.content || "";
      const res = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest",
          Accept: "application/json",
          "X-CSRF-TOKEN": csrfToken2
        },
        body: JSON.stringify({ name: captureName.trim(), preset_type: captureType })
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data?.message || "Failed to capture preset");
      setCaptureName("");
      setShowCaptureForm(false);
      onPresetsChange?.();
    } catch (err) {
      setError(err.message || "Failed to capture preset");
    } finally {
      setCapturing(false);
    }
  }
  return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, typeKeys.map((type2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: type2,
      type: "button",
      onClick: () => setSelectedType(type2),
      className: `rounded-full border px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] transition ${selectedType === type2 ? "border-sky-300/30 bg-sky-400/15 text-sky-100" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${TYPE_ICONS[type2]} mr-1.5` }),
    TYPE_LABELS[type2],
    Array.isArray(presets[type2]) && presets[type2].length > 0 && /* @__PURE__ */ React.createElement("span", { className: "ml-1.5 rounded-full bg-white/10 px-1.5 text-[10px]" }, presets[type2].length)
  ))), listedPresets.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2" }, listedPresets.map((preset) => /* @__PURE__ */ React.createElement(
    PresetCard,
    {
      key: preset.id,
      preset,
      applying: applyingId === preset.id,
      onApply: handleApply,
      onDelete: handleDelete
    }
  ))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "No ", TYPE_LABELS[selectedType]?.toLowerCase(), " presets saved yet."), cardId && endpoints.capturePresetPattern && /* @__PURE__ */ React.createElement("div", { className: "mt-1 border-t border-white/[0.06] pt-3" }, showCaptureForm ? /* @__PURE__ */ React.createElement("form", { onSubmit: handleCapture, className: "flex flex-col gap-2" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "text",
      value: captureName,
      onChange: (e) => setCaptureName(e.target.value),
      placeholder: "Preset name…",
      maxLength: 64,
      required: true,
      className: "w-full rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white placeholder-slate-500 outline-none focus:border-sky-400/40"
    }
  ), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: captureType,
      onChange: (value) => setCaptureType(value),
      options: typeKeys.map((type2) => ({ value: type2, label: TYPE_LABELS[type2] })),
      searchable: false
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "submit",
      disabled: capturing || !captureName.trim(),
      className: "flex-1 rounded-xl bg-sky-500/20 py-2 text-sm font-semibold text-sky-200 transition hover:bg-sky-500/30 disabled:opacity-50"
    },
    capturing ? "Saving…" : "Save preset"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShowCaptureForm(false),
      className: "rounded-xl border border-white/10 px-4 py-2 text-sm text-slate-400 transition hover:bg-white/[0.05]"
    },
    "Cancel"
  ))) : /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setShowCaptureForm(true),
      className: "flex w-full items-center gap-2 rounded-xl border border-dashed border-white/15 px-3 py-2.5 text-sm text-slate-400 transition hover:border-white/25 hover:text-slate-200"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus text-xs" }),
    "Capture current as preset"
  )), error && /* @__PURE__ */ React.createElement("p", { className: "rounded-xl border border-rose-400/20 bg-rose-400/10 px-3 py-2 text-xs text-rose-300" }, error));
}
const defaultMobileSteps = [
  { key: "format", label: "Format", description: "Choose the canvas shape and basic direction." },
  { key: "background", label: "Template & Background", description: "Pick the visual foundation for the card." },
  { key: "content", label: "Text", description: "Write the quote, author, and source." },
  { key: "style", label: "Style", description: "Fine-tune typography and layout." },
  { key: "preview", label: "Preview", description: "Check the live composition before publish." },
  { key: "publish", label: "Publish", description: "Review metadata and release settings." }
];
const overlayOptions = [
  { value: "none", label: "None" },
  { value: "dark-soft", label: "Dark Soft" },
  { value: "dark-strong", label: "Dark Strong" },
  { value: "light-soft", label: "Light Soft" }
];
const layoutPresetMap = {
  quote_heavy: { alignment: "center", position: "center", padding: "comfortable", max_width: "balanced" },
  author_emphasis: { alignment: "left", position: "lower-middle", padding: "comfortable", max_width: "compact" },
  centered: { alignment: "center", position: "center", padding: "airy", max_width: "compact" },
  minimal: { alignment: "left", position: "upper-middle", padding: "tight", max_width: "wide" }
};
function deepMerge(target, source) {
  if (!source || typeof source !== "object") return target;
  const next = Array.isArray(target) ? [...target] : { ...target || {} };
  Object.entries(source).forEach(([key, value]) => {
    if (Array.isArray(value)) {
      next[key] = value;
      return;
    }
    if (value && typeof value === "object") {
      next[key] = deepMerge(next[key], value);
      return;
    }
    next[key] = value;
  });
  return next;
}
function pillClasses(active) {
  return `rounded-full border px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] transition ${active ? "border-sky-300/30 bg-sky-400/15 text-sky-100" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`;
}
function defaultTextBlocks() {
  return [
    { key: "title", type: "title", text: "Untitled card", enabled: true, style: { role: "eyebrow" } },
    { key: "quote", type: "quote", text: "Your next quote starts here.", enabled: true, style: { role: "headline" } },
    { key: "author", type: "author", text: "", enabled: false, style: { role: "byline" } },
    { key: "source", type: "source", text: "", enabled: false, style: { role: "caption" } }
  ];
}
function truncateText(value, limit = 96) {
  const normalized = String(value || "").trim();
  if (normalized.length <= limit) return normalized;
  return `${normalized.slice(0, limit - 1).trimEnd()}...`;
}
function projectTextValue(project, type2, fallbackKey = null) {
  const blocks = Array.isArray(project?.text_blocks) ? project.text_blocks : [];
  const block = blocks.find((item) => item?.type === type2 && String(item?.text || "").trim() !== "");
  if (block) return String(block.text || "");
  if (!fallbackKey) return "";
  return String(project?.content?.[fallbackKey] || "");
}
function summarizeProjectSnapshot(project) {
  const blocks = Array.isArray(project?.text_blocks) ? project.text_blocks : [];
  const enabledBlocks = blocks.filter((block) => block?.enabled !== false && String(block?.text || "").trim() !== "").length;
  return {
    title: truncateText(projectTextValue(project, "title", "title") || "Untitled card", 64),
    quote: truncateText(projectTextValue(project, "quote", "quote_text"), 88),
    blockCount: blocks.length,
    enabledBlocks,
    layout: String(project?.layout?.layout || "quote_heavy"),
    font: String(project?.typography?.font_preset || "modern-sans"),
    background: String(project?.background?.gradient_preset || project?.background?.solid_color || project?.background?.type || "gradient")
  };
}
function compareProjectSnapshots(currentProject, versionProject) {
  if (!versionProject || typeof versionProject !== "object") {
    return ["Snapshot unavailable"];
  }
  const changes = [];
  const currentSummary = summarizeProjectSnapshot(currentProject);
  const versionSummary = summarizeProjectSnapshot(versionProject);
  if (currentSummary.title !== versionSummary.title) changes.push("Title copy changed");
  if (currentSummary.quote !== versionSummary.quote) changes.push("Quote copy changed");
  if (currentSummary.blockCount !== versionSummary.blockCount) changes.push(`Block count ${versionSummary.blockCount}`);
  if (currentSummary.layout !== versionSummary.layout) changes.push(`Layout ${versionSummary.layout.replace(/_/g, " ")}`);
  if (currentSummary.font !== versionSummary.font) changes.push(`Font ${versionSummary.font.replace(/-/g, " ")}`);
  if (currentSummary.background !== versionSummary.background) changes.push("Background treatment changed");
  return changes.length ? changes.slice(0, 4) : ["Matches current draft"];
}
function normalizeProject(project, options, card = null) {
  const defaultGradient = options.gradient_presets?.[0] || null;
  const defaultFont = options.font_presets?.[0] || null;
  const content2 = project?.content || {};
  const blocks = Array.isArray(project?.text_blocks) && project.text_blocks.length ? project.text_blocks : defaultTextBlocks().map((block) => ({
    ...block,
    text: block.type === "title" ? card?.title || content2.title || block.text : block.type === "quote" ? card?.quote_text || content2.quote_text || block.text : block.type === "author" ? card?.quote_author || content2.quote_author || "" : card?.quote_source || content2.quote_source || "",
    enabled: block.type === "title" || block.type === "quote" ? true : Boolean(block.type === "author" ? card?.quote_author || content2.quote_author : card?.quote_source || content2.quote_source)
  }));
  return {
    schema_version: Number(project?.schema_version || 3),
    meta: project?.meta || { editor: "nova-cards-v3" },
    template: project?.template || { id: card?.template_id || null, slug: card?.template?.slug || null },
    content: {
      title: card?.title || content2.title || "Untitled card",
      quote_text: card?.quote_text || content2.quote_text || "Your next quote starts here.",
      quote_author: card?.quote_author || content2.quote_author || "",
      quote_source: card?.quote_source || content2.quote_source || ""
    },
    text_blocks: blocks,
    layout: {
      layout: project?.layout?.layout || "quote_heavy",
      position: project?.layout?.position || "center",
      alignment: project?.layout?.alignment || "center",
      padding: project?.layout?.padding || "comfortable",
      max_width: project?.layout?.max_width || "balanced"
    },
    typography: {
      font_preset: project?.typography?.font_preset || defaultFont?.key || "modern-sans",
      text_color: project?.typography?.text_color || "#ffffff",
      accent_color: project?.typography?.accent_color || "#e0f2fe",
      quote_size: Number(project?.typography?.quote_size || 72),
      quote_width: project?.typography?.quote_width != null ? Number(project.typography.quote_width) : null,
      author_size: Number(project?.typography?.author_size || 28),
      letter_spacing: Number(project?.typography?.letter_spacing || 0),
      line_height: Number(project?.typography?.line_height || 1.2),
      shadow_preset: project?.typography?.shadow_preset || "soft"
    },
    background: {
      type: project?.background?.type || card?.background_type || "gradient",
      gradient_preset: project?.background?.gradient_preset || defaultGradient?.key || "midnight-nova",
      gradient_colors: project?.background?.gradient_colors || defaultGradient?.colors || ["#0f172a", "#1d4ed8"],
      solid_color: project?.background?.solid_color || "#111827",
      background_image_id: project?.background?.background_image_id || card?.background_image_id || null,
      overlay_style: project?.background?.overlay_style || "dark-soft",
      focal_position: project?.background?.focal_position || "center",
      blur_level: Number(project?.background?.blur_level || 0),
      opacity: Number(project?.background?.opacity || 50)
    },
    canvas: {
      density: project?.canvas?.density || "standard",
      safe_zone: project?.canvas?.safe_zone !== false
    },
    frame: {
      preset: project?.frame?.preset || "none",
      color: project?.frame?.color || null,
      width: Number(project?.frame?.width || 1)
    },
    effects: {
      color_grade: project?.effects?.color_grade || "none",
      effect_preset: project?.effects?.effect_preset || "none",
      intensity: Number(project?.effects?.intensity || 50)
    },
    export_preferences: {
      allow_export: project?.export_preferences?.allow_export !== false,
      default_format: project?.export_preferences?.default_format || "preview"
    },
    source_context: {
      style_family: project?.source_context?.style_family || null,
      palette_family: project?.source_context?.palette_family || null,
      editor_mode: project?.source_context?.editor_mode || card?.editor_mode_last_used || "full"
    },
    decorations: Array.isArray(project?.decorations) ? project.decorations : [],
    assets: {
      pack_ids: Array.isArray(project?.assets?.pack_ids) ? project.assets.pack_ids : [],
      template_pack_ids: Array.isArray(project?.assets?.template_pack_ids) ? project.assets.template_pack_ids : [],
      items: Array.isArray(project?.assets?.items) ? project.assets.items : []
    }
  };
}
function syncTextBlocks(blocks, type2, text2) {
  const list2 = Array.isArray(blocks) ? [...blocks] : defaultTextBlocks();
  const index2 = list2.findIndex((block) => block.type === type2);
  const next = {
    key: type2,
    type: type2,
    text: text2,
    enabled: type2 === "title" || type2 === "quote" ? true : Boolean(String(text2 || "").trim()),
    style: list2[index2]?.style || {}
  };
  if (index2 === -1) {
    list2.push(next);
    return list2;
  }
  list2[index2] = { ...list2[index2], ...next };
  return list2;
}
function normalizeCard(card, options) {
  if (!card) {
    const defaultTemplate = options.templates?.[0] || null;
    const defaultCategory = options.categories?.[0] || null;
    const project = normalizeProject(null, options);
    return {
      id: null,
      title: "Untitled card",
      quote_text: "Your next quote starts here.",
      quote_author: "",
      quote_source: "",
      description: "",
      format: options.formats?.[0]?.key || "square",
      visibility: "private",
      status: "draft",
      moderation_status: "pending",
      allow_download: true,
      background_type: "gradient",
      template_id: defaultTemplate?.id || null,
      category_id: defaultCategory?.id || null,
      background_image_id: null,
      tags: [],
      preview_url: null,
      public_url: null,
      schema_version: 2,
      allow_remix: true,
      likes_count: 0,
      favorites_count: 0,
      saves_count: 0,
      remixes_count: 0,
      challenge_entries_count: 0,
      lineage: { original_card: null, root_card: null },
      editor_mode_last_used: "full",
      project_json: project
    };
  }
  return {
    ...card,
    tags: Array.isArray(card.tags) ? card.tags : [],
    allow_remix: card.allow_remix !== false,
    project_json: normalizeProject(card.project_json || {}, options, card)
  };
}
function mergeServerCard(currentCard, serverCard) {
  if (!currentCard) return serverCard;
  if (!serverCard) return currentCard;
  return {
    ...currentCard,
    ...serverCard,
    title: currentCard.title,
    quote_text: currentCard.quote_text,
    quote_author: currentCard.quote_author,
    quote_source: currentCard.quote_source,
    description: currentCard.description,
    format: currentCard.format,
    visibility: currentCard.visibility,
    template_id: currentCard.template_id,
    category_id: currentCard.category_id,
    background_type: currentCard.background_type,
    background_image_id: currentCard.background_image_id,
    allow_download: currentCard.allow_download,
    allow_remix: currentCard.allow_remix,
    allow_background_reuse: currentCard.allow_background_reuse,
    allow_export: currentCard.allow_export,
    style_family: currentCard.style_family,
    palette_family: currentCard.palette_family,
    editor_mode_last_used: currentCard.editor_mode_last_used,
    tags: currentCard.tags,
    project_json: currentCard.project_json
  };
}
function buildPayload(card, tagInput) {
  return {
    title: card.title,
    quote_text: card.quote_text,
    quote_author: card.quote_author,
    quote_source: card.quote_source,
    description: card.description,
    format: card.format,
    visibility: card.visibility,
    allow_download: Boolean(card.allow_download),
    allow_remix: Boolean(card.allow_remix),
    allow_background_reuse: Boolean(card.allow_background_reuse),
    allow_export: Boolean(card.allow_export !== false),
    style_family: card.style_family || null,
    palette_family: card.palette_family || null,
    editor_mode_last_used: card.editor_mode_last_used || card.project_json?.source_context?.editor_mode || "full",
    background_type: card.background_type,
    background_image_id: card.background_image_id,
    template_id: card.template_id,
    category_id: card.category_id,
    tags: String(tagInput || "").split(",").map((item) => item.trim()).filter(Boolean),
    project_json: card.project_json
  };
}
function fillPattern(pattern, replacements) {
  let resolved = String(pattern || "");
  Object.entries(replacements).forEach(([key, value]) => {
    resolved = resolved.replace(`__${key}__`, String(value));
  });
  return resolved;
}
function apiUrl(pattern, id) {
  return fillPattern(pattern, { CARD: id });
}
function StudioCardEditor() {
  const { props } = X$1();
  const editorOptions = props.editorOptions || {};
  const endpoints = props.endpoints || {};
  const previewMode = Boolean(props.previewMode);
  const mobileSteps = Array.isArray(props.mobileSteps) && props.mobileSteps.length ? props.mobileSteps : defaultMobileSteps;
  const [card, setCard] = React.useState(() => normalizeCard(props.card, editorOptions));
  const [cardId, setCardId] = React.useState(props.card?.id || null);
  const [tagInput, setTagInput] = React.useState(() => (props.card?.tags || []).map((tag) => tag.name).join(", "));
  const [versions, setVersions] = React.useState(() => Array.isArray(props.versions) ? props.versions : []);
  const [collections, setCollections] = React.useState([]);
  const [selectedCollectionId, setSelectedCollectionId] = React.useState("");
  const [autosaveStatus, setAutosaveStatus] = React.useState(props.card ? "saved" : "idle");
  const [autosaveMessage, setAutosaveMessage] = React.useState(props.card ? "Loaded" : "Preparing draft");
  const [busy, setBusy] = React.useState(false);
  const [uploading, setUploading] = React.useState(false);
  const [currentMobileStep, setCurrentMobileStep] = React.useState(previewMode ? "preview" : mobileSteps[0]?.key || "format");
  const [activeTab, setActiveTab] = React.useState("background");
  const [creatorPresets, setCreatorPresets] = React.useState(() => editorOptions.creator_presets || {});
  const [aiSuggestions, setAiSuggestions] = React.useState(null);
  const [loadingAi, setLoadingAi] = React.useState(false);
  const [exportStatus, setExportStatus] = React.useState(null);
  const [requestingExport, setRequestingExport] = React.useState(false);
  const [activeExportType, setActiveExportType] = React.useState("preview");
  const createStarted = React.useRef(false);
  const lastSerialized = React.useRef(JSON.stringify(buildPayload(normalizeCard(props.card, editorOptions), tagInput)));
  const autosaveAbortRef = React.useRef(null);
  React.useEffect(() => {
    setCurrentMobileStep(previewMode ? "preview" : mobileSteps[0]?.key || "format");
  }, [mobileSteps, previewMode]);
  function replaceTextBlocks(nextBlocks) {
    setCard((current) => {
      const blocks = Array.isArray(nextBlocks) ? nextBlocks : [];
      const next = { ...current };
      next.project_json = deepMerge(current.project_json || {}, { text_blocks: blocks });
      const quoteBlock = blocks.find((block) => block?.type === "quote");
      const titleBlock = blocks.find((block) => block?.type === "title");
      const authorBlock = blocks.find((block) => block?.type === "author");
      const sourceBlock = blocks.find((block) => block?.type === "source");
      next.title = titleBlock?.text || next.title;
      next.quote_text = quoteBlock?.text || next.quote_text;
      next.quote_author = authorBlock?.text || "";
      next.quote_source = sourceBlock?.text || "";
      next.project_json.content = {
        ...next.project_json.content || {},
        title: next.title,
        quote_text: next.quote_text,
        quote_author: next.quote_author,
        quote_source: next.quote_source
      };
      return next;
    });
  }
  function loadVersions(targetCardId) {
    if (!targetCardId || !endpoints.draftVersionsPattern) return;
    window.axios.get(apiUrl(endpoints.draftVersionsPattern, targetCardId)).then((response) => {
      setVersions(Array.isArray(response.data?.data) ? response.data.data : []);
    }).catch(() => {
    });
  }
  function loadCollections() {
    if (!endpoints.collectionsIndex) return;
    window.axios.get(endpoints.collectionsIndex).then((response) => {
      const items = Array.isArray(response.data?.data) ? response.data.data : [];
      setCollections(items);
      if (!selectedCollectionId && items[0]?.id) {
        setSelectedCollectionId(String(items[0].id));
      }
    }).catch(() => {
    });
  }
  React.useEffect(() => {
    if (!cardId) return;
    loadVersions(cardId);
    loadCollections();
  }, [cardId]);
  React.useEffect(() => {
    if (cardId || createStarted.current) return;
    createStarted.current = true;
    setBusy(true);
    window.axios.post(endpoints.draftStore, {
      format: card.format,
      template_id: card.template_id,
      category_id: card.category_id
    }).then((response) => {
      const nextCard = normalizeCard(response.data.data, editorOptions);
      setCard(nextCard);
      setCardId(nextCard.id);
      setAutosaveStatus("saved");
      setAutosaveMessage("Draft created");
      lastSerialized.current = JSON.stringify(buildPayload(nextCard, tagInput));
    }).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Could not create draft");
    }).finally(() => {
      setBusy(false);
    });
  }, [card, cardId, editorOptions, endpoints.draftStore, tagInput]);
  React.useEffect(() => {
    if (!cardId || busy || uploading) return;
    const payload = buildPayload(card, tagInput);
    const serialized = JSON.stringify(payload);
    if (serialized === lastSerialized.current) return;
    setAutosaveStatus("saving");
    setAutosaveMessage("Saving draft");
    const timer = window.setTimeout(() => {
      if (autosaveAbortRef.current) {
        autosaveAbortRef.current.abort();
      }
      const controller = new AbortController();
      autosaveAbortRef.current = controller;
      window.axios.post(apiUrl(endpoints.draftAutosavePattern, cardId), payload, { signal: controller.signal }).then(() => {
        autosaveAbortRef.current = null;
        lastSerialized.current = serialized;
        setAutosaveStatus("saved");
        setAutosaveMessage("All changes saved");
      }).catch((error) => {
        if (error?.name === "CanceledError" || error?.name === "AbortError" || error?.code === "ERR_CANCELED") return;
        setAutosaveStatus("error");
        setAutosaveMessage("Autosave failed");
      });
    }, 900);
    return () => window.clearTimeout(timer);
  }, [busy, card, cardId, editorOptions, endpoints.draftAutosavePattern, tagInput, uploading]);
  function updateCard(partial, projectPatch = null) {
    setCard((current) => {
      const next = { ...current, ...partial };
      if (projectPatch) {
        next.project_json = deepMerge(current.project_json || {}, projectPatch);
      }
      return next;
    });
  }
  function updateTextField(key, value) {
    const typeMap = {
      title: "title",
      quote_text: "quote",
      quote_author: "author",
      quote_source: "source"
    };
    setCard((current) => {
      const next = { ...current, [key]: value };
      next.project_json = deepMerge(current.project_json || {}, {
        content: { [key]: value },
        text_blocks: syncTextBlocks(current.project_json?.text_blocks, typeMap[key], value)
      });
      return next;
    });
  }
  function updateTextBlock(index2, patch2) {
    const blocks = Array.isArray(card.project_json?.text_blocks) ? [...card.project_json.text_blocks] : [];
    blocks[index2] = { ...blocks[index2], ...patch2 };
    replaceTextBlocks(blocks);
  }
  function addTextBlock(type2 = "body") {
    const nextBlock = {
      key: `${type2}-${Date.now()}`,
      type: type2,
      text: "",
      enabled: true,
      style: {}
    };
    replaceTextBlocks([...Array.isArray(card.project_json?.text_blocks) ? card.project_json.text_blocks : [], nextBlock]);
  }
  function removeTextBlock(index2) {
    const blocks = Array.isArray(card.project_json?.text_blocks) ? card.project_json.text_blocks : [];
    replaceTextBlocks(blocks.filter((_2, itemIndex) => itemIndex !== index2));
  }
  function moveTextBlock(index2, direction) {
    const blocks = Array.isArray(card.project_json?.text_blocks) ? [...card.project_json.text_blocks] : [];
    const nextIndex = index2 + direction;
    if (nextIndex < 0 || nextIndex >= blocks.length) {
      return;
    }
    const [moved] = blocks.splice(index2, 1);
    blocks.splice(nextIndex, 0, moved);
    replaceTextBlocks(blocks);
  }
  function setEditorMode(mode) {
    updateCard({ editor_mode_last_used: mode }, { source_context: { editor_mode: mode } });
  }
  function handleTemplateSelect(template) {
    const layoutPreset = template.config_json?.layout || "quote_heavy";
    updateCard(
      { template_id: template.id },
      {
        template: { id: template.id, slug: template.slug },
        layout: {
          layout: layoutPreset,
          ...layoutPresetMap[layoutPreset] || {},
          alignment: template.config_json?.text_align || layoutPresetMap[layoutPreset]?.alignment || "center"
        },
        typography: {
          font_preset: template.config_json?.font_preset || card.project_json?.typography?.font_preset,
          text_color: template.config_json?.text_color || card.project_json?.typography?.text_color
        },
        background: {
          gradient_preset: template.config_json?.gradient_preset || card.project_json?.background?.gradient_preset,
          overlay_style: template.config_json?.overlay_style || card.project_json?.background?.overlay_style
        }
      }
    );
  }
  function handleGradientSelect(gradient) {
    updateCard({ background_type: "gradient" }, {
      background: {
        type: "gradient",
        gradient_preset: gradient.key,
        gradient_colors: gradient.colors
      }
    });
  }
  function handleFontSelect(font) {
    updateCard({}, {
      typography: {
        font_preset: font.key
      }
    });
  }
  function reloadPresets() {
    if (!endpoints.presetsIndex) return;
    window.axios.get(endpoints.presetsIndex).then((response) => {
      const data = response.data?.data || response.data || {};
      setCreatorPresets(data);
    }).catch(() => {
    });
  }
  function handleApplyPresetPatch(patch2) {
    setCard((current) => ({
      ...current,
      project_json: deepMerge(current.project_json || {}, patch2)
    }));
  }
  function fetchAiSuggestions() {
    if (!cardId || !endpoints.aiSuggestPattern) return;
    const url = endpoints.aiSuggestPattern.replace("__CARD__", cardId);
    setLoadingAi(true);
    window.axios.get(url).then((response) => setAiSuggestions(response.data?.suggestions || response.data || null)).catch(() => {
    }).finally(() => setLoadingAi(false));
  }
  function applyAiTagSuggestions(tags) {
    if (!Array.isArray(tags) || tags.length === 0) return;
    const existing = tagInput ? tagInput.split(",").map((t) => t.trim()).filter(Boolean) : [];
    const merged = [.../* @__PURE__ */ new Set([...existing, ...tags])];
    setTagInput(merged.join(", "));
  }
  function requestExport(exportType) {
    if (!cardId || !endpoints.exportPattern) return;
    const url = endpoints.exportPattern.replace("__CARD__", cardId);
    setRequestingExport(true);
    setExportStatus(null);
    setActiveExportType(exportType);
    const csrfToken2 = document.querySelector('meta[name="csrf-token"]')?.content || "";
    window.axios.post(url, { export_type: exportType }, { headers: { "X-CSRF-TOKEN": csrfToken2 } }).then((response) => {
      const exportData = response.data?.data || response.data;
      setExportStatus(exportData);
      if (exportData?.status === "pending" || exportData?.status === "processing") {
        pollExportStatus(exportData.id);
      }
    }).catch(() => setExportStatus({ status: "failed" })).finally(() => setRequestingExport(false));
  }
  function pollExportStatus(exportId, attempts = 0) {
    if (!endpoints.exportStatusPattern || attempts > 20) return;
    const url = endpoints.exportStatusPattern.replace("__EXPORT__", exportId);
    window.setTimeout(() => {
      window.axios.get(url).then((response) => {
        const data = response.data?.data || response.data;
        setExportStatus(data);
        if (data?.status === "pending" || data?.status === "processing") {
          pollExportStatus(exportId, attempts + 1);
        }
      }).catch(() => {
      });
    }, 2500);
  }
  function handleElementMove(elementId, x2, y2, widthPct) {
    if (elementId.startsWith("block:")) {
      const key = elementId.slice(6);
      setCard((current) => {
        const blocks = Array.isArray(current.project_json?.text_blocks) ? [...current.project_json.text_blocks] : [];
        const idx = blocks.findIndex((b2) => b2.key === key || b2.type === key);
        if (idx === -1) return current;
        const updated = [...blocks];
        updated[idx] = { ...updated[idx], pos_x: x2, pos_y: y2, ...widthPct != null ? { pos_width: widthPct } : {} };
        return { ...current, project_json: { ...current.project_json, text_blocks: updated } };
      });
    } else if (elementId.startsWith("decoration:")) {
      const idx = parseInt(elementId.slice(11), 10);
      setCard((current) => {
        const decorations2 = Array.isArray(current.project_json?.decorations) ? [...current.project_json.decorations] : [];
        if (idx < 0 || idx >= decorations2.length) return current;
        const updated = [...decorations2];
        updated[idx] = { ...updated[idx], pos_x: x2, pos_y: y2 };
        return { ...current, project_json: { ...current.project_json, decorations: updated } };
      });
    }
  }
  function applyLayoutPreset(presetKey) {
    updateCard({}, {
      layout: {
        layout: presetKey,
        ...layoutPresetMap[presetKey] || {}
      }
    });
  }
  function addDecoration(decoration) {
    const placements = ["top-left", "top-right", "bottom-left", "bottom-right"];
    const current = Array.isArray(card.project_json?.decorations) ? card.project_json.decorations : [];
    updateCard({}, {
      decorations: [
        ...current,
        {
          key: decoration.key,
          glyph: decoration.glyph,
          placement: placements[current.length % placements.length],
          size: 28
        }
      ].slice(0, editorOptions.validation?.max_decorations || 6)
    });
  }
  function removeDecoration(index2) {
    const current = Array.isArray(card.project_json?.decorations) ? card.project_json.decorations : [];
    updateCard({}, { decorations: current.filter((_2, itemIndex) => itemIndex !== index2) });
  }
  function updateDecoration(index2, patch2) {
    const current = Array.isArray(card.project_json?.decorations) ? [...card.project_json.decorations] : [];
    current[index2] = { ...current[index2], ...patch2 };
    updateCard({}, { decorations: current });
  }
  function manualSave() {
    if (!cardId) return;
    const payload = buildPayload(card, tagInput);
    const serialized = JSON.stringify(payload);
    if (autosaveAbortRef.current) {
      autosaveAbortRef.current.abort();
      autosaveAbortRef.current = null;
    }
    setBusy(true);
    setAutosaveStatus("saving");
    window.axios.patch(apiUrl(endpoints.draftUpdatePattern, cardId), payload).then((response) => {
      const nextCard = normalizeCard(response.data.data, editorOptions);
      setCard((current) => mergeServerCard(current, nextCard));
      lastSerialized.current = serialized;
      setAutosaveStatus("saved");
      setAutosaveMessage("Draft saved");
      loadVersions(nextCard.id);
    }).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Save failed");
    }).finally(() => setBusy(false));
  }
  function renderPreview() {
    if (!cardId) return;
    const payload = buildPayload(card, tagInput);
    const serialized = JSON.stringify(payload);
    if (autosaveAbortRef.current) {
      autosaveAbortRef.current.abort();
      autosaveAbortRef.current = null;
    }
    setBusy(true);
    setAutosaveStatus("saving");
    setAutosaveMessage("Saving before render…");
    window.axios.post(apiUrl(endpoints.draftAutosavePattern, cardId), payload).then(() => window.axios.post(apiUrl(endpoints.draftRenderPattern, cardId))).then((response) => {
      const nextCard = normalizeCard(response.data.data, editorOptions);
      setCard((current) => mergeServerCard(current, nextCard));
      lastSerialized.current = serialized;
      setAutosaveStatus("saved");
      setAutosaveMessage("Preview image rendered ✓");
      setActiveTab("publish");
    }).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Render failed");
    }).finally(() => setBusy(false));
  }
  function publishCard() {
    if (!cardId) return;
    const payload = buildPayload(card, tagInput);
    const serialized = JSON.stringify(payload);
    if (autosaveAbortRef.current) {
      autosaveAbortRef.current.abort();
      autosaveAbortRef.current = null;
    }
    setBusy(true);
    window.axios.post(apiUrl(endpoints.draftPublishPattern, cardId), payload).then((response) => {
      const nextCard = normalizeCard(response.data.data, editorOptions);
      setCard((current) => mergeServerCard(current, nextCard));
      lastSerialized.current = serialized;
      setAutosaveStatus("saved");
      setAutosaveMessage("Card published");
      loadVersions(nextCard.id);
    }).catch((error) => {
      setAutosaveStatus("error");
      setAutosaveMessage(error?.response?.data?.message || "Publish failed");
    }).finally(() => setBusy(false));
  }
  function deleteDraft() {
    if (!cardId || !window.confirm("Delete this draft?")) return;
    setBusy(true);
    window.axios.delete(apiUrl(endpoints.draftDeletePattern, cardId)).then(() => {
      window.location.assign(endpoints.studioCards || "/studio/cards");
    }).finally(() => setBusy(false));
  }
  function uploadBackground(event) {
    const file = event.target.files?.[0];
    if (!file || !cardId) return;
    const formData = new FormData();
    formData.append("background", file);
    setUploading(true);
    setActiveTab("background");
    window.axios.post(apiUrl(endpoints.draftBackgroundPattern, cardId), formData).then((response) => {
      const nextCard = normalizeCard(response.data.data, editorOptions);
      const bgInfo = response.data.background;
      if (bgInfo?.processed_url) {
        nextCard.background_image = { processed_url: bgInfo.processed_url };
        nextCard.background_type = "upload";
        if (nextCard.project_json) {
          nextCard.project_json = deepMerge(nextCard.project_json, { background: { type: "upload" } });
        }
      }
      setCard(nextCard);
      setAutosaveStatus("saved");
      setAutosaveMessage("Background uploaded");
    }).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Upload failed");
    }).finally(() => setUploading(false));
  }
  function createCollection() {
    const name2 = window.prompt("Collection name");
    if (!name2 || !endpoints.collectionsStore) return;
    window.axios.post(endpoints.collectionsStore, { name: name2 }).then(() => loadCollections()).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Collection could not be created");
    });
  }
  function saveToCollection() {
    if (!cardId || !endpoints.savePattern) return;
    setBusy(true);
    window.axios.post(apiUrl(endpoints.savePattern, cardId), {
      collection_id: selectedCollectionId ? Number(selectedCollectionId) : void 0
    }).then((response) => {
      setCard((current) => ({ ...current, saves_count: Number(response.data?.saves_count || current.saves_count || 0) }));
      setAutosaveStatus("saved");
      setAutosaveMessage("Saved to collection");
      loadCollections();
    }).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Save to collection failed");
    }).finally(() => setBusy(false));
  }
  function restoreVersion(versionId) {
    if (!cardId || !endpoints.draftRestorePattern) return;
    setBusy(true);
    window.axios.post(fillPattern(endpoints.draftRestorePattern, { CARD: cardId, VERSION: versionId })).then((response) => {
      const nextCard = normalizeCard(response.data.data, editorOptions);
      setCard(nextCard);
      lastSerialized.current = JSON.stringify(buildPayload(nextCard, tagInput));
      setAutosaveStatus("saved");
      setAutosaveMessage("Version restored");
      loadVersions(nextCard.id);
    }).catch(() => {
      setAutosaveStatus("error");
      setAutosaveMessage("Restore failed");
    }).finally(() => setBusy(false));
  }
  function submitChallenge(challengeId) {
    if (!cardId || !endpoints.challengeSubmitPattern) return;
    setBusy(true);
    window.axios.post(fillPattern(endpoints.challengeSubmitPattern, { CHALLENGE: challengeId, CARD: cardId })).then((response) => {
      setCard((current) => ({ ...current, challenge_entries_count: Number(response.data?.challenge_entries_count || current.challenge_entries_count || 0) }));
      setAutosaveStatus("saved");
      setAutosaveMessage("Submitted to challenge");
    }).catch((error) => {
      setAutosaveStatus("error");
      setAutosaveMessage(error?.response?.data?.message || "Challenge submission failed");
    }).finally(() => setBusy(false));
  }
  const decorations = Array.isArray(card.project_json?.decorations) ? card.project_json.decorations : [];
  const textBlocks = Array.isArray(card.project_json?.text_blocks) ? card.project_json.text_blocks : [];
  const backgroundType = card.project_json?.background?.type || card.background_type || "gradient";
  Array.isArray(card.project_json?.assets?.items) ? card.project_json.assets.items : [];
  Array.isArray(card.project_json?.assets?.pack_ids) ? card.project_json.assets.pack_ids : [];
  Array.isArray(card.project_json?.assets?.template_pack_ids) ? card.project_json.assets.template_pack_ids : [];
  const currentMobileStepIndex = Math.max(0, mobileSteps.findIndex((step) => step.key === currentMobileStep));
  mobileSteps[currentMobileStepIndex] || mobileSteps[0];
  const editorMode = card.editor_mode_last_used || card.project_json?.source_context?.editor_mode || "full";
  const advancedMode = editorMode !== "quick";
  summarizeProjectSnapshot(card.project_json || {});
  const editorTabs = [
    { key: "background", label: "Canvas" },
    { key: "content", label: "Text" },
    { key: "style", label: "Style" },
    { key: "publish", label: "Publish" }
  ];
  const tabIndex = editorTabs.findIndex((t) => t.key === activeTab);
  function goToNextTab(direction) {
    const next = editorTabs[tabIndex + direction];
    if (next) {
      setActiveTab(next.key);
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  }
  function tabBtnClasses(active) {
    return `flex-none whitespace-nowrap rounded-2xl border px-4 py-2 text-sm font-semibold transition ${active ? "border-sky-400/30 bg-sky-500/15 text-sky-200" : "border-transparent text-slate-400 hover:bg-white/[0.05] hover:text-white"}`;
  }
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: previewMode ? "Card Preview" : "Card Editor" }, /* @__PURE__ */ React.createElement(Se$1, { title: previewMode ? "Nova Card Preview" : "Nova Card Editor" }), /* @__PURE__ */ React.createElement("section", { className: "mb-5 flex flex-wrap items-center justify-between gap-3 rounded-[24px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.10),transparent_40%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] px-5 py-4 shadow-[0_18px_48px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/70" }, "Nova Cards editor"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 truncate text-xl font-semibold tracking-[-0.03em] text-white" }, card.title || "Untitled card"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-1.5" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setEditorMode("quick"), className: pillClasses(editorMode === "quick") }, "Quick mode"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setEditorMode("full"), className: pillClasses(editorMode === "full") }, "Advanced mode"))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(NovaCardAutosaveIndicator, { status: autosaveStatus, message: autosaveMessage }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: manualSave, disabled: busy || !cardId, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:opacity-60" }, "Save"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: publishCard, disabled: busy || !cardId, className: "rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100 transition hover:bg-emerald-400/15 disabled:opacity-60" }, "Publish"), card.public_url ? /* @__PURE__ */ React.createElement("a", { href: card.public_url, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Public page") : null)), /* @__PURE__ */ React.createElement("div", { className: "xl:grid xl:grid-cols-[minmax(0,480px)_minmax(0,1fr)] xl:items-start xl:gap-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 xl:mb-0" }, /* @__PURE__ */ React.createElement("div", { className: "no-scrollbar -mx-1 flex gap-1 overflow-x-auto px-1 pb-2" }, editorTabs.map((tab2) => /* @__PURE__ */ React.createElement("button", { key: tab2.key, type: "button", onClick: () => setActiveTab(tab2.key), className: tabBtnClasses(activeTab === tab2.key) }, tab2.label))), /* @__PURE__ */ React.createElement("div", { className: "mt-2 rounded-[28px] border border-white/10 bg-white/[0.04] p-5" }, activeTab === "background" && /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Canvas format"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (editorOptions.formats || []).map((format) => /* @__PURE__ */ React.createElement("button", { key: format.key, type: "button", onClick: () => updateCard({ format: format.key }), className: pillClasses((card.format || "square") === format.key) }, format.label)))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Template"), /* @__PURE__ */ React.createElement(NovaCardTemplatePicker, { templates: editorOptions.templates || [], selectedId: card.template_id, onSelect: handleTemplateSelect })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Background type"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (editorOptions.background_modes || []).map((mode) => /* @__PURE__ */ React.createElement("button", { key: mode.key, type: "button", onClick: () => updateCard({ background_type: mode.key }, { background: { type: mode.key } }), className: pillClasses(backgroundType === mode.key) }, mode.label)))), (backgroundType === "gradient" || backgroundType === "template") && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Gradient"), /* @__PURE__ */ React.createElement(NovaCardGradientPicker, { gradients: editorOptions.gradient_presets || [], selectedKey: card.project_json?.background?.gradient_preset, onSelect: handleGradientSelect })), backgroundType === "solid" && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Solid color"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "color", value: card.project_json?.background?.solid_color || "#111827", onChange: (event) => updateCard({ background_type: "solid" }, { background: { type: "solid", solid_color: event.target.value } }), className: "h-12 w-16 cursor-pointer rounded-xl border border-white/10 bg-[#0d1726] p-1.5" }), /* @__PURE__ */ React.createElement("span", { className: "font-mono text-sm text-white/60" }, card.project_json?.background?.solid_color || "#111827"))), backgroundType === "upload" && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Custom image"), card.background_image?.processed_url ? /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[18px] border border-white/10" }, /* @__PURE__ */ React.createElement("img", { src: card.background_image.processed_url, alt: "Uploaded background", className: "h-44 w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between bg-white/[0.03] px-4 py-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-emerald-300" }, "✓ Uploaded"), /* @__PURE__ */ React.createElement("label", { className: "cursor-pointer text-xs text-slate-400 transition hover:text-white" }, "Replace image", /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/png,image/jpeg,image/webp", className: "hidden", onChange: uploadBackground, disabled: uploading })))) : /* @__PURE__ */ React.createElement("label", { className: `flex cursor-pointer flex-col items-center gap-3 rounded-[22px] border-2 border-dashed px-6 py-10 text-center transition ${uploading ? "border-sky-400/40 bg-sky-400/[0.04]" : "border-white/12 bg-white/[0.02] hover:border-white/20 hover:bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement("div", { className: "text-3xl" }, uploading ? "⏳" : "🖼️"), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-slate-300" }, uploading ? "Uploading…" : "Choose background image"), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "JPG, PNG or WebP · Max 8 MB · Min 480×480 px"), /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/png,image/jpeg,image/webp", className: "hidden", onChange: uploadBackground, disabled: uploading }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Overlay & depth"), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Overlay style"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.background?.overlay_style || "dark-soft", onChange: (val) => updateCard({}, { background: { overlay_style: val } }), options: (overlayOptions || []).map((o) => ({ value: o.value, label: o.label })) })), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex justify-between" }, /* @__PURE__ */ React.createElement("span", null, "Overlay opacity"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, card.project_json?.background?.opacity || 50, "%")), /* @__PURE__ */ React.createElement("input", { type: "range", min: "0", max: "90", step: "10", value: card.project_json?.background?.opacity || 50, onChange: (event) => updateCard({}, { background: { opacity: Number(event.target.value) } }), className: "w-full" })), advancedMode && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex justify-between" }, /* @__PURE__ */ React.createElement("span", null, "Background blur"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, card.project_json?.background?.blur_level || 0, "px")), /* @__PURE__ */ React.createElement("input", { type: "range", min: "0", max: "32", step: "4", value: card.project_json?.background?.blur_level || 0, onChange: (event) => updateCard({}, { background: { blur_level: Number(event.target.value) } }), className: "w-full" })), /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Focal position"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.background?.focal_position || "center", onChange: (val) => updateCard({}, { background: { focal_position: val } }), options: (editorOptions.focal_positions || []).map((p) => ({ value: p.key, label: p.label })) }))))), advancedMode && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Decorations"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-2 sm:grid-cols-5" }, (editorOptions.decor_presets || []).map((decor) => /* @__PURE__ */ React.createElement("button", { key: decor.key, type: "button", onClick: () => addDecoration(decor), className: "flex flex-col items-center gap-1 rounded-[18px] border border-white/10 bg-white/[0.03] px-2 py-3 text-center transition hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("span", { className: "text-2xl" }, decor.glyph), /* @__PURE__ */ React.createElement("span", { className: "text-[10px] text-slate-400" }, decor.label)))), decorations.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, decorations.map((decor, index2) => /* @__PURE__ */ React.createElement("div", { key: `${decor.key}-${index2}`, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("span", { className: "text-base" }, decor.glyph), /* @__PURE__ */ React.createElement("span", { className: "flex-1 px-3 text-slate-300" }, decor.key), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeDecoration(index2), className: "text-rose-300 transition hover:text-rose-200" }, "Remove")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[10px] uppercase tracking-[0.16em] text-slate-500 w-14 shrink-0" }, "Opacity"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "range",
      min: "10",
      max: "100",
      step: "5",
      value: decor.opacity ?? 85,
      onChange: (event) => updateDecoration(index2, { opacity: Number(event.target.value) }),
      className: "w-full"
    }
  ), /* @__PURE__ */ React.createElement("span", { className: "w-10 shrink-0 text-right font-mono text-xs text-white/70" }, decor.opacity ?? 85, "%"))))))), activeTab === "content" && /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Font family"), /* @__PURE__ */ React.createElement(NovaCardFontPicker, { fonts: editorOptions.font_presets || [], selectedKey: card.project_json?.typography?.font_preset, onSelect: handleFontSelect })), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/10 pt-4" }, /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Title"), /* @__PURE__ */ React.createElement("input", { value: card.title || "", onChange: (event) => updateTextField("title", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35" })), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Quote text"), /* @__PURE__ */ React.createElement("textarea", { value: card.quote_text || "", onChange: (event) => updateTextField("quote_text", event.target.value), rows: 5, className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35" })), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Author"), /* @__PURE__ */ React.createElement("input", { value: card.quote_author || "", onChange: (event) => updateTextField("quote_author", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35" })), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Source"), /* @__PURE__ */ React.createElement("input", { value: card.quote_source || "", onChange: (event) => updateTextField("quote_source", event.target.value), className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35" })), advancedMode && /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/10 pt-4" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Text blocks"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => addTextBlock("body"), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-white" }, "+ Body"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => addTextBlock("caption"), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-white" }, "+ Caption"))), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, textBlocks.map((block, index2) => /* @__PURE__ */ React.createElement("div", { key: `${block.key || block.type}-${index2}`, className: "rounded-[20px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveTextBlock(index2, -1), disabled: index2 === 0, className: "rounded border border-white/10 bg-white/[0.05] px-1.5 py-0.5 text-[10px] text-white disabled:opacity-30" }, "▲"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveTextBlock(index2, 1), disabled: index2 === textBlocks.length - 1, className: "rounded border border-white/10 bg-white/[0.05] px-1.5 py-0.5 text-[10px] text-white disabled:opacity-30" }, "▼")), /* @__PURE__ */ React.createElement(NovaSelect, { value: block.type || "body", onChange: (val) => updateTextBlock(index2, { type: val }), searchable: false, options: [{ value: "title", label: "Title" }, { value: "quote", label: "Quote" }, { value: "author", label: "Author" }, { value: "source", label: "Source" }, { value: "body", label: "Body" }, { value: "caption", label: "Caption" }] }), /* @__PURE__ */ React.createElement("input", { value: block.text || "", onChange: (event) => updateTextBlock(index2, { text: event.target.value, enabled: block.type === "title" || block.type === "quote" ? true : Boolean(event.target.value.trim()) }), className: "min-w-0 flex-1 rounded-xl border border-white/10 bg-[#0d1726] px-3 py-2 text-sm text-white outline-none" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: block.enabled !== false, onChange: (e) => updateTextBlock(index2, { enabled: e.target.checked }), label: "On" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeTextBlock(index2), disabled: block.type === "title" || block.type === "quote", className: "text-rose-300 transition hover:text-rose-200 disabled:opacity-30" }, "×")))))))), activeTab === "style" && /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Quote size"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "range", min: "10", max: "128", value: card.project_json?.typography?.quote_size || 72, onChange: (event) => updateCard({}, { typography: { quote_size: Number(event.target.value) } }), className: "w-full" }), /* @__PURE__ */ React.createElement("span", { className: "w-16 shrink-0 text-right font-mono text-sm font-semibold text-white" }, card.project_json?.typography?.quote_size || 72, "px")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 overflow-hidden rounded-xl border border-white/10 bg-[#0d1726] px-3 py-2" }, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white/90 leading-none", style: {
    fontFamily: (editorOptions.font_presets || []).find((f2) => f2.key === card.project_json?.typography?.font_preset)?.family,
    fontSize: `${Math.min(Math.max(Number(card.project_json?.typography?.quote_size || 72) / 4, 6), 36)}px`,
    color: card.project_json?.typography?.text_color || "#ffffff"
  } }, "Preview text"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Quote width"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "range",
      min: "30",
      max: "100",
      step: "1",
      value: card.project_json?.typography?.quote_width ?? 76,
      onChange: (event) => updateCard({}, { typography: { quote_width: Number(event.target.value) } }),
      className: "w-full"
    }
  ), /* @__PURE__ */ React.createElement("span", { className: "w-16 shrink-0 text-right font-mono text-sm font-semibold text-white" }, card.project_json?.typography?.quote_width ?? 76, "%"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Author & caption size"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "range", min: "14", max: "42", value: card.project_json?.typography?.author_size || 28, onChange: (event) => updateCard({}, { typography: { author_size: Number(event.target.value) } }), className: "w-full" }), /* @__PURE__ */ React.createElement("span", { className: "w-16 shrink-0 text-right font-mono text-sm font-semibold text-white" }, card.project_json?.typography?.author_size || 28, "px"))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Text color"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("input", { type: "color", value: card.project_json?.typography?.text_color || "#ffffff", onChange: (event) => updateCard({}, { typography: { text_color: event.target.value } }), className: "h-10 w-12 shrink-0 cursor-pointer rounded-xl border border-white/10 bg-[#0d1726] p-1" }), /* @__PURE__ */ React.createElement("span", { className: "font-mono text-xs text-white/60" }, card.project_json?.typography?.text_color || "#ffffff"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Accent color"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("input", { type: "color", value: card.project_json?.typography?.accent_color || "#e0f2fe", onChange: (event) => updateCard({}, { typography: { accent_color: event.target.value } }), className: "h-10 w-12 shrink-0 cursor-pointer rounded-xl border border-white/10 bg-[#0d1726] p-1" }), /* @__PURE__ */ React.createElement("span", { className: "font-mono text-xs text-white/60" }, card.project_json?.typography?.accent_color || "#e0f2fe")))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Text opacity"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "range",
      min: "10",
      max: "100",
      step: "5",
      value: card.project_json?.typography?.text_opacity ?? 100,
      onChange: (event) => updateCard({}, { typography: { text_opacity: Number(event.target.value) } }),
      className: "w-full"
    }
  ), /* @__PURE__ */ React.createElement("span", { className: "w-16 shrink-0 text-right font-mono text-sm font-semibold text-white" }, card.project_json?.typography?.text_opacity ?? 100, "%"))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Text shadow"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, (editorOptions.shadow_presets || [{ key: "none", label: "None" }, { key: "soft", label: "Soft" }, { key: "strong", label: "Strong" }]).map((preset) => {
    const active = (card.project_json?.typography?.shadow_preset || "soft") === preset.key;
    const shadowStyle = preset.key === "soft" ? "0 6px 16px rgba(2,6,23,0.6)" : preset.key === "strong" ? "0 10px 28px rgba(2,6,23,0.85)" : "none";
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: preset.key,
        type: "button",
        onClick: () => updateCard({}, { typography: { shadow_preset: preset.key } }),
        className: `flex-1 rounded-2xl border py-3 text-sm font-bold transition ${active ? "border-sky-400/30 bg-sky-500/15 text-white" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`,
        style: { textShadow: shadowStyle }
      },
      preset.label
    );
  }))), advancedMode && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Letter spacing"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "range", min: "-2", max: "10", value: card.project_json?.typography?.letter_spacing || 0, onChange: (event) => updateCard({}, { typography: { letter_spacing: Number(event.target.value) } }), className: "w-full" }), /* @__PURE__ */ React.createElement("span", { className: "w-16 shrink-0 text-right font-mono text-sm font-semibold text-white" }, card.project_json?.typography?.letter_spacing || 0))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Line height"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, (editorOptions.line_height_presets || []).map((preset) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: preset.key,
      type: "button",
      onClick: () => updateCard({}, { typography: { line_height: Number(preset.value) } }),
      className: `flex-1 rounded-2xl border py-2.5 text-sm font-semibold transition ${String(card.project_json?.typography?.line_height || 1.2) === String(preset.value) ? "border-sky-400/30 bg-sky-500/15 text-sky-200" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`
    },
    preset.label
  )))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Quote mark & panel"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-1.5 block text-xs" }, "Quote mark style"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.typography?.quote_mark_preset || "none", onChange: (val) => updateCard({}, { typography: { quote_mark_preset: val } }), options: (editorOptions.quote_mark_presets || []).map((p) => ({ value: p.key, label: p.label })) })), /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-1.5 block text-xs" }, "Text panel style"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.typography?.text_panel_style || "none", onChange: (val) => updateCard({}, { typography: { text_panel_style: val } }), options: (editorOptions.text_panel_styles || []).map((s2) => ({ value: s2.key, label: s2.label })) }))))), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/10 pt-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Layout preset"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (editorOptions.layout_presets || []).map((preset) => /* @__PURE__ */ React.createElement("button", { key: preset.key, type: "button", onClick: () => applyLayoutPreset(preset.key), className: pillClasses((card.project_json?.layout?.layout || "quote_heavy") === preset.key) }, preset.label)))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Text alignment"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, (editorOptions.alignment_presets || [{ key: "left", label: "Left" }, { key: "center", label: "Center" }, { key: "right", label: "Right" }]).map((preset) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: preset.key,
      type: "button",
      onClick: () => updateCard({}, { layout: { alignment: preset.key } }),
      className: `flex-1 rounded-2xl border py-2.5 text-sm font-semibold transition ${(card.project_json?.layout?.alignment || "center") === preset.key ? "border-sky-400/30 bg-sky-500/15 text-sky-200" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`
    },
    preset.label
  )))), advancedMode && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Vertical position"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (editorOptions.position_presets || []).map((preset) => /* @__PURE__ */ React.createElement("button", { key: preset.key, type: "button", onClick: () => updateCard({}, { layout: { position: preset.key } }), className: pillClasses((card.project_json?.layout?.position || "center") === preset.key) }, preset.label)))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Padding"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2" }, (editorOptions.padding_presets || []).map((preset) => /* @__PURE__ */ React.createElement("button", { key: preset.key, type: "button", onClick: () => updateCard({}, { layout: { padding: preset.key } }), className: pillClasses((card.project_json?.layout?.padding || "comfortable") === preset.key) }, preset.label)))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Text width"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2" }, (editorOptions.max_width_presets || []).map((preset) => /* @__PURE__ */ React.createElement("button", { key: preset.key, type: "button", onClick: () => updateCard({}, { layout: { max_width: preset.key } }), className: pillClasses((card.project_json?.layout?.max_width || "balanced") === preset.key) }, preset.label))))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Frame & effects"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-1.5 block" }, "Frame"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.frame?.preset || "none", onChange: (val) => updateCard({}, { frame: { preset: val } }), options: (editorOptions.frame_presets || []).map((p) => ({ value: p.key, label: p.label })) })), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-1.5 block text-xs" }, "Color grade"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.effects?.color_grade || "none", onChange: (val) => updateCard({}, { effects: { color_grade: val } }), options: (editorOptions.color_grade_presets || []).map((p) => ({ value: p.key, label: p.label })) })), /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-1.5 block text-xs" }, "Effect"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.project_json?.effects?.effect_preset || "none", onChange: (val) => updateCard({}, { effects: { effect_preset: val } }), options: (editorOptions.effect_presets || []).map((p) => ({ value: p.key, label: p.label })) })))))), advancedMode && (Object.keys(creatorPresets).length > 0 || endpoints.presetsIndex) && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Creator presets"), /* @__PURE__ */ React.createElement(NovaCardPresetPicker, { presets: creatorPresets, endpoints, cardId, onApplyPatch: handleApplyPresetPatch, onPresetsChange: reloadPresets })), advancedMode && endpoints.aiSuggestPattern && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "AI assist"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: loadingAi || !cardId, onClick: fetchAiSuggestions, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1.5 text-xs font-semibold text-sky-200 transition hover:bg-sky-400/15 disabled:opacity-50" }, loadingAi ? "Analysing…" : "Suggest")), aiSuggestions ? /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, aiSuggestions.tags?.length > 0 && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Suggested tags"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, aiSuggestions.tags.map((tag) => /* @__PURE__ */ React.createElement("button", { key: tag, type: "button", onClick: () => applyAiTagSuggestions([tag]), className: "rounded-full border border-sky-400/20 bg-sky-400/10 px-3 py-1 text-xs font-semibold text-sky-200 transition hover:bg-sky-400/15" }, "+ ", tag))), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => applyAiTagSuggestions(aiSuggestions.tags), className: "mt-1.5 text-xs text-slate-400 underline transition hover:text-white" }, "Add all")), aiSuggestions.mood && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2.5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Mood"), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-white" }, aiSuggestions.mood)), aiSuggestions.layout_suggestion && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2.5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Layout suggestion"), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-white" }, aiSuggestions.layout_suggestion)), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateCard({}, { layout: { layout: aiSuggestions.layout_suggestion } }), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold text-white transition hover:bg-white/[0.08]" }, "Apply")), (aiSuggestions.readability_fixes || []).map((fix, fi) => /* @__PURE__ */ React.createElement("div", { key: fi, className: "rounded-xl border border-amber-400/15 bg-amber-400/[0.06] px-3 py-2.5 text-sm text-amber-100" }, fix))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500" }, "Run a suggestion pass to see AI-powered tips for this card.")))), activeTab === "publish" && /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Category"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(card.category_id || ""), onChange: (val) => updateCard({ category_id: val ? Number(val) : null }), placeholder: "Select category", options: (editorOptions.categories || []).map((c) => ({ value: String(c.id), label: c.name })) })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-2 text-sm text-slate-300" }, "Visibility"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, ["private", "unlisted", "public"].map((v2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: v2,
      type: "button",
      onClick: () => updateCard({ visibility: v2 }),
      className: `flex-1 rounded-2xl border py-2.5 text-sm font-semibold capitalize transition ${(card.visibility || "private") === v2 ? "border-sky-400/30 bg-sky-500/15 text-sky-200" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`
    },
    v2
  )))), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Tags"), /* @__PURE__ */ React.createElement("input", { value: tagInput, onChange: (event) => setTagInput(event.target.value), placeholder: "motivation, calm, poetry", className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, [
    { key: "allow_download", label: "Allow download" },
    { key: "allow_remix", label: "Allow remix" },
    { key: "allow_export", label: "Allow export" },
    { key: "allow_background_reuse", label: "Allow background reuse" }
  ].map(({ key, label }) => /* @__PURE__ */ React.createElement("div", { key, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement(Checkbox, { checked: key === "allow_export" ? Boolean(card.allow_export !== false) : Boolean(card[key]), onChange: (event) => updateCard({ [key]: event.target.checked }) })))), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Description"), /* @__PURE__ */ React.createElement("textarea", { value: card.description || "", onChange: (event) => updateCard({ description: event.target.value }), rows: 3, className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white outline-none transition focus:border-sky-300/35" })), advancedMode && /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Style family"), /* @__PURE__ */ React.createElement(NovaSelect, { value: card.style_family || "", onChange: (val) => updateCard({ style_family: val || null }), placeholder: "None", options: (editorOptions.style_families || []).map((sf) => ({ value: sf.key, label: sf.label })) })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Save to collection"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(selectedCollectionId || ""), onChange: (val) => setSelectedCollectionId(val), placeholder: "Default saved cards", options: collections.map((c) => ({ value: String(c.id), label: c.name })) }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveToCollection, disabled: !cardId || busy, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, "Save")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: createCollection, className: "mt-2 text-sm text-slate-400 transition hover:text-white" }, "+ Create collection")), (editorOptions.challenge_feed || []).length > 0 && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Challenge entry"), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, (editorOptions.challenge_feed || []).slice(0, 4).map((challenge) => /* @__PURE__ */ React.createElement("button", { key: challenge.id, type: "button", onClick: () => submitChallenge(challenge.id), disabled: !cardId || busy, className: "flex w-full items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-left text-sm text-slate-200 transition hover:bg-white/[0.05] disabled:opacity-60" }, /* @__PURE__ */ React.createElement("span", null, challenge.title), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, challenge.status))))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Version history"), /* @__PURE__ */ React.createElement("div", { className: "space-y-2" }, versions.length > 0 ? versions.map((version) => /* @__PURE__ */ React.createElement("div", { key: version.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3 text-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, "Version ", version.version_number), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, version.label || "Autosaved", version.created_at ? ` · ${new Date(version.created_at).toLocaleString()}` : "")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => restoreVersion(version.id), disabled: busy || !cardId, className: "shrink-0 rounded-2xl border border-white/10 bg-white/[0.05] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.08] disabled:opacity-60" }, "Restore")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-1.5 text-[11px] font-semibold uppercase tracking-[0.14em]" }, compareProjectSnapshots(card.project_json || {}, version.snapshot_json || {}).map((item) => /* @__PURE__ */ React.createElement("span", { key: `${version.id}-${item}`, className: "rounded-full border border-sky-300/15 bg-sky-400/10 px-2 py-0.5 text-sky-200/80" }, item))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/12 bg-white/[0.03] px-4 py-4 text-sm text-slate-400" }, "Versions appear here after the first saved snapshot."))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 border-t border-white/10 pt-4" }, cardId ? /* @__PURE__ */ React.createElement(xe, { href: endpoints.studioCards || "/studio/cards", className: "text-sm text-slate-300 transition hover:text-white" }, "← Back to cards") : null, card.lineage?.original_card ? /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-sky-200/70" }, "Remix of: ", card.lineage.original_card.title) : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteDraft, disabled: busy || !cardId, className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, "Delete draft"))))), /* @__PURE__ */ React.createElement("div", { className: "xl:sticky xl:top-5 xl:self-start xl:max-h-[calc(100vh-2.5rem)] xl:overflow-y-auto xl:pb-5" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-5 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Live preview"), /* @__PURE__ */ React.createElement(NovaCardAutosaveIndicator, { status: autosaveStatus, message: autosaveMessage })), /* @__PURE__ */ React.createElement(NovaCardCanvasPreview, { card, fonts: editorOptions.font_presets || [], editable: true, onElementMove: handleElementMove, className: "mx-auto w-full max-w-full" }), card.preview_url && /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[22px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Rendered image"), /* @__PURE__ */ React.createElement("img", { src: `${card.preview_url}?version=${card.render_version || 0}`, alt: "Rendered preview", className: "w-full rounded-[18px] border border-white/10 object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: manualSave, disabled: busy || !cardId, className: "flex-1 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:opacity-60" }, "Save"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: renderPreview, disabled: busy || !cardId, className: "flex-1 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-2.5 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, "Render preview"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: publishCard, disabled: busy || !cardId, className: "flex-1 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-2.5 text-sm font-semibold text-emerald-100 transition hover:bg-emerald-400/15 disabled:opacity-60" }, "Publish")), card.public_url && /* @__PURE__ */ React.createElement("a", { href: card.public_url, className: "mt-2 flex w-full items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.05]" }, "View public page →")), endpoints.exportPattern && /* @__PURE__ */ React.createElement("section", { className: "mt-4 rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Export"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (editorOptions.export_formats || []).map((fmt2) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: fmt2.key,
      type: "button",
      disabled: requestingExport || !cardId,
      onClick: () => requestExport(fmt2.key),
      className: `rounded-full border px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] transition disabled:opacity-50 ${activeExportType === fmt2.key && exportStatus ? "border-sky-300/30 bg-sky-400/15 text-sky-100" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.05]"}`
    },
    fmt2.label
  ))), exportStatus && /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3 rounded-[18px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Export status"), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold capitalize text-white" }, exportStatus.status)), exportStatus.status === "ready" && exportStatus.output_url && /* @__PURE__ */ React.createElement("a", { href: exportStatus.output_url, download: true, className: "ml-auto rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-1.5 text-xs font-semibold text-emerald-200 transition hover:bg-emerald-400/15" }, "Download"))))), /* @__PURE__ */ React.createElement("nav", { className: "sticky bottom-0 z-20 mt-6 border-t border-white/10 bg-[rgba(2,6,23,0.92)] px-4 py-3 backdrop-blur xl:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex max-w-7xl items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => goToNextTab(-1), disabled: tabIndex === 0, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:opacity-50" }, "Back"), /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Step ", tabIndex + 1, " / ", editorTabs.length), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-sm font-semibold text-white" }, editorTabs[tabIndex]?.label)), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => goToNextTab(1), disabled: tabIndex >= editorTabs.length - 1, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-50" }, "Next"))));
}
const __vite_glob_0_114 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioCardEditor
}, Symbol.toStringTag, { value: "Module" }));
function StatCard$1({ label, value, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-12 w-12 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon}` })), /* @__PURE__ */ React.createElement("span", { className: "text-3xl font-semibold tracking-[-0.04em] text-white" }, value)));
}
function StudioCardsIndex() {
  const { props } = X$1();
  const summary = props.summary || {};
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.15),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Creation surface"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Build quote cards, mood cards, and visual text art."), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Cards now live inside the same shared Creator Studio queue as artworks, collections, and stories, while keeping the dedicated editor and analytics flow.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/studio/cards/create", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "New card"), /* @__PURE__ */ React.createElement("a", { href: props.publicBrowseUrl, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass" }), "Browse public cards")))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$1, { label: "All cards", value: summary.count || 0, icon: "fa-layer-group" }), /* @__PURE__ */ React.createElement(StatCard$1, { label: "Drafts", value: summary.draft_count || 0, icon: "fa-file-lines" }), /* @__PURE__ */ React.createElement(StatCard$1, { label: "Archived", value: summary.archived_count || 0, icon: "fa-box-archive" }), /* @__PURE__ */ React.createElement(StatCard$1, { label: "Published", value: summary.published_count || 0, icon: "fa-earth-americas" })), /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      hideModuleFilter: true,
      sortStorageKey: "studio-cards-sort",
      emptyTitle: "No cards yet",
      emptyBody: "Create your first Nova card and it will appear here alongside your other Creator Studio content."
    }
  )));
}
const __vite_glob_0_115 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioCardsIndex
}, Symbol.toStringTag, { value: "Module" }));
const summaryCards$1 = [
  ["active_challenges", "Active challenges", "fa-bolt"],
  ["joined_challenges", "Joined challenges", "fa-trophy"],
  ["entries_submitted", "Entries submitted", "fa-paper-plane"],
  ["featured_entries", "Featured entries", "fa-star"],
  ["winner_entries", "Winner entries", "fa-crown"],
  ["cards_available", "Challenge-ready cards", "fa-layer-group"]
];
function formatDate$4(value) {
  if (!value) return "TBD";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString(void 0, { month: "short", day: "numeric" });
}
function StudioChallenges() {
  const { props } = X$1();
  const { summary, spotlight, activeChallenges, recentEntries, cardLeaders, reminders } = props;
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 xl:grid-cols-6" }, summaryCards$1.map(([key, label, icon]) => /* @__PURE__ */ React.createElement("div", { key, className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-sky-200` })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(summary?.[key] || 0).toLocaleString())))), spotlight ? /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_34%),radial-gradient(circle_at_bottom_right,_rgba(250,204,21,0.12),_transparent_40%),linear-gradient(135deg,_rgba(15,23,42,0.88),_rgba(2,6,23,0.96))] p-6 shadow-[0_22px_60px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/70" }, "Challenge spotlight"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-3xl font-semibold text-white" }, spotlight.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, spotlight.prompt || spotlight.description || "A featured challenge run is active in Nova Cards right now."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3 text-xs uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, spotlight.status), /* @__PURE__ */ React.createElement("span", null, spotlight.official ? "Official" : "Community"), /* @__PURE__ */ React.createElement("span", null, spotlight.entries_count, " entries"), /* @__PURE__ */ React.createElement("span", null, spotlight.is_joined ? `${spotlight.submission_count} submitted` : "Not joined yet"))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: spotlight.url,
      onClick: () => trackStudioEvent("studio_challenge_action_taken", {
        surface: studioSurface(),
        module: "challenges",
        meta: {
          action: "open_spotlight",
          challenge_id: spotlight.id
        }
      }),
      className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15"
    },
    "Open challenge"
  ), /* @__PURE__ */ React.createElement("a", { href: "/studio/cards", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Review cards")))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Open and recent challenge runs"), /* @__PURE__ */ React.createElement("a", { href: "/cards/challenges", className: "text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Public archive")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (activeChallenges || []).map((challenge) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: challenge.id,
      href: challenge.url,
      onClick: () => trackStudioEvent("studio_challenge_action_taken", {
        surface: studioSurface(),
        module: "challenges",
        meta: {
          action: "open_challenge",
          challenge_id: challenge.id
        }
      }),
      className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, challenge.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, challenge.status, " • ", challenge.official ? "official" : "community", " • ", challenge.entries_count, " entries"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, challenge.prompt || challenge.description || "Challenge details are available in the public challenge view.")), /* @__PURE__ */ React.createElement("div", { className: "text-right text-xs uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("div", null, formatDate$4(challenge.starts_at), " start"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, formatDate$4(challenge.ends_at), " end"))),
    /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 ${challenge.is_joined ? "border-emerald-300/20 bg-emerald-300/10 text-emerald-100" : "border-white/10 text-slate-300"}` }, challenge.is_joined ? `${challenge.submission_count} submitted` : "Not joined"), challenge.featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2.5 py-1 text-amber-100" }, "Featured run") : null)
  )))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Workflow reminders"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (reminders || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.title, href: item.href, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("span", { className: "mt-3 inline-flex items-center gap-2 text-sm font-medium text-sky-100" }, item.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent submissions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (recentEntries || []).map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.id, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, entry.card.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, entry.challenge.title, " • ", entry.status)), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, formatDate$4(entry.submitted_at))), entry.note ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, entry.note) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3 text-sm" }, /* @__PURE__ */ React.createElement(
    "a",
    {
      href: entry.challenge.url,
      onClick: () => trackStudioEvent("studio_challenge_action_taken", {
        surface: studioSurface(),
        module: "challenges",
        item_module: "cards",
        item_id: entry.card?.id,
        meta: {
          action: "open_submission_challenge",
          challenge_id: entry.challenge?.id,
          entry_id: entry.id
        }
      }),
      className: "text-sky-100"
    },
    "Challenge"
  ), /* @__PURE__ */ React.createElement("a", { href: entry.card.edit_url, className: "text-slate-300" }, "Edit card"), /* @__PURE__ */ React.createElement("a", { href: entry.card.analytics_url, className: "text-slate-300" }, "Analytics")))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Cards with challenge traction"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (cardLeaders || []).map((card) => /* @__PURE__ */ React.createElement("div", { key: card.id, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, card.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, card.status, " • ", card.challenge_entries_count, " challenge entries")), /* @__PURE__ */ React.createElement("a", { href: card.edit_url, className: "text-xs font-semibold uppercase tracking-[0.16em] text-sky-100" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(card.views_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(card.comments_count || 0).toLocaleString())))))))));
}
const __vite_glob_0_116 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioChallenges
}, Symbol.toStringTag, { value: "Module" }));
function SummaryCard$2({ label, value, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm" }, label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(value || 0).toLocaleString()));
}
function StudioCollections() {
  const { props } = X$1();
  const summary = props.summary || {};
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-4" }, /* @__PURE__ */ React.createElement(SummaryCard$2, { label: "Collections", value: summary.count, icon: "fa-solid fa-layer-group" }), /* @__PURE__ */ React.createElement(SummaryCard$2, { label: "Drafts", value: summary.draft_count, icon: "fa-solid fa-file-pen" }), /* @__PURE__ */ React.createElement(SummaryCard$2, { label: "Published", value: summary.published_count, icon: "fa-solid fa-rocket" }), /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Collection dashboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6" }, "Open the full collection workflow surface for rules, history, and collaboration."))), /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      hideModuleFilter: true,
      sortStorageKey: "studio-collections-sort"
    }
  ));
}
const __vite_glob_0_117 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioCollections
}, Symbol.toStringTag, { value: "Module" }));
const reportReasons = [
  { value: "spam", label: "Spam or scam" },
  { value: "harassment", label: "Harassment" },
  { value: "abuse", label: "Abusive content" },
  { value: "stolen", label: "Stolen or impersonation" },
  { value: "other", label: "Other" }
];
function formatDate$3(value) {
  if (!value) return "Unknown";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unknown";
  return date.toLocaleString();
}
async function requestJson$5(url, method, body2) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.error || "Request failed");
  }
  return payload;
}
function StudioComments() {
  const { props } = X$1();
  const listing = props.listing || {};
  const filters = listing.filters || {};
  const items = listing.items || [];
  const meta = listing.meta || {};
  const moduleOptions = listing.module_options || [];
  const endpoints = props.endpoints || {};
  const [busyKey, setBusyKey] = reactExports.useState(null);
  const [replyFor, setReplyFor] = reactExports.useState(null);
  const [replyText, setReplyText] = reactExports.useState("");
  const [reportFor, setReportFor] = reactExports.useState(null);
  const [reportReason, setReportReason] = reactExports.useState("spam");
  const [reportDetails, setReportDetails] = reactExports.useState("");
  const visibleSummary = reactExports.useMemo(() => {
    return moduleOptions.filter((option) => option.value !== "all").map((option) => ({
      ...option,
      count: items.filter((item) => item.module === option.value).length
    }));
  }, [items, moduleOptions]);
  const updateFilters = (patch2) => {
    const next = {
      ...filters,
      ...patch2
    };
    if (patch2.page == null) {
      next.page = 1;
    }
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: "comments",
      meta: patch2
    });
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  const buildUrl = (pattern, comment) => pattern.replace("__MODULE__", comment.module).replace("__COMMENT__", String(comment.comment_id));
  const submitReply = async (comment) => {
    if (!replyText.trim()) {
      window.alert("Reply cannot be empty.");
      return;
    }
    const key = `reply:${comment.id}`;
    setBusyKey(key);
    try {
      await requestJson$5(buildUrl(endpoints.replyPattern, comment), "POST", {
        content: replyText.trim()
      });
      trackStudioEvent("studio_comment_replied", {
        surface: studioSurface(),
        module: comment.module,
        item_module: comment.module,
        item_id: comment.item_id
      });
      setReplyFor(null);
      setReplyText("");
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to send reply.");
    } finally {
      setBusyKey(null);
    }
  };
  const moderateComment = async (comment) => {
    if (!window.confirm("Remove this comment from the conversation stream?")) {
      return;
    }
    const key = `moderate:${comment.id}`;
    setBusyKey(key);
    try {
      await requestJson$5(buildUrl(endpoints.moderatePattern, comment), "DELETE");
      trackStudioEvent("studio_comment_moderated", {
        surface: studioSurface(),
        module: comment.module,
        item_module: comment.module,
        item_id: comment.item_id
      });
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to remove comment.");
    } finally {
      setBusyKey(null);
    }
  };
  const submitReport = async (comment) => {
    const key = `report:${comment.id}`;
    setBusyKey(key);
    try {
      await requestJson$5(buildUrl(endpoints.reportPattern, comment), "POST", {
        reason: reportReason,
        details: reportDetails.trim() || null
      });
      trackStudioEvent("studio_comment_reported", {
        surface: studioSurface(),
        module: comment.module,
        item_module: comment.module,
        item_id: comment.item_id
      });
      setReportFor(null);
      setReportReason("spam");
      setReportDetails("");
      window.alert("Report sent.");
    } catch (error) {
      window.alert(error?.message || "Unable to report comment.");
    } finally {
      setBusyKey(null);
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[280px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("aside", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Moderation cockpit"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Search across modules, reply without leaving Studio, and escalate suspicious comments when removal is not enough."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: filters.q || "",
      onChange: (event) => updateFilters({ q: event.target.value }),
      placeholder: "Author, item, or comment",
      className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.module || "all",
      onChange: (value) => updateFilters({ module: value }),
      options: moduleOptions.map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Visible on this page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, visibleSummary.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.value, className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/20 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, item.label), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.count)))))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Showing ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, items.length), " of ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(meta.total || 0).toLocaleString()), " comments"), /* @__PURE__ */ React.createElement("p", null, "Page ", meta.current_page || 1, " of ", meta.last_page || 1)), items.length > 0 ? items.map((comment) => {
    const replyBusy = busyKey === `reply:${comment.id}`;
    const moderateBusy = busyKey === `moderate:${comment.id}`;
    const reportBusy = busyKey === `report:${comment.id}`;
    return /* @__PURE__ */ React.createElement("article", { key: comment.id, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 gap-4" }, comment.author_avatar_url ? /* @__PURE__ */ React.createElement("img", { src: comment.author_avatar_url, alt: comment.author_name, className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-black/30 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, /* @__PURE__ */ React.createElement("span", null, comment.module_label), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, comment.time_ago || formatDate$3(comment.created_at))), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-sky-100" }, comment.author_name), " ", "on", " ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, comment.item_title || "Untitled item")), /* @__PURE__ */ React.createElement("p", { className: "mt-3 whitespace-pre-wrap text-sm leading-6 text-slate-300" }, comment.body))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 md:justify-end" }, comment.preview_url && /* @__PURE__ */ React.createElement("a", { href: comment.preview_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-eye" }), "Preview"), /* @__PURE__ */ React.createElement("a", { href: comment.context_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square" }), "Context"), comment.reply_supported && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => {
          setReportFor(null);
          setReplyFor(replyFor === comment.id ? null : comment.id);
          setReplyText("");
        },
        className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs text-sky-100"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-reply" }),
      "Reply"
    ), comment.moderate_supported && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => moderateComment(comment),
        disabled: moderateBusy,
        className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs text-rose-100 disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash" }),
      moderateBusy ? "Removing..." : "Remove"
    ), comment.report_supported && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => {
          setReplyFor(null);
          setReportFor(reportFor === comment.id ? null : comment.id);
        },
        className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1.5 text-xs text-amber-100"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag" }),
      "Report"
    ))), replyFor === comment.id && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("label", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Reply as creator"), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: replyText,
        onChange: (event) => setReplyText(event.target.value),
        rows: 4,
        placeholder: "Write a public reply",
        className: "mt-3 w-full rounded-2xl border border-white/10 bg-black/30 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500"
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => submitReply(comment),
        disabled: replyBusy,
        className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-paper-plane" }),
      replyBusy ? "Sending..." : "Publish reply"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setReplyFor(null),
        className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200"
      },
      "Cancel"
    ))), reportFor === comment.id && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-[220px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Reason"), /* @__PURE__ */ React.createElement(
      NovaSelect,
      {
        value: reportReason,
        onChange: (value) => setReportReason(value),
        options: reportReasons.map((reason) => ({ value: reason.value, label: reason.label })),
        searchable: false
      }
    )), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Details"), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: reportDetails,
        onChange: (event) => setReportDetails(event.target.value),
        rows: 3,
        placeholder: "Optional note for moderation",
        className: "w-full rounded-2xl border border-white/10 bg-black/30 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500"
      }
    ))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => submitReport(comment),
        disabled: reportBusy,
        className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-300/10 px-4 py-2 text-sm font-semibold text-amber-100 disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag" }),
      reportBusy ? "Sending..." : "Send report"
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setReportFor(null),
        className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200"
      },
      "Cancel"
    ))));
  }) : /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-dashed border-white/15 bg-white/[0.02] px-6 py-16 text-center" }, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, "No comments match this view"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-xl text-sm text-slate-400" }, "Try another module or a broader search query.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: (meta.current_page || 1) <= 1,
      onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }),
    "Previous"
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.2em] text-slate-500" }, "Unified comments"), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: (meta.current_page || 1) >= (meta.last_page || 1),
      onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }),
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40"
    },
    "Next",
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })
  )))));
}
const __vite_glob_0_118 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioComments
}, Symbol.toStringTag, { value: "Module" }));
function StudioContentIndex() {
  const { props } = X$1();
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      emptyTitle: "No content matches this filter",
      emptyBody: "Try broadening your search or create something new from the Studio shell."
    }
  ));
}
const __vite_glob_0_119 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioContentIndex
}, Symbol.toStringTag, { value: "Module" }));
const kpiConfig = [
  { key: "total_content", label: "Total content", icon: "fa-solid fa-table-cells-large" },
  { key: "views_30d", label: "Views", icon: "fa-solid fa-eye" },
  { key: "appreciation_30d", label: "Reactions", icon: "fa-solid fa-heart" },
  { key: "shares_30d", label: "Shares / Saves", icon: "fa-solid fa-share-nodes" },
  { key: "comments_30d", label: "Comments", icon: "fa-solid fa-comments" },
  { key: "followers", label: "Followers", icon: "fa-solid fa-user-group" }
];
function KpiCard({ config, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_40px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl bg-sky-300/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: config.icon })), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, config.label)), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-3xl font-semibold text-white tabular-nums" }, typeof value === "number" ? value.toLocaleString() : value));
}
function QuickCreateCard({ item }) {
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: item.url,
      onClick: () => trackStudioEvent("studio_quick_create_used", {
        surface: studioSurface(),
        module: item.key,
        meta: {
          href: item.url,
          label: item.label
        }
      }),
      className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-4 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold" }, "New ", item.label)),
    /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-sky-100/80" }, "Jump straight into the dedicated ", item.label.toLowerCase(), " creation workflow.")
  );
}
function RecentPublishCard({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Published ", new Date(item.published_at || item.updated_at).toLocaleDateString()));
}
function ContinueWorkingCard({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Updated ", new Date(item.updated_at || item.created_at).toLocaleDateString()));
}
function ScheduledItemCard({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Scheduled ", new Date(item.scheduled_at || item.published_at).toLocaleString()));
}
function ActivityRow({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.url, className: "block rounded-[20px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] uppercase tracking-[0.18em] text-slate-500" }, item.module_label)), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400 line-clamp-2" }, item.body));
}
function GrowthHint({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("span", { className: "mt-4 inline-flex items-center gap-2 text-sm font-medium text-sky-100" }, item.label, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })));
}
function ChallengeWidget({ challenge }) {
  return /* @__PURE__ */ React.createElement("a", { href: challenge.url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, challenge.official ? "Official challenge" : "Community challenge"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, challenge.title)), /* @__PURE__ */ React.createElement("span", { className: "text-[10px] uppercase tracking-[0.16em] text-slate-500" }, challenge.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400 line-clamp-3" }, challenge.prompt || challenge.description), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-3 text-xs text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, Number(challenge.entries_count || 0).toLocaleString(), " entries"), /* @__PURE__ */ React.createElement("span", null, challenge.is_joined ? `${challenge.submission_count} submitted` : "Not joined")));
}
function FeaturedStatusCard({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url || item.view_url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, item.subtitle || item.visibility || "Selected for profile presentation"));
}
function CommandCenterColumn({ title, items = [], empty: empty2, renderItem }) {
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold uppercase tracking-[0.18em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, items.length > 0 ? items.map(renderItem) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 px-4 py-6 text-sm text-slate-500" }, empty2)));
}
function InsightBlock({ item }) {
  const toneClasses2 = {
    positive: "border-emerald-400/20 bg-emerald-400/10 text-emerald-100",
    warning: "border-amber-400/20 bg-amber-400/10 text-amber-100",
    action: "border-sky-400/20 bg-sky-400/10 text-sky-100",
    neutral: "border-white/10 bg-white/[0.03] text-slate-200"
  };
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: item.href,
      onClick: () => trackStudioEvent("studio_insight_clicked", {
        surface: studioSurface(),
        module: "overview",
        meta: {
          insight_key: item.key,
          href: item.href
        }
      }),
      className: `block rounded-[24px] border p-4 transition hover:border-white/20 ${toneClasses2[item.tone] || toneClasses2.neutral}`
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl border border-white/10 bg-black/20" }, /* @__PURE__ */ React.createElement("i", { className: item.icon })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, item.body), /* @__PURE__ */ React.createElement("span", { className: "mt-3 inline-flex items-center gap-2 text-sm font-medium text-inherit" }, item.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))
  );
}
function TopPerformerCard({ item }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, item.image_url && /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-16 w-16 flex-shrink-0 rounded-2xl object-cover", loading: "lazy" }), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h4", { className: "mt-1 truncate text-base font-semibold text-white", title: item.title }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, item.subtitle || item.visibility), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, Number(item.metrics?.views || 0).toLocaleString(), " views"), /* @__PURE__ */ React.createElement("span", null, Number(item.metrics?.appreciation || 0).toLocaleString(), " reactions"), /* @__PURE__ */ React.createElement("span", null, Number(item.metrics?.comments || 0).toLocaleString(), " comments")))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-100" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: item.analytics_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-100" }, "Analytics")));
}
function RecentComment({ comment }) {
  return /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/5 py-3 last:border-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-sky-100" }, comment.author_name), " ", "on", " ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, comment.item_title)), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-500 line-clamp-2" }, comment.body), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-[10px] text-slate-600" }, new Date(comment.created_at).toLocaleDateString()));
}
function StudioDashboard() {
  const { props } = X$1();
  const overview = props.overview || {};
  const analytics = props.analytics || {};
  const kpis = overview.kpis || {};
  const widgetVisibility = overview.preferences?.widget_visibility || {};
  const showWidget = (key) => widgetVisibility[key] !== false;
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: "Overview", subtitle: "Create, manage, and grow across artworks, cards, collections, and stories from one shared creator operating surface." }, /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 lg:grid-cols-5" }, kpiConfig.map((config) => /* @__PURE__ */ React.createElement(KpiCard, { key: config.key, config, value: kpis?.[config.key] ?? 0 }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Command center"), /* @__PURE__ */ React.createElement("a", { href: "/studio/calendar", className: "text-sm font-medium text-sky-100" }, "Open calendar")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-5 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement(
    CommandCenterColumn,
    {
      title: "Publishing today",
      items: overview.command_center?.publishing_today || [],
      empty: "Nothing is scheduled today.",
      renderItem: (item) => /* @__PURE__ */ React.createElement(ScheduledItemCard, { key: item.id, item })
    }
  ), /* @__PURE__ */ React.createElement(
    CommandCenterColumn,
    {
      title: "Attention now",
      items: overview.command_center?.attention_now || [],
      empty: "Inbox is quiet right now.",
      renderItem: (item) => /* @__PURE__ */ React.createElement(ActivityRow, { key: item.id, item })
    }
  ), /* @__PURE__ */ React.createElement(
    CommandCenterColumn,
    {
      title: "Ready to schedule",
      items: overview.workflow_focus?.ready_to_schedule || [],
      empty: "No ready drafts yet.",
      renderItem: (item) => /* @__PURE__ */ React.createElement(ContinueWorkingCard, { key: item.id, item })
    }
  ))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Readable insights"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (overview.insight_blocks || []).map((item) => /* @__PURE__ */ React.createElement(InsightBlock, { key: item.key, item }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, showWidget("module_summaries") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Module health"), /* @__PURE__ */ React.createElement("a", { href: "/studio/content", className: "text-sm font-medium text-sky-100" }, "Open content queue")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, (overview.module_summaries || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold text-white" }, item.label)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-3xl font-semibold text-white" }, Number(item.count || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, Number(item.published_count || 0).toLocaleString(), " published"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-sky-200/70" }, Number(item.trend_value || 0).toLocaleString(), " ", item.trend_label || "recent")), /* @__PURE__ */ React.createElement("div", { className: "text-right text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, Number(item.draft_count || 0).toLocaleString(), " drafts"), /* @__PURE__ */ React.createElement("div", null, Number(item.archived_count || 0).toLocaleString(), " archived"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.index_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-100" }, "Manage"), /* @__PURE__ */ React.createElement("a", { href: item.create_url, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs text-sky-100" }, item.quick_action_label || "Create new")))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Quick create"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, "Start with any module")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, (overview.quick_create || []).map((item) => /* @__PURE__ */ React.createElement(QuickCreateCard, { key: item.key, item }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px_360px]" }, showWidget("active_challenges") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Active challenges"), /* @__PURE__ */ React.createElement("a", { href: "/studio/challenges", onClick: () => trackStudioEvent("studio_challenge_action_taken", { surface: studioSurface(), module: "overview", meta: { action: "open_challenges" } }), className: "text-sm font-medium text-sky-100" }, "Open challenges")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-1" }, (overview.active_challenges?.items || []).map((item) => /* @__PURE__ */ React.createElement(ChallengeWidget, { key: item.id, challenge: item })))), showWidget("featured_status") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Featured status"), /* @__PURE__ */ React.createElement("a", { href: "/studio/featured", className: "text-sm font-medium text-sky-100" }, "Manage featured")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-3xl font-semibold text-white" }, overview.featured_status?.selected_count || 0, "/", overview.featured_status?.target_count || 4), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "modules have a selected featured item")), /* @__PURE__ */ React.createElement("div", { className: "text-right text-xs uppercase tracking-[0.16em] text-slate-500" }, (overview.featured_status?.missing_modules || []).length, " missing"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (overview.featured_status?.items || []).slice(0, 3).map((item) => /* @__PURE__ */ React.createElement(FeaturedStatusCard, { key: item.id, item })))), showWidget("creator_health") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Creator health"), /* @__PURE__ */ React.createElement("a", { href: "/studio/growth", className: "text-sm font-medium text-sky-100" }, "Open growth")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-3xl font-semibold text-white" }, overview.creator_health?.score || 0), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "blended workflow health score")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (overview.creator_health?.checkpoints || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.key, href: item.href, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.detail)), /* @__PURE__ */ React.createElement("span", { className: "text-xl font-semibold text-white" }, item.score))))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, showWidget("continue_working") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Continue working"), /* @__PURE__ */ React.createElement("a", { href: "/studio/drafts", className: "text-sm font-medium text-sky-100" }, "Open drafts")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-3" }, (overview.continue_working || []).map((item) => /* @__PURE__ */ React.createElement(ContinueWorkingCard, { key: item.id, item })))), showWidget("scheduled_items") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Upcoming schedule"), /* @__PURE__ */ React.createElement("a", { href: "/studio/scheduled", className: "text-sm font-medium text-sky-100" }, "Open calendar")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (overview.scheduled_items || []).slice(0, 4).map((item) => /* @__PURE__ */ React.createElement(ScheduledItemCard, { key: item.id, item }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Top performers"), /* @__PURE__ */ React.createElement("a", { href: "/studio/analytics", className: "text-sm font-medium text-sky-100" }, "Open insights")), overview.top_performers?.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, overview.top_performers.map((item) => /* @__PURE__ */ React.createElement(TopPerformerCard, { key: item.id, item }))) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-dashed border-white/15 px-6 py-12 text-center text-slate-400" }, "Nothing has enough activity yet to rank here.")), showWidget("draft_reminders") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Draft reminders"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (overview.draft_reminders || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Updated ", new Date(item.updated_at).toLocaleDateString())))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, showWidget("recent_activity") && /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent activity"), /* @__PURE__ */ React.createElement("a", { href: "/studio/activity", className: "text-sm font-medium text-sky-100" }, "Open inbox")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Recent publishes"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, (overview.recent_publishes || []).slice(0, 4).map((item) => /* @__PURE__ */ React.createElement(RecentPublishCard, { key: item.id, item })))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Recent followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, (overview.recent_followers || []).map((follower) => /* @__PURE__ */ React.createElement("a", { key: follower.id, href: follower.profile_url, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, follower.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: follower.avatar_url, alt: follower.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl bg-white/5 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, follower.name), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, "@", follower.username)))))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Inbox feed"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, (overview.recent_activity || []).slice(0, 4).map((item) => /* @__PURE__ */ React.createElement(ActivityRow, { key: item.id, item })))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Growth hints"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (overview.growth_hints || []).map((item) => /* @__PURE__ */ React.createElement(GrowthHint, { key: item.title, item }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent comments"), /* @__PURE__ */ React.createElement("a", { href: "/studio/comments", className: "text-sm font-medium text-sky-100" }, "View all")), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, (overview.recent_comments || []).length > 0 ? overview.recent_comments.map((comment) => /* @__PURE__ */ React.createElement(RecentComment, { key: comment.id, comment })) : /* @__PURE__ */ React.createElement("p", { className: "py-6 text-center text-sm text-slate-500" }, "No comments yet"))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Momentum"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, [
    ["Views", analytics.totals?.views],
    ["Reactions", analytics.totals?.appreciation],
    ["Shares", analytics.totals?.shares],
    ["Comments", analytics.totals?.comments]
  ].map(([label, value]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(value || 0).toLocaleString()))))))), showWidget("stale_drafts") && /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Stale drafts"), /* @__PURE__ */ React.createElement("a", { href: "/studio/content?bucket=drafts&stale=only&module=stories", className: "text-sm font-medium text-sky-100" }, "Filter stale work")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-4" }, (overview.stale_drafts || []).map((item) => /* @__PURE__ */ React.createElement(ContinueWorkingCard, { key: item.id, item })))));
}
const __vite_glob_0_120 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioDashboard
}, Symbol.toStringTag, { value: "Module" }));
function StudioDrafts() {
  const { props } = X$1();
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      hideBucketFilter: true,
      emptyTitle: "No drafts waiting",
      emptyBody: "Every module is caught up. Create something new or switch to the main content queue."
    }
  ));
}
const __vite_glob_0_121 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioDrafts
}, Symbol.toStringTag, { value: "Module" }));
const modules = [
  { key: "artworks", label: "Artworks" },
  { key: "cards", label: "Cards" },
  { key: "collections", label: "Collections" },
  { key: "stories", label: "Stories" }
];
async function requestJson$4(url, method, body2) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.error || "Request failed");
  }
  return payload;
}
function StudioFeatured() {
  const { props } = X$1();
  const [featuredModules, setFeaturedModules] = reactExports.useState(props.featuredModules || []);
  const [selected, setSelected] = reactExports.useState(props.selected || {});
  const [saving, setSaving] = reactExports.useState(false);
  reactExports.useEffect(() => {
    setFeaturedModules(props.featuredModules || []);
    setSelected(props.selected || {});
  }, [props.featuredModules, props.selected]);
  const groupedItems = reactExports.useMemo(() => {
    return (props.items || []).reduce((accumulator, item) => {
      const key = item.module || "unknown";
      accumulator[key] = [...accumulator[key] || [], item];
      return accumulator;
    }, {});
  }, [props.items]);
  const toggleModule = (module) => {
    setFeaturedModules((current) => current.includes(module) ? current.filter((entry) => entry !== module) : [...current, module]);
  };
  const saveSelections = async () => {
    setSaving(true);
    try {
      await requestJson$4(props.endpoints.save, "PUT", {
        featured_modules: featuredModules,
        featured_content: selected
      });
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to save featured content.");
    } finally {
      setSaving(false);
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Profile highlights"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6" }, "Choose which modules are highlighted on your profile, then assign one representative item to each active module."), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveSelections, disabled: saving, className: "mt-4 inline-flex items-center gap-2 rounded-full border border-sky-300/20 px-4 py-2 text-sm font-semibold disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-floppy-disk" }), saving ? "Saving..." : "Save featured layout")), /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Active modules"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, modules.map((module) => {
    const active = featuredModules.includes(module.key);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: module.key,
        type: "button",
        onClick: () => toggleModule(module.key),
        className: `inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition ${active ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 bg-black/20 text-slate-300"}`
      },
      /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${active ? "fa-circle-check" : "fa-circle"}` }),
      module.label
    );
  }))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, modules.map((module) => {
    const items = groupedItems[module.key] || [];
    const active = featuredModules.includes(module.key);
    return /* @__PURE__ */ React.createElement("section", { key: module.key, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, module.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Select one featured item that represents this module on your profile.")), /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] ${active ? "bg-sky-300/10 text-sky-100" : "bg-white/5 text-slate-500"}` }, active ? "Active" : "Hidden")), items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-5 sm:grid-cols-2 xl:grid-cols-3" }, items.map((item) => {
      const isSelected = Number(selected[module.key] || 0) === Number(item.numeric_id || 0);
      return /* @__PURE__ */ React.createElement("article", { key: item.id, className: `overflow-hidden rounded-[28px] border ${isSelected ? "border-sky-300/30 bg-sky-300/5" : "border-white/10 bg-white/[0.02]"}` }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[1.15/1] bg-slate-950/70" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-full w-full object-cover", loading: "lazy" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: item.module_icon || "fa-solid fa-star" }))), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, item.module_label), /* @__PURE__ */ React.createElement("h3", { className: "truncate text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, item.subtitle || item.visibility || "Published item")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setSelected((current) => ({ ...current, [module.key]: item.numeric_id })), className: `inline-flex h-10 w-10 items-center justify-center rounded-full border ${isSelected ? "border-sky-300/30 bg-sky-300/10 text-sky-100" : "border-white/10 bg-black/20 text-slate-400"}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${isSelected ? "fa-check" : "fa-star"}` }))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.views || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Reactions"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.appreciation || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.comments || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-100" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: item.preview_url || item.view_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-100" }, "Preview"))));
    })) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-dashed border-white/15 px-6 py-10 text-center text-sm text-slate-400" }, "No published ", module.label.toLowerCase(), " candidates yet."));
  })));
}
const __vite_glob_0_122 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioFeatured
}, Symbol.toStringTag, { value: "Module" }));
function SummaryCard$1({ label, value, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm" }, label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(value || 0).toLocaleString()));
}
function StudioFollowers() {
  const { props } = X$1();
  const listing = props.listing || {};
  const filters = listing.filters || {};
  const summary = listing.summary || {};
  const items = listing.items || [];
  const meta = listing.meta || {};
  const updateQuery = (patch2) => {
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: "followers",
      meta: {
        patch: patch2
      }
    });
    At.get(window.location.pathname, { ...filters, ...patch2 }, { preserveScroll: true, preserveState: true, replace: true });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(SummaryCard$1, { label: "Total followers", value: summary.total_followers, icon: "fa-solid fa-user-group" }), /* @__PURE__ */ React.createElement(SummaryCard$1, { label: "Following back", value: summary.following_back, icon: "fa-solid fa-arrows-rotate" }), /* @__PURE__ */ React.createElement(SummaryCard$1, { label: "Not followed yet", value: summary.not_followed, icon: "fa-solid fa-user-plus" })), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-[minmax(0,1fr)_220px_220px]" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateQuery({ q: event.target.value, page: 1 }), placeholder: "Search followers", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Sort"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.sort || "recent", onChange: (val) => updateQuery({ sort: val, page: 1 }), options: listing.sort_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Relationship"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.relationship || "all", onChange: (val) => updateQuery({ relationship: val, page: 1 }), options: listing.relationship_options || [], searchable: false }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "flex flex-col gap-4 rounded-[24px] border border-white/10 bg-black/20 p-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("a", { href: item.profile_url, className: "flex min-w-0 items-center gap-4" }, item.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.avatar_url, alt: item.username, className: "h-14 w-14 rounded-[18px] object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 items-center justify-center rounded-[18px] bg-white/5 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, item.name), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "@", item.username))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 text-sm text-slate-400 md:grid-cols-4 md:text-right" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Uploads"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.uploads_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.followers_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Followed"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.followed_at ? new Date(item.followed_at).toLocaleDateString() : "—")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Status"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.is_following_back ? "Following back" : "Not followed")))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateQuery({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }), "Previous"), /* @__PURE__ */ React.createElement("span", null, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateQuery({ page: (meta.current_page || 1) + 1 }), className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })))));
}
const __vite_glob_0_123 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioFollowers
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupActivity() {
  const { props } = X$1();
  const items = Array.isArray(props.activity) ? props.activity : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h2", { className: "text-base font-semibold text-white" }, item.headline), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Pinned") : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.visibility)), item.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, item.actor?.name || item.actor?.username || "System", " • ", item.occurred_at ? new Date(item.occurred_at).toLocaleString() : "Recently"), item.subject?.url ? /* @__PURE__ */ React.createElement("a", { href: item.subject.url, className: "mt-3 inline-flex text-sm font-semibold text-sky-200" }, "Open subject") : null), props.pinPattern ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.pinPattern.replace("__ITEM__", String(item.id)), { is_pinned: !item.is_pinned }), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-sm font-semibold text-white" }, item.is_pinned ? "Unpin" : "Pin") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No activity yet.")));
}
const __vite_glob_0_124 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupActivity
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupArtworks() {
  const { props } = X$1();
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em]" }, "Group publish flow"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold" }, "Upload into ", props.studioGroup?.name), /* @__PURE__ */ React.createElement("a", { href: props.uploadUrl, className: "mt-4 inline-flex rounded-full border border-sky-200/20 bg-sky-200/10 px-4 py-2 text-sm font-semibold text-sky-50" }, "New group artwork")), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: [{ key: "artworks", label: "Artwork", icon: "fa-solid fa-cloud-arrow-up", url: props.uploadUrl }], hideModuleFilter: true }));
}
const __vite_glob_0_125 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupArtworks
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupAssets() {
  const { props } = X$1();
  const items = Array.isArray(props.listing?.items) ? props.listing.items : [];
  const filters = G$1({
    q: props.listing?.filters?.q || "",
    category: props.listing?.filters?.category || "all",
    bucket: props.listing?.filters?.bucket || "all"
  });
  const form = G$1({
    title: "",
    description: "",
    category: props.categoryOptions?.[0]?.value || "misc",
    visibility: props.visibilityOptions?.[0]?.value || "members_only",
    status: props.statusOptions?.[0]?.value || "active",
    linked_project_id: "",
    is_featured: false,
    file: null
  });
  const submit = (event) => {
    event.preventDefault();
    if (!props.storeUrl) return;
    form.post(props.storeUrl, { forceFormData: true, preserveScroll: true });
  };
  const applyFilters = (event) => {
    event.preventDefault();
    At.get(props.studioGroup?.urls?.studio_assets || window.location.pathname, {
      q: filters.data.q || void 0,
      category: filters.data.category !== "all" ? filters.data.category : void 0,
      bucket: filters.data.bucket !== "all" ? filters.data.bucket : void 0
    }, {
      preserveState: true,
      preserveScroll: true,
      replace: true
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, props.storeUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-6" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Asset title", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none lg:col-span-2" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.category, onChange: (val) => form.setData("category", val), options: props.categoryOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: props.visibilityOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.status, onChange: (val) => form.setData("status", val), options: props.statusOptions || [], searchable: false }), /* @__PURE__ */ React.createElement("input", { type: "file", onChange: (event) => form.setData("file", event.target.files?.[0] || null), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), placeholder: "What is this asset for?", rows: 3, className: "mt-4 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_project_id || ""), onChange: (val) => form.setData("linked_project_id", val), placeholder: "No linked project", options: (props.projectOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_featured, onChange: (event) => form.setData("is_featured", event.target.checked), label: "Featured asset" }))), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Upload asset")) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Browse library"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Search and filter shared assets by visibility and category.")), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Apply filters")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("input", { value: filters.data.q, onChange: (event) => filters.setData("q", event.target.value), placeholder: "Search title, description, or filename", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.data.category, onChange: (val) => filters.setData("category", val), options: [{ value: "all", label: "All categories" }, ...props.categoryOptions || []], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.data.bucket, onChange: (val) => filters.setData("bucket", val), options: [{ value: "all", label: "All visibility levels" }, ...(props.listing?.bucket_options || []).filter((option) => option.value !== "all")], searchable: false }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((asset) => /* @__PURE__ */ React.createElement("div", { key: asset.id, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, asset.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, asset.category, " • ", asset.visibility, " • ", asset.status)), /* @__PURE__ */ React.createElement("a", { href: asset.download_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-sm font-semibold text-white" }, "Download")), asset.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, asset.description) : null, props.updatePattern ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.patch(props.updatePattern.replace("__ASSET__", String(asset.id)), { title: asset.title, description: asset.description || "", category: asset.category, visibility: asset.visibility, status: asset.status === "active" ? "archived" : "active", linked_project_id: asset.linked_project?.id || "", is_featured: asset.is_featured }), className: "mt-4 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, asset.status === "active" ? "Archive" : "Reactivate") : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No assets yet.")));
}
const __vite_glob_0_126 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupAssets
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupChallengeEditor() {
  const { props } = X$1();
  const challenge = props.challenge || null;
  const outcomeArtworkOptions = Array.isArray(challenge?.artworks) ? challenge.artworks : [];
  const form = G$1({
    title: challenge?.title || "",
    summary: challenge?.summary || "",
    description: challenge?.description || "",
    visibility: challenge?.visibility || props.visibilityOptions?.[0]?.value || "public",
    participation_scope: challenge?.participation_scope || props.participationScopeOptions?.[0]?.value || "group_only",
    status: challenge?.status || props.statusOptions?.[0]?.value || "draft",
    start_at: challenge?.start_at ? challenge.start_at.slice(0, 16) : "",
    end_at: challenge?.end_at ? challenge.end_at.slice(0, 16) : "",
    rules_text: challenge?.rules_text || "",
    submission_instructions: challenge?.submission_instructions || "",
    judging_mode: challenge?.judging_mode || "",
    linked_collection_id: challenge?.linked_collection?.id || "",
    linked_project_id: challenge?.linked_project?.id || "",
    featured_artwork_id: challenge?.featured_artwork?.id || "",
    outcomes: Array.isArray(challenge?.outcomes) ? challenge.outcomes.map((outcome) => ({
      artwork_id: outcome.artwork_id || "",
      outcome_type: outcome.outcome_type || props.outcomeTypeOptions?.[0]?.value || "winner",
      position: outcome.position || "",
      sort_order: outcome.sort_order ?? 0,
      title_override: outcome.title_override || "",
      note: outcome.note || ""
    })) : [],
    cover_file: null
  });
  const attachForm = G$1({ artwork_id: "" });
  const submit = (event) => {
    event.preventDefault();
    const options = { forceFormData: true, preserveScroll: true };
    if (props.updateUrl) {
      form.post(props.updateUrl, { ...options, _method: "patch" });
      return;
    }
    form.post(props.storeUrl, options);
  };
  const updateOutcome = (index2, key, value) => {
    const next = [...form.data.outcomes || []];
    next[index2] = { ...next[index2], [key]: value };
    form.setData("outcomes", next);
  };
  const addOutcome = () => {
    form.setData("outcomes", [
      ...form.data.outcomes || [],
      {
        artwork_id: outcomeArtworkOptions[0]?.id || "",
        outcome_type: props.outcomeTypeOptions?.[0]?.value || "winner",
        position: "",
        sort_order: form.data.outcomes?.length || 0,
        title_override: "",
        note: ""
      }
    ]);
  };
  const removeOutcome = (index2) => {
    form.setData("outcomes", (form.data.outcomes || []).filter((_2, currentIndex) => currentIndex !== index2));
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Challenge title", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.summary, onChange: (event) => form.setData("summary", event.target.value), placeholder: "Short summary", rows: 3, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), placeholder: "Challenge description", rows: 8, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: props.visibilityOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.participation_scope, onChange: (val) => form.setData("participation_scope", val), options: props.participationScopeOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.status, onChange: (val) => form.setData("status", val), options: props.statusOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.start_at, onChange: (nextValue) => form.setData("start_at", nextValue), placeholder: "Challenge start", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.end_at, onChange: (nextValue) => form.setData("end_at", nextValue), placeholder: "Challenge end", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("textarea", { value: form.data.rules_text, onChange: (event) => form.setData("rules_text", event.target.value), placeholder: "Rules", rows: 4, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.submission_instructions, onChange: (event) => form.setData("submission_instructions", event.target.value), placeholder: "Submission instructions", rows: 4, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.judging_mode || "", onChange: (val) => form.setData("judging_mode", val), placeholder: "No judging mode", options: (props.judgingModeOptions || []).map((o) => ({ value: o.value, label: o.label })), searchable: false }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_collection_id || ""), onChange: (val) => form.setData("linked_collection_id", val), placeholder: "No linked collection", options: (props.collectionOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_project_id || ""), onChange: (val) => form.setData("linked_project_id", val), placeholder: "No linked project", options: (props.projectOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-6 text-slate-300" }, "Featured result rendering now comes from structured outcomes. Attach entries first, then assign winners and finalists below.")), /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/*", onChange: (event) => form.setData("cover_file", event.target.files?.[0] || null), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), props.updateUrl ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Challenge outcomes"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, "Choose from attached challenge entries only. These outcomes now drive public winners, finalists, and linked-world reward automation.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addOutcome, className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Add outcome")), outcomeArtworkOptions.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-dashed border-white/10 bg-black/20 p-4 text-sm leading-6 text-slate-400" }, "Attach challenge entries first. Outcomes are intentionally limited to artworks already entered into this challenge.") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, (form.data.outcomes || []).map((outcome, index2) => /* @__PURE__ */ React.createElement("div", { key: `${outcome.artwork_id || "new"}-${index2}`, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(outcome.artwork_id || ""), onChange: (val) => updateOutcome(index2, "artwork_id", val), placeholder: "Choose challenge entry", options: outcomeArtworkOptions.map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: outcome.outcome_type, onChange: (val) => updateOutcome(index2, "outcome_type", val), options: props.outcomeTypeOptions || [], searchable: false }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeOutcome(index2), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-slate-300" }, "Remove")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-3 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("input", { value: outcome.position, onChange: (event) => updateOutcome(index2, "position", event.target.value), placeholder: "Position", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: outcome.sort_order, onChange: (event) => updateOutcome(index2, "sort_order", event.target.value), placeholder: "Sort order", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: outcome.title_override, onChange: (event) => updateOutcome(index2, "title_override", event.target.value), placeholder: "Optional label override", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: outcome.note, onChange: (event) => updateOutcome(index2, "note", event.target.value), placeholder: "Optional editorial note", rows: 3, className: "mt-3 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))))) : null), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-6 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Save challenge")), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, props.publishUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    form.post(props.publishUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Publish challenge")) : null, props.attachArtworkUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    attachForm.post(props.attachArtworkUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attach artwork"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(attachForm.data.artwork_id || ""), onChange: (val) => attachForm.setData("artwork_id", val), placeholder: "Choose artwork", options: (props.artworkOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Attach")) : null)));
}
const __vite_glob_0_127 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupChallengeEditor
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupChallenges() {
  const { props } = X$1();
  const items = Array.isArray(props.listing?.items) ? props.listing.items : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Challenges keep the group active between releases and give members a focused creative prompt."), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create challenge") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((challenge) => /* @__PURE__ */ React.createElement("a", { key: challenge.id, href: challenge.urls?.edit || challenge.url, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, challenge.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, challenge.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, challenge.summary || "Challenge page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, challenge.entry_count || 0, " linked entries"))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No challenges yet.")));
}
const __vite_glob_0_128 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupChallenges
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupCollections() {
  const { props } = X$1();
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em]" }, "Shared curation"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold" }, "Create collections for ", props.studioGroup?.name), /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "mt-4 inline-flex rounded-full border border-sky-200/20 bg-sky-200/10 px-4 py-2 text-sm font-semibold text-sky-50" }, "New group collection")), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: [{ key: "collections", label: "Collection", icon: "fa-solid fa-layer-group", url: props.createUrl }], hideModuleFilter: true }));
}
const __vite_glob_0_129 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupCollections
}, Symbol.toStringTag, { value: "Module" }));
function GroupStudioPromoCard({ title, description, bullets = [], primaryLabel, primaryHref, secondaryLabel, secondaryHref }) {
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-6 shadow-[0_18px_55px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Studio groups"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-6 text-slate-300" }, description), bullets.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-3" }, bullets.map((bullet) => /* @__PURE__ */ React.createElement("div", { key: bullet.title, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, bullet.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-400" }, bullet.body)))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, primaryHref ? /* @__PURE__ */ React.createElement("a", { href: primaryHref, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, primaryLabel) : null, secondaryHref ? /* @__PURE__ */ React.createElement("a", { href: secondaryHref, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.07]" }, secondaryLabel) : null));
}
function slugifyGroupValue(value) {
  return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 90);
}
function resolveMediaPreviewUrl$1(path, filesCdnUrl) {
  const trimmed = String(path || "").trim();
  if (!trimmed) {
    return "";
  }
  if (trimmed.startsWith("blob:") || trimmed.startsWith("data:") || trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
    return trimmed;
  }
  return `${String(filesCdnUrl || "").replace(/\/$/, "")}/${trimmed.replace(/^\/+/, "")}`;
}
function StudioGroupCreate() {
  const { props } = X$1();
  const filesCdnUrl = props?.cdn?.files_url || "";
  const avatarInputRef = reactExports.useRef(null);
  const bannerInputRef = reactExports.useRef(null);
  const [slugManuallyEdited, setSlugManuallyEdited] = reactExports.useState(false);
  const [form, setForm] = reactExports.useState({
    name: "",
    slug: "",
    headline: "",
    bio: "",
    type: "",
    founded_at: "",
    avatar_path: "",
    banner_path: "",
    visibility: "public",
    membership_policy: "invite_only",
    website_url: "",
    links_json: [{ label: "", url: "" }],
    avatar_file: null,
    banner_file: null
  });
  const [avatarPreview, setAvatarPreview] = reactExports.useState("");
  const [bannerPreview, setBannerPreview] = reactExports.useState("");
  const resolvedAvatarPreview = reactExports.useMemo(() => avatarPreview || resolveMediaPreviewUrl$1(form.avatar_path, filesCdnUrl), [avatarPreview, form.avatar_path, filesCdnUrl]);
  const resolvedBannerPreview = reactExports.useMemo(() => bannerPreview || resolveMediaPreviewUrl$1(form.banner_path, filesCdnUrl), [bannerPreview, form.banner_path, filesCdnUrl]);
  const updateLink = (index2, key, value) => {
    setForm((current) => ({
      ...current,
      links_json: current.links_json.map((item, itemIndex) => itemIndex === index2 ? { ...item, [key]: value } : item)
    }));
  };
  const addLink = () => {
    setForm((current) => ({
      ...current,
      links_json: [...current.links_json, { label: "", url: "" }]
    }));
  };
  const removeLink = (index2) => {
    setForm((current) => ({
      ...current,
      links_json: current.links_json.filter((_2, itemIndex) => itemIndex !== index2)
    }));
  };
  const submit = () => {
    At.post(props.endpoints?.store, {
      ...form,
      links_json: form.links_json.filter((item) => item.label.trim() !== "" || item.url.trim() !== "")
    }, {
      forceFormData: true
    });
  };
  const handleFileSelected = (field, setPreview) => (event) => {
    const file = event.target.files?.[0] || null;
    setForm((current) => ({ ...current, [field]: file }));
    setPreview(file ? URL.createObjectURL(file) : "");
  };
  const clearSelectedFile = (field, setPreview, inputRef) => {
    setForm((current) => ({ ...current, [field]: null }));
    setPreview("");
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };
  const handleNameChange = (event) => {
    const nextName = event.target.value;
    setForm((current) => ({
      ...current,
      name: nextName,
      slug: slugManuallyEdited ? current.slug : slugifyGroupValue(nextName)
    }));
  };
  const handleSlugChange = (event) => {
    const nextSlug = slugifyGroupValue(event.target.value);
    setSlugManuallyEdited(nextSlug !== "");
    setForm((current) => ({ ...current, slug: nextSlug }));
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto mb-6 max-w-5xl" }, /* @__PURE__ */ React.createElement(
    GroupStudioPromoCard,
    {
      title: "Set up the public identity before the first release",
      description: "A strong group page makes collaborative publishing legible: who leads the team, what kind of work you make, and why contributors should join or follow.",
      bullets: [
        { title: "Headline first", body: "Use the headline to explain what the collective publishes and what makes the group distinct." },
        { title: "Recruit with clarity", body: "After creation, configure recruitment so open roles surface across search and browse experiences." },
        { title: "Own the presentation", body: "Avatar, cover art, and links shape how the group appears on artworks, profile summaries, and leaderboards." }
      ],
      primaryLabel: "Back to groups",
      primaryHref: "/studio/groups",
      secondaryLabel: "Browse public groups",
      secondaryHref: "/groups"
    }
  )), /* @__PURE__ */ React.createElement("section", { className: "mx-auto max-w-3xl rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Name"), /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: handleNameChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: handleSlugChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Short description"), /* @__PURE__ */ React.createElement("input", { value: form.headline, onChange: (event) => setForm((current) => ({ ...current, headline: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "About"), /* @__PURE__ */ React.createElement("textarea", { value: form.bio, onChange: (event) => setForm((current) => ({ ...current, bio: event.target.value })), rows: 6, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Type / category"), /* @__PURE__ */ React.createElement("input", { value: form.type, onChange: (event) => setForm((current) => ({ ...current, type: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Founded date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.founded_at, onChange: (nextValue) => setForm((current) => ({ ...current, founded_at: nextValue })), mode: "date", placeholder: "Pick the founding date", clearable: true, className: "bg-black/20" }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Website"), /* @__PURE__ */ React.createElement("input", { value: form.website_url, onChange: (event) => setForm((current) => ({ ...current, website_url: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Avatar / logo"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-28 items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedAvatarPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedAvatarPreview, alt: "Avatar preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: avatarInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("avatar_file", setAvatarPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => avatarInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload avatar"), form.avatar_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("avatar_file", setAvatarPreview, avatarInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use URL instead") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.avatar_path, onChange: (event) => setForm((current) => ({ ...current, avatar_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Cover image"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-full items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedBannerPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedBannerPreview, alt: "Cover preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-panorama text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: bannerInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("banner_file", setBannerPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => bannerInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload cover"), form.banner_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("banner_file", setBannerPreview, bannerInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use URL instead") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.banner_path, onChange: (event) => setForm((current) => ({ ...current, banner_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => setForm((current) => ({ ...current, visibility: val })), options: props.visibilityOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Membership policy"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.membership_policy, onChange: (val) => setForm((current) => ({ ...current, membership_policy: val })), options: props.membershipPolicyOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-200" }, "Links"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addLink, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Add link")), form.links_json.map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: `link-${index2}`, className: "grid gap-3 md:grid-cols-[0.8fr_1.2fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: item.label, onChange: (event) => updateLink(index2, "label", event.target.value), placeholder: "Label", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: item.url, onChange: (event) => updateLink(index2, "url", event.target.value), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeLink(index2), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Remove")))), /* @__PURE__ */ React.createElement("div", { className: "flex justify-end gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/studio/groups", className: "rounded-full border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-semibold text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: submit, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Create group")))));
}
const __vite_glob_0_130 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupCreate
}, Symbol.toStringTag, { value: "Module" }));
function StatCard({ label, value, icon }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: icon }), /* @__PURE__ */ React.createElement("span", null, label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(value || 0).toLocaleString()));
}
function ContentCard({ item, fallbackLabel }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.manage_url || item.urls?.edit || item.edit_url || item.preview_url || item.view_url || item.url, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 transition hover:border-white/20" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "aspect-[4/3] w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[4/3] items-center justify-center bg-white/[0.03] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-2xl" })), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.status || item.event_type || fallbackLabel)), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, item.subtitle || item.description || item.summary || fallbackLabel)));
}
function EmptyCard({ title, description }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 leading-6" }, description));
}
function ActivityCard({ item }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.headline), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Pinned") : null), item.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, item.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, item.actor?.name || item.actor?.username || "System", " • ", item.occurred_at ? new Date(item.occurred_at).toLocaleString() : "Recently"), item.subject?.url ? /* @__PURE__ */ React.createElement("a", { href: item.subject.url, className: "mt-3 inline-flex text-sm font-semibold text-sky-200" }, "Open subject") : null);
}
function StudioGroupDashboard() {
  const { props } = X$1();
  const group = props.studioGroup;
  const members = Array.isArray(props.members) ? props.members : [];
  const dashboard = props.dashboard || {};
  const draftsPendingAction = Array.isArray(props.draftsPendingAction) ? props.draftsPendingAction : [];
  const recentArtworks = Array.isArray(props.recentArtworks) ? props.recentArtworks : [];
  const recentCollections = Array.isArray(props.recentCollections) ? props.recentCollections : [];
  const recentPosts = Array.isArray(props.recentPosts) ? props.recentPosts : [];
  const recentProjects = Array.isArray(props.recentProjects) ? props.recentProjects : [];
  const recentReleases = Array.isArray(props.recentReleases) ? props.recentReleases : [];
  const recentChallenges = Array.isArray(props.recentChallenges) ? props.recentChallenges : [];
  const recentEvents = Array.isArray(props.recentEvents) ? props.recentEvents : [];
  const recentActivity = Array.isArray(props.recentActivity) ? props.recentActivity : [];
  const trustSignals = Array.isArray(props.trustSignals) ? props.trustSignals : [];
  const reputationSummary = props.reputationSummary || {};
  const pendingJoinRequests = Array.isArray(props.pendingJoinRequests) ? props.pendingJoinRequests : [];
  const reviewQueuePreview = Array.isArray(props.reviewQueuePreview) ? props.reviewQueuePreview : [];
  const recruitment = props.recruitment || null;
  const recentHistory = Array.isArray(props.recentHistory) ? props.recentHistory : [];
  const roleSummary = members.reduce((summary, member) => {
    const role = String(member.role || "member");
    summary[role] = (summary[role] || 0) + 1;
    return summary;
  }, {});
  const quickActions = [
    { label: "Upload artwork", href: group?.urls?.upload, icon: "fa-solid fa-cloud-arrow-up", tone: "sky", detail: "Start a new group-published artwork." },
    { label: "Invite member", href: group?.urls?.studio_invitations, icon: "fa-solid fa-user-plus", tone: "emerald", detail: `Manage invites${Number(dashboard.pending_invites_count || 0) > 0 ? ` (${Number(dashboard.pending_invites_count)})` : ""}.` },
    { label: "Review queue", href: group?.urls?.studio_review, icon: "fa-solid fa-list-check", tone: "amber", detail: `${Number(dashboard.pending_reviews_count || 0)} submissions waiting.` },
    { label: "Posts", href: group?.urls?.studio_posts, icon: "fa-solid fa-bullhorn", tone: "violet", detail: `${Number(dashboard.published_posts_count || 0)} published posts.` },
    { label: "Projects", href: group?.urls?.studio_projects, icon: "fa-solid fa-diagram-project", tone: "sky", detail: `${Number(dashboard.projects_count || 0)} total projects.` },
    { label: "Releases", href: group?.urls?.studio_releases, icon: "fa-solid fa-rocket", tone: "amber", detail: `${Number(dashboard.published_releases_count || 0)} published releases.` },
    { label: "Challenges", href: group?.urls?.studio_challenges, icon: "fa-solid fa-trophy", tone: "amber", detail: `${Number(dashboard.active_challenges_count || 0)} active or published.` },
    { label: "Events", href: group?.urls?.studio_events, icon: "fa-solid fa-calendar-day", tone: "emerald", detail: `${Number(dashboard.events_count || 0)} scheduled or archived.` },
    { label: "Assets", href: group?.urls?.studio_assets, icon: "fa-solid fa-box-archive", tone: "violet", detail: `${Number(dashboard.assets_count || 0)} shared files.` },
    { label: "Reputation", href: group?.urls?.studio_reputation, icon: "fa-solid fa-shield-heart", tone: "sky", detail: `${Number(reputationSummary?.counts?.contributors || 0)} contributors tracked.` },
    { label: "Activity", href: group?.urls?.studio_activity, icon: "fa-solid fa-wave-square", tone: "sky", detail: `${Number(dashboard.activity_count || 0)} feed items recorded.` },
    { label: "Edit profile", href: group?.urls?.studio_settings, icon: "fa-solid fa-pen-to-square", tone: "amber", detail: "Update headline, visuals, and links." },
    { label: "Recruitment", href: group?.urls?.studio_recruitment, icon: "fa-solid fa-user-plus", tone: "emerald", detail: recruitment?.is_recruiting ? "Recruitment is live." : "Configure recruiting status." },
    { label: "Create collection", href: group?.urls?.collection_create, icon: "fa-solid fa-layer-group", tone: "violet", detail: "Publish a new collection under this group." }
  ].filter((item) => Boolean(item.href));
  const toneClasses2 = {
    sky: "border-sky-300/20 bg-sky-300/10 text-sky-100",
    emerald: "border-emerald-300/20 bg-emerald-300/10 text-emerald-100",
    amber: "border-amber-300/20 bg-amber-300/10 text-amber-100",
    violet: "border-violet-300/20 bg-violet-300/10 text-violet-100"
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3 xl:grid-cols-6" }, /* @__PURE__ */ React.createElement(StatCard, { label: "Artworks", value: group?.counts?.artworks, icon: "fa-solid fa-images" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Collections", value: group?.counts?.collections, icon: "fa-solid fa-layer-group" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Followers", value: group?.counts?.followers, icon: "fa-solid fa-user-group" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Active members", value: dashboard?.active_members_count || group?.counts?.members, icon: "fa-solid fa-people-group" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Projects", value: dashboard?.projects_count, icon: "fa-solid fa-diagram-project" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Releases", value: dashboard?.published_releases_count || dashboard?.releases_count, icon: "fa-solid fa-rocket" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Assets", value: dashboard?.assets_count, icon: "fa-solid fa-box-archive" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Quick actions"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Run the most common group tasks without leaving the dashboard."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, quickActions.map((action) => /* @__PURE__ */ React.createElement("a", { key: action.label, href: action.href, className: `rounded-[24px] border px-4 py-4 transition hover:translate-y-[-1px] hover:border-white/20 ${toneClasses2[action.tone] || toneClasses2.sky}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-current/20 bg-black/10" }, /* @__PURE__ */ React.createElement("i", { className: action.icon })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, action.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs opacity-80" }, action.detail)))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Pending action"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Drafts and scheduled items that still need a publishing decision.")), /* @__PURE__ */ React.createElement("div", { className: "text-right text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, Number(dashboard?.draft_artworks_count || 0), " drafts"), /* @__PURE__ */ React.createElement("div", null, Number(dashboard?.scheduled_artworks_count || 0), " scheduled"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, draftsPendingAction.length > 0 ? draftsPendingAction.map((artwork) => /* @__PURE__ */ React.createElement(ContentCard, { key: artwork.id, item: artwork, fallbackLabel: "Draft" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No drafts waiting", description: "This group has no draft artworks waiting for review or completion right now." }))), pendingJoinRequests.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Pending join requests"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Applicants waiting for a review decision.")), group?.urls?.studio_join_requests ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_join_requests, className: "text-sm font-semibold text-sky-200" }, "Open queue") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, pendingJoinRequests.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.user?.name || item.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, item.desired_role_label || item.desired_role || "Contributor", " • ", item.created_at ? new Date(item.created_at).toLocaleDateString() : "New"))))) : null), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Members"), /* @__PURE__ */ React.createElement("a", { href: group?.urls?.studio_members, className: "text-sm font-semibold text-sky-200" }, "Manage")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2 sm:grid-cols-2" }, Object.entries(roleSummary).map(([role, count]) => /* @__PURE__ */ React.createElement("div", { key: role, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, role), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xl font-semibold text-white" }, Number(count))))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, members.slice(0, 6).map((member) => /* @__PURE__ */ React.createElement("div", { key: member.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, member.role))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recruitment"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, recruitment?.is_recruiting ? recruitment.headline || "Recruiting is active" : "Recruitment is off"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, recruitment?.description || "Set open roles, skills, and contact instructions from the recruitment page.")))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Releases"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Track featured drops and current release pipelines.")), group?.urls?.studio_releases ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_releases, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentReleases.length > 0 ? recentReleases.map((release) => /* @__PURE__ */ React.createElement(ContentCard, { key: release.id, item: release, fallbackLabel: "Release" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No releases yet", description: "Create a release to track milestones, contributors, and publication status." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Projects"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Recent structured releases and collaboration hubs.")), group?.urls?.studio_projects ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_projects, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentProjects.length > 0 ? recentProjects.map((project) => /* @__PURE__ */ React.createElement(ContentCard, { key: project.id, item: project, fallbackLabel: "Project" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No projects yet", description: "Create a project to bundle shared assets, linked artworks, and a release state." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Challenges"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Current creative prompts and challenge arcs.")), group?.urls?.studio_challenges ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_challenges, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentChallenges.length > 0 ? recentChallenges.map((challenge) => /* @__PURE__ */ React.createElement(ContentCard, { key: challenge.id, item: challenge, fallbackLabel: "Challenge" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No challenges yet", description: "Launch a challenge to keep the group active between major releases." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Trust summary"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Public-facing trust labels and internal contributor health snapshot.")), group?.urls?.studio_reputation ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_reputation, className: "text-sm font-semibold text-sky-200" }, "Open dashboard") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, trustSignals.map((signal) => /* @__PURE__ */ React.createElement("span", { key: signal.key, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, signal.label))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputationSummary?.counts?.contributors || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Group badges"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputationSummary?.counts?.group_badges || 0))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Contributor highlights"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Recent high-trust contributors and badge unlocks."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, Array.isArray(reputationSummary?.top_contributors) && reputationSummary.top_contributors.length > 0 ? reputationSummary.top_contributors.slice(0, 4).map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.user?.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, entry.user?.name || entry.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, entry.summary || "Contributor"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, entry.counts?.releases || 0, " releases • ", entry.counts?.credited_artworks || 0, " artworks"))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No contributor signals yet", description: "Release and milestone activity will populate contributor reputation here." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent artworks"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Latest published work released under this group identity.")), /* @__PURE__ */ React.createElement("a", { href: group?.urls?.studio_artworks, className: "text-sm font-semibold text-sky-200" }, "View all")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentArtworks.length > 0 ? recentArtworks.map((artwork) => /* @__PURE__ */ React.createElement(ContentCard, { key: artwork.id, item: artwork, fallbackLabel: "Published" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No published artworks yet", description: "Publish the first group artwork to start building this feed." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Events"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Upcoming or recently updated moments on the group timeline.")), group?.urls?.studio_events ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_events, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentEvents.length > 0 ? recentEvents.map((event) => /* @__PURE__ */ React.createElement(ContentCard, { key: event.id, item: event, fallbackLabel: "Event" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No events yet", description: "Schedule a launch, stream, or milestone to start the group timeline." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Collections most recently updated in this group workspace.")), /* @__PURE__ */ React.createElement("a", { href: group?.urls?.studio_collections, className: "text-sm font-semibold text-sky-200" }, "View all")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentCollections.length > 0 ? recentCollections.map((collection) => /* @__PURE__ */ React.createElement(ContentCard, { key: collection.id, item: collection, fallbackLabel: "Collection" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No collections yet", description: "Create a collection to organize group work into campaigns, series, or themed sets." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Activity feed"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Pinned and recent internal or public timeline items.")), group?.urls?.studio_activity ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_activity, className: "text-sm font-semibold text-sky-200" }, "Open feed") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, recentActivity.length > 0 ? recentActivity.map((item) => /* @__PURE__ */ React.createElement(ActivityCard, { key: item.id, item })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No activity items yet", description: "Publishing projects, events, posts, and member milestones will populate this feed." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Review queue"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Latest artwork submissions waiting for moderation.")), group?.urls?.studio_review ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_review, className: "text-sm font-semibold text-sky-200" }, "Open queue") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, reviewQueuePreview.length > 0 ? reviewQueuePreview.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.urls?.edit, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.group_review_status))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No pending reviews", description: "Contributor submissions will appear here when they are sent for review." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent posts"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Announcements and updates published from the group.")), group?.urls?.studio_posts ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_posts, className: "text-sm font-semibold text-sky-200" }, "Manage posts") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentPosts.length > 0 ? recentPosts.map((post2) => /* @__PURE__ */ React.createElement("a", { key: post2.id, href: post2.url, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, post2.type), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, post2.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, post2.excerpt || "Open post"))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No posts yet", description: "Create the first group announcement to add a public news feed." })))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent history"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, recentHistory.length > 0 ? recentHistory.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.summary || item.action_type), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-400" }, item.actor?.name || item.actor?.username || "System", " • ", item.created_at ? new Date(item.created_at).toLocaleString() : "Recently"))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No history yet", description: "Audit events will appear here as members review requests, posts, and submissions." }))));
}
const __vite_glob_0_131 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupDashboard
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupEventEditor() {
  const { props } = X$1();
  const eventRecord = props.event || null;
  const form = G$1({
    title: eventRecord?.title || "",
    summary: eventRecord?.summary || "",
    description: eventRecord?.description || "",
    event_type: eventRecord?.event_type || props.typeOptions?.[0]?.value || "launch",
    visibility: eventRecord?.visibility || props.visibilityOptions?.[0]?.value || "public",
    status: eventRecord?.status || props.statusOptions?.[0]?.value || "draft",
    start_at: eventRecord?.start_at ? eventRecord.start_at.slice(0, 16) : "",
    end_at: eventRecord?.end_at ? eventRecord.end_at.slice(0, 16) : "",
    timezone: eventRecord?.timezone || "UTC",
    location: eventRecord?.location || "",
    external_url: eventRecord?.external_url || "",
    linked_project_id: eventRecord?.linked_project?.id || "",
    linked_collection_id: eventRecord?.linked_collection?.id || "",
    linked_challenge_id: eventRecord?.linked_challenge?.id || "",
    is_featured: Boolean(eventRecord?.is_featured),
    cover_file: null
  });
  const submit = (event) => {
    event.preventDefault();
    const options = { forceFormData: true, preserveScroll: true };
    if (props.updateUrl) {
      form.post(props.updateUrl, { ...options, _method: "patch" });
      return;
    }
    form.post(props.storeUrl, options);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Event title", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.summary, onChange: (event) => form.setData("summary", event.target.value), placeholder: "Short summary", rows: 3, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), placeholder: "Event description", rows: 8, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.event_type, onChange: (val) => form.setData("event_type", val), options: props.typeOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: props.visibilityOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.status, onChange: (val) => form.setData("status", val), options: props.statusOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.start_at, onChange: (nextValue) => form.setData("start_at", nextValue), placeholder: "Event start", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.end_at, onChange: (nextValue) => form.setData("end_at", nextValue), placeholder: "Event end", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: form.data.timezone, onChange: (event) => form.setData("timezone", event.target.value), placeholder: "Timezone", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: form.data.location, onChange: (event) => form.setData("location", event.target.value), placeholder: "Location", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("input", { value: form.data.external_url, onChange: (event) => form.setData("external_url", event.target.value), placeholder: "External link", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_project_id || ""), onChange: (val) => form.setData("linked_project_id", val), placeholder: "No linked project", options: (props.projectOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_collection_id || ""), onChange: (val) => form.setData("linked_collection_id", val), placeholder: "No linked collection", options: (props.collectionOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_challenge_id || ""), onChange: (val) => form.setData("linked_challenge_id", val), placeholder: "No linked challenge", options: (props.challengeOptions || []).map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_featured, onChange: (event) => form.setData("is_featured", event.target.checked), label: "Featured event" })), /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/*", onChange: (event) => form.setData("cover_file", event.target.files?.[0] || null), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-6 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Save event")), props.publishUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    form.post(props.publishUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Publish event")) : null));
}
const __vite_glob_0_132 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupEventEditor
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupEvents() {
  const { props } = X$1();
  const items = Array.isArray(props.listing?.items) ? props.listing.items : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Events let the group announce launches, sessions, milestones, and time-based updates."), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create event") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((event) => /* @__PURE__ */ React.createElement("a", { key: event.id, href: event.urls?.edit || event.url, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, event.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, event.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, event.summary || "Event page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, event.start_at ? new Date(event.start_at).toLocaleString() : "Unscheduled", " • ", event.event_type))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No events yet.")));
}
const __vite_glob_0_133 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupEvents
}, Symbol.toStringTag, { value: "Module" }));
function formatInviteTimestamp(value) {
  if (!value) return null;
  try {
    return new Date(value).toLocaleString();
  } catch {
    return value;
  }
}
function StudioGroupInvitations() {
  const { props } = X$1();
  const invitations = Array.isArray(props.invitations) ? props.invitations : [];
  const activeMembers = Array.isArray(props.members) ? props.members.filter((member) => member.status === "active") : [];
  const [invite, setInvite] = reactExports.useState({ username: "", role: "contributor", note: "", expires_in_days: 7 });
  const pendingInvites = reactExports.useMemo(
    () => invitations.filter((item) => item.status === "pending"),
    [invitations]
  );
  const revokedInvites = reactExports.useMemo(
    () => invitations.filter((item) => item.status === "revoked"),
    [invitations]
  );
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/75" }, "Group invitations"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Invite collaborators into ", props.studioGroup?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-300" }, "Pending invites stay separate from active members here, so owners and admins can review who was invited, when the invite expires, and revoke access before acceptance.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: props.studioGroup?.urls?.studio_members, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Members"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, pendingInvites.length, " pending"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-[1.1fr_0.8fr_1fr_0.7fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: invite.username, onChange: (event) => setInvite((current) => ({ ...current, username: event.target.value })), placeholder: "Username", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: invite.role, onChange: (val) => setInvite((current) => ({ ...current, role: val })), searchable: false, options: [{ value: "contributor", label: "Contributor" }, { value: "editor", label: "Editor" }, { value: "admin", label: "Admin" }] }), /* @__PURE__ */ React.createElement("input", { value: invite.note, onChange: (event) => setInvite((current) => ({ ...current, note: event.target.value })), placeholder: "Optional note", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: invite.expires_in_days, onChange: (event) => setInvite((current) => ({ ...current, expires_in_days: event.target.value })), type: "number", min: "1", max: "30", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.endpoints?.invite, { ...invite, expires_in_days: Number(invite.expires_in_days || 7) || 7 }), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Send invite"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Pending invitations"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, pendingInvites.length, " outstanding")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, pendingInvites.length > 0 ? pendingInvites.map((inviteRow) => /* @__PURE__ */ React.createElement("article", { key: inviteRow.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, inviteRow.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: inviteRow.user.avatar_url, alt: inviteRow.user.name || inviteRow.user.username, className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, inviteRow.user?.name || inviteRow.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, inviteRow.role_label || inviteRow.role))), /* @__PURE__ */ React.createElement("div", { className: "md:ml-auto flex flex-wrap items-center gap-3 text-xs text-slate-400" }, inviteRow.invited_by ? /* @__PURE__ */ React.createElement("span", null, "Invited by ", inviteRow.invited_by.name || inviteRow.invited_by.username) : null, inviteRow.invited_at ? /* @__PURE__ */ React.createElement("span", null, "Sent ", formatInviteTimestamp(inviteRow.invited_at)) : null, inviteRow.expires_at ? /* @__PURE__ */ React.createElement("span", null, "Expires ", formatInviteTimestamp(inviteRow.expires_at)) : null)), inviteRow.note ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, inviteRow.note) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, inviteRow.can_revoke && inviteRow.revoke_url ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.delete(inviteRow.revoke_url), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-sm font-semibold text-rose-100" }, "Revoke invite") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 px-6 py-12 text-center text-slate-400" }, "No pending invites for this group."))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent invite history"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, revokedInvites.length, " revoked or expired")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, revokedInvites.length > 0 ? revokedInvites.map((inviteRow) => /* @__PURE__ */ React.createElement("article", { key: inviteRow.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, inviteRow.user?.name || inviteRow.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, inviteRow.is_expired ? "Expired" : "Revoked", " • ", inviteRow.role_label || inviteRow.role), inviteRow.invited_at ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, "Originally sent ", formatInviteTimestamp(inviteRow.invited_at)) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 px-4 py-8 text-center text-slate-400" }, "No recent invite history yet."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Active members"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, activeMembers.length, " active")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, activeMembers.slice(0, 6).map((member) => /* @__PURE__ */ React.createElement("div", { key: member.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, member.role_label || member.role)))))))));
}
const __vite_glob_0_134 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupInvitations
}, Symbol.toStringTag, { value: "Module" }));
function HistoryList({ items }) {
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No recent history yet.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.summary || item.action_type), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, item.actor?.name || item.actor?.username || "System", " • ", item.created_at ? new Date(item.created_at).toLocaleString() : "Recently"))));
}
function StudioGroupJoinRequests() {
  const { props } = X$1();
  const listing = props.listing || {};
  const items = Array.isArray(listing.items) ? listing.items : [];
  const approve = (request) => {
    const role = window.prompt("Role to assign on approval? contributor, editor, or admin", request.desired_role || "contributor") || request.desired_role || "contributor";
    const notes = window.prompt("Optional approval note", "") || "";
    At.post(request.can_approve ? routeUrl(props.studioGroup?.urls?.studio_join_requests, request.id, "approve") : "", { action: "approve", role, review_notes: notes });
  };
  const reject = (request) => {
    const notes = window.prompt("Optional rejection note", "") || "";
    At.post(request.can_reject ? routeUrl(props.studioGroup?.urls?.studio_join_requests, request.id, "reject") : "", { action: "reject", review_notes: notes });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Incoming requests"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Approve, reject, and assign roles from one queue.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, listing.filters?.bucket || "pending")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, item.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.user.avatar_url, alt: item.user.name || item.user.username, className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.user?.name || item.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Requested role: ", item.desired_role_label || item.desired_role || "Contributor"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.status)), item.message ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-6 text-slate-300" }, item.message) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-3 text-xs text-slate-400" }, item.portfolio_url ? /* @__PURE__ */ React.createElement("a", { href: item.portfolio_url, className: "text-sky-200 underline underline-offset-4" }, "Portfolio") : null, Array.isArray(item.skills) && item.skills.length > 0 ? /* @__PURE__ */ React.createElement("span", null, item.skills.join(", ")) : null, item.created_at ? /* @__PURE__ */ React.createElement("span", null, new Date(item.created_at).toLocaleString()) : null), item.review_notes ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-300" }, item.review_notes) : null, item.can_approve || item.can_reject ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.can_approve ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => approve(item), className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve") : null, item.can_reject ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => reject(item), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Reject") : null) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No join requests in this bucket."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent history"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Audit trail for moderation-sensitive group actions."), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(HistoryList, { items: props.recentHistory })))));
}
function routeUrl(baseUrl, id, action) {
  if (!baseUrl) return "";
  return `${String(baseUrl).replace(/\/$/, "")}/${id}/${action}`;
}
const __vite_glob_0_135 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupJoinRequests
}, Symbol.toStringTag, { value: "Module" }));
function overrideMap(member) {
  const entries = Array.isArray(member.permission_overrides) ? member.permission_overrides : [];
  return entries.reduce((carry, item) => {
    if (!item?.key) return carry;
    carry[item.key] = item.is_allowed === true ? "allow" : "deny";
    return carry;
  }, {});
}
function prettifyPermission(value) {
  return String(value || "").replaceAll("_", " ");
}
function StudioGroupMembers() {
  const { props } = X$1();
  const canManageMembers = Boolean(props.canManageMembers);
  const [invite, setInvite] = reactExports.useState({ username: "", role: "contributor", note: "" });
  const [search2, setSearch] = reactExports.useState("");
  const [editingMemberId, setEditingMemberId] = reactExports.useState(null);
  const [permissionDrafts, setPermissionDrafts] = reactExports.useState({});
  const members = Array.isArray(props.members) ? props.members : [];
  const permissionOptions = Array.isArray(props.permissionOverrideOptions) ? props.permissionOverrideOptions : [];
  const filteredMembers = members.filter((member) => {
    const haystack = `${member.user?.name || ""} ${member.user?.username || ""} ${member.role_label || member.role || ""}`.toLowerCase();
    return haystack.includes(search2.trim().toLowerCase());
  });
  const confirmTransfer = (member) => {
    if (!window.confirm(`Transfer ownership of this group to ${member.user?.name || member.user?.username}? This removes your owner privileges immediately.`)) {
      return;
    }
    At.post(props.endpoints?.transferPattern.replace("__MEMBER__", String(member.id)));
  };
  const confirmRemoval = (member) => {
    if (!window.confirm(`Remove ${member.user?.name || member.user?.username} from this group?`)) {
      return;
    }
    At.delete(props.endpoints?.deletePattern.replace("__MEMBER__", String(member.id)));
  };
  const openPermissionEditor = (member) => {
    setEditingMemberId(member.id);
    setPermissionDrafts((current) => ({ ...current, [member.id]: overrideMap(member) }));
  };
  const setPermissionState = (memberId, key, value) => {
    setPermissionDrafts((current) => ({
      ...current,
      [memberId]: {
        ...current[memberId] || {},
        [key]: value
      }
    }));
  };
  const savePermissions = (member) => {
    const state = permissionDrafts[member.id] || {};
    const payload = permissionOptions.filter((option) => state[option.value] === "allow" || state[option.value] === "deny").map((option) => ({ key: option.value, is_allowed: state[option.value] === "allow" }));
    At.patch(props.endpoints?.permissionsPattern.replace("__MEMBER__", String(member.id)), {
      permission_overrides: payload
    }, {
      onSuccess: () => setEditingMemberId(null)
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, canManageMembers ? /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Invite member"), props.endpoints?.invitations ? /* @__PURE__ */ React.createElement("a", { href: props.endpoints.invitations, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Manage invitations") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-[1.2fr_0.8fr_1fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: invite.username, onChange: (event) => setInvite((current) => ({ ...current, username: event.target.value })), placeholder: "Username", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: invite.role, onChange: (val) => setInvite((current) => ({ ...current, role: val })), searchable: false, options: [{ value: "contributor", label: "Contributor" }, { value: "editor", label: "Editor" }, { value: "admin", label: "Admin" }] }), /* @__PURE__ */ React.createElement("input", { value: invite.note, onChange: (event) => setInvite((current) => ({ ...current, note: event.target.value })), placeholder: "Optional note", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.endpoints?.invite, invite), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Invite"))) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-end md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Member directory"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Search the current roster, then adjust roles or membership status.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300 md:min-w-[260px]" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search members"), /* @__PURE__ */ React.createElement("input", { value: search2, onChange: (event) => setSearch(event.target.value), placeholder: "Name, username, or role", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 overflow-hidden rounded-[24px] border border-white/10" }, /* @__PURE__ */ React.createElement("div", { className: "hidden grid-cols-[minmax(0,1.5fr)_160px_120px_minmax(0,220px)] gap-3 border-b border-white/10 bg-white/[0.04] px-4 py-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400 md:grid" }, /* @__PURE__ */ React.createElement("span", null, "Member"), /* @__PURE__ */ React.createElement("span", null, "Role"), /* @__PURE__ */ React.createElement("span", null, "Status"), /* @__PURE__ */ React.createElement("span", null, "Actions")), /* @__PURE__ */ React.createElement("div", { className: "divide-y divide-white/10" }, filteredMembers.map((member) => /* @__PURE__ */ React.createElement("article", { key: member.id, className: "grid gap-4 px-4 py-4 md:grid-cols-[minmax(0,1.5fr)_160px_120px_minmax(0,220px)] md:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "@", member.user?.username || "member"))), /* @__PURE__ */ React.createElement("div", null, canManageMembers && member.role !== "owner" ? /* @__PURE__ */ React.createElement(NovaSelect, { value: member.role, onChange: (val) => At.patch(props.endpoints?.updatePattern.replace("__MEMBER__", String(member.id)), { role: val }), searchable: false, options: [{ value: "contributor", label: "Contributor" }, { value: "editor", label: "Editor" }, { value: "admin", label: "Admin" }] }) : /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-2 text-sm font-semibold text-emerald-100" }, member.role === "owner" ? "Owner" : member.role_label || member.role), Array.isArray(member.permission_overrides) && member.permission_overrides.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, member.permission_overrides.map((permission) => /* @__PURE__ */ React.createElement("span", { key: `${permission.key}-${permission.is_allowed ? "allow" : "deny"}`, className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] ${permission.is_allowed ? "border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border-rose-300/20 bg-rose-400/10 text-rose-100"}` }, permission.is_allowed ? "Allow" : "Deny", " ", prettifyPermission(permission.key)))) : null), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-slate-300" }, member.status)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, member.can_manage_permissions ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => openPermissionEditor(member), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Permissions") : null, canManageMembers && member.can_transfer ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => confirmTransfer(member), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Transfer") : null, canManageMembers && member.can_revoke ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => confirmRemoval(member), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-sm font-semibold text-rose-100" }, "Remove") : null), editingMemberId === member.id ? /* @__PURE__ */ React.createElement("div", { className: "md:col-span-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, "Permission overrides"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, "Set each advanced capability to inherit, allow, or deny.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setEditingMemberId(null), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => savePermissions(member), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-2 text-sm font-semibold text-sky-100" }, "Save"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-2" }, permissionOptions.map((option) => {
    const current = permissionDrafts[member.id]?.[option.value] || "inherit";
    return /* @__PURE__ */ React.createElement("div", { key: option.value, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setPermissionState(member.id, option.value, "inherit"), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${current === "inherit" ? "border-white/20 bg-white/[0.08] text-white" : "border-white/10 bg-transparent text-slate-300"}` }, "Inherit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setPermissionState(member.id, option.value, "allow"), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${current === "allow" ? "border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border-white/10 bg-transparent text-slate-300"}` }, "Allow"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setPermissionState(member.id, option.value, "deny"), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${current === "deny" ? "border-rose-300/20 bg-rose-400/10 text-rose-100" : "border-white/10 bg-transparent text-slate-300"}` }, "Deny")));
  }))) : null)), filteredMembers.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "px-4 py-8 text-sm text-slate-400" }, "No members match the current search.") : null))));
}
const __vite_glob_0_136 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupMembers
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupPostEditor() {
  const { props } = X$1();
  const post2 = props.post || {};
  const form = G$1({
    type: post2.type || "announcement",
    title: post2.title || "",
    excerpt: post2.excerpt || "",
    content: post2.content || "",
    cover_path: post2.cover_url || ""
  });
  const submit = (event) => {
    event.preventDefault();
    if (props.updateUrl) {
      form.patch(props.updateUrl);
      return;
    }
    form.post(props.storeUrl);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.type, onChange: (val) => form.setData("type", val), options: Array.isArray(props.typeOptions) ? props.typeOptions : [], searchable: false })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Excerpt"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.excerpt, onChange: (event) => form.setData("excerpt", event.target.value), rows: 3, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Content"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.content, onChange: (event) => form.setData("content", event.target.value), rows: 12, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Post controls"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "w-full rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-3 text-sm font-semibold text-sky-100 disabled:opacity-60" }, "Save"), props.publishUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.publishUrl), className: "w-full rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm font-semibold text-emerald-100" }, "Publish") : null, props.pinUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.pinUrl), className: "w-full rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm font-semibold text-amber-100" }, "Toggle pinned") : null, props.archiveUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.archiveUrl), className: "w-full rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100" }, "Archive") : null))));
}
const __vite_glob_0_137 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupPostEditor
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupPosts() {
  const { props } = X$1();
  const items = Array.isArray(props.listing?.items) ? props.listing.items : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Post library"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Draft, publish, pin, and archive public group posts.")), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "New post") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.type), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, item.title)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-end gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.status), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Pinned") : null)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.excerpt || item.content || "No excerpt yet."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.urls?.edit, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Edit"), item.urls?.public ? /* @__PURE__ */ React.createElement("a", { href: item.urls.public, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "View") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No posts yet."))));
}
const __vite_glob_0_138 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupPosts
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupProjectEditor() {
  const { props } = X$1();
  const project = props.project || null;
  const form = G$1({
    title: project?.title || "",
    summary: project?.summary || "",
    description: project?.description || "",
    visibility: project?.visibility || props.visibilityOptions?.[0]?.value || "public",
    status: project?.status || props.statusOptions?.[0]?.value || "planned",
    start_date: project?.start_date || "",
    target_date: project?.target_date || "",
    lead_user_id: project?.lead?.id || "",
    linked_collection_id: project?.linked_collection?.id || "",
    linked_featured_artwork_id: "",
    pinned_post_id: project?.pinned_post?.id || "",
    member_user_ids: Array.isArray(project?.team) ? project.team.map((member) => member.id) : [],
    cover_file: null
  });
  const artworkAttach = G$1({ artwork_id: "" });
  const assetAttach = G$1({ asset_id: "" });
  const statusForm = G$1({ status: project?.status || props.statusOptions?.[0]?.value || "planned" });
  const milestoneForm = G$1({ title: "", summary: "", status: "pending", due_date: "", owner_user_id: "", notes: "" });
  const submit = (event) => {
    event.preventDefault();
    const options = { forceFormData: true, preserveScroll: true };
    if (props.updateUrl) {
      form.post(props.updateUrl, { ...options, _method: "patch" });
      return;
    }
    form.post(props.storeUrl, options);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Project title", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.summary, onChange: (event) => form.setData("summary", event.target.value), placeholder: "Short summary", rows: 3, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), placeholder: "Longer project description", rows: 8, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: props.visibilityOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.status, onChange: (val) => form.setData("status", val), options: props.statusOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.start_date, onChange: (nextValue) => form.setData("start_date", nextValue), mode: "date", placeholder: "Project start", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.target_date, onChange: (nextValue) => form.setData("target_date", nextValue), mode: "date", placeholder: "Target date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.lead_user_id || ""), onChange: (val) => form.setData("lead_user_id", val), placeholder: "No lead", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_collection_id || ""), onChange: (val) => form.setData("linked_collection_id", val), placeholder: "No linked collection", options: (props.collectionOptions || []).map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement(NovaSelect, { multi: true, value: form.data.member_user_ids, onChange: (vals) => form.setData("member_user_ids", (vals || []).map(Number).filter(Boolean)), placeholder: "Select team members", options: (props.memberOptions || []).map((o) => ({ value: o.id, label: o.name || o.username })) }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_featured_artwork_id || ""), onChange: (val) => form.setData("linked_featured_artwork_id", val), placeholder: "No featured artwork", options: (props.artworkOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.pinned_post_id || ""), onChange: (val) => form.setData("pinned_post_id", val), placeholder: "No pinned post", options: (props.postOptions || []).map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/*", onChange: (event) => form.setData("cover_file", event.target.files?.[0] || null), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "mt-6 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, form.processing ? "Saving…" : "Save project")), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, props.statusUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    statusForm.post(props.statusUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Status"), /* @__PURE__ */ React.createElement(NovaSelect, { value: statusForm.data.status, onChange: (val) => statusForm.setData("status", val), options: props.statusOptions || [], searchable: false }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Update status")) : null, props.attachArtworkUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    artworkAttach.post(props.attachArtworkUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attach artwork"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(artworkAttach.data.artwork_id || ""), onChange: (val) => artworkAttach.setData("artwork_id", val), placeholder: "Choose artwork", options: (props.artworkOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Attach artwork")) : null, props.attachAssetUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    assetAttach.post(props.attachAssetUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attach asset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(assetAttach.data.asset_id || ""), onChange: (val) => assetAttach.setData("asset_id", val), placeholder: "Choose asset", options: (props.assetOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Attach asset")) : null, props.storeMilestoneUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    milestoneForm.post(props.storeMilestoneUrl, { preserveScroll: true, onSuccess: () => milestoneForm.reset("title", "summary", "due_date", "owner_user_id", "notes") });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: milestoneForm.data.title, onChange: (event) => milestoneForm.setData("title", event.target.value), placeholder: "Milestone title", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.summary, onChange: (event) => milestoneForm.setData("summary", event.target.value), placeholder: "Summary", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: milestoneForm.data.status, onChange: (val) => milestoneForm.setData("status", val), searchable: false, options: ["pending", "active", "blocked", "completed", "cancelled"].map((s2) => ({ value: s2, label: s2 })) }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: milestoneForm.data.due_date, onChange: (nextValue) => milestoneForm.setData("due_date", nextValue), mode: "date", placeholder: "Due date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(milestoneForm.data.owner_user_id || ""), onChange: (val) => milestoneForm.setData("owner_user_id", val), placeholder: "No owner", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.notes, onChange: (event) => milestoneForm.setData("notes", event.target.value), placeholder: "Notes", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Add milestone")), Array.isArray(project?.milestones) && project.milestones.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, project.milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, milestone.owner?.name || milestone.owner?.username || "No owner", milestone.due_date ? ` • due ${milestone.due_date}` : "")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.patch(props.updateMilestonePattern.replace("__MILESTONE__", String(milestone.id)), { title: milestone.title, summary: milestone.summary || "", status: milestone.status === "completed" ? "active" : "completed", due_date: milestone.due_date || "", owner_user_id: milestone.owner?.id || "", notes: milestone.notes || "" }, { preserveScroll: true }), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold text-white" }, "Mark ", milestone.status === "completed" ? "active" : "complete")), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null))) : null) : null)));
}
const __vite_glob_0_139 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupProjectEditor
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupProjects() {
  const { props } = X$1();
  const listing = props.listing || {};
  const items = Array.isArray(listing.items) ? listing.items : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Projects give the group a structured place for releases, teams, and linked outputs."), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create project") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((project) => /* @__PURE__ */ React.createElement("a", { key: project.id, href: project.urls?.edit || project.url, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, project.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, project.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, project.summary || "Project page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, project.counts?.artworks || 0, " artworks • ", project.counts?.assets || 0, " assets • ", project.counts?.team || 0, " team • ", project.counts?.milestones || 0, " milestones • ", project.counts?.releases || 0, " releases"))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No projects yet.")));
}
const __vite_glob_0_140 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupProjects
}, Symbol.toStringTag, { value: "Module" }));
function toggleItem(list2, value) {
  return list2.includes(value) ? list2.filter((item) => item !== value) : [...list2, value];
}
function StudioGroupRecruitment() {
  const { props } = X$1();
  const recruitment = props.recruitment || {};
  const form = G$1({
    is_recruiting: Boolean(recruitment.is_recruiting),
    headline: recruitment.headline || "",
    description: recruitment.description || "",
    roles_json: Array.isArray(recruitment.roles) ? recruitment.roles : [],
    skills_json: Array.isArray(recruitment.skills) ? recruitment.skills : [],
    contact_mode: recruitment.contact_mode || "join_request",
    visibility: recruitment.visibility || "public"
  });
  const submit = (event) => {
    event.preventDefault();
    form.patch(props.updateUrl);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recruitment profile"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Describe what the group is looking for and how applicants should reach you.")), /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_recruiting, onChange: (event) => form.setData("is_recruiting", event.target.checked), label: "Recruiting now" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Headline"), /* @__PURE__ */ React.createElement("input", { value: form.data.headline, onChange: (event) => form.setData("headline", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), rows: 7, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Roles"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 rounded-[24px] border border-white/10 bg-black/20 p-4" }, (Array.isArray(props.roleOptions) ? props.roleOptions : []).map((option) => {
    const selected = form.data.roles_json.includes(option.value);
    return /* @__PURE__ */ React.createElement("button", { key: option.value, type: "button", onClick: () => form.setData("roles_json", toggleItem(form.data.roles_json, option.value)), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${selected ? "border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border-white/10 bg-white/[0.03] text-slate-300"}` }, option.label);
  }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Skills"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 rounded-[24px] border border-white/10 bg-black/20 p-4" }, (Array.isArray(props.skillOptions) ? props.skillOptions : []).map((option) => {
    const selected = form.data.skills_json.includes(option.value);
    return /* @__PURE__ */ React.createElement("button", { key: option.value, type: "button", onClick: () => form.setData("skills_json", toggleItem(form.data.skills_json, option.value)), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${selected ? "border-sky-300/20 bg-sky-300/10 text-sky-100" : "border-white/10 bg-white/[0.03] text-slate-300"}` }, option.label);
  }))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Application settings"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contact mode"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.contact_mode, onChange: (val) => form.setData("contact_mode", val), options: Array.isArray(props.contactModes) ? props.contactModes : [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: Array.isArray(props.visibilityOptions) ? props.visibilityOptions : [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Public preview"), /* @__PURE__ */ React.createElement("p", { className: "mt-2" }, form.data.headline || "No headline yet."), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-slate-400" }, form.data.description || "Recruitment copy will show here once you add it."), form.data.roles_json.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, form.data.roles_json.map((role) => /* @__PURE__ */ React.createElement("span", { key: role, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-white" }, role))) : null), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-3 text-sm font-semibold text-sky-100 disabled:opacity-60" }, "Save recruitment profile")))));
}
const __vite_glob_0_141 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupRecruitment
}, Symbol.toStringTag, { value: "Module" }));
function toDateTimeInput(value) {
  return value ? String(value).slice(0, 16) : "";
}
function StudioGroupReleaseEditor() {
  const { props } = X$1();
  const release = props.release || null;
  const form = G$1({
    title: release?.title || "",
    summary: release?.summary || "",
    description: release?.description || "",
    release_notes: release?.release_notes || "",
    visibility: release?.visibility || props.visibilityOptions?.[0]?.value || "public",
    status: release?.status || props.statusOptions?.[0]?.value || "draft",
    current_stage: release?.current_stage || props.stageOptions?.[0]?.value || "concept",
    planned_release_at: toDateTimeInput(release?.planned_release_at),
    lead_user_id: release?.lead?.id || "",
    linked_project_id: release?.linked_project?.id || "",
    linked_collection_id: release?.linked_collection?.id || "",
    featured_artwork_id: release?.featured_artwork?.id || "",
    is_featured: Boolean(release?.is_featured),
    cover_file: null
  });
  const stageForm = G$1({ current_stage: release?.current_stage || props.stageOptions?.[0]?.value || "concept" });
  const artworkAttach = G$1({ artwork_id: "" });
  const contributorForm = G$1({ user_id: "", role_label: "" });
  const milestoneForm = G$1({ title: "", summary: "", status: "pending", due_date: "", owner_user_id: "", notes: "" });
  const submit = (event) => {
    event.preventDefault();
    const options = { forceFormData: true, preserveScroll: true };
    if (props.updateUrl) {
      form.transform((data) => ({ ...data, _method: "patch" })).post(props.updateUrl, options);
      return;
    }
    form.post(props.storeUrl, options);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Release title", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.summary, onChange: (event) => form.setData("summary", event.target.value), placeholder: "Short summary", rows: 3, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), placeholder: "Release overview", rows: 8, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: form.data.release_notes, onChange: (event) => form.setData("release_notes", event.target.value), placeholder: "Release notes", rows: 7, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: props.visibilityOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.status, onChange: (val) => form.setData("status", val), options: props.statusOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.current_stage, onChange: (val) => form.setData("current_stage", val), options: props.stageOptions || [], searchable: false })), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.planned_release_at, onChange: (nextValue) => form.setData("planned_release_at", nextValue), placeholder: "Planned release", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.lead_user_id || ""), onChange: (val) => form.setData("lead_user_id", val), placeholder: "No release lead", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_project_id || ""), onChange: (val) => form.setData("linked_project_id", val), placeholder: "No linked project", options: (props.projectOptions || []).map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_collection_id || ""), onChange: (val) => form.setData("linked_collection_id", val), placeholder: "No linked collection", options: (props.collectionOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.featured_artwork_id || ""), onChange: (val) => form.setData("featured_artwork_id", val), placeholder: "No featured artwork", options: (props.artworkOptions || []).map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_featured, onChange: (event) => form.setData("is_featured", event.target.checked), label: "Feature this release on the public group page" })), /* @__PURE__ */ React.createElement("input", { type: "file", accept: "image/*", onChange: (event) => form.setData("cover_file", event.target.files?.[0] || null), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, form.processing ? "Saving…" : "Save release"), release?.url ? /* @__PURE__ */ React.createElement("a", { href: release.url, className: "rounded-full border border-white/10 bg-black/20 px-5 py-2.5 text-sm font-semibold text-white" }, "View public page") : null)), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, props.stageUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    stageForm.post(props.stageUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Stage"), /* @__PURE__ */ React.createElement(NovaSelect, { value: stageForm.data.current_stage, onChange: (val) => stageForm.setData("current_stage", val), options: props.stageOptions || [], searchable: false }), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Update stage"), props.publishUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.publishUrl, {}, { preserveScroll: true }), className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Publish") : null)) : null, props.attachArtworkUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    artworkAttach.post(props.attachArtworkUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attach artwork"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(artworkAttach.data.artwork_id || ""), onChange: (val) => artworkAttach.setData("artwork_id", val), placeholder: "Choose artwork", options: (props.artworkOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Attach artwork")) : null, props.attachContributorUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    contributorForm.post(props.attachContributorUrl, { preserveScroll: true });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Contributor credit"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(contributorForm.data.user_id || ""), onChange: (val) => contributorForm.setData("user_id", val), placeholder: "Choose contributor", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement("input", { value: contributorForm.data.role_label, onChange: (event) => contributorForm.setData("role_label", event.target.value), placeholder: "Role label", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Attach contributor")), Array.isArray(release?.contributors) && release.contributors.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, release.contributors.map((contributor) => /* @__PURE__ */ React.createElement("div", { key: contributor.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, contributor.name || contributor.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, contributor.role_label || "Contributor")))) : null) : null, props.storeMilestoneUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    milestoneForm.post(props.storeMilestoneUrl, { preserveScroll: true, onSuccess: () => milestoneForm.reset("title", "summary", "due_date", "owner_user_id", "notes") });
  }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: milestoneForm.data.title, onChange: (event) => milestoneForm.setData("title", event.target.value), placeholder: "Milestone title", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.summary, onChange: (event) => milestoneForm.setData("summary", event.target.value), placeholder: "Summary", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: milestoneForm.data.status, onChange: (val) => milestoneForm.setData("status", val), searchable: false, options: ["pending", "active", "blocked", "completed", "cancelled"].map((s2) => ({ value: s2, label: s2 })) }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: milestoneForm.data.due_date, onChange: (nextValue) => milestoneForm.setData("due_date", nextValue), mode: "date", placeholder: "Due date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(milestoneForm.data.owner_user_id || ""), onChange: (val) => milestoneForm.setData("owner_user_id", val), placeholder: "No owner", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.notes, onChange: (event) => milestoneForm.setData("notes", event.target.value), placeholder: "Notes", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Add milestone")), Array.isArray(release?.milestones) && release.milestones.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, release.milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, milestone.owner?.name || milestone.owner?.username || "No owner", milestone.due_date ? ` • due ${milestone.due_date}` : "")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.patch(props.updateMilestonePattern.replace("__MILESTONE__", String(milestone.id)), { title: milestone.title, summary: milestone.summary || "", status: milestone.status === "completed" ? "active" : "completed", due_date: milestone.due_date || "", owner_user_id: milestone.owner?.id || "", notes: milestone.notes || "" }, { preserveScroll: true }), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold text-white" }, "Mark ", milestone.status === "completed" ? "active" : "complete")), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null))) : null) : null)));
}
const __vite_glob_0_142 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupReleaseEditor
}, Symbol.toStringTag, { value: "Module" }));
function StudioGroupReleases() {
  const { props } = X$1();
  const listing = props.listing || {};
  const items = Array.isArray(listing.items) ? listing.items : [];
  const bucketOptions = Array.isArray(listing.bucket_options) ? listing.bucket_options : [];
  const currentBucket = listing.filters?.bucket || "all";
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Track the release pipeline from draft through public launch, with milestones and contributor credits."), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: currentBucket, onChange: (val) => At.get(window.location.pathname, { bucket: val }, { preserveScroll: true, preserveState: true }), options: bucketOptions, searchable: false }), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create release") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((release) => /* @__PURE__ */ React.createElement("div", { key: release.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.03]" }, release.cover_url ? /* @__PURE__ */ React.createElement("img", { src: release.cover_url, alt: release.title, className: "aspect-[4/3] w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[4/3] items-center justify-center bg-white/[0.03] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket text-2xl" })), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.status), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.current_stage), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.visibility)), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-xl font-semibold text-white" }, release.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, release.summary || "Release page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, release.counts?.artworks || 0, " artworks • ", release.counts?.contributors || 0, " contributors • ", release.counts?.milestones || 0, " milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: release.urls?.edit || release.url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Manage"), release.urls?.public ? /* @__PURE__ */ React.createElement("a", { href: release.urls.public, className: "rounded-full border border-white/10 bg-black/20 px-4 py-2 text-sm font-semibold text-white" }, "View public") : null)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No releases yet.")));
}
const __vite_glob_0_143 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupReleases
}, Symbol.toStringTag, { value: "Module" }));
function MetricCard({ label, value }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(value || 0).toFixed(1)));
}
function StudioGroupReputation() {
  const { props } = X$1();
  const reputation = props.reputation || {};
  const trustSignals = Array.isArray(props.trustSignals) ? props.trustSignals : [];
  const metrics = props.metrics || {};
  const topContributors = Array.isArray(reputation.top_contributors) ? reputation.top_contributors : [];
  const recentBadges = Array.isArray(reputation.recent_badges) ? reputation.recent_badges : [];
  const memberBadgeUnlocks = Array.isArray(reputation.member_badge_unlocks) ? reputation.member_badge_unlocks : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement(MetricCard, { label: "Freshness", value: metrics.freshness_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Activity", value: metrics.activity_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Release", value: metrics.release_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Trust", value: metrics.trust_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Collaboration", value: metrics.collaboration_score })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Trust signals"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Public-safe labels that shape discovery and confidence."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, trustSignals.map((signal) => /* @__PURE__ */ React.createElement("span", { key: signal.key, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, signal.label))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputation.counts?.contributors || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Member badges"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputation.counts?.member_badges || 0)))), metrics.last_calculated_at ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, "Last calculated ", new Date(metrics.last_calculated_at).toLocaleString()) : null), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Top contributors"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Reputation summaries derived from visible collaboration history."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, topContributors.length > 0 ? topContributors.map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.user?.id, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, entry.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: entry.user.avatar_url, alt: entry.user?.name || entry.user?.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, entry.user?.name || entry.user?.username), entry.trusted_indicator ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Trusted") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, entry.summary || "Contributor"))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, entry.counts?.releases || 0, " releases • ", entry.counts?.projects || 0, " projects • ", entry.counts?.credited_artworks || 0, " artworks • ", entry.counts?.review_actions || 0, " reviews"), Array.isArray(entry.badges) && entry.badges.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, entry.badges.map((badge) => /* @__PURE__ */ React.createElement("span", { key: `${entry.user?.id}-${badge.key}`, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, badge.label))) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No contributor reputation signals yet.")))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Group badges"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, recentBadges.length > 0 ? recentBadges.map((badge) => /* @__PURE__ */ React.createElement("div", { key: badge.key, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, badge.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, badge.reason))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No group badges awarded yet."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent member badge unlocks"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, memberBadgeUnlocks.length > 0 ? memberBadgeUnlocks.map((entry) => /* @__PURE__ */ React.createElement("div", { key: `${entry.user?.id}-${entry.badge?.key}`, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, entry.user?.name || entry.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-sky-200" }, entry.badge?.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, entry.badge?.reason))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No member badge unlocks yet.")))));
}
const __vite_glob_0_144 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupReputation
}, Symbol.toStringTag, { value: "Module" }));
function actionUrl(item, key) {
  return item?.urls?.[key] || "";
}
function StudioGroupReviewQueue() {
  const { props } = X$1();
  const listing = props.listing || {};
  const items = Array.isArray(listing.items) ? listing.items : [];
  const sendAction = (item, action) => {
    const notes = window.prompt("Optional reviewer note", "") || "";
    At.post(actionUrl(item, action), { action, review_notes: notes });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Submission queue"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Review artwork drafts before they publish under the group identity.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, listing.filters?.bucket || "submitted")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start gap-4" }, item.thumb ? /* @__PURE__ */ React.createElement("img", { src: item.thumb, alt: item.title, className: "h-24 w-24 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-24 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.group_review_status)), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-3 text-xs text-slate-400" }, item.primary_author ? /* @__PURE__ */ React.createElement("span", null, "Author: ", item.primary_author.name || item.primary_author.username) : null, item.uploader ? /* @__PURE__ */ React.createElement("span", null, "Uploader: ", item.uploader.name || item.uploader.username) : null, item.submitted_at ? /* @__PURE__ */ React.createElement("span", null, "Submitted ", new Date(item.submitted_at).toLocaleString()) : null), item.group_review_notes ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-300" }, item.group_review_notes) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.urls?.edit, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Open draft"), item.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => sendAction(item, "approve"), className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve") : null, item.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => sendAction(item, "needs_changes"), className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-sm font-semibold text-amber-100" }, "Needs changes") : null, item.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => sendAction(item, "reject"), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Reject") : null))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No submissions in this bucket."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent history"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (Array.isArray(props.recentHistory) ? props.recentHistory : []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.summary || item.action_type), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, item.actor?.name || item.actor?.username || "System", " • ", item.created_at ? new Date(item.created_at).toLocaleString() : "Recently")))))));
}
const __vite_glob_0_145 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupReviewQueue
}, Symbol.toStringTag, { value: "Module" }));
function resolveMediaPreviewUrl(path, filesCdnUrl) {
  const trimmed = String(path || "").trim();
  if (!trimmed) {
    return "";
  }
  if (trimmed.startsWith("blob:") || trimmed.startsWith("data:") || trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
    return trimmed;
  }
  return `${String(filesCdnUrl || "").replace(/\/$/, "")}/${trimmed.replace(/^\/+/, "")}`;
}
function StudioGroupSettings() {
  const { props } = X$1();
  const group = props.studioGroup || {};
  const filesCdnUrl = props?.cdn?.files_url || "";
  const featuredArtworkOptions = Array.isArray(props.featuredArtworkOptions) ? props.featuredArtworkOptions : [];
  const avatarInputRef = reactExports.useRef(null);
  const bannerInputRef = reactExports.useRef(null);
  const [form, setForm] = reactExports.useState({
    name: group.name || "",
    slug: group.slug || "",
    headline: group.headline || "",
    bio: group.bio || "",
    type: group.type || "",
    founded_at: group.founded_at ? String(group.founded_at).slice(0, 10) : "",
    avatar_path: group.avatar_path || group.avatar_url || "",
    banner_path: group.banner_path || group.banner_url || "",
    visibility: group.visibility || "public",
    membership_policy: group.membership_policy || "invite_only",
    website_url: group.website_url || "",
    links_json: Array.isArray(group.links) && group.links.length > 0 ? group.links : [{ label: "", url: "" }],
    featured_artwork_id: group.featured_artwork_id || "",
    avatar_file: null,
    banner_file: null
  });
  const [avatarPreview, setAvatarPreview] = reactExports.useState("");
  const [bannerPreview, setBannerPreview] = reactExports.useState("");
  const resolvedAvatarPreview = reactExports.useMemo(() => avatarPreview || resolveMediaPreviewUrl(form.avatar_path || group.avatar_url, filesCdnUrl), [avatarPreview, form.avatar_path, group.avatar_url, filesCdnUrl]);
  const resolvedBannerPreview = reactExports.useMemo(() => bannerPreview || resolveMediaPreviewUrl(form.banner_path || group.banner_url, filesCdnUrl), [bannerPreview, form.banner_path, group.banner_url, filesCdnUrl]);
  const selectedFeaturedArtwork = reactExports.useMemo(
    () => featuredArtworkOptions.find((item) => Number(item.id) === Number(form.featured_artwork_id)) || null,
    [featuredArtworkOptions, form.featured_artwork_id]
  );
  const updateLink = (index2, key, value) => {
    setForm((current) => ({
      ...current,
      links_json: current.links_json.map((item, itemIndex) => itemIndex === index2 ? { ...item, [key]: value } : item)
    }));
  };
  const addLink = () => {
    setForm((current) => ({
      ...current,
      links_json: [...current.links_json, { label: "", url: "" }]
    }));
  };
  const removeLink = (index2) => {
    setForm((current) => ({
      ...current,
      links_json: current.links_json.filter((_2, itemIndex) => itemIndex !== index2)
    }));
  };
  const submit = () => {
    At.post(props.endpoints?.update, {
      _method: "patch",
      ...form,
      links_json: form.links_json.filter((item) => item.label.trim() !== "" || item.url.trim() !== "")
    }, {
      forceFormData: true
    });
  };
  const handleFileSelected = (field, setPreview) => (event) => {
    const file = event.target.files?.[0] || null;
    setForm((current) => ({ ...current, [field]: file }));
    setPreview(file ? URL.createObjectURL(file) : "");
  };
  const clearSelectedFile = (field, setPreview, inputRef) => {
    setForm((current) => ({ ...current, [field]: null }));
    setPreview("");
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };
  const archiveGroup = () => {
    if (!window.confirm("Archive this group? New group publishing will stop immediately until you reopen it through admin tooling.")) {
      return;
    }
    At.post(props.endpoints?.archive);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "mx-auto max-w-3xl rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Name"), /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Short description"), /* @__PURE__ */ React.createElement("input", { value: form.headline, onChange: (event) => setForm((current) => ({ ...current, headline: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "About"), /* @__PURE__ */ React.createElement("textarea", { value: form.bio, onChange: (event) => setForm((current) => ({ ...current, bio: event.target.value })), rows: 6, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Type / category"), /* @__PURE__ */ React.createElement("input", { value: form.type, onChange: (event) => setForm((current) => ({ ...current, type: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Founded date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.founded_at, onChange: (nextValue) => setForm((current) => ({ ...current, founded_at: nextValue })), mode: "date", placeholder: "Pick the founding date", clearable: true, className: "bg-black/20" }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Website"), /* @__PURE__ */ React.createElement("input", { value: form.website_url, onChange: (event) => setForm((current) => ({ ...current, website_url: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Avatar / logo"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-28 items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedAvatarPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedAvatarPreview, alt: "Avatar preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: avatarInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("avatar_file", setAvatarPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => avatarInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload avatar"), form.avatar_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("avatar_file", setAvatarPreview, avatarInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use current path") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.avatar_path, onChange: (event) => setForm((current) => ({ ...current, avatar_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Cover image"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-full items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedBannerPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedBannerPreview, alt: "Cover preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-panorama text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: bannerInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("banner_file", setBannerPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => bannerInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload cover"), form.banner_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("banner_file", setBannerPreview, bannerInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use current path") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.banner_path, onChange: (event) => setForm((current) => ({ ...current, banner_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Featured artwork"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.featured_artwork_id || ""), onChange: (val) => setForm((current) => ({ ...current, featured_artwork_id: val })), placeholder: "Use latest published artwork", options: featuredArtworkOptions.map((item) => ({ value: String(item.id), label: item.title })) })), selectedFeaturedArtwork ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-[20px] border border-white/10 bg-white/[0.04] p-3" }, selectedFeaturedArtwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: selectedFeaturedArtwork.thumb, alt: selectedFeaturedArtwork.title, className: "h-16 w-16 rounded-2xl object-cover" }) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, selectedFeaturedArtwork.title), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, selectedFeaturedArtwork.author || "Group member"))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "When this is empty, the public overview falls back to the latest published works automatically.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => setForm((current) => ({ ...current, visibility: val })), options: props.visibilityOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Membership policy"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.membership_policy, onChange: (val) => setForm((current) => ({ ...current, membership_policy: val })), options: props.membershipPolicyOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-200" }, "Links"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addLink, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Add link")), form.links_json.map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: `link-${index2}`, className: "grid gap-3 md:grid-cols-[0.8fr_1.2fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: item.label, onChange: (event) => updateLink(index2, "label", event.target.value), placeholder: "Label", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: item.url, onChange: (event) => updateLink(index2, "url", event.target.value), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeLink(index2), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Remove")))), /* @__PURE__ */ React.createElement("div", { className: "flex justify-between gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: archiveGroup, className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Archive group"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: submit, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Save settings")))));
}
const __vite_glob_0_146 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupSettings
}, Symbol.toStringTag, { value: "Module" }));
function GroupCard({ group }) {
  return /* @__PURE__ */ React.createElement("article", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(3,7,18,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 items-center justify-center overflow-hidden rounded-2xl border border-white/10 bg-slate-900/70 text-slate-300" }, group.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: group.avatar_url, alt: group.name, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h2", { className: "truncate text-lg font-semibold text-white" }, group.name), group.viewer?.role ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, group.viewer.role) : null, Number(group.pending_invites_count || 0) > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, Number(group.pending_invites_count), " pending invite", Number(group.pending_invites_count) === 1 ? "" : "s") : null), group.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, group.headline) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, Number(group.counts?.artworks || 0).toLocaleString(), " artworks"), /* @__PURE__ */ React.createElement("span", null, Number(group.counts?.collections || 0).toLocaleString(), " collections"), /* @__PURE__ */ React.createElement("span", null, Number(group.counts?.followers || 0).toLocaleString(), " followers")))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.studio, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, "Open Studio"), /* @__PURE__ */ React.createElement("a", { href: group.urls?.studio_invitations, className: "rounded-full border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.06]" }, "Invitations"), /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "rounded-full border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.06]" }, "Public page")));
}
function StudioGroupsIndex() {
  const { props } = X$1();
  const groups = Array.isArray(props.groups) ? props.groups : [];
  const pendingInvites = Array.isArray(props.pendingInvites) ? props.pendingInvites : [];
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement(
    GroupStudioPromoCard,
    {
      title: "Publish as a team, not just an individual",
      description: "Groups let you share ownership across artworks, releases, collections, reviews, and recruiting while keeping one public identity for the whole collective.",
      bullets: [
        { title: "Shared publishing", body: "Release under one name while keeping credited contributors visible across the artwork and group pages." },
        { title: "Team workflow", body: "Invite reviewers, managers, and contributors into one studio space with role-based permissions." },
        { title: "Public discovery", body: "Groups now appear across search, homepage modules, leaderboards, and public browse surfaces." }
      ],
      primaryLabel: "Create a group",
      primaryHref: props.endpoints?.create,
      secondaryLabel: "Browse public groups",
      secondaryHref: "/groups"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center justify-between gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Collective publishing"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Launch and manage shared identities")), /* @__PURE__ */ React.createElement(xe, { href: props.endpoints?.create, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, "Create group")), pendingInvites.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-amber-300/20 bg-amber-400/10 p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-amber-50" }, "Pending invites"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, pendingInvites.map((invite) => /* @__PURE__ */ React.createElement("article", { key: invite.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-white" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold" }, invite.group?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-amber-50/80" }, "Role: ", invite.role), invite.invited_by ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-amber-50/70" }, "Invited by ", invite.invited_by.name || invite.invited_by.username) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(invite.accept_url), className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-2 text-sm font-semibold text-emerald-100" }, "Accept"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(invite.decline_url), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Decline")))))) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, groups.length > 0 ? groups.map((group) => /* @__PURE__ */ React.createElement(GroupCard, { key: group.slug, group })) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 px-6 py-16 text-center text-slate-400" }, "No groups yet. Create one to start publishing collaboratively.")));
}
const __vite_glob_0_147 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGroupsIndex
}, Symbol.toStringTag, { value: "Module" }));
const rangeOptions = [7, 14, 30, 60, 90];
const summaryCards = [
  ["followers", "Followers", "fa-user-group"],
  ["published_in_range", "Published", "fa-calendar-check"],
  ["engagement_actions", "Engagement actions", "fa-bolt"],
  ["profile_completion", "Profile completion", "fa-id-card"],
  ["challenge_entries", "Challenge entries", "fa-trophy"],
  ["featured_modules", "Featured modules", "fa-star"]
];
function formatShortDate(value) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return value;
  return date.toLocaleDateString(void 0, { month: "short", day: "numeric" });
}
function TrendBars({ title, subtitle, points, colorClass }) {
  const normalizedPoints = Array.isArray(points) ? points : [];
  const values = normalizedPoints.map((point2) => Number(point2.value || point2.count || 0));
  const maxValue = Math.max(...values, 1);
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle), normalizedPoints.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex h-52 items-center justify-center rounded-[22px] border border-dashed border-white/10 bg-black/20 px-6 text-sm text-slate-400" }, "No growth points are available for this time window yet.") : /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex h-52 items-end gap-2" }, normalizedPoints.map((point2) => {
    const value = Number(point2.value || point2.count || 0);
    const height = `${Math.max(8, Math.round(value / maxValue * 100))}%`;
    return /* @__PURE__ */ React.createElement("div", { key: point2.date, className: "flex h-full min-w-0 flex-1 flex-col items-center justify-end gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[10px] font-medium text-slate-500" }, value.toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "flex w-full flex-1 items-end rounded-t-[18px] bg-white/[0.03] px-[2px]" }, /* @__PURE__ */ React.createElement("div", { className: `w-full rounded-t-[16px] ${colorClass}`, style: { height } })), /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.14em] text-slate-500" }, formatShortDate(point2.date)));
  })));
}
function StudioGrowth() {
  const { props } = X$1();
  const { summary, moduleFocus, checkpoints, opportunities, milestones, momentum, topContent, rangeDays } = props;
  const updateRange = (days) => {
    trackStudioEvent("studio_filter_used", {
      surface: studioSurface(),
      module: "growth",
      meta: {
        range_days: days
      }
    });
    At.get(window.location.pathname, { range_days: days }, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(34,197,94,0.12),_transparent_34%),radial-gradient(circle_at_bottom_right,_rgba(56,189,248,0.12),_transparent_40%),linear-gradient(135deg,_rgba(15,23,42,0.88),_rgba(2,6,23,0.96))] p-5 shadow-[0_22px_60px_rgba(2,6,23,0.28)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Growth window"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Creator growth over the last ", rangeDays || 30, " days"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, "This view blends audience momentum, profile readiness, featured curation, and challenge participation into one operating surface.")), /* @__PURE__ */ React.createElement("div", { className: "inline-flex rounded-full border border-white/10 bg-black/20 p-1" }, rangeOptions.map((days) => /* @__PURE__ */ React.createElement("button", { key: days, type: "button", onClick: () => updateRange(days), className: `rounded-full px-4 py-2 text-sm font-semibold transition ${Number(rangeDays || 30) === days ? "bg-white text-slate-950" : "text-slate-300 hover:text-white"}` }, days, "d"))))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 xl:grid-cols-6" }, summaryCards.map(([key, label, icon]) => /* @__PURE__ */ React.createElement("div", { key, className: "rounded-[26px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${icon} text-sky-200` })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(summary?.[key] || 0).toLocaleString())))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(TrendBars, { title: "Views momentum", subtitle: "Cross-module reach across the current growth window.", points: momentum?.views_trend || [], colorClass: "bg-emerald-400/60" }), /* @__PURE__ */ React.createElement(TrendBars, { title: "Engagement momentum", subtitle: "Reactions, comments, shares, and saves translated into a cleaner direction-of-travel signal.", points: momentum?.engagement_trend || [], colorClass: "bg-pink-400/60" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Growth checkpoints"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (checkpoints || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.detail)), /* @__PURE__ */ React.createElement("div", { className: "text-right" }, /* @__PURE__ */ React.createElement("div", { className: "text-2xl font-semibold text-white" }, item.score), /* @__PURE__ */ React.createElement("div", { className: "text-[10px] uppercase tracking-[0.16em] text-slate-500" }, item.status.replace("_", " ")))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: `h-full rounded-full ${item.score >= 80 ? "bg-emerald-400/70" : item.score >= 55 ? "bg-amber-400/70" : "bg-rose-400/70"}`, style: { width: `${Math.max(6, item.score)}%` } })), /* @__PURE__ */ React.createElement(
    "a",
    {
      href: item.href,
      onClick: () => trackStudioEvent("studio_insight_clicked", {
        surface: studioSurface(),
        module: "growth",
        meta: {
          insight_key: item.key,
          href: item.href
        }
      }),
      className: "mt-4 inline-flex items-center gap-2 text-sm font-medium text-sky-100"
    },
    item.cta,
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })
  ))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Growth opportunities"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (opportunities || []).map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.title,
      href: item.href,
      onClick: () => trackStudioEvent("studio_insight_clicked", {
        surface: studioSurface(),
        module: "growth",
        meta: {
          insight_key: item.title,
          href: item.href
        }
      }),
      className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20"
    },
    /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, item.title),
    /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body),
    /* @__PURE__ */ React.createElement("span", { className: "mt-3 inline-flex items-center gap-2 text-sm font-medium text-sky-100" }, item.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))
  ))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Module focus"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Share of workspace output")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (moduleFocus || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.key, href: item.href, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, item.published_count, " published • ", item.draft_count, " drafts"))), /* @__PURE__ */ React.createElement("span", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-sky-100" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Views"), /* @__PURE__ */ React.createElement("span", null, item.views.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-emerald-400/60", style: { width: `${Math.max(4, item.view_share)}%` } }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Engagement"), /* @__PURE__ */ React.createElement("span", null, item.engagement.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-pink-400/60", style: { width: `${Math.max(4, item.engagement_share)}%` } })))))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (milestones || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.current.toLocaleString(), " of ", item.target.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "text-xl font-semibold text-white" }, item.progress, "%")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-sky-300/60", style: { width: `${Math.max(6, item.progress)}%` } }))))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Publishing rhythm"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (momentum?.publishing_timeline || []).map((point2) => /* @__PURE__ */ React.createElement("div", { key: point2.date }, /* @__PURE__ */ React.createElement("div", { className: "mb-1 flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatShortDate(point2.date)), /* @__PURE__ */ React.createElement("span", null, point2.count)), /* @__PURE__ */ React.createElement("div", { className: "h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-sky-300/60", style: { width: `${Math.min(100, Number(point2.count || 0) * 18)}%` } })))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Top content this window"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (topContent || []).map((item) => /* @__PURE__ */ React.createElement(
    "a",
    {
      key: item.id,
      href: item.analytics_url || item.view_url,
      onClick: () => trackStudioEvent("studio_insight_clicked", {
        surface: studioSurface(),
        module: "growth",
        item_module: item.module_key,
        item_id: item.numeric_id,
        meta: {
          insight_key: "top_content",
          href: item.analytics_url || item.view_url
        }
      }),
      className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20"
    },
    /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.module_label),
    /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, item.title),
    /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.views || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Reactions"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.appreciation || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.comments || 0).toLocaleString())))
  ))))));
}
const __vite_glob_0_148 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioGrowth
}, Symbol.toStringTag, { value: "Module" }));
async function requestJson$3(url, method = "POST") {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) throw new Error(payload?.message || "Request failed");
  return payload;
}
function formatDate$2(value) {
  if (!value) return "Unknown";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Unknown";
  return date.toLocaleString(void 0, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
}
const priorityClasses = {
  high: "border-rose-300/20 bg-rose-300/10 text-rose-100",
  medium: "border-sky-300/20 bg-sky-300/10 text-sky-100",
  low: "border-white/10 bg-white/[0.03] text-slate-300"
};
function StudioInbox() {
  const { props } = X$1();
  const inbox = props.inbox || {};
  const filters = inbox.filters || {};
  const items = inbox.items || [];
  const meta = inbox.meta || {};
  const summary = inbox.summary || {};
  const [marking, setMarking] = reactExports.useState(false);
  const updateFilters = (patch2) => {
    const next = { ...filters, ...patch2 };
    if (patch2.page == null) next.page = 1;
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  const markAllRead = async () => {
    setMarking(true);
    try {
      await requestJson$3(props.endpoints.markAllRead);
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to mark inbox as read.");
    } finally {
      setMarking(false);
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description, actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: markAllRead, disabled: marking, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check-double" }), marking ? "Updating..." : "Mark all read") }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Unread"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.unread_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "High priority"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.high_priority_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.comment_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.follower_count || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[320px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Filters"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Actor, title, or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "all", onChange: (val) => updateFilters({ type: val }), options: inbox.type_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: inbox.module_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Read state"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.read_state || "all", onChange: (val) => updateFilters({ read_state: val }), options: inbox.read_state_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Priority"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.priority || "all", onChange: (val) => updateFilters({ priority: val }), options: inbox.priority_options || [], searchable: false })))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attention now"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (inbox.panels?.attention_now || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label)))))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: `rounded-[28px] border p-5 ${item.is_new ? "border-sky-300/20 bg-sky-300/10" : "border-white/10 bg-white/[0.03]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-4" }, item.actor?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.actor.avatar_url, alt: item.actor.name || "Actor", className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-black/20 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bell" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, item.module_label), /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2 py-1 ${priorityClasses[item.priority] || priorityClasses.low}` }, item.priority), item.is_new && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-300/20 px-2 py-1 text-sky-100" }, "Unread")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatDate$2(item.created_at)), item.actor?.name && /* @__PURE__ */ React.createElement("span", null, item.actor.name), /* @__PURE__ */ React.createElement("a", { href: item.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-slate-200" }, "Open")))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No inbox items match this filter."), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Previous"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next"))))));
}
const __vite_glob_0_149 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioInbox
}, Symbol.toStringTag, { value: "Module" }));
let _toastId = 0;
function useToast() {
  const [toasts, setToasts] = reactExports.useState([]);
  const push2 = reactExports.useCallback((message, type2 = "info") => {
    const id = ++_toastId;
    setToasts((prev) => [...prev, { id, message, type: type2 }]);
    setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 5e3);
  }, []);
  const dismiss = reactExports.useCallback((id) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);
  return { toasts, push: push2, dismiss };
}
function ToastStack({ toasts, onDismiss }) {
  if (!toasts.length) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "fixed bottom-6 right-6 z-[9999] flex flex-col gap-2", "aria-live": "polite" }, toasts.map((t) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: t.id,
      className: [
        "flex items-start gap-3 rounded-2xl border px-4 py-3 text-sm shadow-2xl backdrop-blur-sm",
        t.type === "success" ? "border-emerald-400/30 bg-emerald-950/90 text-emerald-100" : t.type === "error" ? "border-rose-400/30 bg-rose-950/90 text-rose-100" : "border-white/15 bg-slate-900/90 text-slate-100"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 text-base leading-none" }, t.type === "success" ? "✓" : t.type === "error" ? "✕" : "ℹ"),
    /* @__PURE__ */ React.createElement("span", { className: "flex-1 leading-5" }, t.message),
    /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => onDismiss(t.id),
        className: "ml-2 opacity-60 hover:opacity-100",
        "aria-label": "Dismiss"
      },
      "×"
    )
  )));
}
function SearchResultList$3({ items, onSelect, emptyLabel = "No matches yet." }) {
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-3 text-xs text-slate-500" }, emptyLabel);
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, items.map((item) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: `${item.entity_type}-${item.id}`,
      type: "button",
      onClick: () => onSelect(item),
      className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-3 py-3 text-left transition hover:border-white/20"
    },
    item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: item.title, className: "h-10 w-10 rounded-2xl border border-white/10 object-cover" }) : null,
    /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 line-clamp-2 text-xs text-slate-400" }, item.description) : null)
  )));
}
function FieldError({ message }) {
  if (!message) return null;
  return /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, message);
}
function normalizeNewTagName(value) {
  return String(value || "").replace(/\s+/g, " ").trim().slice(0, 80);
}
function normalizeNewsTagKey(value) {
  return normalizeNewTagName(value).toLowerCase();
}
function parseNewsTagList(input) {
  return String(input || "").split(/[\n,]+/).map((item) => normalizeNewTagName(item)).filter(Boolean);
}
function analyzePastedNewsTags(rawText, selectedKeys) {
  const parts = parseNewsTagList(rawText);
  const tagsToAdd = [];
  const skippedDuplicates = [];
  const skippedInvalid = [];
  for (const part of parts) {
    const normalized = normalizeNewTagName(part);
    const key = normalizeNewsTagKey(normalized);
    if (!normalized || !key) {
      skippedInvalid.push(String(part || "").trim());
      continue;
    }
    if (selectedKeys.includes(key) || tagsToAdd.some((item) => item.key === key)) {
      skippedDuplicates.push(normalized);
      continue;
    }
    tagsToAdd.push({ key, name: normalized });
  }
  return {
    parsedCount: parts.length,
    tagsToAdd,
    skippedDuplicates,
    skippedInvalid
  };
}
function SectionCard({ eyebrow, title, description, actions, children, tone = "default" }) {
  const toneClass = tone === "feature" ? "bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] shadow-[0_24px_70px_rgba(2,6,23,0.28)]" : "bg-white/[0.03]";
  return /* @__PURE__ */ React.createElement("section", { className: `rounded-[28px] border border-white/10 p-5 ${toneClass}` }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/75" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, description) : null), actions ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, actions) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children));
}
function NewsTagInputDialog({ open, preview, onClose, onConfirm }) {
  const backdropRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open || !preview) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "dialog",
          "aria-modal": "true",
          "aria-labelledby": "news-tag-import-title",
          className: "w-full max-w-lg overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]"
        },
        /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Tag Import"), /* @__PURE__ */ React.createElement("h3", { id: "news-tag-import-title", className: "mt-2 text-lg font-semibold text-white" }, "Add ", preview.tagsToAdd.length, " pasted tag", preview.tagsToAdd.length === 1 ? "" : "s", "?"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Parsed ", preview.parsedCount, " item", preview.parsedCount === 1 ? "" : "s", " from your paste. Confirm before adding them to the article.")),
        /* @__PURE__ */ React.createElement("div", { className: "space-y-4 px-6 py-5" }, preview.skippedDuplicates.length > 0 || preview.skippedInvalid.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-white/70" }, preview.skippedDuplicates.length > 0 ? `${preview.skippedDuplicates.length} duplicate tag${preview.skippedDuplicates.length === 1 ? "" : "s"} ignored.` : "", preview.skippedDuplicates.length > 0 && preview.skippedInvalid.length > 0 ? " " : "", preview.skippedInvalid.length > 0 ? `${preview.skippedInvalid.length} invalid tag${preview.skippedInvalid.length === 1 ? "" : "s"} ignored.` : "") : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-xs font-semibold uppercase tracking-[0.18em] text-white/40" }, "Tags to add"), /* @__PURE__ */ React.createElement("div", { className: "max-h-56 overflow-auto rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, preview.tagsToAdd.map((tag) => /* @__PURE__ */ React.createElement(
          "span",
          {
            key: tag.key,
            className: "inline-flex items-center rounded-full border border-sky-300/25 bg-sky-400/10 px-3 py-1.5 text-xs font-medium text-sky-100"
          },
          tag.name
        )))))),
        /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onClose?.(),
            className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white"
          },
          "Cancel"
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onConfirm?.(),
            className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110"
          },
          "Add tags"
        ))
      )
    ),
    document.body
  );
}
function NewsTagInput({ options, selectedIds, newTagNames, onSelectedIdsChange, onNewTagNamesChange, manageUrl, maxNewTags = NEWS_NEW_TAG_LIMIT }) {
  const [query, setQuery] = reactExports.useState("");
  const [isOpen, setIsOpen] = reactExports.useState(false);
  const [highlightedIndex, setHighlightedIndex] = reactExports.useState(-1);
  const [error, setError] = reactExports.useState("");
  const [pastePreview, setPastePreview] = reactExports.useState(null);
  const selectedIdSet = reactExports.useMemo(() => new Set((selectedIds || []).map((id) => Number(id))), [selectedIds]);
  const existingTags = reactExports.useMemo(() => (Array.isArray(options) ? options : []).filter((tag) => selectedIdSet.has(Number(tag.id))), [options, selectedIdSet]);
  const pendingTags = reactExports.useMemo(() => (Array.isArray(newTagNames) ? newTagNames : []).map((name2) => ({ key: normalizeNewsTagKey(name2), name: normalizeNewTagName(name2) })).filter((tag) => tag.key), [newTagNames]);
  const combinedNames = reactExports.useMemo(() => [...existingTags.map((tag) => String(tag.name || "")), ...pendingTags.map((tag) => tag.name)], [existingTags, pendingTags]);
  const combinedKeys = reactExports.useMemo(() => combinedNames.map((name2) => normalizeNewsTagKey(name2)).filter(Boolean), [combinedNames]);
  const newTagLimit = Math.max(0, Number(maxNewTags || NEWS_NEW_TAG_LIMIT));
  const remainingNewTagSlots = Math.max(0, newTagLimit - pendingTags.length);
  const normalizedQuery = reactExports.useMemo(() => normalizeNewTagName(query), [query]);
  const syncNames = reactExports.useCallback((names) => {
    const seen = /* @__PURE__ */ new Set();
    const nextIds = [];
    const nextNewNames = [];
    names.forEach((rawName) => {
      const nextName = normalizeNewTagName(rawName);
      const key = normalizeNewsTagKey(nextName);
      if (!key || seen.has(key)) {
        return;
      }
      seen.add(key);
      const existing = (Array.isArray(options) ? options : []).find((tag) => normalizeNewsTagKey(tag.name) === key);
      if (existing) {
        nextIds.push(Number(existing.id));
        return;
      }
      nextNewNames.push(nextName);
    });
    onSelectedIdsChange(nextIds);
    onNewTagNamesChange(nextNewNames);
  }, [onNewTagNamesChange, onSelectedIdsChange, options]);
  const exactMatch = reactExports.useMemo(() => {
    if (!normalizedQuery) return null;
    return (Array.isArray(options) ? options : []).find((tag) => normalizeNewsTagKey(tag.name) === normalizeNewsTagKey(normalizedQuery)) || null;
  }, [normalizedQuery, options]);
  const suggestions = reactExports.useMemo(() => {
    const source = Array.isArray(options) ? options : [];
    const lowerQuery = normalizeNewsTagKey(query);
    return source.filter((tag) => !selectedIdSet.has(Number(tag.id))).filter((tag) => !pendingTags.some((pendingTag) => pendingTag.key === normalizeNewsTagKey(tag.name))).filter((tag) => lowerQuery === "" ? true : normalizeNewsTagKey(tag.name).includes(lowerQuery)).slice(0, 8);
  }, [options, pendingTags, query, selectedIdSet]);
  reactExports.useEffect(() => {
    setHighlightedIndex(suggestions.length > 0 ? 0 : -1);
  }, [suggestions]);
  const addCandidate = reactExports.useCallback((rawName) => {
    const nextName = normalizeNewTagName(rawName);
    if (!nextName) {
      return;
    }
    const key = normalizeNewsTagKey(nextName);
    if (combinedKeys.includes(key)) {
      setError("Duplicate tag");
      return;
    }
    if (pendingTags.length >= newTagLimit) {
      setError(`You can add up to ${newTagLimit} new tags per article.`);
      return;
    }
    setError("");
    syncNames([...combinedNames, nextName]);
    setQuery("");
    setIsOpen(false);
  }, [combinedKeys, combinedNames, newTagLimit, pendingTags.length, syncNames]);
  const removeExisting = reactExports.useCallback((tagId) => {
    onSelectedIdsChange((selectedIds || []).filter((id) => Number(id) !== Number(tagId)));
  }, [onSelectedIdsChange, selectedIds]);
  const removePending = reactExports.useCallback((tagName) => {
    onNewTagNamesChange((newTagNames || []).filter((name2) => normalizeNewsTagKey(name2) !== normalizeNewsTagKey(tagName)));
  }, [newTagNames, onNewTagNamesChange]);
  const handlePaste = reactExports.useCallback((event) => {
    const raw = event.clipboardData?.getData("text");
    if (!raw) return;
    const parts = parseNewsTagList(raw);
    if (parts.length <= 1) return;
    event.preventDefault();
    const preview = analyzePastedNewsTags(raw, combinedKeys);
    if (preview.tagsToAdd.length === 0) {
      setError("No new tags found in pasted text");
      return;
    }
    if (preview.tagsToAdd.length > remainingNewTagSlots) {
      setError(`You can only add ${remainingNewTagSlots} more new tag${remainingNewTagSlots === 1 ? "" : "s"} to this article.`);
      return;
    }
    setError("");
    setPastePreview(preview);
  }, [combinedKeys, remainingNewTagSlots]);
  const handleConfirmPaste = reactExports.useCallback(() => {
    if (!pastePreview) return;
    syncNames([...combinedNames, ...pastePreview.tagsToAdd.map((tag) => tag.name)]);
    setPastePreview(null);
    setQuery("");
    setIsOpen(false);
  }, [combinedNames, pastePreview, syncNames]);
  const handleKeyDown2 = reactExports.useCallback((event) => {
    if (event.key === "Escape") {
      setIsOpen(false);
      return;
    }
    if (event.key === "Backspace" && query.length === 0 && combinedNames.length > 0) {
      const lastPending = pendingTags[pendingTags.length - 1];
      if (lastPending) {
        removePending(lastPending.name);
        return;
      }
      const lastExisting = existingTags[existingTags.length - 1];
      if (lastExisting) {
        removeExisting(lastExisting.id);
      }
      return;
    }
    if (event.key === "ArrowDown") {
      event.preventDefault();
      if (suggestions.length === 0) return;
      setIsOpen(true);
      setHighlightedIndex((current) => Math.min(current + 1, suggestions.length - 1));
      return;
    }
    if (event.key === "ArrowUp") {
      event.preventDefault();
      if (suggestions.length === 0) return;
      setIsOpen(true);
      setHighlightedIndex((current) => Math.max(current - 1, 0));
      return;
    }
    if (!["Enter", ",", "Tab"].includes(event.key)) {
      return;
    }
    if (event.key === "Tab" && !isOpen && normalizedQuery === "") {
      return;
    }
    event.preventDefault();
    if ((event.key === "Enter" || event.key === "Tab") && isOpen && highlightedIndex >= 0 && suggestions[highlightedIndex]) {
      addCandidate(suggestions[highlightedIndex].name);
      return;
    }
    if (!normalizedQuery) {
      return;
    }
    if (exactMatch) {
      addCandidate(exactMatch.name);
      return;
    }
    addCandidate(normalizedQuery);
  }, [addCandidate, combinedNames.length, exactMatch, existingTags, highlightedIndex, isOpen, normalizedQuery, pendingTags, query.length, removeExisting, removePending, suggestions]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Selected tags"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "Attach article topics with the same chip-based flow used on artwork tags.")), manageUrl ? /* @__PURE__ */ React.createElement("a", { href: manageUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, "Manage tags") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 min-h-[3rem] rounded-xl border border-white/10 bg-white/5 p-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, existingTags.length === 0 && pendingTags.length === 0 ? /* @__PURE__ */ React.createElement("span", { className: "px-2 py-1 text-xs text-white/50" }, "No tags selected") : null, existingTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag.id, className: "group inline-flex max-w-full items-center gap-2 rounded-full border border-white/20 bg-slate-900/80 px-3 py-1.5 text-xs text-slate-100" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, tag.name), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeExisting(tag.id), className: "rounded-full p-0.5 text-slate-300 transition hover:bg-white/10 hover:text-white", "aria-label": `Remove tag ${tag.name}` }, "✕"))), pendingTags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag.key, className: "group inline-flex max-w-full items-center gap-2 rounded-full border border-emerald-300/25 bg-emerald-400/10 px-3 py-1.5 text-xs text-emerald-50" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, tag.name), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-200/30 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] text-emerald-100/80" }, "New"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removePending(tag.name), className: "rounded-full p-0.5 text-emerald-100/75 transition hover:bg-white/10 hover:text-white", "aria-label": `Remove new tag ${tag.name}` }, "✕"))))), /* @__PURE__ */ React.createElement("div", { className: `mt-3 rounded-2xl border px-3 py-2 text-xs ${remainingNewTagSlots === 0 ? "border-amber-300/25 bg-amber-400/10 text-amber-100" : remainingNewTagSlots <= 3 ? "border-amber-300/20 bg-amber-400/8 text-amber-100" : "border-white/10 bg-white/[0.03] text-slate-400"}` }, remainingNewTagSlots === 0 ? `New tag limit reached: up to ${newTagLimit} new tags can be staged for one article.` : `${pendingTags.length}/${newTagLimit} new tags staged. ${remainingNewTagSlots} slot${remainingNewTagSlots === 1 ? "" : "s"} left.`)), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Find tags"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: query,
      onChange: (event) => {
        setQuery(event.target.value);
        setError("");
        setIsOpen(true);
      },
      onFocus: () => setIsOpen(true),
      onKeyDown: handleKeyDown2,
      onPaste: handlePaste,
      placeholder: "Search existing tags or type a new one",
      className: "w-full rounded-xl border border-white/10 bg-white/10 px-3 py-2 text-sm text-white placeholder:text-white/45 focus:border-sky-400 focus:outline-none",
      "aria-label": "Search or add news tags"
    }
  )), isOpen ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 overflow-hidden rounded-xl bg-slate-950/98 shadow-xl shadow-black/50 ring-1 ring-white/10" }, /* @__PURE__ */ React.createElement("ul", { role: "listbox", className: "max-h-56 overflow-auto py-1" }, suggestions.length > 0 ? suggestions.map((tag, index2) => {
    const active = index2 === highlightedIndex;
    return /* @__PURE__ */ React.createElement(
      "li",
      {
        key: tag.id,
        role: "option",
        "aria-selected": active,
        className: `flex cursor-pointer items-center justify-between gap-2 px-3 py-2 text-sm transition ${active ? "bg-sky-500/20 text-white" : "text-white/85 hover:bg-white/10"}`,
        onMouseDown: (event) => {
          event.preventDefault();
          addCandidate(tag.name);
        }
      },
      /* @__PURE__ */ React.createElement("span", { className: "truncate" }, tag.name)
    );
  }) : /* @__PURE__ */ React.createElement("li", { className: "px-3 py-2 text-xs text-white/50" }, "No suggestions"))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-between gap-3 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: error ? "text-amber-200" : "text-white/55", role: "status", "aria-live": "polite" }, error || `Type and press Enter, comma, or Tab to add. Paste a comma-separated list to review multiple tags. Up to ${newTagLimit} new tags can be staged.`), /* @__PURE__ */ React.createElement("span", { className: "text-white/50" }, existingTags.length + pendingTags.length, " selected")))), /* @__PURE__ */ React.createElement(
    NewsTagInputDialog,
    {
      open: Boolean(pastePreview),
      preview: pastePreview,
      onClose: () => setPastePreview(null),
      onConfirm: handleConfirmPaste
    }
  ));
}
function RelationCard({ relation, index: index2, onChange, onRemove, onSearch, results, relationTypeOptions }) {
  const isSourceRelation = String(relation.entity_type || "").trim().toLowerCase() === "source";
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[180px_minmax(0,1fr)_auto] lg:items-end" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: relation.entity_type, onChange: (val) => onChange(index2, { ...relation, entity_type: val, entity_id: "", external_url: "", preview: null, query: "" }), options: relationTypeOptions, searchable: false })), isSourceRelation ? /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Source URL"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: relation.external_url || "",
      onChange: (event) => onChange(index2, { ...relation, external_url: event.target.value, query: event.target.value, entity_id: "" }),
      placeholder: "https://example.com/original-article",
      className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
    }
  )) : /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search entity"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("input", { value: relation.query || "", onChange: (event) => onChange(index2, { ...relation, query: event.target.value }), placeholder: "Search by name, slug, or title", className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onSearch(index2), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white" }, "Search"))), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onRemove(index2), className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100" }, "Remove")), !isSourceRelation && relation.preview ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 p-4 text-sm text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, "Linked: ", relation.preview.title), relation.preview.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-emerald-100/70" }, relation.preview.subtitle) : null) : null, isSourceRelation ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/15 bg-sky-400/10 px-4 py-3 text-sm text-sky-100/90" }, "Source relations store a direct external URL instead of an internal Nova entity ID.") : /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(SearchResultList$3, { items: results, onSelect: (item) => onChange(index2, { ...relation, entity_id: item.id, preview: item, query: item.title }), emptyLabel: "Search to attach a related entity." })), /* @__PURE__ */ React.createElement("label", { className: "mt-4 grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Context label"), /* @__PURE__ */ React.createElement("input", { value: relation.context_label || "", onChange: (event) => onChange(index2, { ...relation, context_label: event.target.value }), placeholder: "Featured release, Meet the creator, Join this challenge…", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })));
}
function stripHtml$1(value) {
  return String(value || "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
}
function unwrapMarkdownLinkUrl(value) {
  const raw = String(value || "").trim();
  if (!raw) return "";
  const markdownMatch = raw.match(/^\[[^\]]+\]\((https?:\/\/[^)]+)\)$/i);
  if (markdownMatch) {
    return String(markdownMatch[1] || "").trim();
  }
  return raw;
}
function isSourceRelationType(entityType) {
  return String(entityType || "").trim().toLowerCase() === "source";
}
const NEWS_NEW_TAG_LIMIT = 30;
function slugifyNewsTitle(value) {
  return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 180);
}
function selectOptionsFromValues(options, emptyLabel = null) {
  const base = Array.isArray(options) ? options.map((option) => ({
    value: String(option.value ?? option.id),
    label: option.label ?? option.name
  })) : [];
  return emptyLabel ? [{ value: "", label: emptyLabel }, ...base] : base;
}
function buildSubmitPayload(data) {
  return {
    title: String(data.title || "").trim(),
    slug: String(data.slug || "").trim(),
    excerpt: String(data.excerpt || ""),
    content: String(data.content || ""),
    cover_image: String(data.cover_image || "").trim(),
    type: String(data.type || ""),
    category_id: data.category_id === "" || data.category_id == null ? null : Number(data.category_id),
    author_id: data.author_id === "" || data.author_id == null ? null : Number(data.author_id),
    editorial_status: String(data.editorial_status || ""),
    published_at: data.published_at ? String(data.published_at) : null,
    is_featured: Boolean(data.is_featured),
    is_pinned: Boolean(data.is_pinned),
    comments_enabled: Boolean(data.comments_enabled),
    tag_ids: Array.isArray(data.tag_ids) ? data.tag_ids.map((id) => Number(id)).filter(Boolean) : [],
    new_tag_names: Array.isArray(data.new_tag_names) ? data.new_tag_names.map((name2) => normalizeNewTagName(name2)).filter(Boolean) : [],
    meta_title: String(data.meta_title || ""),
    meta_description: String(data.meta_description || ""),
    meta_keywords: String(data.meta_keywords || ""),
    og_title: String(data.og_title || ""),
    og_description: String(data.og_description || ""),
    og_image: String(data.og_image || "").trim(),
    relations: Array.isArray(data.relations) ? data.relations.map((relation) => ({
      entity_type: String(relation.entity_type || "").trim(),
      entity_id: isSourceRelationType(relation.entity_type) || relation.entity_id === "" || relation.entity_id == null ? "" : Number(relation.entity_id),
      external_url: isSourceRelationType(relation.entity_type) ? unwrapMarkdownLinkUrl(relation.external_url || relation.entity_id || relation.query || "") : "",
      context_label: String(relation.context_label || "").trim()
    })) : []
  };
}
function hasRequiredCategory(categoryId) {
  if (categoryId === "" || categoryId == null) {
    return false;
  }
  return Number(categoryId) > 0;
}
function getDraftValue(source, key, fallback = "") {
  if (source && Object.prototype.hasOwnProperty.call(source, key)) {
    const val = source[key];
    return val != null ? val : fallback;
  }
  return fallback;
}
function buildInitialFormData(article, defaultAuthor, defaultPublishedAt, typeOptions, oldInput = {}) {
  return {
    title: String(getDraftValue(oldInput, "title", article.title || "")),
    slug: String(getDraftValue(oldInput, "slug", article.slug || "")),
    excerpt: String(getDraftValue(oldInput, "excerpt", article.excerpt || "")),
    content: String(getDraftValue(oldInput, "content", article.content || "")),
    cover_image: String(getDraftValue(oldInput, "cover_image", article.cover_image || "")),
    type: String(getDraftValue(oldInput, "type", article.type || (typeOptions?.[0]?.value || "announcement"))),
    category_id: String(getDraftValue(oldInput, "category_id", article.category_id ? String(article.category_id) : "")),
    author_id: getDraftValue(oldInput, "author_id", article.author_id || defaultAuthor?.id || ""),
    editorial_status: String(getDraftValue(oldInput, "editorial_status", article.editorial_status || "draft")),
    published_at: String(getDraftValue(oldInput, "published_at", article.published_at ? String(article.published_at).slice(0, 16) : defaultPublishedAt || "")),
    is_featured: parseBooleanish(getDraftValue(oldInput, "is_featured", Boolean(article.is_featured))),
    is_pinned: parseBooleanish(getDraftValue(oldInput, "is_pinned", Boolean(article.is_pinned))),
    comments_enabled: parseBooleanish(getDraftValue(oldInput, "comments_enabled", article.id ? Boolean(article.comments_enabled) : true)),
    tag_ids: Array.isArray(getDraftValue(oldInput, "tag_ids", article.tag_ids)) ? getDraftValue(oldInput, "tag_ids", article.tag_ids) : [],
    new_tag_names: Array.isArray(getDraftValue(oldInput, "new_tag_names", [])) ? getDraftValue(oldInput, "new_tag_names", []) : [],
    meta_title: String(getDraftValue(oldInput, "meta_title", article.meta_title || "")),
    meta_description: String(getDraftValue(oldInput, "meta_description", article.meta_description || "")),
    meta_keywords: String(getDraftValue(oldInput, "meta_keywords", article.meta_keywords || "")),
    og_title: String(getDraftValue(oldInput, "og_title", article.og_title || "")),
    og_description: String(getDraftValue(oldInput, "og_description", article.og_description || "")),
    og_image: String(getDraftValue(oldInput, "og_image", article.og_image || "")),
    relations: Array.isArray(getDraftValue(oldInput, "relations", article.relations)) ? getDraftValue(oldInput, "relations", article.relations).map((relation) => ({
      entity_type: relation.entity_type || "group",
      entity_id: isSourceRelationType(relation.entity_type) ? "" : relation.entity_id || "",
      external_url: isSourceRelationType(relation.entity_type) ? unwrapMarkdownLinkUrl(relation.external_url || relation.entity_id || relation.query || "") : "",
      context_label: relation.context_label || "",
      preview: relation.preview || null,
      query: isSourceRelationType(relation.entity_type) ? unwrapMarkdownLinkUrl(relation.external_url || relation.entity_id || relation.query || "") : relation.preview?.title || relation.query || ""
    })) : []
  };
}
const NEWS_EDITOR_TABS = [
  {
    id: "content",
    label: "Main content",
    description: "Headline, excerpt, cover, and article body."
  },
  {
    id: "publishing",
    label: "Publishing",
    description: "Category, author, scheduling, and visibility."
  },
  {
    id: "discoverability",
    label: "Social + SEO",
    description: "Tags, metadata, and social preview fields."
  },
  {
    id: "connections",
    label: "Connections",
    description: "Related entities and structured import."
  }
];
function parseBooleanish(value) {
  if (typeof value === "boolean") return value;
  if (typeof value === "number") return value !== 0;
  const normalized = String(value || "").trim().toLowerCase();
  if (["1", "true", "yes", "on"].includes(normalized)) return true;
  if (["0", "false", "no", "off"].includes(normalized)) return false;
  return Boolean(value);
}
function normalizeImportedStringArray(value) {
  if (Array.isArray(value)) {
    return value.map((item) => String(item || "").trim()).filter(Boolean);
  }
  return String(value || "").split(/[\n,]+/).map((item) => item.trim()).filter(Boolean);
}
function normalizeImportedTagList(value) {
  if (!Array.isArray(value)) {
    return normalizeImportedStringArray(value);
  }
  return value.map((item) => {
    if (typeof item === "string" || typeof item === "number") {
      return normalizeNewTagName(item);
    }
    if (item && typeof item === "object") {
      return normalizeNewTagName(item.name ?? item.title ?? item.label ?? item.slug ?? "");
    }
    return normalizeNewTagName(item);
  }).filter(Boolean);
}
function normalizeImportedDateTime(value) {
  const raw = String(value || "").trim();
  if (!raw) return "";
  const dateTimeMatch = raw.match(/^(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2})(?::\d{2})?)?$/);
  if (dateTimeMatch) {
    return dateTimeMatch[2] ? `${dateTimeMatch[1]}T${dateTimeMatch[2]}` : dateTimeMatch[1];
  }
  const parsed = new Date(raw);
  if (Number.isNaN(parsed.getTime())) {
    return raw;
  }
  const pad2 = (input) => String(input).padStart(2, "0");
  return `${parsed.getFullYear()}-${pad2(parsed.getMonth() + 1)}-${pad2(parsed.getDate())}T${pad2(parsed.getHours())}:${pad2(parsed.getMinutes())}`;
}
function parseStructuredNewsImport(rawValue, context) {
  const parsed = JSON.parse(String(rawValue || "").trim());
  const categoryOptions = Array.isArray(context.categoryOptions) ? context.categoryOptions : [];
  const tagOptions = Array.isArray(context.tagOptions) ? context.tagOptions : [];
  const typeOptions = Array.isArray(context.typeOptions) ? context.typeOptions : [];
  const statusOptions = Array.isArray(context.statusOptions) ? context.statusOptions : [];
  const next = {};
  const applied = [];
  const applyString = (inputKey, formKey = inputKey) => {
    if (parsed[inputKey] == null) return;
    next[formKey] = String(parsed[inputKey]);
    applied.push(formKey);
  };
  const applyBoolean = (inputKey, formKey = inputKey) => {
    if (parsed[inputKey] == null) return;
    next[formKey] = parseBooleanish(parsed[inputKey]);
    applied.push(formKey);
  };
  applyString("title");
  applyString("slug");
  applyString("excerpt");
  applyString("content");
  applyString("cover_image");
  if (parsed.published_at != null) {
    next.published_at = normalizeImportedDateTime(parsed.published_at);
    applied.push("published_at");
  }
  applyString("meta_title");
  applyString("meta_description");
  applyString("meta_keywords");
  applyString("og_title");
  applyString("og_description");
  if (parsed.type != null) {
    const requested = String(parsed.type).trim().toLowerCase();
    const match = typeOptions.find((option) => String(option.value ?? option.id ?? "").trim().toLowerCase() === requested || String(option.label ?? option.name ?? "").trim().toLowerCase() === requested);
    next.type = match ? String(match.value ?? match.id ?? "") : String(parsed.type);
    applied.push("type");
  }
  if (parsed.editorial_status != null) {
    const requested = String(parsed.editorial_status).trim().toLowerCase();
    const match = statusOptions.find((option) => String(option.value ?? option.id ?? "").trim().toLowerCase() === requested || String(option.label ?? option.name ?? "").trim().toLowerCase() === requested);
    next.editorial_status = match ? String(match.value ?? match.id ?? "") : String(parsed.editorial_status);
    applied.push("editorial_status");
  }
  if (parsed.category_id != null || parsed.category != null || parsed.category_slug != null) {
    const requested = String(parsed.category_id ?? parsed.category_slug ?? parsed.category).trim().toLowerCase();
    const match = categoryOptions.find((option) => [option.id, option.value, option.slug, option.name, option.label].map((candidate) => String(candidate ?? "").trim().toLowerCase()).includes(requested));
    if (match) {
      next.category_id = String(match.id ?? match.value ?? "");
      applied.push("category_id");
    }
  }
  if (parsed.author_id != null) {
    next.author_id = String(parsed.author_id);
    applied.push("author_id");
  }
  applyBoolean("is_featured");
  applyBoolean("is_pinned");
  applyBoolean("comments_enabled");
  const tagNames = normalizeImportedTagList(parsed.tags ?? parsed.tag_names);
  const tagIds = Array.isArray(parsed.tag_ids) ? parsed.tag_ids.map((item) => Number(item)).filter(Boolean) : [];
  if (tagNames.length > 0 || tagIds.length > 0) {
    const existingIds = new Set(tagIds);
    const newTagNames = [];
    tagNames.forEach((tagName) => {
      const normalized = normalizeNewsTagKey(tagName);
      const match = tagOptions.find((option) => normalizeNewsTagKey(option.name) === normalized);
      if (match) {
        existingIds.add(Number(match.id));
      } else {
        newTagNames.push(normalizeNewTagName(tagName));
      }
    });
    next.tag_ids = Array.from(existingIds);
    next.new_tag_names = newTagNames;
    applied.push("tag_ids", "new_tag_names");
  }
  if (Array.isArray(parsed.relations)) {
    next.relations = parsed.relations.map((relation) => {
      const entityType = String(relation?.entity_type || relation?.type || "group").trim();
      const externalUrl = isSourceRelationType(entityType) ? unwrapMarkdownLinkUrl(relation?.external_url || relation?.url || relation?.entity_id || relation?.query || relation?.title || "") : "";
      return {
        entity_type: entityType,
        entity_id: isSourceRelationType(entityType) || relation?.entity_id == null || relation?.entity_id === "" ? "" : Number(relation.entity_id),
        external_url: externalUrl,
        context_label: String(relation?.context_label || relation?.label || "").trim(),
        preview: null,
        query: isSourceRelationType(entityType) ? externalUrl : String(relation?.query || relation?.title || "").trim()
      };
    }).filter((relation) => relation.entity_type);
    applied.push("relations");
  }
  return {
    next,
    applied,
    authorQuery: parsed.author_query != null ? String(parsed.author_query) : parsed.author_name != null ? String(parsed.author_name) : null
  };
}
let newsMarkdownTurndown = null;
let newsMarkdownTurndownPromise = null;
async function loadNewsMarkdownTurndown() {
  if (newsMarkdownTurndown) {
    return newsMarkdownTurndown;
  }
  if (typeof window === "undefined") {
    return null;
  }
  if (!newsMarkdownTurndownPromise) {
    newsMarkdownTurndownPromise = import("./assets/turndown.es-8lfE8z0s.js").then(({ default: TurndownService }) => new TurndownService({
      headingStyle: "atx",
      codeBlockStyle: "fenced",
      bulletListMarker: "-"
    })).then((service) => {
      newsMarkdownTurndown = service;
      return service;
    }).catch(() => null);
  }
  return newsMarkdownTurndownPromise;
}
function findNewsOptionById(options, value) {
  const normalized = String(value || "").trim();
  if (!normalized) return null;
  return (Array.isArray(options) ? options : []).find((option) => String(option.id ?? option.value ?? "").trim() === normalized) || null;
}
function findNewsTagsByIds(options, ids) {
  const idSet = new Set((Array.isArray(ids) ? ids : []).map((id) => Number(id)));
  return (Array.isArray(options) ? options : []).filter((option) => idSet.has(Number(option.id))).map((option) => ({
    id: Number(option.id),
    name: String(option.name || option.label || ""),
    slug: String(option.slug || "")
  }));
}
function buildStructuredPlainTextExport(data) {
  const lines = [];
  if (data.title) lines.push(`Title: ${data.title}`);
  if (data.excerpt) lines.push(`Excerpt: ${data.excerpt}`);
  if (data.date) lines.push(`Date: ${data.date}`);
  if (data.category) lines.push(`Category: ${data.category}`);
  if (data.body) {
    lines.push("");
    lines.push("Body:");
    lines.push(data.body);
  }
  return lines.join("\n").trim();
}
function convertNewsHtmlToMarkdown(value) {
  const html2 = String(value || "").trim();
  if (!html2) return "";
  if (!newsMarkdownTurndown) {
    return stripHtml$1(html2);
  }
  return newsMarkdownTurndown.turndown(html2).trim();
}
function buildNewsMarkdownExport(data) {
  const lines = [];
  if (data.title) {
    lines.push(`# ${data.title}`);
  }
  if (data.excerpt) {
    lines.push(data.excerpt);
  }
  if (data.date) {
    lines.push(`- Date: ${data.date}`);
  }
  if (data.category) {
    lines.push(`- Category: ${data.category}`);
  }
  const bodyMarkdown = convertNewsHtmlToMarkdown(data.body_html);
  if (bodyMarkdown) {
    lines.push(bodyMarkdown);
  }
  return lines.join("\n\n").trim();
}
const NEWS_PROMPT_TYPE_MOODS = {
  announcement: "Futuristic",
  release: "Software Release",
  editorial: "Editorial",
  opinion: "Editorial",
  tutorial: "Clean Instructional",
  platform_update: "Modern Tech",
  event: "Futuristic",
  challenge: "Futuristic",
  interview: "Editorial",
  spotlight: "Editorial",
  archive: "Retro Tech",
  industry_news: "Modern Tech",
  review: "Modern Tech",
  roundup: "Modern Tech"
};
const NEWS_PROMPT_TYPE_ADDONS = {
  release: "Use a glossy software-release poster style with product UI panels, feature highlights, and a polished launch atmosphere.",
  announcement: "Use a clean announcement-poster style with a strong headline, clear hero image, and supporting modules that communicate the main update quickly.",
  editorial: "Use a refined editorial magazine-cover style with a strong visual concept, cleaner composition, and slightly more cinematic atmosphere.",
  opinion: "Use a refined editorial magazine-cover style with a strong visual concept, cleaner composition, and slightly more cinematic atmosphere.",
  event: "Use a conference or event-poster style with keynote energy, glowing screens, stage-like lighting, and a premium event atmosphere.",
  tutorial: "Use a clear structured instructional poster style with organized UI panels, workflow callouts, and helpful visual hierarchy.",
  platform_update: "Use a modern platform-update style with system UI visuals, feature modules, and a polished ecosystem presentation.",
  archive: "Use a retro-tech editorial style inspired by early 2000s computer magazines, with classic hardware, vintage UI influences, and modern polished lighting."
};
const NEWS_PROMPT_KEYWORD_PATTERNS = [
  {
    keywords: ["apple", "wwdc", "ios", "macos", "iphone", "ipad", "swift"],
    addon: "Use a sleek developer-conference atmosphere with modern device screens, app ecosystem visuals, and a premium keynote mood."
  },
  {
    keywords: ["google", "gemini", "google i/o", "android", "pixel", "tensorflow"],
    addon: "Use a colorful futuristic creative AI studio style with glowing panels, image and video creation tools, search elements, and generative media visuals."
  },
  {
    keywords: ["intel", "amd", "processor", "cpu", "gpu", "nvidia", "radeon", "chip"],
    addon: "Use a retro computing hardware feature style with processor chips, technical callouts, old-school PC references, and magazine-cover energy."
  },
  {
    keywords: ["skin", "theme", "desktop", "customize", "customization", "rainmeter", "widget"],
    addon: "Use a desktop customization promo style with theme previews, icon panels, widget windows, and a glossy desktop software aesthetic."
  },
  {
    keywords: ["ai", "artificial intelligence", "llm", "chatgpt", "openai", "midjourney", "stable diffusion", "generative"],
    addon: "Use a colorful futuristic creative AI studio style with glowing panels, generative media outputs, neural network visuals, and advanced AI tool interfaces."
  }
];
function resolveNewsPromptHeadline(data) {
  return String(data.title || data.meta_title || "").trim() || "Skinbase News";
}
function resolveNewsPromptSubheadline(data) {
  const raw = String(data.excerpt || data.meta_description || "").replace(/<[^>]*>/g, "").trim();
  if (raw) {
    const words = raw.split(/\s+/);
    return words.slice(0, 18).join(" ") + (words.length > 18 ? "…" : "");
  }
  const plain = String(data.content || "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
  if (plain) {
    const sentence = plain.split(/[.!?]/)[0].trim();
    if (sentence.length > 10) {
      const words = sentence.split(/\s+/);
      return words.slice(0, 18).join(" ");
    }
  }
  return "Latest technology and creative industry update";
}
function resolveNewsPromptTopic(data) {
  const parts = [];
  const cat = String(data.category || "").trim();
  if (cat) parts.push(cat);
  const tagList = (Array.isArray(data.tag_names) ? data.tag_names : []).slice(0, 5).filter(Boolean);
  if (tagList.length) parts.push(tagList.join(", "));
  if (!parts.length) {
    const words = String(data.title || "").split(/\s+/).filter((w2) => w2.length > 3).slice(0, 4);
    if (words.length) parts.push(words.join(" "));
  }
  return parts.join(" · ") || "Technology and digital culture news";
}
function resolveNewsPromptType(data) {
  const raw = String(data.type || "").trim();
  if (!raw) return "News";
  return raw.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
function resolveNewsPromptHeroSubject(data) {
  const title = String(data.title || "").toLowerCase();
  const tags = (Array.isArray(data.tag_names) ? data.tag_names : []).join(" ").toLowerCase();
  const combined = `${title} ${tags}`;
  const type2 = String(data.type || "").toLowerCase();
  if (/apple|wwdc|ios|macos/.test(combined)) return "sleek developer conference scene with modern Apple devices, app ecosystem screens, and a keynote stage atmosphere";
  if (/google|gemini|google i\/o/.test(combined)) return "futuristic creative AI workspace with Google AI tools, image and video generation screens, and colorful generative panels";
  if (/intel|amd|cpu|processor|gpu|nvidia|radeon/.test(combined)) return "high-detail processor chip and PC hardware setup with technical callouts and magazine-style editorial framing";
  if (/\bai\b|artificial intelligence|llm|chatgpt|openai|midjourney|stable diffusion/.test(combined)) return "futuristic AI creative studio with generative media outputs, neural network interfaces, and glowing AI panels";
  if (/skin|theme|desktop|customiz|rainmeter|widget/.test(combined)) return "polished desktop customization interface with theme previews, icon panels, and widget windows on a dark desktop";
  if (/game|gaming/.test(combined)) return "immersive gaming setup or game UI with dynamic lighting, modern peripherals, and a premium game atmosphere";
  if (/microsoft|windows/.test(combined)) return "modern Windows interface with system UI panels, taskbar, settings, and a polished OS environment";
  if (type2 === "tutorial") return "organized instructional workflow panel with step-by-step UI callouts and visual hierarchy";
  if (type2 === "event") return "keynote conference stage with large screens, glowing hall, and event atmosphere";
  if (type2 === "archive") return "retro computing hardware from the early 2000s with classic monitors and vintage PC aesthetic";
  return "professional editorial tech workspace with software screens, feature panels, and a polished digital newsroom atmosphere";
}
function resolveNewsPromptSupportingModules(data) {
  const type2 = String(data.type || "").toLowerCase();
  const title = String(data.title || "").toLowerCase();
  const tags = (Array.isArray(data.tag_names) ? data.tag_names : []).join(" ").toLowerCase();
  const combined = `${title} ${tags}`;
  if (type2 === "release" || /release|launch|version/.test(combined)) return "version badge, feature highlight cards, changelog strip, UI screenshots, product icon panels";
  if (type2 === "tutorial") return "step-by-step panels, UI callouts, workflow arrows, numbered feature blocks";
  if (type2 === "event") return "schedule panels, speaker cards, keynote countdown, location badge, feature preview cards";
  if (type2 === "archive") return "retro spec badges, vintage hardware panels, timeline strip, era-appropriate UI screenshots";
  if (/\bai\b|artificial intelligence|generative/.test(combined)) return "AI feature cards, generative output previews, glowing interface panels, model capability badges";
  if (/hardware|chip|cpu|gpu/.test(combined)) return "performance charts, spec comparison cards, hardware close-ups, benchmark badges";
  return "feature cards, interface panels, product highlights, mini screenshots, icon blocks";
}
function resolveNewsPromptMood(data) {
  const type2 = String(data.type || "").toLowerCase().replace(/\s+/g, "_");
  return NEWS_PROMPT_TYPE_MOODS[type2] || "Modern Tech";
}
function resolveNewsPromptTypeAddon(data) {
  const type2 = String(data.type || "").toLowerCase().replace(/\s+/g, "_");
  return NEWS_PROMPT_TYPE_ADDONS[type2] || "";
}
function resolveNewsPromptKeywordAddon(data) {
  const title = String(data.title || "").toLowerCase();
  const tags = (Array.isArray(data.tag_names) ? data.tag_names : []).join(" ").toLowerCase();
  const category = String(data.category || "").toLowerCase();
  const combined = `${title} ${tags} ${category}`;
  const addons = [];
  for (const pattern of NEWS_PROMPT_KEYWORD_PATTERNS) {
    if (pattern.keywords.some((kw) => combined.includes(kw))) {
      addons.push(pattern.addon);
    }
  }
  return [...new Set(addons)].join("\n");
}
function buildNewsImagePrompt(data) {
  const headline2 = resolveNewsPromptHeadline(data);
  const subheadline = resolveNewsPromptSubheadline(data);
  const topic = resolveNewsPromptTopic(data);
  const newsType = resolveNewsPromptType(data);
  const heroSubject = resolveNewsPromptHeroSubject(data);
  const supportingModules = resolveNewsPromptSupportingModules(data);
  const mood = resolveNewsPromptMood(data);
  const typeAddon = resolveNewsPromptTypeAddon(data);
  const keywordAddon = resolveNewsPromptKeywordAddon(data);
  const lines = [
    "Create a premium Skinbase news cover image in 16:9 aspect ratio.",
    "",
    "Design it as a professional editorial tech poster for a digital culture, software, hardware, AI, creative tools, desktop customization, or retro computing news article.",
    "",
    "ARTICLE DETAILS:",
    `Headline: "${headline2}"`,
    `Subheadline: "${subheadline}"`,
    `Topic: ${topic}`,
    `News type: ${newsType}`,
    `Hero subject: ${heroSubject}`,
    `Supporting modules: ${supportingModules}`,
    `Mood: ${mood}`,
    "",
    "LAYOUT:",
    "Use a structured 16:9 news hero composition with:",
    "- Large bold headline in the upper-left or top-center",
    "- Smaller subtitle directly below the headline",
    "- One strong central hero visual",
    "- Supporting side panels, feature cards, icons, UI windows, diagrams, or mini screenshots",
    "- A bottom strip with 3 to 6 small highlight blocks or visual details",
    "- Clean spacing and a strong visual hierarchy",
    "",
    "VISUAL STYLE:",
    "Use a dark premium background with blue, cyan, violet, neon, or topic-matching accent colors. Add glossy highlights, subtle glow, cinematic depth, crisp lighting, and a polished high-tech editorial look.",
    "",
    "The image should feel like a professional magazine cover, software release poster, tech conference banner, or retro computing feature graphic. It should be visually rich, but still clean, readable, and organized.",
    "",
    "TEXT STYLE:",
    "Use bold clean sans-serif typography. Keep all visible text short and readable. Avoid long paragraphs inside the image. Use only short labels, feature names, or headline-style phrases.",
    "",
    "CONTENT DIRECTION:",
    "Represent the topic clearly through the central visual. Use relevant objects such as:",
    "- software windows",
    "- futuristic workstations",
    "- creative AI panels",
    "- computer chips",
    "- retro hardware",
    "- desktop customization elements",
    "- conference screens",
    "- app interface mockups",
    "- glowing diagrams",
    "- feature cards",
    "- product-style panels",
    "",
    "QUALITY RULES:",
    "Make it sharp, premium, polished, high detail, thumbnail-friendly, and suitable as a Skinbase news article cover image.",
    "",
    "Avoid clutter, random filler objects, unreadable microtext, messy typography, distorted UI, weak composition, watermarks, fake signatures, low-quality stock-photo style, and irrelevant logos."
  ];
  if (typeAddon) {
    lines.push("", typeAddon);
  }
  if (keywordAddon) {
    lines.push("", keywordAddon);
  }
  return lines.join("\n");
}
function buildNewsExportPayloads(data, context = {}) {
  const normalized = buildSubmitPayload(data || {});
  const category = findNewsOptionById(context.categoryOptions, normalized.category_id);
  const existingTags = findNewsTagsByIds(context.tagOptions, normalized.tag_ids);
  const author = context.author || null;
  const full = {
    title: normalized.title,
    slug: normalized.slug,
    excerpt: normalized.excerpt,
    content: normalized.content,
    cover_image: normalized.cover_image,
    type: normalized.type,
    category_id: normalized.category_id,
    category: category?.name ?? category?.label ?? "",
    category_slug: category?.slug ?? "",
    author_id: normalized.author_id,
    author_name: author?.title ?? author?.name ?? "",
    editorial_status: normalized.editorial_status,
    published_at: normalized.published_at,
    is_featured: normalized.is_featured,
    is_pinned: normalized.is_pinned,
    comments_enabled: normalized.comments_enabled,
    tags: [
      ...existingTags,
      ...normalized.new_tag_names.map((name2) => ({ name: name2, slug: "" }))
    ],
    tag_names: [
      ...existingTags.map((tag) => tag.name),
      ...normalized.new_tag_names
    ],
    tag_ids: normalized.tag_ids,
    new_tag_names: normalized.new_tag_names,
    meta_title: normalized.meta_title,
    meta_description: normalized.meta_description,
    meta_keywords: normalized.meta_keywords,
    og_title: normalized.og_title,
    og_description: normalized.og_description,
    og_image: normalized.og_image,
    relations: normalized.relations
  };
  const structured = {
    title: normalized.title,
    excerpt: normalized.excerpt,
    date: normalized.published_at,
    body: stripHtml$1(normalized.content),
    category: category?.name ?? category?.label ?? ""
  };
  const markdown = {
    title: normalized.title,
    excerpt: normalized.excerpt,
    date: normalized.published_at,
    category: category?.name ?? category?.label ?? "",
    body_html: normalized.content
  };
  return {
    full: JSON.stringify(full, null, 2),
    structured: JSON.stringify(structured, null, 2),
    structuredPlain: buildStructuredPlainTextExport(structured),
    markdown: buildNewsMarkdownExport(markdown),
    markdownInput: markdown
  };
}
function JsonImportDialog({ open, value, error, onChange, onClose, onApply, exportPayloads, articleData = {}, newTagLimit = NEWS_NEW_TAG_LIMIT }) {
  const backdropRef = reactExports.useRef(null);
  const [activeImportTab, setActiveImportTab] = reactExports.useState("input");
  const [copyFeedback, setCopyFeedback] = reactExports.useState("");
  const [exportMode, setExportMode] = reactExports.useState("full");
  const [markdownExportText, setMarkdownExportText] = reactExports.useState(String(exportPayloads?.markdown || ""));
  const [promptText, setPromptText] = reactExports.useState("");
  const [promptIsManual, setPromptIsManual] = reactExports.useState(false);
  const importTabs = [
    { id: "input", label: "Input", description: "Paste JSON and apply it to the editor." },
    { id: "structure", label: "Structure example", description: "A working example of the expected payload." },
    { id: "docs", label: "Documentation", description: "Field notes and mapping rules." },
    { id: "prompts", label: "AI prompts", description: "Prompt examples for generating structured news." },
    { id: "export", label: "Export", description: "Copy the current article out as JSON, text, or Markdown." },
    { id: "image_prompt", label: "Image Prompt", description: "Auto-generate a cover image prompt from article data." }
  ];
  const structureExample = {
    title: "Sample News Title",
    slug: "sample-news-title",
    excerpt: "This is a sample news excerpt that demonstrates the structured import format.",
    content: "<p>This is sample news content written in HTML.</p><p>You can replace it with your own editorial copy.</p>",
    cover_image: "sample-news-cover.webp",
    type: "Announcement",
    category_id: 1,
    category: "General",
    category_slug: "general",
    editorial_status: "draft",
    published_at: "2026-05-03 09:00:00",
    author_id: 1,
    author_name: "Sample Author",
    is_featured: false,
    is_pinned: false,
    comments_enabled: true,
    tags: [
      { name: "Sample Tag", slug: "sample-tag" },
      { name: "News Import", slug: "news-import" }
    ],
    tag_names: ["Sample Tag", "News Import"],
    tag_ids: [],
    relations: {
      related_articles: [],
      related_artworks: [],
      related_users: [],
      source_urls: ["https://example.com/sample-news-source"]
    },
    meta_title: "Sample News Title - Skinbase Example",
    meta_description: "This is a sample news meta description for the structured import example.",
    meta_keywords: "sample news, structured import, editorial example",
    og_title: "Sample News Title",
    og_description: "This is a sample news OG description for the structured import example."
  };
  const newsJsonSchemaSummary = `You are generating a Skinbase news article JSON object.

Return only valid JSON. No markdown, no commentary, no code fences.

Required fields:
- title: string
- content: HTML string

Recommended fields:
- slug: SEO slug
- excerpt: short summary
- cover_image: image path or URL
- type: one of the editor's news types
- category_id: preferred category id
- editorial_status: draft|review|scheduled|published|archived
- published_at: YYYY-MM-DD HH:MM:SS
- author_id or author_name
- comments_enabled: boolean
- is_featured: boolean
- is_pinned: boolean
- meta_title, meta_description, meta_keywords
- og_title, og_description
- tags: array of strings or objects with name/title/label/slug
- tag_names: array of strings
- tag_ids: array of ids if you already know them
- relations: array of objects with entity_type, entity_id, context_label

Rules:
- Use HTML paragraphs in content.
- Keep excerpt concise.
- Prefer category_id when you know it; otherwise include category/category_slug for matching.
- If a tag is an object, keep the name field readable.
- If source URLs are available, include them in a relations-related field or source notes field.
`;
  const aiPromptExamples = [
    {
      title: "Blog-to-news generator",
      prompt: `${newsJsonSchemaSummary}

Transform the following article into a news payload for the editor.
- Preserve the factual meaning and the editorial tone.
- Choose a concise title and an SEO-friendly slug.
- Write content as HTML paragraphs.
- Include 8 to 14 highly relevant tags.
- Include category_id when possible, otherwise use category_slug or category to help matching.
- Fill meta_title, meta_description, og_title, and og_description when available.
- Make comments_enabled true unless the source clearly says otherwise.

Input article text:
{{ARTICLE_TEXT}}`
    },
    {
      title: "Release announcement prompt",
      prompt: `${newsJsonSchemaSummary}

Create a structured release announcement JSON object.
- Use a direct product/news style headline.
- Keep the excerpt short and easy to scan.
- Write the content as 3 to 6 HTML paragraphs.
- Include a realistic published_at timestamp in local time.
- Set editorial_status to published if the article is already live, otherwise draft.
- Set comments_enabled to true unless the release is sensitive or comments should be disabled.
- Add 8 to 12 tags.

Release notes:
{{RELEASE_NOTES}}`
    },
    {
      title: "Migration import prompt",
      prompt: `${newsJsonSchemaSummary}

Convert the source article into Skinbase news JSON.
- Preserve the factual content and keep the article structure readable.
- Return only JSON.
- Normalize tags into an array of objects with name and slug.
- If the source contains article links, place them in a source_urls field inside the relations object.
- If the source provides an author, category, or publish date, map those into the matching editor fields.
- Use sensible defaults for any missing metadata.

Source article:
{{SOURCE_ARTICLE}}`
    }
  ];
  function tabButtonClass(active) {
    return `flex-1 rounded-2xl border px-4 py-3 text-left transition ${active ? "border-sky-300/25 bg-sky-400/10 text-white" : "border-white/10 bg-white/[0.03] text-slate-400 hover:border-white/20 hover:bg-white/[0.05] hover:text-slate-200"}`;
  }
  const activeExportText = exportMode === "structured" ? String(exportPayloads?.structured || "") : exportMode === "markdown" ? markdownExportText : String(exportPayloads?.full || "");
  const copyText = async (text2, label) => {
    try {
      await navigator.clipboard.writeText(String(text2));
      setCopyFeedback(`${label} copied`);
      window.setTimeout(() => setCopyFeedback(""), 1800);
    } catch (copyError) {
      setCopyFeedback("Copy failed");
      window.setTimeout(() => setCopyFeedback(""), 1800);
    }
  };
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  reactExports.useEffect(() => {
    setMarkdownExportText(String(exportPayloads?.markdown || ""));
  }, [exportPayloads]);
  reactExports.useEffect(() => {
    if (!open || activeImportTab !== "export" || exportMode !== "markdown") {
      return void 0;
    }
    let cancelled = false;
    loadNewsMarkdownTurndown().then(() => {
      if (cancelled) {
        return;
      }
      setMarkdownExportText(buildNewsMarkdownExport(exportPayloads?.markdownInput || {}));
    });
    return () => {
      cancelled = true;
    };
  }, [activeImportTab, exportMode, exportPayloads, open]);
  reactExports.useEffect(() => {
    if (!open || activeImportTab !== "image_prompt") return;
    if (promptIsManual) return;
    setPromptText(buildNewsImagePrompt(articleData));
  }, [open, activeImportTab, articleData, promptIsManual]);
  const handleRegeneratePrompt = reactExports.useCallback(() => {
    setPromptIsManual(false);
    setPromptText(buildNewsImagePrompt(articleData));
  }, [articleData]);
  const handleResetPrompt = reactExports.useCallback(() => {
    setPromptIsManual(false);
    setPromptText(buildNewsImagePrompt(articleData));
  }, [articleData]);
  if (!open) return null;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "dialog",
          "aria-modal": "true",
          "aria-labelledby": "news-json-import-title",
          className: "flex h-[min(90vh,780px)] w-full max-w-5xl flex-col overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]"
        },
        /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Structured import"), /* @__PURE__ */ React.createElement("h3", { id: "news-json-import-title", className: "mt-2 text-lg font-semibold text-white" }, "Import or export article JSON"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Use this for migrations, AI-assisted drafting, bulk handoff from another editorial system, or copying the current article into reusable JSON.")),
        /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 grid-cols-2 md:grid-cols-3 lg:grid-cols-6" }, importTabs.map((tab2) => /* @__PURE__ */ React.createElement(
          "button",
          {
            key: tab2.id,
            type: "button",
            onClick: () => setActiveImportTab(tab2.id),
            className: tabButtonClass(activeImportTab === tab2.id)
          },
          /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, tab2.label),
          /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-current/70" }, tab2.description)
        )))),
        /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar flex-1 min-h-0 overflow-y-auto px-6 py-5" }, activeImportTab === "input" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
          "textarea",
          {
            value,
            onChange: (event) => onChange?.(event.target.value),
            rows: 18,
            placeholder: '{\n  "title": "My news title",\n  "slug": "my-news-title",\n  "excerpt": "Short summary",\n  "tags": ["release", "community"]\n}',
            className: "nova-scrollbar w-full rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 font-mono text-sm text-white outline-none placeholder:text-white/30"
          }
        ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recognized keys"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "`title`, `slug`, `excerpt`, `content`, `cover_image`"), /* @__PURE__ */ React.createElement("p", null, "`type`, `category_id`, `category`, `category_slug`"), /* @__PURE__ */ React.createElement("p", null, "`editorial_status`, `published_at`, `author_id`, `author_name`"), /* @__PURE__ */ React.createElement("p", null, "`is_featured`, `is_pinned`, `comments_enabled`"), /* @__PURE__ */ React.createElement("p", null, "`tags`, `tag_names`, `tag_ids`, `relations`"), /* @__PURE__ */ React.createElement("p", null, "`new_tag_names` is capped at ", newTagLimit, " items per article."), /* @__PURE__ */ React.createElement("p", null, "`meta_title`, `meta_description`, `meta_keywords`, `og_title`, `og_description`")))) : null, activeImportTab === "structure" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Structure example"), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => copyText(JSON.stringify(structureExample, null, 2), "Structure example"),
            className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]"
          },
          "Copy example"
        )), /* @__PURE__ */ React.createElement("pre", { className: "nova-scrollbar max-h-[52vh] overflow-auto rounded-[20px] border border-white/10 bg-slate-950/80 p-4 text-xs leading-6 text-slate-200" }, JSON.stringify(structureExample, null, 2))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Tags can be an array of strings or objects with `name`, `title`, `label`, or `slug`."), /* @__PURE__ */ React.createElement("p", null, "`content` accepts HTML. Keep paragraph tags and inline formatting in the JSON string."), /* @__PURE__ */ React.createElement("p", null, "`relations` may contain structured links and source URLs, but only direct entity fields are currently applied automatically.")))) : null, activeImportTab === "docs" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Field guide"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "title"), " - article headline. If `slug` is omitted the editor can derive it from the title."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "excerpt"), " - short summary shown in listings and metadata."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "content"), " - HTML body, usually paragraph tags plus basic formatting."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "category_id"), " - preferred category selector value. `category_slug` and `category` are accepted for matching, but `category_id` is the reliable one."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "tags"), " - array of strings or objects. Existing tags are matched by name; new ones are staged automatically."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "new_tag_names"), " - capped at ", newTagLimit, " items per article. Use existing tags where possible to stay within the limit."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "meta_keywords"), " - max 255 characters. Keep it concise or the save will fail validation."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Import rules"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Boolean fields accept `true`/`false`, `1`/`0`, `yes`/`no`, and `on`/`off`."), /* @__PURE__ */ React.createElement("p", null, "Date values should be in `YYYY-MM-DD HH:MM:SS` format for scheduled stories."), /* @__PURE__ */ React.createElement("p", null, "Keep `new_tag_names` at or below ", newTagLimit, " items, which matches the editor validation."), /* @__PURE__ */ React.createElement("p", null, "Unknown keys are ignored, so you can paste a broader object safely.")))) : null, activeImportTab === "prompts" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, aiPromptExamples.map((example) => /* @__PURE__ */ React.createElement("div", { key: example.title, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-200/70" }, example.title), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => copyText(example.prompt, example.title),
            className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]"
          },
          "Copy prompt"
        )), /* @__PURE__ */ React.createElement("pre", { className: "nova-scrollbar mt-3 max-h-56 overflow-auto whitespace-pre-wrap rounded-[18px] border border-white/10 bg-slate-950/80 p-4 text-sm leading-6 text-slate-200" }, example.prompt)))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Prompt tips"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "Tell the model to return JSON only, with no explanation text."), /* @__PURE__ */ React.createElement("p", null, "Ask for `tags` as an array of objects when you want the most compatible import shape."), /* @__PURE__ */ React.createElement("p", null, "Include `source_urls` or reference links in the source instruction if you want them copied into the story notes.")))) : null, activeImportTab === "export" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => setExportMode("full"),
            className: tabButtonClass(exportMode === "full")
          },
          /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, "Full news JSON"),
          /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-current/70" }, "Exports the current article with metadata, tags, and relations.")
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => setExportMode("structured"),
            className: tabButtonClass(exportMode === "structured")
          },
          /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, "Structured JSON"),
          /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-current/70" }, "Exports only title, excerpt, date, body, and category.")
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => setExportMode("markdown"),
            className: tabButtonClass(exportMode === "markdown")
          },
          /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, "Markdown"),
          /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-current/70" }, "Exports the current article as Markdown with heading, summary, and body.")
        )), /* @__PURE__ */ React.createElement(
          "textarea",
          {
            readOnly: true,
            value: activeExportText,
            rows: 18,
            className: "nova-scrollbar w-full rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 font-mono text-sm text-white outline-none"
          }
        )), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Export options"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "Full news JSON"), " includes the current editable article state: slug, status, tags, metadata, and relations."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "Structured JSON"), " keeps the reduced handoff shape: title, excerpt, date, body, and category."), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "Markdown"), " converts the current article body into Markdown and includes the title plus summary fields for external reuse."), /* @__PURE__ */ React.createElement("p", null, "The export uses the live editor state, so unsaved changes are included immediately.")))) : null, activeImportTab === "image_prompt" ? /* @__PURE__ */ React.createElement("div", { className: "grid h-full min-h-0 gap-5 xl:grid-cols-[minmax(0,1.2fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "flex-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Generated cover image prompt", promptIsManual ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-2 py-0.5 text-[10px] text-amber-100" }, "Manually edited") : null), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: handleRegeneratePrompt,
            className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white transition hover:bg-white/[0.08]"
          },
          "Regenerate"
        ), promptIsManual ? /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: handleResetPrompt,
            className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1.5 text-xs font-semibold text-amber-100 transition hover:bg-amber-400/20"
          },
          "Reset to auto"
        ) : null, /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => copyText(promptText, "Image prompt"),
            className: "rounded-full border border-sky-300/25 bg-sky-400/90 px-3 py-1.5 text-xs font-semibold text-slate-950 transition hover:brightness-110"
          },
          "Copy prompt"
        )), /* @__PURE__ */ React.createElement(
          "textarea",
          {
            value: promptText,
            onChange: (event) => {
              setPromptText(event.target.value);
              setPromptIsManual(true);
            },
            rows: 22,
            spellCheck: false,
            className: "nova-scrollbar w-full rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 font-mono text-sm leading-6 text-white outline-none placeholder:text-white/30",
            placeholder: "Opening the tab will generate a prompt automatically…"
          }
        )), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "How it works"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "The prompt is built automatically from the current article fields: title, excerpt, type, category, and tags."), /* @__PURE__ */ React.createElement("p", null, "You can edit the prompt freely. It will be marked as ", /* @__PURE__ */ React.createElement("span", { className: "rounded border border-amber-300/20 bg-amber-400/10 px-1 text-amber-100" }, "Manually edited"), " once you change it."), /* @__PURE__ */ React.createElement("p", null, "Click ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "Regenerate"), " or ", /* @__PURE__ */ React.createElement("strong", { className: "text-slate-200" }, "Reset to auto"), " to rebuild from the current article state."), /* @__PURE__ */ React.createElement("p", null, "Copy the prompt and paste it into an AI image generator such as Midjourney, DALL-E, Stable Diffusion, or Flux.")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Auto-filled from"), /* @__PURE__ */ React.createElement("ul", { className: "mt-2 space-y-1 text-xs leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "Headline"), " — title, meta_title"), /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "Subheadline"), " — excerpt, meta_description, content"), /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "Topic"), " — category, tags"), /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "Type"), " — article type"), /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "Hero / Mood"), " — inferred from title, tags, type"), /* @__PURE__ */ React.createElement("li", null, /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, "Addons"), " — type-based and keyword-based style blocks")))) : null),
        copyFeedback ? /* @__PURE__ */ React.createElement("div", { className: "px-6 pb-2 text-right text-xs font-medium text-sky-200/80" }, copyFeedback) : null,
        /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onClose?.(),
            className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white"
          },
          "Cancel"
        ), activeImportTab === "export" ? /* @__PURE__ */ React.createElement(React.Fragment, null, exportMode === "structured" ? /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => copyText(String(exportPayloads?.structuredPlain || ""), "Structured plain text export"),
            className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white"
          },
          "Copy plain text"
        ) : null, /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => copyText(activeExportText, exportMode === "structured" ? "Structured export" : exportMode === "markdown" ? "Markdown export" : "Full news export"),
            className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110"
          },
          "Copy export"
        )) : activeImportTab === "image_prompt" ? null : /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onApply?.(),
            className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110"
          },
          "Apply JSON"
        ))
      )
    ),
    document.body
  );
}
function StudioNewsEditor() {
  const { props } = X$1();
  const { toasts, push: pushToast, dismiss: dismissToast } = useToast();
  const article = props.article || {};
  const initialFormData = reactExports.useMemo(() => buildInitialFormData(article, props.defaultAuthor, props.defaultPublishedAt, props.typeOptions, props.oldInput || {}), [article, props.defaultAuthor, props.defaultPublishedAt, props.oldInput, props.typeOptions]);
  const articleSyncKey = reactExports.useMemo(() => JSON.stringify(initialFormData), [initialFormData]);
  const [authorResults, setAuthorResults] = reactExports.useState([]);
  const [authorQuery, setAuthorQuery] = reactExports.useState(article.author?.title || article.author?.subtitle?.replace(/^@/, "") || "");
  const [selectedAuthor, setSelectedAuthor] = reactExports.useState(article.author || props.defaultAuthor || null);
  const [relationResults, setRelationResults] = reactExports.useState({});
  const [coverPreviewUrl, setCoverPreviewUrl] = reactExports.useState(article.cover_url || (String(article.cover_image || "").startsWith("http") ? article.cover_image : ""));
  const [stagedCoverPath, setStagedCoverPath] = reactExports.useState("");
  const [activeTab, setActiveTab] = reactExports.useState("content");
  const [jsonImportOpen, setJsonImportOpen] = reactExports.useState(false);
  const [jsonImportValue, setJsonImportValue] = reactExports.useState("");
  const [jsonImportError, setJsonImportError] = reactExports.useState("");
  const lastSyncedArticleKeyRef = reactExports.useRef(articleSyncKey);
  const slugTouchedRef = reactExports.useRef(Boolean(String(article.slug || "").trim()));
  const form = G$1(initialFormData);
  const normalizedInitialPayload = reactExports.useMemo(() => JSON.stringify(buildSubmitPayload(initialFormData)), [initialFormData]);
  const normalizedCurrentPayload = reactExports.useMemo(() => JSON.stringify(buildSubmitPayload(form.data)), [form.data]);
  const hasUnsavedChanges = normalizedCurrentPayload !== normalizedInitialPayload;
  const frontendArticleUrl = String(article.canonical_url || "").trim();
  reactExports.useEffect(() => {
    if (lastSyncedArticleKeyRef.current === articleSyncKey) {
      return;
    }
    lastSyncedArticleKeyRef.current = articleSyncKey;
    form.setData(initialFormData);
    form.clearErrors();
    setSelectedAuthor(article.author || props.defaultAuthor || null);
    setAuthorQuery(article.author?.title || article.author?.subtitle?.replace(/^@/, "") || "");
    setRelationResults({});
    setCoverPreviewUrl(article.cover_url || (String(article.cover_image || "").startsWith("http") ? article.cover_image : ""));
    setStagedCoverPath("");
    slugTouchedRef.current = Boolean(String(article.slug || initialFormData.slug || "").trim());
  }, [article, articleSyncKey, form, initialFormData, props.defaultAuthor]);
  reactExports.useEffect(() => {
    if (slugTouchedRef.current) {
      return;
    }
    const nextSlug = slugifyNewsTitle(form.data.title);
    if (nextSlug === String(form.data.slug || "")) {
      return;
    }
    form.setData("slug", nextSlug);
  }, [form, form.data.slug, form.data.title]);
  reactExports.useEffect(() => {
    if (!hasUnsavedChanges || form.processing) {
      return void 0;
    }
    const message = "You have unsaved article changes. Leave without saving?";
    const handleBeforeUnload = (event) => {
      event.preventDefault();
      event.returnValue = message;
      return message;
    };
    const handleDocumentClick = (event) => {
      if (event.defaultPrevented) {
        return;
      }
      const anchor = event.target instanceof Element ? event.target.closest("a[href]") : null;
      if (!anchor) {
        return;
      }
      const href = anchor.getAttribute("href");
      if (!href || href.startsWith("#") || anchor.getAttribute("download") != null) {
        return;
      }
      if (anchor.target && anchor.target.toLowerCase() === "_blank") {
        return;
      }
      if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) {
        return;
      }
      const destination = new URL(anchor.href, window.location.href);
      const current = new URL(window.location.href);
      if (destination.href === current.href) {
        return;
      }
      if (!window.confirm(message)) {
        event.preventDefault();
      }
    };
    window.addEventListener("beforeunload", handleBeforeUnload);
    document.addEventListener("click", handleDocumentClick, true);
    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
      document.removeEventListener("click", handleDocumentClick, true);
    };
  }, [form.processing, hasUnsavedChanges]);
  const excerptLength = String(form.data.excerpt || "").trim().length;
  const bodyWordCount = reactExports.useMemo(() => {
    const plain = stripHtml$1(form.data.content);
    return plain === "" ? 0 : plain.split(/\s+/).length;
  }, [form.data.content]);
  const typeOptions = reactExports.useMemo(() => selectOptionsFromValues(props.typeOptions || []), [props.typeOptions]);
  const statusOptions = reactExports.useMemo(() => selectOptionsFromValues(props.statusOptions || []), [props.statusOptions]);
  const categoryOptions = reactExports.useMemo(() => selectOptionsFromValues(props.categoryOptions || [], "Select category"), [props.categoryOptions]);
  const currentTabIndex = Math.max(0, NEWS_EDITOR_TABS.findIndex((tab2) => tab2.id === activeTab));
  const currentTab = NEWS_EDITOR_TABS[currentTabIndex] || NEWS_EDITOR_TABS[0];
  const tabErrorCounts = reactExports.useMemo(() => ({
    content: ["title", "slug", "excerpt", "content", "cover_image"].filter((key) => Boolean(form.errors[key])).length,
    publishing: ["type", "category_id", "author_id", "editorial_status", "published_at", "comments_enabled"].filter((key) => Boolean(form.errors[key])).length,
    discoverability: ["tag_ids", "new_tag_names", "meta_title", "meta_description", "meta_keywords", "og_title", "og_description", "og_image"].filter((key) => Boolean(form.errors[key])).length,
    connections: ["relations"].filter((key) => Boolean(form.errors[key])).length
  }), [form.errors]);
  const overviewItems = reactExports.useMemo(() => [
    { label: "Headline", done: String(form.data.title || "").trim().length > 0 },
    { label: "Category", done: hasRequiredCategory(form.data.category_id) },
    { label: "Excerpt", done: String(form.data.excerpt || "").trim().length > 0 },
    { label: "Body", done: bodyWordCount > 0 },
    { label: "Cover image", done: String(form.data.cover_image || "").trim().length > 0 },
    { label: "Author", done: Boolean(form.data.author_id) }
  ], [bodyWordCount, form.data.author_id, form.data.category_id, form.data.cover_image, form.data.excerpt, form.data.title]);
  const completedCount = overviewItems.filter((item) => item.done).length;
  const jsonExportPayloads = reactExports.useMemo(() => buildNewsExportPayloads(form.data, {
    categoryOptions: props.categoryOptions,
    tagOptions: props.tagOptions,
    author: selectedAuthor
  }), [form.data, props.categoryOptions, props.tagOptions, selectedAuthor]);
  const imagePromptArticleData = reactExports.useMemo(() => {
    const category = findNewsOptionById(props.categoryOptions, form.data.category_id);
    const existingTags = findNewsTagsByIds(props.tagOptions, form.data.tag_ids);
    return {
      title: form.data.title,
      excerpt: form.data.excerpt,
      content: form.data.content,
      type: form.data.type,
      category: category?.name ?? category?.label ?? "",
      category_slug: category?.slug ?? "",
      tag_names: [
        ...existingTags.map((t) => t.name),
        ...Array.isArray(form.data.new_tag_names) ? form.data.new_tag_names : []
      ],
      meta_title: form.data.meta_title,
      meta_description: form.data.meta_description
    };
  }, [form.data, props.categoryOptions, props.tagOptions]);
  reactExports.useEffect(() => {
    const firstErrorTab = NEWS_EDITOR_TABS.find((tab2) => tabErrorCounts[tab2.id] > 0);
    if (firstErrorTab) {
      setActiveTab(firstErrorTab.id);
    }
  }, [tabErrorCounts]);
  const searchEntities = async (type2, query) => {
    const url = new URL(props.entitySearchUrl, window.location.origin);
    url.searchParams.set("type", type2);
    url.searchParams.set("q", query);
    const response = await fetch(url.toString(), {
      headers: {
        Accept: "application/json"
      },
      credentials: "same-origin"
    });
    if (!response.ok) {
      return [];
    }
    const payload = await response.json();
    return Array.isArray(payload.items) ? payload.items : [];
  };
  const runAuthorSearch = async () => {
    const items = await searchEntities("user", authorQuery);
    setAuthorResults(items);
  };
  const addRelation = () => {
    form.setData("relations", [
      ...form.data.relations,
      {
        entity_type: props.relationTypeOptions?.[0]?.value || "group",
        entity_id: "",
        external_url: "",
        context_label: "",
        preview: null,
        query: ""
      }
    ]);
  };
  const updateRelation = (index2, nextRelation) => {
    form.setData("relations", form.data.relations.map((relation, relationIndex) => relationIndex === index2 ? nextRelation : relation));
  };
  const removeRelation = (index2) => {
    form.setData("relations", form.data.relations.filter((_2, relationIndex) => relationIndex !== index2));
    setRelationResults((current) => {
      const next = { ...current };
      delete next[index2];
      return next;
    });
  };
  const runRelationSearch = async (index2) => {
    const relation = form.data.relations[index2];
    if (!relation) return;
    const items = await searchEntities(relation.entity_type, relation.query || "");
    setRelationResults((current) => ({ ...current, [index2]: items }));
  };
  const handleManualCoverChange = (nextValue) => {
    form.setData("cover_image", nextValue);
    if (stagedCoverPath && nextValue !== stagedCoverPath) {
      setStagedCoverPath("");
    }
    if (!nextValue) {
      setCoverPreviewUrl("");
      return;
    }
    if (String(nextValue).startsWith("http://") || String(nextValue).startsWith("https://")) {
      setCoverPreviewUrl(nextValue);
      return;
    }
    setCoverPreviewUrl(`${props.coverCdnBaseUrl}/${String(nextValue).replace(/^\/+/, "")}`);
  };
  const submit = (event) => {
    event.preventDefault();
    if (!hasRequiredCategory(form.data.category_id)) {
      form.setError("category_id", "Choose a category before saving the article.");
      pushToast("Choose a category before saving the article.", "error");
      return;
    }
    const options = {
      preserveScroll: true,
      preserveState: "errors",
      onSuccess: () => {
        setStagedCoverPath("");
        pushToast("Article saved successfully.", "success");
      },
      onError: (errors) => {
        const errorMessages = Object.values(errors);
        const first = errorMessages[0] || "The article could not be saved.";
        const extra = errorMessages.length > 1 ? ` (${errorMessages.length - 1} more field${errorMessages.length > 2 ? "s" : ""})` : "";
        const firstErrorTab = NEWS_EDITOR_TABS.find((tab2) => tabErrorCounts[tab2.id] > 0);
        if (firstErrorTab) {
          setActiveTab(firstErrorTab.id);
        }
        pushToast(first + extra, "error");
      }
    };
    form.transform((data) => buildSubmitPayload(data));
    if (props.updateUrl) {
      form.patch(props.updateUrl, options);
      return;
    }
    form.post(props.storeUrl, options);
  };
  const deleteArticle = () => {
    if (!props.destroyUrl) return;
    if (!window.confirm("Move this article to trash? This uses soft delete so the record stays in the database.")) return;
    At.delete(props.destroyUrl, {
      preserveScroll: true
    });
  };
  const goToNextTab = (direction) => {
    const next = NEWS_EDITOR_TABS[currentTabIndex + direction];
    if (!next) return;
    setActiveTab(next.id);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };
  const applyJsonImport = () => {
    try {
      const parsed = parseStructuredNewsImport(jsonImportValue, {
        categoryOptions: props.categoryOptions,
        tagOptions: props.tagOptions,
        typeOptions: props.typeOptions,
        statusOptions: props.statusOptions
      });
      Object.entries(parsed.next).forEach(([key, value]) => {
        form.setData(key, value);
      });
      if (parsed.authorQuery) {
        setAuthorQuery(parsed.authorQuery);
      }
      if (parsed.next.cover_image != null) {
        handleManualCoverChange(parsed.next.cover_image);
      }
      if (parsed.next.slug != null) {
        slugTouchedRef.current = true;
      }
      setJsonImportError("");
      setJsonImportOpen(false);
      pushToast(`Applied ${parsed.applied.length} field${parsed.applied.length === 1 ? "" : "s"} from JSON.`, "success");
    } catch (error) {
      setJsonImportError(error instanceof Error ? error.message : "Could not parse JSON.");
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement(ToastStack, { toasts, onDismiss: dismissToast }), /* @__PURE__ */ React.createElement("div", { className: "space-y-6 pb-24" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] shadow-[0_24px_70px_rgba(2,6,23,0.34)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 border-b border-white/10 px-5 py-4 lg:grid-cols-[minmax(0,1fr)_360px] lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, props.indexUrl ? /* @__PURE__ */ React.createElement("a", { href: props.indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white transition hover:bg-white/[0.08]" }, "Back to news list") : null, /* @__PURE__ */ React.createElement("span", null, article.id ? `Article #${article.id}` : "New article"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 px-3 py-1.5 text-sky-100/80" }, currentTab.label)), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 truncate text-2xl font-semibold tracking-[-0.03em] text-white" }, String(form.data.title || "").trim() || (article.id ? "Untitled article" : "Create article")), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Keep the draft flow simple: write the story in one place, handle publishing in one place, and keep promotion metadata nearby instead of buried below the fold.")), coverPreviewUrl ? /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 shadow-[0_18px_40px_rgba(2,6,23,0.35)]" }, /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[16/9] bg-black/30" }, /* @__PURE__ */ React.createElement("img", { src: coverPreviewUrl, alt: String(form.data.title || "").trim() || "News cover preview", className: "h-full w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-[#020611d9] via-[#02061144] to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Header cover preview"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 line-clamp-2 text-sm font-semibold text-white" }, String(form.data.title || "").trim() || "Cover image preview")))) : null), /* @__PURE__ */ React.createElement("div", { className: "sticky top-16 z-30 border-y border-white/10 bg-[linear-gradient(180deg,rgba(9,14,24,0.98),rgba(6,10,18,0.98))] px-4 py-3 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex justify-end gap-2 overflow-x-auto" }, frontendArticleUrl ? /* @__PURE__ */ React.createElement("a", { href: frontendArticleUrl, target: "_blank", rel: "noreferrer", className: "rounded-2xl border border-cyan-300/20 bg-cyan-400/10 px-4 py-2.5 text-sm font-semibold text-cyan-100 transition hover:bg-cyan-400/15" }, "Frontend link") : null, props.previewUrl ? /* @__PURE__ */ React.createElement("a", { href: props.previewUrl, target: "_blank", rel: "noreferrer", className: "rounded-2xl border border-indigo-300/20 bg-indigo-400/10 px-4 py-2.5 text-sm font-semibold text-indigo-100 transition hover:bg-indigo-400/15" }, "Preview") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Import JSON"), /* @__PURE__ */ React.createElement("button", { type: "submit", form: "studio-news-editor-form", disabled: form.processing, className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, hasUnsavedChanges && !form.processing ? /* @__PURE__ */ React.createElement("span", { className: "h-2.5 w-2.5 rounded-full bg-rose-400 shadow-[0_0_10px_rgba(251,113,133,0.9)] animate-pulse", "aria-hidden": "true" }) : null, /* @__PURE__ */ React.createElement("span", null, form.processing ? "Saving…" : "Save article")), props.publishUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.publishUrl), className: "rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-2.5 text-sm font-semibold text-emerald-100 transition hover:bg-emerald-400/15" }, "Publish now") : null)), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2 overflow-x-auto px-4 py-3" }, NEWS_EDITOR_TABS.map((tab2) => {
    const active = tab2.id === activeTab;
    const errorCount = tabErrorCounts[tab2.id] || 0;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.id,
        type: "button",
        onClick: () => setActiveTab(tab2.id),
        className: `flex min-w-[170px] flex-col rounded-[22px] border px-4 py-3 text-left transition ${active ? "border-sky-300/30 bg-sky-400/12 text-white" : "border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"}`
      },
      /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-sm font-semibold" }, /* @__PURE__ */ React.createElement("span", null, tab2.label), errorCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] text-rose-100" }, errorCount) : null),
      /* @__PURE__ */ React.createElement("span", { className: "mt-1 text-xs leading-5 text-slate-400" }, tab2.description)
    );
  }))), /* @__PURE__ */ React.createElement("form", { id: "studio-news-editor-form", onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, activeTab === "content" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    SectionCard,
    {
      eyebrow: "Story workspace",
      title: article.id ? "Shape the full newsroom story before it goes live." : "Create a newsroom story that reads like an editorial feature, not a raw database form.",
      description: "The cover, excerpt, body, and structure below are the core writing flow. Everything else is support, not a distraction.",
      tone: "feature"
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Headline that can carry the article alone", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Aim for a clear editorial headline that still makes sense in cards, notifications, and social previews."), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.title })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Slug"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement(
      "input",
      {
        value: form.data.slug,
        onChange: (event) => {
          const nextValue = event.target.value;
          slugTouchedRef.current = String(nextValue).trim() !== "";
          form.setData("slug", nextValue);
        },
        placeholder: "optional-manual-slug",
        className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
      }
    ), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => {
          slugTouchedRef.current = false;
          form.setData("slug", slugifyNewsTitle(form.data.title));
        },
        className: "shrink-0 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]"
      },
      "Sync"
    )), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "The slug now follows the title automatically until you edit it manually. Use Sync to regenerate it from the current headline."), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.slug })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Excerpt"), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, excerptLength, "/800")), /* @__PURE__ */ React.createElement("textarea", { value: form.data.excerpt, onChange: (event) => form.setData("excerpt", event.target.value), rows: 6, placeholder: "Write the concise summary used in listing cards, metadata, and archive previews.", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Lead with the update, why it matters, and the audience hook. Two to four punchy sentences usually land better than one dense paragraph."), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.excerpt })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement(
      WorldMediaUploadField,
      {
        label: "Cover image",
        slot: "cover",
        value: form.data.cover_image,
        previewUrl: coverPreviewUrl,
        emptyLabel: "Drop a cover image",
        helperText: "Upload the hero image directly to object storage. A wide landscape image works best for cards, preview surfaces, and social sharing.",
        uploadUrl: props.coverUploadUrl,
        deleteUrl: props.coverDeleteUrl,
        onChange: ({ path, url }) => {
          setStagedCoverPath(path || "");
          form.setData("cover_image", path || "");
          setCoverPreviewUrl(url || "");
        },
        isTemporaryValue: Boolean(stagedCoverPath) && form.data.cover_image === stagedCoverPath
      }
    ), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.cover_image }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Advanced cover path or URL"), /* @__PURE__ */ React.createElement("input", { value: form.data.cover_image, onChange: (event) => handleManualCoverChange(event.target.value), placeholder: "Optional external URL or stored object path", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Keep this for migrations, imported legacy stories, or when you already have the exact asset URL you want to use."))))
  ), /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Full message", title: "Body editor", description: "Write the main article in a richer editing surface so the content reads like a polished story, not pasted plain text.", actions: /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, bodyWordCount.toLocaleString(), " words") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
    RichTextEditor,
    {
      content: form.data.content,
      onChange: (nextValue) => form.setData("content", nextValue),
      placeholder: "Open with the update, add context, use links, pull quotes, headings, and imagery where the story needs structure.",
      error: form.errors.content,
      minHeight: 24,
      autofocus: false,
      advancedNews: true,
      searchEntities,
      mediaSupport: {
        uploadUrl: props.bodyMediaUploadUrl || props.coverUploadUrl,
        deleteUrl: props.bodyMediaDeleteUrl || props.coverDeleteUrl,
        slot: "body"
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-xs leading-6 text-slate-400" }, "Story workflow suggestion: lead with the change, explain why it matters, add supporting detail, then end with a clear call to action or next step.")))) : null, activeTab === "publishing" ? /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Editorial controls", title: "Publishing", description: "Set ownership, placement, timing, and surface behavior before the article leaves draft." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Type", value: form.data.type || null, onChange: (nextValue) => form.setData("type", String(nextValue || "")), options: typeOptions, searchable: false, className: "bg-black/20", error: form.errors.type })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Category", value: form.data.category_id || "", onChange: (nextValue) => {
    form.setData("category_id", String(nextValue || ""));
    if (nextValue) {
      form.clearErrors("category_id");
    }
  }, options: categoryOptions, searchable: false, className: "bg-black/20", error: form.errors.category_id }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Workflow status", value: form.data.editorial_status || null, onChange: (nextValue) => form.setData("editorial_status", String(nextValue || "")), options: statusOptions, searchable: false, className: "bg-black/20", error: form.errors.editorial_status })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Publish at"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.published_at || "", onChange: (nextValue) => form.setData("published_at", nextValue), placeholder: "Pick a publish slot", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.published_at }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Author"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("input", { value: authorQuery, onChange: (event) => setAuthorQuery(event.target.value), placeholder: "Search for an author", className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: runAuthorSearch, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white" }, "Search")), selectedAuthor ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-400/10 p-4 text-sm text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, "Selected author: ", selectedAuthor.title), selectedAuthor.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-emerald-100/70" }, selectedAuthor.subtitle) : null) : null, /* @__PURE__ */ React.createElement(SearchResultList$3, { items: authorResults, onSelect: (item) => {
    setSelectedAuthor(item);
    setAuthorQuery(item.title);
    form.setData("author_id", item.id);
  }, emptyLabel: "Search to choose an author profile." }), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.author_id })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_featured, onChange: (event) => form.setData("is_featured", event.target.checked), label: "Feature on newsroom surfaces", size: 20, variant: "accent" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_pinned, onChange: (event) => form.setData("is_pinned", event.target.checked), label: "Pin to the top of the newsroom", size: 20, variant: "accent" }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.comments_enabled, onChange: (event) => form.setData("comments_enabled", event.target.checked), label: "Allow comments on the article page", size: 20, variant: "accent" }), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.comments_enabled })))) : null, activeTab === "discoverability" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Taxonomy", title: "Tags", description: "Search and apply tags quickly instead of scanning a wall of checkboxes." }, /* @__PURE__ */ React.createElement(
    NewsTagInput,
    {
      options: Array.isArray(props.tagOptions) ? props.tagOptions : [],
      selectedIds: form.data.tag_ids,
      newTagNames: form.data.new_tag_names,
      onSelectedIdsChange: (nextIds) => form.setData("tag_ids", nextIds),
      onNewTagNamesChange: (nextNames) => form.setData("new_tag_names", nextNames),
      manageUrl: props.tagsUrl,
      maxNewTags: props.newsTagLimit || NEWS_NEW_TAG_LIMIT
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.tag_ids || form.errors.new_tag_names }))), /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Metadata", title: "SEO and social", description: "Keep search and sharing fields aligned with the main editorial package." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Meta title"), /* @__PURE__ */ React.createElement("input", { value: form.data.meta_title, onChange: (event) => form.setData("meta_title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Meta description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.meta_description, onChange: (event) => form.setData("meta_description", event.target.value), rows: 3, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Meta keywords"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: form.data.meta_keywords,
      onChange: (event) => form.setData("meta_keywords", event.target.value),
      placeholder: "creator-story, release, tutorial",
      maxLength: 255,
      className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none"
    }
  ), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Maximum 255 characters. The field now stops at the limit so it fails less often on save."), /* @__PURE__ */ React.createElement(FieldError, { message: form.errors.meta_keywords })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "OG title"), /* @__PURE__ */ React.createElement("input", { value: form.data.og_title, onChange: (event) => form.setData("og_title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "OG image"), /* @__PURE__ */ React.createElement("input", { value: form.data.og_image, onChange: (event) => form.setData("og_image", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "OG description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.og_description, onChange: (event) => form.setData("og_description", event.target.value), rows: 3, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))))) : null, activeTab === "connections" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Context links", title: "Related entities", description: "Attach groups, artworks, collections, releases, projects, challenges, events, and profiles so the article becomes part of the rest of Nova instead of a dead-end page.", actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addRelation, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Add relation") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, form.data.relations.length > 0 ? form.data.relations.map((relation, index2) => /* @__PURE__ */ React.createElement(
    RelationCard,
    {
      key: `${relation.entity_type}-${index2}`,
      relation,
      index: index2,
      onChange: updateRelation,
      onRemove: removeRelation,
      onSearch: runRelationSearch,
      results: relationResults[index2] || [],
      relationTypeOptions: Array.isArray(props.relationTypeOptions) ? props.relationTypeOptions : []
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No related entities attached yet."))), /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Structured workflows", title: "Paste article JSON", description: "Import known fields from structured data, then refine the result inside the normal editor flow.", actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Open import") }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-6 text-slate-400" }, "This is useful when another tool already generated article structure for you. Paste JSON, map it into the form, then review copy, metadata, and publish controls before saving."))) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-6 xl:sticky xl:top-[9.75rem]" }, /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Overview", title: "Editing progress", description: "A compact status rail so you can see what still needs attention without leaving the current tab." }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, hasUnsavedChanges ? /* @__PURE__ */ React.createElement("div", { className: "mb-4 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "You have unsaved changes.") : /* @__PURE__ */ React.createElement("div", { className: "mb-4 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-100" }, "All changes saved."), /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-3xl font-semibold tracking-[-0.04em] text-white" }, completedCount, "/", overviewItems.length), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, "Core article pieces ready")), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, bodyWordCount.toLocaleString(), " words")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, overviewItems.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2.5 text-sm" }, /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, item.label), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${item.done ? "border border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border border-white/10 bg-white/[0.04] text-slate-400"}` }, item.done ? "Ready" : "Missing")))))), /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Actions", title: "Always-visible controls", description: "Primary article actions stay pinned here as a second access point while you write." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, Object.keys(form.errors || {}).length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, "The article was not saved. Fix the highlighted fields and try again.") : null, /* @__PURE__ */ React.createElement("button", { type: "submit", form: "studio-news-editor-form", disabled: form.processing, className: "w-full rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 disabled:opacity-60" }, form.processing ? "Saving article…" : "Save article"), props.previewUrl ? /* @__PURE__ */ React.createElement("a", { href: props.previewUrl, target: "_blank", rel: "noreferrer", className: "w-full rounded-full border border-indigo-300/20 bg-indigo-400/10 px-4 py-3 text-center text-sm font-semibold text-indigo-100" }, "Preview article") : null, props.publishUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.publishUrl), className: "w-full rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm font-semibold text-emerald-100" }, "Publish now") : null, props.archiveUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.archiveUrl), className: "w-full rounded-full border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white" }, "Archive article") : null, props.featureUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.featureUrl), className: "w-full rounded-full border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white" }, "Toggle featured") : null, props.pinUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.pinUrl), className: "w-full rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm font-semibold text-amber-100" }, "Toggle pinned") : null, props.destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteArticle, className: "w-full rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100" }, "Move to trash") : null)), /* @__PURE__ */ React.createElement(SectionCard, { eyebrow: "Utilities", title: "Editor shortcuts", description: "Keep taxonomy management and structured import nearby without leaving the writing flow." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Paste structured JSON"), props.categoriesUrl ? /* @__PURE__ */ React.createElement("a", { href: props.categoriesUrl, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm font-semibold text-slate-100 transition hover:bg-white/[0.06]" }, "Manage categories") : null, props.tagsUrl ? /* @__PURE__ */ React.createElement("a", { href: props.tagsUrl, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm font-semibold text-slate-100 transition hover:bg-white/[0.06]" }, "Manage tags") : null)))), /* @__PURE__ */ React.createElement("nav", { className: "sticky bottom-0 z-20 border-t border-white/10 bg-[rgba(2,6,23,0.92)] px-4 py-3 backdrop-blur xl:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex max-w-7xl items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => goToNextTab(-1), disabled: currentTabIndex === 0, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:opacity-50" }, "Back"), /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Step ", currentTabIndex + 1, " / ", NEWS_EDITOR_TABS.length), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-sm font-semibold text-white" }, currentTab.label)), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => goToNextTab(1), disabled: currentTabIndex >= NEWS_EDITOR_TABS.length - 1, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-50" }, "Next")))), /* @__PURE__ */ React.createElement(
    JsonImportDialog,
    {
      open: jsonImportOpen,
      value: jsonImportValue,
      error: jsonImportError,
      exportPayloads: jsonExportPayloads,
      articleData: imagePromptArticleData,
      newTagLimit: props.newsTagLimit || NEWS_NEW_TAG_LIMIT,
      onChange: (nextValue) => {
        setJsonImportValue(nextValue);
        if (jsonImportError) {
          setJsonImportError("");
        }
      },
      onClose: () => {
        setJsonImportOpen(false);
        setJsonImportError("");
      },
      onApply: applyJsonImport
    }
  ));
}
const __vite_glob_0_150 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioNewsEditor
}, Symbol.toStringTag, { value: "Module" }));
function formatDate$1(value) {
  if (!value) return "Draft";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Draft";
  return date.toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric"
  });
}
function statusTone$1(status2) {
  switch (status2) {
    case "published":
      return "border-emerald-300/20 bg-emerald-400/10 text-emerald-100";
    case "scheduled":
      return "border-sky-300/20 bg-sky-400/10 text-sky-100";
    case "in_review":
      return "border-amber-300/20 bg-amber-400/10 text-amber-100";
    case "archived":
      return "border-white/10 bg-white/[0.05] text-slate-300";
    default:
      return "border-white/10 bg-white/[0.05] text-slate-300";
  }
}
function buildPaginationPages(current, last) {
  if (last <= 1) return [1];
  if (last <= 7) {
    return Array.from({ length: last }, (_2, index2) => index2 + 1);
  }
  const pages2 = /* @__PURE__ */ new Set([1, 2, current - 1, current, current + 1, last - 1, last]);
  const sorted = [...pages2].filter((page) => page >= 1 && page <= last).sort((left, right) => left - right);
  const result = [];
  for (let index2 = 0; index2 < sorted.length; index2 += 1) {
    if (index2 > 0 && sorted[index2] - sorted[index2 - 1] > 1) {
      result.push("ellipsis");
    }
    result.push(sorted[index2]);
  }
  return result;
}
function StudioNewsIndex() {
  const { props } = X$1();
  const items = Array.isArray(props.listing?.items) ? props.listing.items : [];
  const filters = props.listing?.filters || {};
  const meta = props.listing?.meta || {};
  const currentPage = Number(meta.current_page || 1);
  const lastPage = Number(meta.last_page || 1);
  const from = Number(meta.from || 0);
  const to = Number(meta.to || 0);
  const paginationPages = buildPaginationPages(currentPage, lastPage);
  const deleteItem = (item) => {
    if (!item?.delete_url) return;
    if (!window.confirm(`Move "${item.title}" to trash?`)) return;
    At.delete(item.delete_url, {
      preserveScroll: true
    });
  };
  const updateFilter = (next, resetPage = true) => {
    const hasExplicitPage = Object.prototype.hasOwnProperty.call(next, "page");
    At.get("/studio/news", {
      ...filters,
      ...next,
      page: hasExplicitPage ? next.page : resetPage ? 1 : currentPage
    }, {
      preserveState: true,
      preserveScroll: true
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.9))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Editorial surface"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Run a first-party newsroom for launches, tutorials, and community stories."), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Pinned stories drive the hero, featured pieces strengthen discovery, and related entity links keep News wired into Groups, releases, collections, and profiles.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "New article"), /* @__PURE__ */ React.createElement("a", { href: props.categoriesUrl, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tags" }), "Taxonomies")))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_220px_220px_220px_auto] lg:items-center" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement(
    "input",
    {
      defaultValue: filters.q || "",
      placeholder: "Search titles, excerpts, and metadata",
      className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none",
      onKeyDown: (event) => {
        if (event.key === "Enter") {
          updateFilter({
            q: event.currentTarget.value || "",
            status: filters.status || "",
            type: filters.type || "",
            category_id: filters.category_id || "",
            order: filters.order || "",
            direction: filters.direction || ""
          });
        }
      }
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.status || "",
      onChange: (value) => updateFilter({ status: value, q: filters.q || "", type: filters.type || "", category_id: filters.category_id || "", order: filters.order || "", direction: filters.direction || "" }),
      placeholder: "All statuses",
      options: (Array.isArray(props.statusOptions) ? props.statusOptions : []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.type || "",
      onChange: (value) => updateFilter({ type: value, q: filters.q || "", status: filters.status || "", category_id: filters.category_id || "", order: filters.order || "", direction: filters.direction || "" }),
      placeholder: "All types",
      options: (Array.isArray(props.typeOptions) ? props.typeOptions : []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Category"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.category_id || "",
      onChange: (value) => updateFilter({ category_id: value, q: filters.q || "", status: filters.status || "", type: filters.type || "", order: filters.order || "", direction: filters.direction || "" }),
      placeholder: "All categories",
      options: (Array.isArray(props.categoryOptions) ? props.categoryOptions : []).map((option) => ({ value: String(option.id), label: option.name })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Order"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.order || "",
      onChange: (value) => updateFilter({ order: value, q: filters.q || "", status: filters.status || "", type: filters.type || "", category_id: filters.category_id || "", direction: filters.direction || "" }),
      placeholder: "Order by",
      options: [
        { value: "date", label: "Date" },
        { value: "title", label: "Title" },
        { value: "views", label: "Views" }
      ],
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Direction"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: filters.direction || "",
      onChange: (value) => updateFilter({ direction: value, q: filters.q || "", status: filters.status || "", type: filters.type || "", category_id: filters.category_id || "", order: filters.order || "" }),
      placeholder: "Asc / Desc",
      options: [
        { value: "desc", label: "Desc" },
        { value: "asc", label: "Asc" }
      ],
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Per page"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: String(filters.per_page || 15),
      onChange: (value) => updateFilter({ per_page: value }),
      placeholder: "Per page",
      options: [
        { value: "15", label: "15 articles" },
        { value: "30", label: "30 articles" },
        { value: "50", label: "50 articles" }
      ],
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400 lg:text-right" }, Number(meta.total || 0).toLocaleString(), " articles"))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 shadow-[0_18px_40px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/9] bg-slate-950/60" }, item.cover_url ? /* @__PURE__ */ React.createElement("img", { src: item.cover_url, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-newspaper text-3xl" }))), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-white/70" }, item.type_label), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 ${statusTone$1(item.editorial_status)}` }, item.editorial_status.replaceAll("_", " ")), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-2.5 py-1 text-amber-100" }, "Pinned") : null, item.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-2.5 py-1 text-emerald-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-xl font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-3 text-sm text-slate-400" }, item.category_name ? /* @__PURE__ */ React.createElement("span", null, item.category_name) : null, /* @__PURE__ */ React.createElement("span", null, item.author_name), /* @__PURE__ */ React.createElement("span", null, formatDate$1(item.published_at))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.edit_url, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: item.editorial_status === "published" ? item.public_url : item.preview_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, item.editorial_status === "published" ? "View" : "Preview"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => deleteItem(item), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Trash"))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No News articles match the current filters.")), lastPage > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-col gap-3 rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-300 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-slate-400" }, "Showing ", from.toLocaleString(), "-", to.toLocaleString(), " of ", Number(meta.total || 0).toLocaleString(), " articles"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: currentPage <= 1,
      onClick: () => updateFilter({ page: Math.max(1, currentPage - 1) }, false),
      className: "rounded-full border border-white/10 px-4 py-2 font-semibold text-white transition hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-40"
    },
    "Previous"
  ), paginationPages.map((page, index2) => page === "ellipsis" ? /* @__PURE__ */ React.createElement("span", { key: `ellipsis-${index2}`, className: "px-2 text-slate-500" }, "...") : /* @__PURE__ */ React.createElement(
    "button",
    {
      key: page,
      type: "button",
      onClick: () => updateFilter({ page }, false),
      "aria-current": page === currentPage ? "page" : void 0,
      className: `min-w-10 rounded-full border px-3 py-2 text-sm font-semibold transition ${page === currentPage ? "border-sky-300/20 bg-sky-400/10 text-sky-100" : "border-white/10 bg-white/[0.03] text-white hover:bg-white/[0.06]"}`
    },
    page
  )), /* @__PURE__ */ React.createElement("span", { className: "ml-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", currentPage, " of ", lastPage), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: currentPage >= lastPage,
      onClick: () => updateFilter({ page: currentPage + 1 }, false),
      className: "rounded-full border border-white/10 px-4 py-2 font-semibold text-white transition hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-40"
    },
    "Next"
  ))) : null);
}
const __vite_glob_0_151 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioNewsIndex
}, Symbol.toStringTag, { value: "Module" }));
function replacePattern(pattern, token, value) {
  return String(pattern || "").replace(token, String(value));
}
function StudioNewsTaxonomies() {
  const { props } = X$1();
  const [categories, setCategories] = reactExports.useState(Array.isArray(props.categories) ? props.categories : []);
  const [tags, setTags] = reactExports.useState(Array.isArray(props.tags) ? props.tags : []);
  const categoryForm = G$1({ name: "", slug: "", description: "", position: 0, is_active: true });
  const tagForm = G$1({ name: "", slug: "" });
  const updateCategory = (index2, field, value) => {
    setCategories((current) => current.map((item, itemIndex) => itemIndex === index2 ? { ...item, [field]: value } : item));
  };
  const updateTag = (index2, field, value) => {
    setTags((current) => current.map((item, itemIndex) => itemIndex === index2 ? { ...item, [field]: value } : item));
  };
  const saveCategory = (category) => {
    At.patch(replacePattern(props.updateCategoryUrlPattern, "__CATEGORY__", category.id), category, { preserveScroll: true });
  };
  const saveTag = (tag) => {
    At.patch(replacePattern(props.updateTagUrlPattern, "__TAG__", tag.id), tag, { preserveScroll: true });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 text-sm font-semibold" }, /* @__PURE__ */ React.createElement("a", { href: "/studio/news/categories", className: `rounded-full px-4 py-2 ${props.activeTab === "categories" ? "border border-sky-300/20 bg-sky-400/10 text-sky-100" : "border border-white/10 bg-white/[0.04] text-white"}` }, "Categories"), /* @__PURE__ */ React.createElement("a", { href: "/studio/news/tags", className: `rounded-full px-4 py-2 ${props.activeTab === "tags" ? "border border-sky-300/20 bg-sky-400/10 text-sky-100" : "border border-white/10 bg-white/[0.04] text-white"}` }, "Tags"), /* @__PURE__ */ React.createElement("a", { href: "/studio/news", className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-white" }, "Back to newsroom"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Categories"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Stable editorial buckets for the newsroom.")), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, categories.length, " total")), /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    categoryForm.post(props.storeCategoryUrl);
  }, className: "mt-5 grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: categoryForm.data.name, onChange: (event) => categoryForm.setData("name", event.target.value), placeholder: "Category name", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: categoryForm.data.slug, onChange: (event) => categoryForm.setData("slug", event.target.value), placeholder: "optional slug", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: categoryForm.data.description, onChange: (event) => categoryForm.setData("description", event.target.value), rows: 3, placeholder: "Description", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "number", value: categoryForm.data.position, onChange: (event) => categoryForm.setData("position", event.target.value), min: "0", className: "w-28 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: categoryForm.data.is_active, onChange: (event) => categoryForm.setData("is_active", event.target.checked), label: "Active" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Create category"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3" }, categories.map((category, index2) => /* @__PURE__ */ React.createElement("div", { key: category.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: category.name, onChange: (event) => updateCategory(index2, "name", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: category.slug, onChange: (event) => updateCategory(index2, "slug", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: category.description || "", onChange: (event) => updateCategory(index2, "description", event.target.value), rows: 2, className: "mt-3 w-full rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "number", value: category.position || 0, min: "0", onChange: (event) => updateCategory(index2, "position", event.target.value), className: "w-24 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(category.is_active), onChange: (event) => updateCategory(index2, "is_active", event.target.checked), label: "Active" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.14em] text-slate-500" }, Number(category.published_count || 0).toLocaleString(), " published"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveCategory(category), className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Save")))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Tags"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Flexible labels for search, discovery, and internal linking.")), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, tags.length, " total")), /* @__PURE__ */ React.createElement("form", { onSubmit: (event) => {
    event.preventDefault();
    tagForm.post(props.storeTagUrl);
  }, className: "mt-5 grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] md:items-center" }, /* @__PURE__ */ React.createElement("input", { value: tagForm.data.name, onChange: (event) => tagForm.setData("name", event.target.value), placeholder: "Tag name", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: tagForm.data.slug, onChange: (event) => tagForm.setData("slug", event.target.value), placeholder: "optional slug", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100" }, "Create tag")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3" }, tags.map((tag, index2) => /* @__PURE__ */ React.createElement("div", { key: tag.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto_auto] md:items-center" }, /* @__PURE__ */ React.createElement("input", { value: tag.name, onChange: (event) => updateTag(index2, "name", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: tag.slug, onChange: (event) => updateTag(index2, "slug", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.14em] text-slate-500" }, Number(tag.published_count || 0).toLocaleString(), " published"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveTag(tag), className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Save"))))))));
}
const __vite_glob_0_152 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioNewsTaxonomies
}, Symbol.toStringTag, { value: "Module" }));
const shortcutOptions = [
  { value: "/dashboard/profile", label: "Dashboard profile" },
  { value: "/dashboard/notifications", label: "Notifications" },
  { value: "/dashboard/comments/received", label: "Received comments" },
  { value: "/dashboard/followers", label: "Followers" },
  { value: "/dashboard/following", label: "Following" },
  { value: "/dashboard/favorites", label: "Favorites" },
  { value: "/dashboard/artworks", label: "Artwork dashboard" },
  { value: "/dashboard/gallery", label: "Gallery" },
  { value: "/dashboard/awards", label: "Awards" },
  { value: "/creator/stories", label: "Story dashboard" },
  { value: "/studio", label: "Creator Studio" }
];
const widgetOptions = [
  { value: "quick_stats", label: "Quick stats" },
  { value: "continue_working", label: "Continue working" },
  { value: "scheduled_items", label: "Scheduled items" },
  { value: "recent_activity", label: "Recent activity" },
  { value: "top_performers", label: "Top performers" },
  { value: "draft_reminders", label: "Draft reminders" },
  { value: "module_summaries", label: "Module summaries" },
  { value: "growth_hints", label: "Growth hints" },
  { value: "active_challenges", label: "Active challenges" },
  { value: "creator_health", label: "Creator health" },
  { value: "featured_status", label: "Featured status" },
  { value: "comments_snapshot", label: "Comments snapshot" },
  { value: "stale_drafts", label: "Stale drafts" }
];
const landingOptions = [
  ["overview", "Overview"],
  ["content", "Content"],
  ["drafts", "Drafts"],
  ["scheduled", "Scheduled"],
  ["calendar", "Calendar"],
  ["inbox", "Inbox"],
  ["analytics", "Analytics"],
  ["growth", "Growth"],
  ["challenges", "Challenges"],
  ["search", "Search"],
  ["preferences", "Preferences"]
];
async function requestJson$2(url, method, body2) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.error || "Request failed");
  }
  return payload;
}
function StudioPreferences() {
  const { props } = X$1();
  const preferences = props.preferences || {};
  const [form, setForm] = reactExports.useState({
    default_content_view: preferences.default_content_view || "grid",
    analytics_range_days: preferences.analytics_range_days || 30,
    dashboard_shortcuts: preferences.dashboard_shortcuts || [],
    draft_behavior: preferences.draft_behavior || "resume-last",
    default_landing_page: preferences.default_landing_page || "overview",
    widget_visibility: preferences.widget_visibility || {},
    widget_order: preferences.widget_order || widgetOptions.map((option) => option.value),
    card_density: preferences.card_density || "comfortable",
    scheduling_timezone: preferences.scheduling_timezone || ""
  });
  const [saving, setSaving] = reactExports.useState(false);
  reactExports.useEffect(() => {
    setForm({
      default_content_view: preferences.default_content_view || "grid",
      analytics_range_days: preferences.analytics_range_days || 30,
      dashboard_shortcuts: preferences.dashboard_shortcuts || [],
      draft_behavior: preferences.draft_behavior || "resume-last",
      default_landing_page: preferences.default_landing_page || "overview",
      widget_visibility: preferences.widget_visibility || {},
      widget_order: preferences.widget_order || widgetOptions.map((option) => option.value),
      card_density: preferences.card_density || "comfortable",
      scheduling_timezone: preferences.scheduling_timezone || ""
    });
  }, [preferences]);
  const toggleShortcut = (value) => {
    setForm((current) => ({
      ...current,
      dashboard_shortcuts: current.dashboard_shortcuts.includes(value) ? current.dashboard_shortcuts.filter((entry) => entry !== value) : [...current.dashboard_shortcuts, value].slice(0, 8)
    }));
  };
  const toggleWidget = (value) => {
    setForm((current) => ({
      ...current,
      widget_visibility: {
        ...current.widget_visibility,
        [value]: !(current.widget_visibility?.[value] !== false)
      }
    }));
  };
  const moveWidget = (value, direction) => {
    setForm((current) => {
      const items = [...current.widget_order];
      const index2 = items.indexOf(value);
      if (index2 < 0) return current;
      const nextIndex = direction === "up" ? index2 - 1 : index2 + 1;
      if (nextIndex < 0 || nextIndex >= items.length) return current;
      const swapped = items[nextIndex];
      items[nextIndex] = value;
      items[index2] = swapped;
      trackStudioEvent("studio_widget_reordered", {
        surface: studioSurface(),
        module: "preferences",
        meta: {
          widget: value,
          direction,
          from: index2 + 1,
          to: nextIndex + 1
        }
      });
      return { ...current, widget_order: items };
    });
  };
  const saveSettings = async () => {
    setSaving(true);
    try {
      await requestJson$2(props.endpoints.save, "PUT", form);
      window.alert("Studio preferences saved.");
    } catch (error) {
      window.alert(error?.message || "Unable to save Studio preferences.");
    } finally {
      setSaving(false);
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Workspace preferences"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Choose where Studio opens, how dense content cards feel, and which overview modules stay visible.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveSettings, disabled: saving, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-floppy-disk" }), saving ? "Saving..." : "Save preferences")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Default content view"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.default_content_view, onChange: (val) => setForm((current) => ({ ...current, default_content_view: val })), searchable: false, options: [{ value: "grid", label: "Grid" }, { value: "list", label: "List" }] })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Analytics date range"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.analytics_range_days, onChange: (val) => setForm((current) => ({ ...current, analytics_range_days: Number(val) })), searchable: false, options: [7, 14, 30, 60, 90].map((days) => ({ value: days, label: `Last ${days} days` })) })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Draft behavior"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.draft_behavior, onChange: (val) => setForm((current) => ({ ...current, draft_behavior: val })), searchable: false, options: [{ value: "resume-last", label: "Resume the last draft I edited" }, { value: "open-drafts", label: "Open the drafts library first" }, { value: "focus-published", label: "Open published content first" }] })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Default landing page"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.default_landing_page, onChange: (val) => setForm((current) => ({ ...current, default_landing_page: val })), searchable: false, options: landingOptions.map(([value, label]) => ({ value, label })) })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Card density"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.card_density, onChange: (val) => setForm((current) => ({ ...current, card_density: val })), searchable: false, options: [{ value: "comfortable", label: "Comfortable" }, { value: "compact", label: "Compact" }] })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Scheduling timezone"), /* @__PURE__ */ React.createElement("input", { value: form.scheduling_timezone, onChange: (event) => setForm((current) => ({ ...current, scheduling_timezone: event.target.value })), placeholder: "Europe/Helsinki", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Dashboard shortcuts"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Pin up to 8 destinations that should stay easy to reach from the wider workspace.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 px-3 py-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, form.dashboard_shortcuts.length, "/8 selected")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, shortcutOptions.map((option) => {
    const active = form.dashboard_shortcuts.includes(option.value);
    return /* @__PURE__ */ React.createElement("button", { key: option.value, type: "button", onClick: () => toggleShortcut(option.value), className: `flex items-center justify-between rounded-[22px] border px-4 py-3 text-left transition ${active ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 bg-black/20 text-slate-300"}` }, /* @__PURE__ */ React.createElement("span", null, option.label), /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${active ? "fa-circle-check" : "fa-circle"} text-sm` }));
  }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Overview widgets"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Show, hide, and prioritize dashboard sections for your daily workflow."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, form.widget_order.map((widgetKey, index2) => {
    const option = widgetOptions.find((entry) => entry.value === widgetKey);
    if (!option) return null;
    const enabled = form.widget_visibility?.[widgetKey] !== false;
    return /* @__PURE__ */ React.createElement("div", { key: widgetKey, className: "flex flex-col gap-3 rounded-[22px] border border-white/10 bg-black/20 p-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Position ", index2 + 1)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => toggleWidget(widgetKey), className: `rounded-full border px-3 py-1.5 text-xs ${enabled ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 text-slate-300"}` }, enabled ? "Visible" : "Hidden"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveWidget(widgetKey, "up"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-300" }, "Up"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveWidget(widgetKey, "down"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-300" }, "Down")));
  })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Related surfaces"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (props.links || []).map((link2) => /* @__PURE__ */ React.createElement("a", { key: link2.url, href: link2.url, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: link2.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold text-white" }, link2.label)))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Preference notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, "Landing page and widget order are stored in the shared Studio preference record, so new Creator Studio surfaces can plug into the same contract without another migration."), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, "Analytics range and card density stay here so Analytics, Growth, and the main dashboard can stay visually consistent."))))));
}
const __vite_glob_0_153 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioPreferences
}, Symbol.toStringTag, { value: "Module" }));
async function requestJson$1(url, method, body2) {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: body2 ? JSON.stringify(body2) : void 0
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.error || "Request failed");
  }
  return payload;
}
async function uploadFile(url, fieldName, file, extra = {}) {
  const formData = new FormData();
  formData.append(fieldName, file);
  Object.entries(extra).forEach(([key, value]) => {
    formData.append(key, String(value));
  });
  const response = await fetch(url, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    },
    body: formData
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || payload?.error || "Upload failed");
  }
  return payload;
}
function socialPlatformLabel(value) {
  return value.split(/[_-]/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
}
function StudioProfile() {
  const { props } = X$1();
  const profile = props.profile || {};
  const endpoints = props.endpoints || {};
  const featuredContent = props.featuredContent || {};
  const featuredModules = props.featuredModules || [];
  const avatarInputRef = reactExports.useRef(null);
  const coverInputRef = reactExports.useRef(null);
  const [form, setForm] = reactExports.useState({
    display_name: profile.name || "",
    tagline: profile.tagline || "",
    bio: profile.bio || "",
    website: profile.website || "",
    social_links: (profile.social_links || []).length > 0 ? profile.social_links : [{ platform: "", url: "" }]
  });
  const [coverPosition, setCoverPosition] = reactExports.useState(profile.cover_position ?? 50);
  const [savingProfile, setSavingProfile] = reactExports.useState(false);
  const [uploadingAvatar, setUploadingAvatar] = reactExports.useState(false);
  const [uploadingCover, setUploadingCover] = reactExports.useState(false);
  const [savingCoverPosition, setSavingCoverPosition] = reactExports.useState(false);
  const [deletingCover, setDeletingCover] = reactExports.useState(false);
  reactExports.useEffect(() => {
    setForm({
      display_name: profile.name || "",
      tagline: profile.tagline || "",
      bio: profile.bio || "",
      website: profile.website || "",
      social_links: (profile.social_links || []).length > 0 ? profile.social_links : [{ platform: "", url: "" }]
    });
    setCoverPosition(profile.cover_position ?? 50);
  }, [profile.bio, profile.cover_position, profile.name, profile.social_links, profile.tagline, profile.website]);
  const updateSocialLink = (index2, key, value) => {
    setForm((current) => ({
      ...current,
      social_links: current.social_links.map((link2, linkIndex) => linkIndex === index2 ? { ...link2, [key]: value } : link2)
    }));
  };
  const addSocialLink = () => {
    setForm((current) => ({
      ...current,
      social_links: [...current.social_links, { platform: "", url: "" }]
    }));
  };
  const removeSocialLink = (index2) => {
    setForm((current) => ({
      ...current,
      social_links: current.social_links.filter((_2, linkIndex) => linkIndex !== index2)
    }));
  };
  const saveProfile = async () => {
    setSavingProfile(true);
    try {
      await requestJson$1(endpoints.profile, "PUT", {
        display_name: form.display_name,
        tagline: form.tagline || null,
        bio: form.bio || null,
        website: form.website || null,
        social_links: form.social_links.filter((link2) => link2.platform.trim() && link2.url.trim())
      });
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to save profile.");
    } finally {
      setSavingProfile(false);
    }
  };
  const handleAvatarSelected = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    setUploadingAvatar(true);
    try {
      await uploadFile(endpoints.avatarUpload, "avatar", file, { avatar_position: "center" });
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to upload avatar.");
    } finally {
      event.target.value = "";
      setUploadingAvatar(false);
    }
  };
  const handleCoverSelected = async (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    setUploadingCover(true);
    try {
      await uploadFile(endpoints.coverUpload, "cover", file);
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to upload cover image.");
    } finally {
      event.target.value = "";
      setUploadingCover(false);
    }
  };
  const saveCoverPosition = async () => {
    setSavingCoverPosition(true);
    try {
      await requestJson$1(endpoints.coverPosition, "POST", { position: coverPosition });
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to update cover position.");
    } finally {
      setSavingCoverPosition(false);
    }
  };
  const deleteCover = async () => {
    if (!window.confirm("Remove your current banner image?")) {
      return;
    }
    setDeletingCover(true);
    try {
      await requestJson$1(endpoints.coverDelete, "DELETE");
      At.reload({ preserveScroll: true, preserveState: true });
    } catch (error) {
      window.alert(error?.message || "Unable to delete cover image.");
    } finally {
      setDeletingCover(false);
    }
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "relative min-h-[220px] bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.25),_transparent_35%),radial-gradient(circle_at_bottom_right,_rgba(34,197,94,0.18),_transparent_40%),linear-gradient(135deg,_rgba(15,23,42,0.94),_rgba(2,6,23,1))]",
      style: profile.cover_url ? {
        backgroundImage: `linear-gradient(rgba(2,6,23,0.35), rgba(2,6,23,0.8)), url(${profile.cover_url})`,
        backgroundSize: "cover",
        backgroundPosition: `center ${coverPosition}%`
      } : void 0
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 p-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-black/30 px-4 py-2 text-xs uppercase tracking-[0.2em] text-slate-200" }, "Creator identity"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("input", { ref: coverInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleCoverSelected, className: "hidden" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => coverInputRef.current?.click(), disabled: uploadingCover, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-black/30 px-4 py-2 text-sm text-white disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" }), uploadingCover ? "Uploading..." : profile.cover_url ? "Replace banner" : "Upload banner"), profile.cover_url && /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteCover, disabled: deletingCover, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm text-rose-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash" }), deletingCover ? "Removing..." : "Remove banner"), /* @__PURE__ */ React.createElement("a", { href: profile.profile_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-black/30 px-4 py-2 text-sm text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square" }), "View public profile"))),
    /* @__PURE__ */ React.createElement("div", { className: "p-6 pt-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, profile.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: profile.avatar_url, alt: profile.username, className: "h-24 w-24 rounded-[28px] border border-white/10 object-cover shadow-lg" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-24 items-center justify-center rounded-[28px] border border-white/10 bg-black/30 text-slate-400 shadow-lg" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-2xl" })), /* @__PURE__ */ React.createElement("input", { ref: avatarInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleAvatarSelected, className: "hidden" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => avatarInputRef.current?.click(), disabled: uploadingAvatar, className: "absolute -bottom-2 -right-2 inline-flex h-10 w-10 items-center justify-center rounded-full border border-sky-300/25 bg-sky-300/15 text-sky-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploadingAvatar ? "fa-spinner fa-spin" : "fa-camera"}` }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-3xl font-semibold text-white" }, profile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, "@", profile.username), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, Number(profile.followers || 0).toLocaleString(), " followers"), profile.location && /* @__PURE__ */ React.createElement("span", null, profile.location)))), profile.cover_url && /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-sm rounded-[24px] border border-white/10 bg-black/30 p-4" }, /* @__PURE__ */ React.createElement("label", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Banner position"), /* @__PURE__ */ React.createElement("input", { type: "range", min: "0", max: "100", value: coverPosition, onChange: (event) => setCoverPosition(Number(event.target.value)), className: "mt-3 w-full" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveCoverPosition, disabled: savingCoverPosition, className: "mt-3 inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-white disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrows-up-down" }), savingCoverPosition ? "Saving..." : "Save banner position"))))
  )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Public profile details"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Update the creator information that supports your public presence across Nova.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveProfile, disabled: savingProfile, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-floppy-disk" }), savingProfile ? "Saving..." : "Save profile")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Display name"), /* @__PURE__ */ React.createElement("input", { value: form.display_name, onChange: (event) => setForm((current) => ({ ...current, display_name: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Tagline"), /* @__PURE__ */ React.createElement("input", { value: form.tagline, onChange: (event) => setForm((current) => ({ ...current, tagline: event.target.value })), placeholder: "One-line creator summary", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Bio"), /* @__PURE__ */ React.createElement("textarea", { value: form.bio, onChange: (event) => setForm((current) => ({ ...current, bio: event.target.value })), rows: 5, placeholder: "Tell visitors what you create and what makes your work distinct.", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Website"), /* @__PURE__ */ React.createElement("input", { value: form.website, onChange: (event) => setForm((current) => ({ ...current, website: event.target.value })), placeholder: "https://example.com", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Social links"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Add the channels that matter for your creator identity.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addSocialLink, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "Add link")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, form.social_links.map((link2, index2) => /* @__PURE__ */ React.createElement("div", { key: `${index2}-${link2.platform}`, className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 md:grid-cols-[180px_minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement("input", { value: link2.platform, onChange: (event) => updateSocialLink(index2, "platform", event.target.value), placeholder: "instagram", className: "rounded-2xl border border-white/10 bg-black/30 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" }), /* @__PURE__ */ React.createElement("input", { value: link2.url, onChange: (event) => updateSocialLink(index2, "url", event.target.value), placeholder: "https://...", className: "rounded-2xl border border-white/10 bg-black/30 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeSocialLink(index2), className: "inline-flex items-center justify-center rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash" }))))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Publishing footprint"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, (props.moduleSummaries || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", null, item.label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(item.count || 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, Number(item.published_count || 0).toLocaleString(), " published, ", Number(item.draft_count || 0).toLocaleString(), " drafts"))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Featured identity"), /* @__PURE__ */ React.createElement("a", { href: "/studio/featured", className: "text-sm font-medium text-sky-100" }, "Manage featured")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, featuredModules.length > 0 ? featuredModules.map((module) => /* @__PURE__ */ React.createElement("span", { key: module, className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-sky-100" }, socialPlatformLabel(module))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No featured modules selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, Object.entries(featuredContent).map(([module, item]) => item ? /* @__PURE__ */ React.createElement("a", { key: module, href: item.view_url || item.preview_url || "/studio/featured", className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 p-3" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-14 w-14 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 items-center justify-center rounded-2xl bg-white/5 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: item.module_icon || "fa-solid fa-star" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, socialPlatformLabel(module)), /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title))) : null)))))));
}
const __vite_glob_0_154 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioProfile
}, Symbol.toStringTag, { value: "Module" }));
async function requestJson(url, method = "POST") {
  const response = await fetch(url, {
    method,
    credentials: "same-origin",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
      "X-Requested-With": "XMLHttpRequest"
    }
  });
  const payload = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(payload?.message || "Request failed");
  }
  return payload;
}
function StudioScheduled() {
  const { props } = X$1();
  const listing = props.listing || {};
  const filters = listing.filters || {};
  const summary = listing.summary || {};
  const agenda = listing.agenda || [];
  const items = listing.items || [];
  const meta = listing.meta || {};
  const rangeOptions2 = listing.range_options || [];
  const endpoints = props.endpoints || {};
  const [busyId, setBusyId] = reactExports.useState(null);
  const [nowMs, setNowMs] = reactExports.useState(() => Date.now());
  const updateFilters = (patch2) => {
    const next = { ...filters, ...patch2 };
    if (patch2.page == null) next.page = 1;
    trackStudioEvent("studio_scheduled_opened", {
      surface: studioSurface(),
      module: next.module,
      meta: patch2
    });
    At.get(window.location.pathname, next, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  const actionUrl2 = (pattern, item) => String(pattern || "").replace("__MODULE__", item.module).replace("__ID__", item.numeric_id);
  const runAction = async (item, key) => {
    const url = actionUrl2(key === "publish" ? endpoints.publishNowPattern : endpoints.unschedulePattern, item);
    if (!url) return;
    setBusyId(`${key}:${item.id}`);
    try {
      await requestJson(url);
      trackStudioEvent(key === "publish" ? "studio_schedule_updated" : "studio_schedule_cleared", {
        surface: studioSurface(),
        module: item.module,
        item_module: item.module,
        item_id: item.numeric_id
      });
      At.reload({ only: ["listing", "overview"] });
    } catch (error) {
      window.alert(error?.message || "Unable to update schedule.");
    } finally {
      setBusyId(null);
    }
  };
  reactExports.useEffect(() => {
    const hasTimedEntries = Boolean(summary.next_publish_at) || items.some((item) => Boolean(item.scheduled_at || item.published_at));
    if (!hasTimedEntries) return void 0;
    const timer = window.setInterval(() => {
      setNowMs(Date.now());
    }, 1e3);
    return () => window.clearInterval(timer);
  }, [items, summary.next_publish_at]);
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 xl:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Scheduled total"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.total || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 md:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Next publish slot"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xl font-semibold text-white" }, formatReleaseCountdown(summary.next_publish_at, nowMs)), summary.next_publish_at && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, formatScheduledDate(summary.next_publish_at)))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, (summary.by_module || []).map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: entry.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white" }, entry.label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-2xl font-semibold text-white" }, Number(entry.count || 0).toLocaleString()))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Agenda"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, agenda.length > 0 ? agenda.slice(0, 6).map((day) => /* @__PURE__ */ React.createElement("div", { key: day.date, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, day.label), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, day.count, " items")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, day.items.slice(0, 2).map((item) => item.title).join(" • ")))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-dashed border-white/15 px-4 py-8 text-sm text-slate-400" }, "No scheduled items yet.")))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search scheduled work"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Title or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: listing.module_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Date range"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.range || "upcoming", onChange: (val) => updateFilters({ range: val }), options: rangeOptions2, searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Start date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: filters.start_date || "", onChange: (nextValue) => updateFilters({ range: "custom", start_date: nextValue }), mode: "date", placeholder: "Start date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "End date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: filters.end_date || "", onChange: (nextValue) => updateFilters({ range: "custom", end_date: nextValue }), mode: "date", placeholder: "End date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateFilters({ q: "", module: "all", range: "upcoming", start_date: "", end_date: "" }), className: "w-full rounded-2xl border border-white/10 px-4 py-3 text-sm text-slate-200" }, "Reset")))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, /* @__PURE__ */ React.createElement("span", null, item.module_label), /* @__PURE__ */ React.createElement("span", null, item.status)), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-4 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatReleaseCountdown(item.scheduled_at || item.published_at, nowMs)), /* @__PURE__ */ React.createElement("span", null, formatScheduledDate(item.scheduled_at || item.published_at)), item.visibility && /* @__PURE__ */ React.createElement("span", null, "Visibility: ", item.visibility), item.updated_at && /* @__PURE__ */ React.createElement("span", null, "Last edited ", formatScheduledDate(item.updated_at)), item.schedule_timezone && /* @__PURE__ */ React.createElement("span", null, item.schedule_timezone))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200" }, "Reschedule"), item.preview_url && /* @__PURE__ */ React.createElement("a", { href: item.preview_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200" }, "Preview"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyId === `publish:${item.id}`, onClick: () => runAction(item, "publish"), className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm text-sky-100 disabled:opacity-50" }, "Publish now"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyId === `unschedule:${item.id}`, onClick: () => runAction(item, "unschedule"), className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200 disabled:opacity-50" }, "Unschedule"))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No scheduled content matches this view.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Previous"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next"))));
}
const __vite_glob_0_155 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioScheduled
}, Symbol.toStringTag, { value: "Module" }));
function StudioSearch() {
  const { props } = X$1();
  const search2 = props.search || {};
  const filters = search2.filters || {};
  const sections = search2.sections || [];
  const updateFilters = (patch2) => {
    At.get(window.location.pathname, { ...filters, ...patch2 }, {
      preserveScroll: true,
      preserveState: true,
      replace: true
    });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 xl:col-span-3" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search Studio"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Search content, comments, inbox, or assets" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Surface"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "all", onChange: (val) => updateFilters({ type: val }), options: search2.type_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: search2.module_options || [], searchable: false })))), filters.q ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Found ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(search2.summary?.total || 0).toLocaleString()), " matches for ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, search2.summary?.query)), sections.length > 0 ? sections.map((section) => /* @__PURE__ */ React.createElement("section", { key: section.key, className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, section.label), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, section.count, " matches")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, section.items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.href, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl bg-white/[0.04] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: item.icon })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.subtitle), /* @__PURE__ */ React.createElement("p", { className: "mt-3 line-clamp-3 text-sm leading-6 text-slate-400" }, item.description)))))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No results matched this search yet.")) : /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Continue working"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, (search2.empty_state?.continue_working || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label, " · ", item.workflow?.readiness?.label))))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Stale drafts"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (search2.empty_state?.stale_drafts || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Quick create"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, (props.quickCreate || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.key, href: item.url, className: "inline-flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-100" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", null, "New ", item.label)))))))));
}
const __vite_glob_0_156 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioSearch
}, Symbol.toStringTag, { value: "Module" }));
function StudioSettings() {
  const { props } = X$1();
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "System handoff"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, "Studio now keeps creator workflow preferences in their own surface. This page stays focused on links out to adjacent dashboards and the control points that do not belong in the day-to-day workflow UI."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, (props.links || []).map((link2) => /* @__PURE__ */ React.createElement("a", { key: link2.url, href: link2.url, className: "rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20 hover:bg-black/30" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: link2.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold text-white" }, link2.label)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, "Open the linked dashboard or settings surface without losing the Studio navigation shell as the default control plane."))))), /* @__PURE__ */ React.createElement("section", { className: "space-y-6" }, (props.sections || []).map((section) => /* @__PURE__ */ React.createElement("div", { key: section.title, className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, section.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, section.body), /* @__PURE__ */ React.createElement("a", { href: section.href, className: "mt-4 inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, section.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })))))));
}
const __vite_glob_0_157 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioSettings
}, Symbol.toStringTag, { value: "Module" }));
function StudioStories() {
  const { props } = X$1();
  const summary = props.summary || {};
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-4" }, [
    ["Stories", summary.count, "fa-solid fa-feather-pointed"],
    ["Drafts", summary.draft_count, "fa-solid fa-file-pen"],
    ["Published", summary.published_count, "fa-solid fa-sparkles"]
  ].map(([label, value, icon]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm" }, label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(value || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Story dashboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6" }, "Jump into the existing story workspace when you need the full editor and publishing controls."))), /* @__PURE__ */ React.createElement(
    StudioContentBrowser,
    {
      listing: props.listing,
      quickCreate: props.quickCreate,
      hideModuleFilter: true,
      sortStorageKey: "studio-stories-sort"
    }
  ));
}
const __vite_glob_0_158 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioStories
}, Symbol.toStringTag, { value: "Module" }));
const MIN_CHUNK_SIZE_BYTES$2 = 256 * 1024;
function formatDate(value) {
  if (!value) return "Just now";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Just now";
  return date.toLocaleString(void 0, {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit"
  });
}
function formatPercent$5(value) {
  const normalized = Number(value || 0);
  if (!Number.isFinite(normalized)) return "0%";
  return `${Math.max(0, Math.min(100, Math.round(normalized)))}%`;
}
function parseTags(raw) {
  return String(raw || "").split(/[\n,]+/).map((tag) => tag.trim()).filter(Boolean);
}
function statusClasses(status2) {
  switch (status2) {
    case "ready":
      return "border-emerald-400/30 bg-emerald-400/10 text-emerald-100";
    case "published":
      return "border-sky-400/30 bg-sky-400/10 text-sky-100";
    case "failed":
      return "border-rose-400/30 bg-rose-400/10 text-rose-100";
    case "needs_review":
    case "needs_metadata":
      return "border-amber-400/30 bg-amber-400/10 text-amber-100";
    default:
      return "border-white/15 bg-white/5 text-slate-300";
  }
}
function batchStatusClasses(status2) {
  switch (status2) {
    case "completed":
      return "border-emerald-400/30 bg-emerald-400/10 text-emerald-100";
    case "completed_with_errors":
      return "border-amber-400/30 bg-amber-400/10 text-amber-100";
    case "processing":
      return "border-sky-400/30 bg-sky-400/10 text-sky-100";
    default:
      return "border-white/15 bg-white/5 text-slate-300";
  }
}
function noticeClasses(type2) {
  switch (type2) {
    case "success":
      return "border-emerald-400/30 bg-emerald-400/10 text-emerald-100";
    case "warning":
      return "border-amber-400/30 bg-amber-400/10 text-amber-100";
    default:
      return "border-rose-400/30 bg-rose-400/10 text-rose-100";
  }
}
function humanStage(stage) {
  return String(stage || "queued").replace(/_/g, " ");
}
function flattenCategories(contentTypes) {
  return (Array.isArray(contentTypes) ? contentTypes : []).flatMap((type2) => {
    const parents = Array.isArray(type2?.categories) ? type2.categories : [];
    return parents.flatMap((category) => {
      const children = Array.isArray(category?.children) ? category.children : [];
      if (children.length === 0) {
        return [{
          id: category.id,
          label: `${type2.name} / ${category.name}`
        }];
      }
      return children.map((child) => ({
        id: child.id,
        label: `${type2.name} / ${category.name} / ${child.name}`
      }));
    });
  });
}
function SummaryCard({ label, value, hint }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold text-white" }, value), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, hint));
}
function StudioUploadQueue() {
  const { props } = X$1();
  const queueProp = props.queue || {};
  const chunkSize = Math.max(MIN_CHUNK_SIZE_BYTES$2, Number(props.chunkSize || 0) || 5 * 1024 * 1024);
  const chunkRequestTimeoutMs = Math.max(15e3, Number(props.chunkRequestTimeoutMs || 0) || 45e3);
  const categoryOptions = reactExports.useMemo(() => flattenCategories(props.contentTypes || []), [props.contentTypes]);
  const [queue, setQueue] = reactExports.useState(queueProp);
  const [selectedBatchId, setSelectedBatchId] = reactExports.useState(queueProp?.filters?.batch_id ?? queueProp?.current_batch?.id ?? "");
  const [statusFilter, setStatusFilter] = reactExports.useState(queueProp?.filters?.status || "all");
  const [sort, setSort] = reactExports.useState(queueProp?.filters?.sort || "newest");
  const [selectedIds, setSelectedIds] = reactExports.useState([]);
  const [files, setFiles] = reactExports.useState([]);
  const [uploading, setUploading] = reactExports.useState(false);
  const [uploadState, setUploadState] = reactExports.useState({});
  const [notice, setNotice] = reactExports.useState(null);
  const [busyAction, setBusyAction] = reactExports.useState("");
  const [defaults2, setDefaults] = reactExports.useState({
    name: "",
    categoryId: "",
    tags: "",
    visibility: "public",
    isMature: false
  });
  const [bulkForm, setBulkForm] = reactExports.useState({
    categoryId: "",
    tags: "",
    visibility: "public"
  });
  const fileInputRef = reactExports.useRef(null);
  const noticeTimeoutRef = reactExports.useRef(null);
  const items = Array.isArray(queue?.items) ? queue.items : [];
  const currentBatch = queue?.current_batch || null;
  const batches = Array.isArray(queue?.batches) ? queue.batches : [];
  const selectableIds = items.filter((item) => item?.actions?.can_delete || item?.actions?.can_publish || item?.actions?.can_generate_ai).map((item) => Number(item.id));
  const allSelected = selectableIds.length > 0 && selectableIds.every((id) => selectedIds.includes(id));
  const activeProcessing = uploading || ["uploading", "processing"].includes(String(currentBatch?.status || ""));
  const pushNotice = (type2, message) => {
    setNotice({ type: type2, message });
    window.clearTimeout(noticeTimeoutRef.current);
    noticeTimeoutRef.current = window.setTimeout(() => setNotice(null), 4500);
  };
  reactExports.useEffect(() => () => window.clearTimeout(noticeTimeoutRef.current), []);
  const syncSelectedIds = (queueItems) => {
    const validIds = new Set((queueItems || []).map((item) => Number(item.id)));
    setSelectedIds((current) => current.filter((id) => validIds.has(id)));
  };
  const loadQueue = async (overrides = {}) => {
    const params = {
      batch_id: overrides.batch_id ?? (selectedBatchId || void 0),
      status: overrides.status ?? statusFilter,
      sort: overrides.sort ?? sort
    };
    try {
      const response = await window.axios.get("/api/studio/upload-queue", { params });
      const nextQueue = response.data || {};
      setQueue(nextQueue);
      setSelectedBatchId(nextQueue?.filters?.batch_id ?? "");
      syncSelectedIds(nextQueue?.items || []);
      return nextQueue;
    } catch (error) {
      pushNotice("error", error?.response?.data?.message || "Failed to refresh the upload queue.");
      return null;
    }
  };
  reactExports.useEffect(() => {
    if (!activeProcessing || !selectedBatchId) return void 0;
    const timer = window.setInterval(() => {
      loadQueue({ batch_id: selectedBatchId });
    }, 3e3);
    return () => window.clearInterval(timer);
  }, [activeProcessing, selectedBatchId, statusFilter, sort]);
  const uploadChunk = async (sessionId, uploadToken, blob, offset, totalSize) => {
    const payload = new FormData();
    payload.append("session_id", sessionId);
    payload.append("offset", String(offset));
    payload.append("chunk_size", String(blob.size));
    payload.append("total_size", String(totalSize));
    payload.append("chunk", blob);
    payload.append("upload_token", uploadToken);
    const response = await window.axios.post("/api/uploads/chunk", payload, {
      timeout: chunkRequestTimeoutMs,
      headers: { "X-Upload-Token": uploadToken }
    });
    return response.data || {};
  };
  const uploadSingleFile = async (item, file) => {
    const init2 = await window.axios.post("/api/uploads/init", { client: "web" });
    const sessionId = init2?.data?.session_id;
    const uploadToken = init2?.data?.upload_token;
    if (!sessionId || !uploadToken) {
      throw new Error("Upload session initialization failed.");
    }
    let offset = 0;
    while (offset < file.size) {
      const nextOffset = Math.min(offset + chunkSize, file.size);
      const chunk2 = file.slice(offset, nextOffset);
      const data = await uploadChunk(sessionId, uploadToken, chunk2, offset, file.size);
      offset = Number(data?.received_bytes ?? nextOffset);
      const progress = Math.max(1, Math.min(100, Math.round(offset / file.size * 100)));
      setUploadState((current) => ({
        ...current,
        [item.id]: {
          ...current[item.id],
          status: "uploading",
          progress
        }
      }));
    }
    await window.axios.post("/api/uploads/finish", {
      session_id: sessionId,
      artwork_id: item.artwork_id,
      batch_item_id: item.id,
      file_name: file.name,
      upload_token: uploadToken
    }, {
      headers: { "X-Upload-Token": uploadToken }
    });
    setUploadState((current) => ({
      ...current,
      [item.id]: {
        status: "processing",
        progress: 100
      }
    }));
  };
  const markItemFailed = async (itemId, error) => {
    try {
      await window.axios.post(`/api/studio/upload-queue/items/${itemId}/fail`, {
        error_code: error?.response?.data?.reason || "upload_failed",
        error_message: error?.response?.data?.message || error?.message || "Upload failed."
      });
    } catch (markError) {
    }
  };
  const startUpload = async () => {
    if (files.length === 0) {
      pushNotice("error", "Choose at least one image file to start a batch.");
      return;
    }
    setUploading(true);
    setBusyAction("create-batch");
    try {
      const response = await window.axios.post("/api/studio/upload-queue/batches", {
        name: defaults2.name || null,
        files: files.map((file) => ({ name: file.name })),
        defaults: {
          category_id: defaults2.categoryId ? Number(defaults2.categoryId) : null,
          tags: parseTags(defaults2.tags),
          visibility: defaults2.visibility,
          is_mature: Boolean(defaults2.isMature)
        }
      });
      const createdItems = Array.isArray(response?.data?.items) ? response.data.items : [];
      const batchId = response?.data?.batch?.id;
      if (!batchId || createdItems.length !== files.length) {
        throw new Error("Batch registration did not return a usable file map.");
      }
      setQueue(response.data.queue || queue);
      setSelectedBatchId(batchId);
      setSelectedIds([]);
      for (let index2 = 0; index2 < createdItems.length; index2 += 1) {
        const item = createdItems[index2];
        const file = files[index2];
        setUploadState((current) => ({
          ...current,
          [item.id]: { status: "queued", progress: 0 }
        }));
        try {
          await uploadSingleFile(item, file);
        } catch (error) {
          await markItemFailed(item.id, error);
          setUploadState((current) => ({
            ...current,
            [item.id]: {
              status: "failed",
              progress: current[item.id]?.progress || 0
            }
          }));
        }
        await loadQueue({ batch_id: batchId });
      }
      setFiles([]);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
      pushNotice("success", "Upload batch created. Processing continues in the queue.");
    } catch (error) {
      pushNotice("error", error?.response?.data?.message || error?.message || "Failed to create the upload batch.");
    } finally {
      setUploading(false);
      setBusyAction("");
    }
  };
  const handleSelectAll = () => {
    if (allSelected) {
      setSelectedIds([]);
      return;
    }
    setSelectedIds(selectableIds);
  };
  const handleToggleSelected = (itemId) => {
    setSelectedIds((current) => current.includes(itemId) ? current.filter((id) => id !== itemId) : [...current, itemId]);
  };
  const summarizePublishSelection = (ids) => {
    const selectedItems = items.filter((item) => ids.includes(Number(item.id)));
    const readyItems = selectedItems.filter((item) => item?.is_ready_to_publish);
    const blockedItems = selectedItems.filter((item) => !item?.is_ready_to_publish);
    const reviewBlockedCount = blockedItems.filter((item) => item?.status === "needs_review").length;
    const metadataBlockedCount = blockedItems.filter((item) => item?.status === "needs_metadata").length;
    const processingBlockedCount = blockedItems.filter((item) => item?.status === "processing").length;
    const failedBlockedCount = blockedItems.filter((item) => item?.status === "failed").length;
    return {
      totalCount: selectedItems.length,
      readyCount: readyItems.length,
      blockedCount: blockedItems.length,
      reviewBlockedCount,
      metadataBlockedCount,
      processingBlockedCount,
      failedBlockedCount
    };
  };
  const confirmPublishSelection = (ids) => {
    const summary = summarizePublishSelection(ids);
    if (summary.totalCount === 0) {
      pushNotice("warning", "Select at least one queue item first.");
      return false;
    }
    if (summary.readyCount === 0) {
      pushNotice("warning", "None of the selected drafts are ready to publish yet.");
      return false;
    }
    const message = [
      `Publish ${summary.readyCount} ready draft(s)?`,
      `Selected: ${summary.totalCount}`,
      `Ready now: ${summary.readyCount}`,
      `Blocked and skipped: ${summary.blockedCount}`
    ];
    if (summary.reviewBlockedCount > 0) {
      message.push(`Needs review: ${summary.reviewBlockedCount}`);
    }
    if (summary.metadataBlockedCount > 0) {
      message.push(`Missing metadata: ${summary.metadataBlockedCount}`);
    }
    if (summary.processingBlockedCount > 0) {
      message.push(`Still processing: ${summary.processingBlockedCount}`);
    }
    if (summary.failedBlockedCount > 0) {
      message.push(`Failed items: ${summary.failedBlockedCount}`);
    }
    message.push("Blocked drafts will not be published.");
    return window.confirm(message.join("\n"));
  };
  const runBulkAction = async (action, params = {}, ids = selectedIds) => {
    if (!Array.isArray(ids) || ids.length === 0) {
      pushNotice("warning", "Select at least one queue item first.");
      return;
    }
    let confirmValue = void 0;
    if (action === "publish") {
      if (!confirmPublishSelection(ids)) {
        return;
      }
    }
    if (action === "delete") {
      const value = window.prompt("Type DELETE to remove the selected drafts from the queue.");
      if (value !== "DELETE") {
        return;
      }
      confirmValue = value;
    }
    setBusyAction(action);
    try {
      const response = await window.axios.post("/api/studio/upload-queue/bulk", {
        action,
        item_ids: ids,
        params,
        confirm: confirmValue
      });
      const success = Number(response?.data?.success || 0);
      const failed = Number(response?.data?.failed || 0);
      if (failed > 0 && success === 0) {
        pushNotice("error", response?.data?.errors?.[0] || "The queue action failed.");
      } else if (failed > 0) {
        pushNotice("warning", `${success} item(s) updated. ${failed} item(s) could not be changed.`);
      } else {
        pushNotice("success", `${success} item(s) updated.`);
      }
      await loadQueue({ batch_id: selectedBatchId });
      setSelectedIds([]);
    } catch (error) {
      const message = error?.response?.data?.errors?.[0] || error?.response?.data?.message || "The queue action failed.";
      pushNotice("error", message);
    } finally {
      setBusyAction("");
    }
  };
  const retryItem = async (itemId) => {
    setBusyAction(`retry-${itemId}`);
    try {
      await window.axios.post(`/api/studio/upload-queue/items/${itemId}/retry`);
      pushNotice("success", "Background processing has been queued again for this draft.");
      await loadQueue({ batch_id: selectedBatchId });
    } catch (error) {
      pushNotice("error", error?.response?.data?.message || "Retry failed for this queue item.");
    } finally {
      setBusyAction("");
    }
  };
  const handleBatchChange = async (nextBatchId) => {
    setSelectedBatchId(nextBatchId);
    await loadQueue({ batch_id: nextBatchId || void 0 });
  };
  const onDropFiles = (event) => {
    event.preventDefault();
    const dropped = Array.from(event.dataTransfer.files || []);
    setFiles(dropped);
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, notice && /* @__PURE__ */ React.createElement("div", { className: `rounded-[24px] border px-4 py-3 text-sm ${noticeClasses(notice.type)}` }, notice.message), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_28%),linear-gradient(135deg,_rgba(15,23,42,0.84),_rgba(2,6,23,0.96))] p-6 shadow-[0_20px_60px_rgba(2,6,23,0.3)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-6 xl:flex-row xl:items-start xl:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/70" }, "Bulk upload drafts"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Start a batch, then let Studio handle the review queue."), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Each file becomes a normal draft artwork. Upload transport happens now, thumbnail and maturity work continue in the background, and publishing stays blocked until the draft is actually ready.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:w-[380px]" }, /* @__PURE__ */ React.createElement(SummaryCard, { label: "Selected files", value: files.length, hint: "Add multiple images to build a batch." }), /* @__PURE__ */ React.createElement(SummaryCard, { label: "Current batch", value: currentBatch?.total_items || 0, hint: currentBatch ? `Status: ${String(currentBatch.status || "uploading").replace(/_/g, " ")}` : "No active batch selected." }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-[1.2fr,0.8fr]" }, /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "rounded-[28px] border border-dashed border-white/15 bg-white/[0.03] p-5 transition hover:border-sky-300/35",
      onDragOver: (event) => event.preventDefault(),
      onDrop: onDropFiles
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex h-full flex-col justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Drag multiple image files here"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, "PNG, JPG, and WebP files are supported through the normal upload pipeline. Each file becomes one draft artwork.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => fileInputRef.current?.click(),
        className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/15"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-cloud-arrow-up" }),
      "Choose files"
    ), /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: fileInputRef,
        type: "file",
        multiple: true,
        accept: "image/png,image/jpeg,image/webp",
        className: "hidden",
        onChange: (event) => setFiles(Array.from(event.target.files || []))
      }
    ), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, files.length > 0 ? `${files.length} file(s) ready` : "Nothing selected yet")), files.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-slate-950/30 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Batch contents"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 max-h-48 space-y-2 overflow-y-auto pr-1 text-sm text-slate-300" }, files.map((file) => /* @__PURE__ */ React.createElement("div", { key: `${file.name}-${file.size}`, className: "flex items-center justify-between gap-3 rounded-2xl border border-white/5 bg-white/[0.02] px-3 py-2" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, file.name), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, Math.max(1, Math.round(file.size / 1024)), " KB"))))))
  ), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Shared defaults"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Batch name"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: defaults2.name,
      onChange: (event) => setDefaults((current) => ({ ...current, name: event.target.value })),
      className: "mt-2 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35",
      placeholder: "Optional batch label"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Category"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: defaults2.categoryId,
      onChange: (value) => setDefaults((current) => ({ ...current, categoryId: value })),
      className: "mt-2",
      options: categoryOptions.map((option) => ({ value: String(option.id), label: option.label })),
      placeholder: "No shared category"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Visibility when published"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: defaults2.visibility,
      onChange: (value) => setDefaults((current) => ({ ...current, visibility: value })),
      className: "mt-2",
      options: [
        { value: "public", label: "Public" },
        { value: "unlisted", label: "Unlisted" },
        { value: "private", label: "Private" }
      ],
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("label", { className: "block text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Shared tags"), /* @__PURE__ */ React.createElement(
    "textarea",
    {
      value: defaults2.tags,
      onChange: (event) => setDefaults((current) => ({ ...current, tags: event.target.value })),
      className: "mt-2 min-h-[92px] w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35",
      placeholder: "fantasy, portrait, wallpaper"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: defaults2.isMature,
      onChange: (event) => setDefaults((current) => ({ ...current, isMature: event.target.checked })),
      label: "Mark all files as creator-declared mature"
    }
  )), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: startUpload,
      disabled: uploading || files.length === 0,
      className: "inline-flex w-full items-center justify-center gap-2 rounded-full border border-emerald-400/25 bg-emerald-400/10 px-4 py-3 text-sm font-semibold text-emerald-100 transition hover:border-emerald-400/45 hover:bg-emerald-400/15 disabled:cursor-not-allowed disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-play" }),
    busyAction === "create-batch" ? "Creating batch..." : "Start upload batch"
  ))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Queue view"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Review a batch, then work the drafts that actually need attention.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Batch"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: selectedBatchId,
      onChange: handleBatchChange,
      className: "mt-2",
      options: batches.map((batch) => ({ value: String(batch.id), label: batch.name || `Batch #${batch.id}` })),
      placeholder: "Latest batch"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Filter"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: statusFilter,
      onChange: async (nextStatus) => {
        setStatusFilter(nextStatus);
        await loadQueue({ status: nextStatus });
      },
      className: "mt-2",
      options: (queue?.status_options || []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Sort"), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: sort,
      onChange: async (nextSort) => {
        setSort(nextSort);
        await loadQueue({ sort: nextSort });
      },
      className: "mt-2",
      options: (queue?.sort_options || []).map((option) => ({ value: option.value, label: option.label })),
      searchable: false
    }
  )))), currentBatch && /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-5" }, /* @__PURE__ */ React.createElement(SummaryCard, { label: "Batch status", value: String(currentBatch.status || "uploading").replace(/_/g, " "), hint: `Updated ${formatDate(currentBatch.updated_at)}` }), /* @__PURE__ */ React.createElement(SummaryCard, { label: "Ready", value: currentBatch.ready_items || 0, hint: "Can be published right now." }), /* @__PURE__ */ React.createElement(SummaryCard, { label: "Processing", value: currentBatch.processing_items || 0, hint: "Still moving through the pipeline." }), /* @__PURE__ */ React.createElement(SummaryCard, { label: "Needs review", value: currentBatch.needs_review_items || 0, hint: "Blocked on maturity or review." }), /* @__PURE__ */ React.createElement(SummaryCard, { label: "Failed", value: currentBatch.failed_items || 0, hint: "Needs retry or a fresh upload." })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-white/10 bg-slate-950/35 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleSelectAll,
      disabled: selectableIds.length === 0,
      className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-4 py-2 text-sm text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-50"
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check-double" }),
    allSelected ? "Clear selection" : "Select visible"
  ), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-500" }, selectedIds.length, " selected")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => runBulkAction("publish"),
      disabled: busyAction !== "" || selectedIds.length === 0,
      className: "inline-flex items-center gap-2 rounded-full border border-emerald-400/25 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100 transition hover:border-emerald-400/40 hover:bg-emerald-400/15 disabled:cursor-not-allowed disabled:opacity-50"
    },
    "Publish selected"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => runBulkAction("generate_ai"),
      disabled: busyAction !== "" || selectedIds.length === 0,
      className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/15 disabled:cursor-not-allowed disabled:opacity-50"
    },
    "Generate AI"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => runBulkAction("delete"),
      disabled: busyAction !== "" || selectedIds.length === 0,
      className: "inline-flex items-center gap-2 rounded-full border border-rose-400/25 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100 transition hover:border-rose-400/40 hover:bg-rose-400/15 disabled:cursor-not-allowed disabled:opacity-50"
    },
    "Delete selected"
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-[1fr,1fr,auto,auto]" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: bulkForm.categoryId,
      onChange: (value) => setBulkForm((current) => ({ ...current, categoryId: value })),
      options: categoryOptions.map((option) => ({ value: String(option.id), label: option.label })),
      placeholder: "Apply category..."
    }
  ), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: bulkForm.tags,
      onChange: (event) => setBulkForm((current) => ({ ...current, tags: event.target.value })),
      className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none transition focus:border-sky-300/35",
      placeholder: "Add shared tags to selection"
    }
  ), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      value: bulkForm.visibility,
      onChange: (value) => setBulkForm((current) => ({ ...current, visibility: value })),
      options: [
        { value: "public", label: "Public" },
        { value: "unlisted", label: "Unlisted" },
        { value: "private", label: "Private" }
      ],
      searchable: false
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => runBulkAction("apply_category", { category_id: Number(bulkForm.categoryId) }),
      disabled: busyAction !== "" || selectedIds.length === 0 || !bulkForm.categoryId,
      className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-50"
    },
    "Apply category"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => runBulkAction("apply_tags", { tags: parseTags(bulkForm.tags) }),
      disabled: busyAction !== "" || selectedIds.length === 0 || parseTags(bulkForm.tags).length === 0,
      className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-50"
    },
    "Apply tags"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => runBulkAction("set_visibility", { visibility: bulkForm.visibility }),
      disabled: busyAction !== "" || selectedIds.length === 0,
      className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06] disabled:cursor-not-allowed disabled:opacity-50"
    },
    "Set visibility"
  )))), items.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.02] p-8 text-center text-sm text-slate-400" }, "No items match this view yet. Start a batch above or switch to another recent batch.") : /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, items.map((item) => {
    const localUpload = uploadState[item.id] || null;
    const progress = localUpload?.progress ?? null;
    const actionState = item.actions || {};
    return /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(3,7,18,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement(
      Checkbox,
      {
        checked: selectedIds.includes(Number(item.id)),
        onChange: () => handleToggleSelected(Number(item.id))
      }
    ), /* @__PURE__ */ React.createElement("div", { className: "h-24 w-24 overflow-hidden rounded-2xl border border-white/10 bg-slate-950/60" }, item.thumbnail_url ? /* @__PURE__ */ React.createElement("img", { src: item.thumbnail_url, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-2xl" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${statusClasses(item.status)}` }, String(item.status || "processing").replace(/_/g, " ")), /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${batchStatusClasses(item.processing_stage === "finalized" ? "completed" : "processing")}` }, humanStage(item.processing_stage)), item.is_ready_to_publish && /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-emerald-400/30 bg-emerald-400/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Ready to publish")), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 truncate text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm text-slate-400" }, item.original_filename), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2 text-sm text-slate-300 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-slate-950/30 px-3 py-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Metadata"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-white" }, item.metadata_label)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-slate-950/30 px-3 py-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Updated"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-white" }, formatDate(item.updated_at)))), typeof progress === "number" && progress < 100 && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/20 bg-sky-300/10 px-3 py-3 text-sm text-sky-100" }, "Uploading now: ", formatPercent$5(progress)), Array.isArray(item.missing) && item.missing.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-slate-950/30 px-3 py-3 text-sm text-slate-300" }, item.missing.join(" • ")), item.error_message && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-400/30 bg-rose-400/10 px-3 py-3 text-sm text-rose-100" }, item.error_message), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, actionState.can_edit && item.edit_url && /* @__PURE__ */ React.createElement("a", { href: item.edit_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-200 transition hover:border-white/20 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square" }), "Edit in Studio"), actionState.can_publish && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => runBulkAction("publish", {}, [item.id]),
        disabled: busyAction !== "",
        className: "inline-flex items-center gap-2 rounded-full border border-emerald-400/25 bg-emerald-400/10 px-3 py-2 text-sm font-semibold text-emerald-100 transition hover:border-emerald-400/40 hover:bg-emerald-400/15 disabled:cursor-not-allowed disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket" }),
      "Publish"
    ), actionState.can_generate_ai && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => runBulkAction("generate_ai", {}, [item.id]),
        disabled: busyAction !== "",
        className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-300/10 px-3 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-300/15 disabled:cursor-not-allowed disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-wand-magic-sparkles" }),
      "Generate AI"
    ), actionState.can_retry_processing && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => retryItem(item.id),
        disabled: busyAction !== "",
        className: "inline-flex items-center gap-2 rounded-full border border-amber-400/25 bg-amber-400/10 px-3 py-2 text-sm font-semibold text-amber-100 transition hover:border-amber-400/40 hover:bg-amber-400/15 disabled:cursor-not-allowed disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-right" }),
      "Retry"
    ), actionState.can_delete && /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => runBulkAction("delete", {}, [item.id]),
        disabled: busyAction !== "",
        className: "inline-flex items-center gap-2 rounded-full border border-rose-400/25 bg-rose-400/10 px-3 py-2 text-sm font-semibold text-rose-100 transition hover:border-rose-400/40 hover:bg-rose-400/15 disabled:cursor-not-allowed disabled:opacity-50"
      },
      /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash" }),
      "Delete draft"
    )))));
  })))));
}
const __vite_glob_0_159 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioUploadQueue
}, Symbol.toStringTag, { value: "Module" }));
function WorldDuplicateActionMenu({ duplicateUrl, newEditionUrl, canCreateEdition, onDuplicate, onCreateEdition, copyModeCount = 0 }) {
  if (!duplicateUrl && !newEditionUrl) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Reuse this world"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Duplicate the current campaign structure or roll it forward into the next edition without rebuilding the curated setup.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, duplicateUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onDuplicate, className: "rounded-full border border-white/10 bg-white/[0.06] px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white" }, "Duplicate world") : null, newEditionUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onCreateEdition, disabled: !canCreateEdition, className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-emerald-100 disabled:cursor-not-allowed disabled:opacity-50" }, "Create next edition") : null)), !canCreateEdition ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs leading-5 text-slate-500" }, "Next-edition creation unlocks once this world has recurrence data.") : null, copyModeCount > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs leading-5 text-slate-500" }, "Each action lets you choose whether to carry over curated relations or start from a clean structural shell.") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs leading-5 text-slate-500" }, "Next-edition drafts preserve the recurrence key, increment the edition year, and reset live dates plus homepage flags so the new edition starts clean."));
}
function SearchResultList$2({ items, loading, selectedId, onSelect }) {
  if (loading) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "Searching recap articles…");
  }
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "Search published news by title, slug, or category to link a recap article.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, items.map((item) => /* @__PURE__ */ React.createElement("button", { key: item.id, type: "button", onClick: () => onSelect(item), className: `min-w-0 flex items-start gap-3 rounded-[24px] border px-4 py-4 text-left transition ${String(selectedId) === String(item.id) ? "border-emerald-300/25 bg-emerald-400/10" : "border-white/10 bg-black/20 hover:border-white/20"}` }, /* @__PURE__ */ React.createElement("div", { className: "relative h-14 w-14 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-950" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && !item.avatar ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-newspaper" })) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, item.entity_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, item.entity_label) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-sm leading-6 text-slate-400" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-slate-500" }, item.meta.map((meta) => /* @__PURE__ */ React.createElement("span", { key: meta }, meta))) : null))));
}
function WorldRecapArticlePickerModal({ open, onClose, onSave, initialArticle, searchEntities }) {
  const [query, setQuery] = reactExports.useState("");
  const [results, setResults] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [selected, setSelected] = reactExports.useState(initialArticle || null);
  reactExports.useEffect(() => {
    if (!open) return;
    setQuery(initialArticle?.title || "");
    setSelected(initialArticle || null);
    setResults([]);
    setLoading(false);
  }, [open, initialArticle]);
  reactExports.useEffect(() => {
    if (!open) {
      setResults([]);
      setLoading(false);
      return void 0;
    }
    let cancelled = false;
    const timeoutId = window.setTimeout(async () => {
      setLoading(true);
      try {
        const items = await searchEntities("news", query || "");
        if (!cancelled) {
          setResults(Array.isArray(items) ? items : []);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }, query ? 220 : 0);
    return () => {
      cancelled = true;
      window.clearTimeout(timeoutId);
    };
  }, [open, query, searchEntities]);
  const selectedPreview = reactExports.useMemo(() => selected || null, [selected]);
  const footer2 = /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-full border border-white/10 px-4 py-2 text-sm font-semibold text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => selectedPreview && onSave(selectedPreview), disabled: !selectedPreview, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:cursor-not-allowed disabled:opacity-50" }, "Link article"));
  return /* @__PURE__ */ React.createElement(Modal, { open, onClose, title: "Link recap article", size: "2xl", footer: footer2 }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 overflow-x-hidden" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: query, onChange: (event) => setQuery(event.target.value), placeholder: "Search article title, slug, or category", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(SearchResultList$2, { items: results, loading, selectedId: selectedPreview?.id, onSelect: (item) => {
    setSelected(item);
    setQuery(item.title);
  } }), selectedPreview ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-emerald-300/20 bg-emerald-400/10 p-4 text-sm text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "break-words font-semibold" }, "Selected: ", selectedPreview.title), selectedPreview.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 break-words text-xs uppercase tracking-[0.14em] text-emerald-100/70" }, selectedPreview.subtitle) : null, Array.isArray(selectedPreview.meta) && selectedPreview.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-emerald-100/75" }, selectedPreview.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry }, entry))) : null) : null));
}
function SearchResultList$1({ items, loading, selectedId, onSelect }) {
  if (loading) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "Searching group challenges…");
  }
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "Search by challenge title, slug, or group name to link a primary challenge.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, items.map((item) => /* @__PURE__ */ React.createElement("button", { key: item.id, type: "button", onClick: () => onSelect(item), className: `min-w-0 flex items-start gap-3 rounded-[24px] border px-4 py-4 text-left transition ${String(selectedId) === String(item.id) ? "border-emerald-300/25 bg-emerald-400/10" : "border-white/10 bg-black/20 hover:border-white/20"}` }, /* @__PURE__ */ React.createElement("div", { className: "relative h-14 w-14 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-950" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && !item.avatar ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy" })) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, item.entity_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, item.entity_label) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-sm leading-6 text-slate-400" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-slate-500" }, item.meta.map((meta) => /* @__PURE__ */ React.createElement("span", { key: meta }, meta))) : null))));
}
function WorldLinkedChallengePickerModal({ open, onClose, onSave, initialChallenge, searchEntities }) {
  const [query, setQuery] = reactExports.useState("");
  const [results, setResults] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [selected, setSelected] = reactExports.useState(initialChallenge || null);
  reactExports.useEffect(() => {
    if (!open) return;
    setQuery(initialChallenge?.title || "");
    setSelected(initialChallenge || null);
    setResults([]);
    setLoading(false);
  }, [open, initialChallenge]);
  reactExports.useEffect(() => {
    if (!open) {
      setResults([]);
      setLoading(false);
      return void 0;
    }
    let cancelled = false;
    const timeoutId = window.setTimeout(async () => {
      setLoading(true);
      try {
        const items = await searchEntities("challenge", query || "");
        if (!cancelled) {
          setResults(Array.isArray(items) ? items : []);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }, query ? 220 : 0);
    return () => {
      cancelled = true;
      window.clearTimeout(timeoutId);
    };
  }, [open, query, searchEntities]);
  const selectedPreview = reactExports.useMemo(() => selected || null, [selected]);
  const footer2 = /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-full border border-white/10 px-4 py-2 text-sm font-semibold text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => selectedPreview && onSave(selectedPreview), disabled: !selectedPreview, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:cursor-not-allowed disabled:opacity-50" }, "Link challenge"));
  return /* @__PURE__ */ React.createElement(Modal, { open, onClose, title: "Link primary challenge", size: "2xl", footer: footer2 }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 overflow-x-hidden" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: query, onChange: (event) => setQuery(event.target.value), placeholder: "Search challenge title, slug, or group", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(SearchResultList$1, { items: results, loading, selectedId: selectedPreview?.id, onSelect: (item) => {
    setSelected(item);
    setQuery(item.title);
  } }), selectedPreview ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-emerald-300/20 bg-emerald-400/10 p-4 text-sm text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "break-words font-semibold" }, "Selected: ", selectedPreview.title), selectedPreview.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 break-words text-xs uppercase tracking-[0.14em] text-emerald-100/70" }, selectedPreview.subtitle) : null, Array.isArray(selectedPreview.meta) && selectedPreview.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-emerald-100/75" }, selectedPreview.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry }, entry))) : null) : null));
}
function WorldPreviewButton({ previewUrl, className = "", disabledReason = "Save the world once to unlock the full preview page." }) {
  if (!previewUrl) {
    return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-400 ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-slate-200" }, "Full preview unavailable"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-500" }, disabledReason));
  }
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      href: previewUrl,
      target: "_blank",
      rel: "noreferrer",
      className: `inline-flex items-center justify-center gap-2 rounded-2xl border border-indigo-300/20 bg-indigo-400/10 px-4 py-3 text-sm font-semibold text-indigo-100 transition hover:bg-indigo-400/15 ${className}`.trim()
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-eye" }),
    "Open full preview"
  );
}
function WorldMiniPreviewPanel({ world, sections, previewUrl }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Live mini preview"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Hero hierarchy, CTA, badges, section order, and attached content update immediately as you edit.")), /* @__PURE__ */ React.createElement(WorldPreviewButton, { previewUrl })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 overflow-hidden rounded-[28px] border border-white/10 bg-slate-950" }, /* @__PURE__ */ React.createElement("div", { className: "relative px-5 py-5", style: { background: `linear-gradient(135deg, ${world?.accent_color || "#38bdf8"}22, transparent 45%), linear-gradient(180deg, #020617 0%, #0f172a 100%)` } }, world?.cover_url ? /* @__PURE__ */ React.createElement("img", { src: world.cover_url, alt: "", className: "absolute inset-0 h-full w-full object-cover opacity-25" }) : null, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-white/10 px-3 py-1" }, world?.type || "seasonal"), world?.badge_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/25 px-3 py-1" }, world.badge_label) : null, world?.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-1 text-emerald-100" }, "Homepage feature") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] text-white" }, world?.title || "Untitled world"), world?.tagline ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs uppercase tracking-[0.22em] text-white/60" }, world.tagline) : null, world?.summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 max-w-2xl text-sm leading-7 text-slate-200/85" }, world.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, world?.cta_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-slate-950" }, world.cta_label, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null, world?.badge_description ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/8 px-4 py-2 text-sm font-semibold text-white" }, world.badge_description) : null))), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Visible section order"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-3" }, Array.isArray(sections) && sections.length > 0 ? sections.map((section) => /* @__PURE__ */ React.createElement("div", { key: section.key, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, section.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, section.count, " attached items")), section.count === 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Empty") : null), Array.isArray(section.items) && section.items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-xs text-slate-400" }, section.items.map((item) => /* @__PURE__ */ React.createElement("span", { key: `${section.key}-${item.id}`, className: "rounded-full bg-white/[0.04] px-3 py-1.5" }, item.title))) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No sections are visible yet. Enable sections and attach content to shape the public world.")))));
}
function WorldRecurrenceHelper({ enabled, recurrenceKey, editionYear, recurrenceKeyError, editionYearError }) {
  if (!enabled) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm leading-6 text-slate-400" }, "Turn on recurrence when this world belongs to a campaign family such as Halloween, Retro Month, or Pixel Week and needs a reusable edition pattern.");
  }
  const exampleKey = recurrenceKey || "halloween";
  const exampleYear = editionYear || (/* @__PURE__ */ new Date()).getFullYear();
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/15 bg-sky-400/10 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, "Recurring world guidance"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 space-y-2 leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("p", null, "Use the recurrence key to identify the campaign family. Example: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, exampleKey), "."), /* @__PURE__ */ React.createElement("p", null, "Use the edition year for the specific annual or seasonal instance. Example: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, exampleYear), "."), /* @__PURE__ */ React.createElement("p", { className: "text-sky-100" }, "Example output: ", exampleKey === "" ? "Halloween" : exampleKey.replace(/-/g, " "), " ", exampleYear, " is part of the recurring world ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, exampleKey), "."), /* @__PURE__ */ React.createElement("p", null, "The family route resolves to the current or latest edition, while archived editions remain available on a year-specific URL.")), recurrenceKeyError || editionYearError ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-xs leading-5 text-rose-100" }, recurrenceKeyError || editionYearError) : null);
}
function SmallBadge({ children, tone = "default" }) {
  const styles2 = {
    default: "border-white/10 bg-white/[0.06] text-slate-200",
    accent: "border-sky-300/20 bg-sky-400/10 text-sky-100",
    feature: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${styles2[tone] || styles2.default}` }, children);
}
function WorldRelationCard({ relation, index: index2, total, sectionLabel, onEdit, onRemove, onMove }) {
  const preview = relation?.preview || null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-20 w-20 shrink-0 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, preview?.image ? /* @__PURE__ */ React.createElement("img", { src: preview.image, alt: "", className: "h-full w-full object-cover" }) : null, !preview?.image && preview?.avatar ? /* @__PURE__ */ React.createElement("img", { src: preview.avatar, alt: "", className: "h-full w-full object-cover" }) : null, !preview?.image && !preview?.avatar ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shapes" })) : null, preview?.avatar && preview?.image ? /* @__PURE__ */ React.createElement("img", { src: preview.avatar, alt: "", className: "absolute bottom-2 left-2 h-8 w-8 rounded-xl border border-white/10 object-cover" }) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, preview?.entity_label ? /* @__PURE__ */ React.createElement(SmallBadge, { tone: "accent" }, preview.entity_label) : null, sectionLabel ? /* @__PURE__ */ React.createElement(SmallBadge, null, sectionLabel) : null, relation?.is_featured ? /* @__PURE__ */ React.createElement(SmallBadge, { tone: "feature" }, "Featured") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-base font-semibold text-white" }, preview?.title || "Choose a relation"), preview?.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, preview.subtitle) : null, preview?.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-sm leading-6 text-slate-400" }, preview.description) : null, relation?.context_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-medium text-sky-100" }, relation.context_label) : null, Array.isArray(preview?.meta) && preview.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-slate-500" }, preview.meta.map((item) => /* @__PURE__ */ React.createElement("span", { key: item }, item))) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onMove(index2, -1), disabled: index2 === 0, className: "rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-white disabled:opacity-40" }, "Up"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onMove(index2, 1), disabled: index2 === total - 1, className: "rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-white disabled:opacity-40" }, "Down"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onEdit, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-2 text-xs font-semibold text-sky-100" }, "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onRemove, className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-xs font-semibold text-rose-100" }, "Remove"))), preview?.url ? /* @__PURE__ */ React.createElement("a", { href: preview.url, target: "_blank", rel: "noreferrer", className: "mt-4 inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300 hover:text-white" }, "Open entity ", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-up-right-from-square" })) : null);
}
function relationTypeForSection(sectionKey, sectionOptions, relationTypeOptions) {
  const section = sectionOptions.find((option) => option.value === sectionKey);
  return section?.relation_types?.[0] || relationTypeOptions?.[0]?.value || "artwork";
}
function emptyRelation(sectionOptions, relationTypeOptions) {
  const sectionKey = sectionOptions?.[0]?.value || "featured_artworks";
  const relationType = relationTypeForSection(sectionKey, sectionOptions, relationTypeOptions);
  return {
    section_key: sectionKey,
    related_type: relationType,
    related_id: "",
    context_label: "",
    sort_order: 0,
    is_featured: false,
    preview: null,
    query: ""
  };
}
function SearchResultList({ items, loading, selectedId, onSelect }) {
  if (loading) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "Searching campaign entities…");
  }
  if (!Array.isArray(items) || items.length === 0) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "Search by title, slug, creator, or project name to attach curated content.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, items.map((item) => /* @__PURE__ */ React.createElement("button", { key: `${item.entity_type}-${item.id}`, type: "button", onClick: () => onSelect(item), className: `min-w-0 flex items-start gap-3 rounded-[24px] border px-4 py-4 text-left transition ${String(selectedId) === String(item.id) ? "border-emerald-300/25 bg-emerald-400/10" : "border-white/10 bg-black/20 hover:border-white/20"}` }, /* @__PURE__ */ React.createElement("div", { className: "relative h-14 w-14 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-950" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && !item.avatar ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shapes" })) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, item.entity_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, item.entity_label) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-sm leading-6 text-slate-400" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-slate-500" }, item.meta.map((meta) => /* @__PURE__ */ React.createElement("span", { key: meta }, meta))) : null))));
}
function WorldRelationPickerModal({ open, onClose, onSave, initialRelation, sectionOptions, relationTypeOptions, searchEntities }) {
  const [draft, setDraft] = reactExports.useState(() => emptyRelation(sectionOptions, relationTypeOptions));
  const [results, setResults] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (!open) return;
    const nextDraft = initialRelation || emptyRelation(sectionOptions, relationTypeOptions);
    setDraft({
      ...nextDraft,
      query: nextDraft.query || nextDraft.preview?.title || ""
    });
    setResults([]);
    setLoading(false);
  }, [open, initialRelation, sectionOptions, relationTypeOptions]);
  const selectedSection = reactExports.useMemo(() => sectionOptions.find((option) => option.value === draft.section_key), [sectionOptions, draft.section_key]);
  const availableRelationTypes = reactExports.useMemo(() => relationTypeOptions.filter((option) => !selectedSection?.relation_types?.length || selectedSection.relation_types.includes(option.value)), [relationTypeOptions, selectedSection]);
  const selectedPreview = reactExports.useMemo(() => {
    if (draft.preview) return draft.preview;
    return results.find((item) => String(item.id) === String(draft.related_id)) || null;
  }, [draft.preview, draft.related_id, results]);
  reactExports.useEffect(() => {
    if (!open || availableRelationTypes.length === 0) return;
    if (availableRelationTypes.some((option) => option.value === draft.related_type)) return;
    setDraft((current) => ({
      ...current,
      related_type: availableRelationTypes[0].value,
      related_id: "",
      preview: null
    }));
  }, [open, availableRelationTypes, draft.related_type]);
  reactExports.useEffect(() => {
    if (!open || !draft.related_type) {
      setResults([]);
      setLoading(false);
      return void 0;
    }
    let cancelled = false;
    const timeoutId = window.setTimeout(async () => {
      setLoading(true);
      try {
        const items = await searchEntities(draft.related_type, draft.query || "");
        if (!cancelled) {
          setResults(Array.isArray(items) ? items : []);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    }, draft.query ? 220 : 0);
    return () => {
      cancelled = true;
      window.clearTimeout(timeoutId);
    };
  }, [open, draft.related_type, draft.query, searchEntities]);
  const actionLabel = initialRelation?.related_id ? "Save relation" : "Attach relation";
  const canSubmit = Boolean(draft.related_id);
  const nextRelation = selectedPreview ? { ...draft, preview: selectedPreview } : draft;
  const footer2 = /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-full border border-white/10 px-4 py-2 text-sm font-semibold text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onSave(nextRelation), disabled: !canSubmit, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:cursor-not-allowed disabled:opacity-50" }, actionLabel));
  return /* @__PURE__ */ React.createElement(Modal, { open, onClose, title: "Attach curated relation", size: "2xl", footer: footer2 }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 overflow-x-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.35fr)] lg:items-end" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Section", value: draft.section_key || null, onChange: (nextValue) => setDraft((current) => {
    const nextSectionKey = String(nextValue || "");
    return {
      ...current,
      section_key: nextSectionKey,
      related_type: relationTypeForSection(nextSectionKey, sectionOptions, relationTypeOptions),
      related_id: "",
      preview: null
    };
  }), options: sectionOptions, searchable: false, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(NovaSelect, { label: "Entity type", value: draft.related_type || null, onChange: (nextValue) => setDraft((current) => ({ ...current, related_type: String(nextValue || ""), related_id: "", preview: null })), options: availableRelationTypes, searchable: false, className: "bg-black/20" }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 flex-wrap gap-2 sm:flex-nowrap" }, /* @__PURE__ */ React.createElement("input", { value: draft.query || "", onChange: (event) => setDraft((current) => ({ ...current, query: event.target.value })), placeholder: "Search title, slug, group, or creator", className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "shrink-0 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-slate-300" }, "Auto")))), /* @__PURE__ */ React.createElement(SearchResultList, { items: results, loading, selectedId: draft.related_id, onSelect: (item) => setDraft((current) => ({ ...current, related_id: item.id, preview: item, query: item.title })) }), selectedPreview ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-emerald-300/20 bg-emerald-400/10 p-4 text-sm text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "break-words font-semibold" }, "Selected: ", selectedPreview.title), selectedPreview.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 break-words text-xs uppercase tracking-[0.14em] text-emerald-100/70" }, selectedPreview.subtitle) : null, Array.isArray(selectedPreview.meta) && selectedPreview.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-emerald-100/75" }, selectedPreview.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry }, entry))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 break-words text-xs text-emerald-100/80" }, "Section: ", selectedSection?.label || draft.section_key, " · ", draft.is_featured ? "Featured relation" : "Standard relation")) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[minmax(0,1fr)_10rem] lg:grid-cols-[minmax(0,1fr)_10rem_minmax(0,15rem)] md:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Context label"), /* @__PURE__ */ React.createElement("input", { value: draft.context_label || "", onChange: (event) => setDraft((current) => ({ ...current, context_label: event.target.value })), placeholder: "Featured release, Join this challenge, Meet the creator", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Sort order"), /* @__PURE__ */ React.createElement("input", { type: "number", min: "0", value: draft.sort_order, onChange: (event) => setDraft((current) => ({ ...current, sort_order: Number(event.target.value) || 0 })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 md:col-span-2 lg:col-span-1" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(draft.is_featured), onChange: (event) => setDraft((current) => ({ ...current, is_featured: event.target.checked })), label: "Featured relation", size: 20, variant: "accent" })))));
}
function Pill$1({ children, tone = "default" }) {
  const tones2 = {
    default: "border-white/10 bg-white/[0.05] text-slate-200",
    accent: "border-sky-300/20 bg-sky-400/10 text-sky-100",
    muted: "border-white/10 bg-black/20 text-slate-400",
    warn: "border-amber-300/20 bg-amber-400/10 text-amber-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${tones2[tone]}` }, children);
}
function WorldSectionToggleList({ sectionOptions, order: order2, visibility, relationCounts, onChange }) {
  const selected = Array.isArray(order2) && order2.length > 0 ? order2 : sectionOptions.map((option) => option.value);
  const move = (index2, delta) => {
    const nextIndex = index2 + delta;
    if (nextIndex < 0 || nextIndex >= selected.length) return;
    const next = [...selected];
    const [entry] = next.splice(index2, 1);
    next.splice(nextIndex, 0, entry);
    onChange(next, visibility);
  };
  const toggle = (key, enabled) => {
    onChange(selected, { ...visibility, [key]: enabled });
  };
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, selected.map((key, index2) => {
    const option = sectionOptions.find((entry) => entry.value === key);
    if (!option) return null;
    return /* @__PURE__ */ React.createElement("div", { key, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: visibility?.[key] !== false, onChange: (event) => toggle(key, event.target.checked), label: option.label, size: 20, variant: "accent" }), option.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-400" }, option.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Pill$1, { tone: visibility?.[key] !== false ? "accent" : "muted" }, visibility?.[key] !== false ? "Visible on public page" : "Hidden on public page"), /* @__PURE__ */ React.createElement(Pill$1, { tone: (relationCounts?.[key] || 0) > 0 ? "default" : "warn" }, relationCounts?.[key] || 0, " attached items")), (relationCounts?.[key] || 0) === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "This section is ready, but it will stay empty until you attach curated items.") : null), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => move(index2, -1), disabled: index2 === 0, className: "rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-white disabled:cursor-not-allowed disabled:opacity-40" }, "Up"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => move(index2, 1), disabled: index2 === selected.length - 1, className: "rounded-full border border-white/10 px-3 py-2 text-xs font-semibold text-white disabled:cursor-not-allowed disabled:opacity-40" }, "Down"))));
  }));
}
function WorldAnalyticsSummaryCard({ label, value, hint = "", tone = "default" }) {
  const toneClass = tone === "accent" ? "border-sky-300/20 bg-sky-400/10 text-sky-100" : tone === "emerald" ? "border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border-white/10 bg-black/20 text-white";
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-[22px] border px-4 py-4 ${toneClass}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] opacity-75" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em]" }, value), hint ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 opacity-80" }, hint) : null);
}
function formatNumber$7(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function formatPercent$4(value) {
  return `${Math.round(Number(value || 0) * 100)}%`;
}
function WorldAnalyticsMetricGrid({ summary = {} }) {
  const cards = [
    {
      label: "Views",
      value: formatNumber$7(summary.views),
      hint: summary.top_source_surface?.label ? `Top source: ${summary.top_source_surface.label} • ${formatPercent$4(summary.top_source_surface.clickthrough_rate)} CTR` : "Traffic to the world page."
    },
    {
      label: "Unique Visitors",
      value: formatNumber$7(summary.unique_visitors),
      hint: "Distinct visitors in the selected window."
    },
    {
      label: "Promotion Impressions",
      value: formatNumber$7(summary.promotion_impressions),
      hint: `Source CTR: ${formatPercent$4(summary.promotion_clickthrough_rate)}`,
      tone: "accent"
    },
    {
      label: "CTA Clicks",
      value: formatNumber$7(summary.cta_clicks),
      hint: "Tracked world and challenge actions.",
      tone: "accent"
    },
    {
      label: "Submissions",
      value: formatNumber$7(summary.submissions),
      hint: `Live: ${formatNumber$7(summary.approved_live_participations)} • Approval: ${formatPercent$4(summary.approval_rate)}`,
      tone: "emerald"
    },
    {
      label: "Reward Grants",
      value: formatNumber$7(summary.reward_grants),
      hint: `Challenge clicks: ${formatNumber$7(summary.challenge_clicks)} • View-to-submit: ${formatPercent$4(summary.view_to_submission_conversion)}`
    }
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, cards.map((card) => /* @__PURE__ */ React.createElement(WorldAnalyticsSummaryCard, { key: card.label, ...card })));
}
function formatNumber$6(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function formatPercent$3(value) {
  return `${Math.round(Number(value || 0) * 100)}%`;
}
function WorldAnalyticsSourceBreakdown({ sources = [] }) {
  if (!Array.isArray(sources) || sources.length === 0) {
    return null;
  }
  const maxViews = Math.max(...sources.map((row) => Number(row.views || 0)), 1);
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Source breakdown"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, sources.map((row) => /* @__PURE__ */ React.createElement("div", { key: row.source_surface, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, row.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.14em] text-slate-400" }, formatNumber$6(row.views), " views")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 h-2 overflow-hidden rounded-full bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-sky-300/80", style: { width: `${Math.max(8, Number(row.views || 0) / maxViews * 100)}%` } })), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatNumber$6(row.impressions), " impressions"), /* @__PURE__ */ React.createElement("span", null, formatNumber$6(row.unique_visitors), " unique"), /* @__PURE__ */ React.createElement("span", null, formatNumber$6(row.clicks), " source clicks"), /* @__PURE__ */ React.createElement("span", null, formatPercent$3(row.clickthrough_rate), " CTR"))))));
}
function formatNumber$5(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function WorldAnalyticsSectionPerformance({ sections = [], entities = [] }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Section performance"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, Array.isArray(sections) && sections.length > 0 ? sections.slice(0, 6).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.section_key, className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.section_key)), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-sky-100" }, formatNumber$5(item.clicks)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] px-4 py-3 text-sm text-slate-400" }, "No tracked section engagement yet."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Top clicked entities"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, Array.isArray(entities) && entities.length > 0 ? entities.slice(0, 6).map((item) => /* @__PURE__ */ React.createElement("div", { key: `${item.entity_type}-${item.entity_id}`, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.entity_title), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-sky-100" }, formatNumber$5(item.clicks))), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.section_key || item.entity_type))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] px-4 py-3 text-sm text-slate-400" }, "No linked entity clicks recorded yet."))));
}
function formatNumber$4(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function formatPercent$2(value) {
  return `${Math.round(Number(value || 0) * 100)}%`;
}
function WorldAnalyticsParticipationPanel({ participation = {} }) {
  const currentCards = [
    ["Pending", participation.pending],
    ["Live", participation.live],
    ["Removed", participation.removed],
    ["Blocked", participation.blocked],
    ["Featured", participation.featured]
  ];
  const activityCards = [
    ["Submitted", participation.submitted],
    ["Approved", participation.approved],
    ["Removed Actions", participation.removed_actions],
    ["Blocked Actions", participation.blocked_actions],
    ["Featured Actions", participation.featured_actions]
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Participation state"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, currentCards.map(([label, value]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xl font-semibold text-white" }, formatNumber$4(value)))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Participation funnel"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, activityCards.map(([label, value]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, label), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-sky-100" }, formatNumber$4(value))))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, "Approval rate: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatPercent$2(participation.approval_rate))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, "Removal rate: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatPercent$2(participation.removal_rate))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, "Block rate: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatPercent$2(participation.block_rate))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, "View-to-submit: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatPercent$2(participation.view_to_submission_conversion))))));
}
function formatNumber$3(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function formatPercent$1(value) {
  return `${Math.round(Number(value || 0) * 100)}%`;
}
function WorldAnalyticsChallengePanel({ challenge = {} }) {
  if (!challenge?.linked_challenge_id) {
    return null;
  }
  const cards = [
    ["Challenge CTA clicks", challenge.challenge_cta_clicks, "number"],
    ["Recap clicks", challenge.recap_clicks, "number"],
    ["Entry clicks", challenge.entry_clicks, "number"],
    ["Winner clicks", challenge.winner_clicks, "number"],
    ["Finalist clicks", challenge.finalist_clicks, "number"],
    ["Total challenge clicks", challenge.total_clicks, "number"],
    ["Submission starts", challenge.submission_starts, "number"],
    ["Created submissions", challenge.submissions_created, "number"],
    ["Click-to-submit", challenge.click_to_submission_conversion, "percent"]
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Challenge-linked engagement"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, cards.map(([label, value, type2]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xl font-semibold text-white" }, type2 === "percent" ? formatPercent$1(value) : formatNumber$3(value))))));
}
function formatNumber$2(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function WorldAnalyticsEditionComparisonCard({ comparison = null }) {
  if (!comparison?.editions || comparison.editions.length < 2) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recurring edition comparison"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, comparison.label)), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, comparison.recurrence_key)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full text-left text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/10 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Edition"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Views"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Unique"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Submissions"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Featured"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Challenge"), /* @__PURE__ */ React.createElement("th", { className: "pb-3" }, "Rewards"))), /* @__PURE__ */ React.createElement("tbody", null, comparison.editions.map((edition) => /* @__PURE__ */ React.createElement("tr", { key: edition.world_id, className: "border-b border-white/[0.06] last:border-b-0" }, /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, edition.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, edition.edition_year || "Unversioned", edition.is_current_world ? " • current editor" : "")), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4" }, formatNumber$2(edition.metrics?.views)), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4" }, formatNumber$2(edition.metrics?.unique_visitors)), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4" }, formatNumber$2(edition.metrics?.submissions)), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4" }, formatNumber$2(edition.metrics?.featured_participations)), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4" }, formatNumber$2(edition.metrics?.challenge_clicks)), /* @__PURE__ */ React.createElement("td", { className: "py-3" }, formatNumber$2(edition.metrics?.reward_grants))))))));
}
function WorldAnalyticsPanel({ analytics = null, world = null }) {
  const [activeRange, setActiveRange] = reactExports.useState(analytics?.default_range || "30d");
  const range2 = reactExports.useMemo(() => analytics?.ranges?.[activeRange] || analytics?.ranges?.[analytics?.default_range || "30d"] || null, [activeRange, analytics]);
  if (!world?.id || !analytics || !range2) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm leading-6 text-slate-400" }, "Analytics will populate after the world starts receiving traffic, clicks, submissions, or rewards.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "World analytics"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold text-white" }, "Campaign performance and editorial signals"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Traffic, promotion surfaces, engagement, participation, challenge energy, and recurring-edition readiness for this world.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (analytics.range_options || []).map((option) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: option.value,
      type: "button",
      onClick: () => setActiveRange(option.value),
      className: `rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition ${activeRange === option.value ? "border-sky-300/25 bg-sky-400/12 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-300 hover:bg-white/[0.08]"}`
    },
    option.label
  ))))), /* @__PURE__ */ React.createElement(WorldAnalyticsMetricGrid, { summary: range2.summary }), /* @__PURE__ */ React.createElement(WorldAnalyticsSourceBreakdown, { sources: range2.sources }), /* @__PURE__ */ React.createElement(WorldAnalyticsSectionPerformance, { sections: range2.section_performance, entities: range2.entity_performance }), /* @__PURE__ */ React.createElement(WorldAnalyticsParticipationPanel, { participation: range2.participation }), /* @__PURE__ */ React.createElement(WorldAnalyticsChallengePanel, { challenge: range2.challenge }), /* @__PURE__ */ React.createElement(WorldAnalyticsEditionComparisonCard, { comparison: analytics.edition_comparison }));
}
function Button({ tone = "default", children, ...props }) {
  const tones2 = {
    default: "border-white/10 bg-white/[0.04] text-slate-200",
    sky: "border-sky-300/20 bg-sky-400/10 text-sky-100",
    emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
    amber: "border-amber-300/20 bg-amber-400/10 text-amber-100",
    rose: "border-rose-300/20 bg-rose-400/10 text-rose-100"
  };
  return /* @__PURE__ */ React.createElement("button", { type: "button", ...props, className: `rounded-2xl border px-3 py-2 text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-50 ${tones2[tone] || tones2.default} ${props.className || ""}`.trim() }, children);
}
function WorldSuggestionActions({ item, busyKey = "", onAddFeatured, onAddSection, onPin, onDismiss, onNotRelevant, onRestore }) {
  const targets = Array.isArray(item?.section_targets) ? item.section_targets : [];
  const [selectedSection, setSelectedSection] = reactExports.useState(item?.default_section_key || targets[0]?.value || "");
  const isBusy = Boolean(busyKey);
  reactExports.useEffect(() => {
    setSelectedSection(item?.state?.section_key || item?.default_section_key || targets[0]?.value || "");
  }, [item?.default_section_key, item?.state?.section_key, targets]);
  if (!item) {
    return null;
  }
  if (item.state?.status === "dismissed" || item.state?.status === "not_relevant") {
    return /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Button, { tone: "sky", disabled: isBusy, onClick: () => onRestore(item) }, "Restore"));
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-end" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Section target"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2 sm:flex-row" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: selectedSection, onChange: (val) => setSelectedSection(val), options: targets, searchable: false, className: "min-w-0 flex-1" }), /* @__PURE__ */ React.createElement(Button, { tone: "emerald", disabled: isBusy || !selectedSection, onClick: () => onAddSection(item, selectedSection, false) }, "Add to section"), /* @__PURE__ */ React.createElement(Button, { tone: "amber", disabled: isBusy || !selectedSection, onClick: () => onAddFeatured(item, selectedSection) }, "Add as featured"))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap justify-start gap-2 lg:justify-end" }, /* @__PURE__ */ React.createElement(Button, { tone: item.state?.status === "pinned" ? "sky" : "default", disabled: isBusy || !selectedSection, onClick: () => item.state?.status === "pinned" ? onRestore(item) : onPin(item, selectedSection) }, item.state?.status === "pinned" ? "Unpin" : "Pin for later"), /* @__PURE__ */ React.createElement(Button, { tone: "default", disabled: isBusy, onClick: () => onDismiss(item) }, "Dismiss"), /* @__PURE__ */ React.createElement(Button, { tone: "rose", disabled: isBusy, onClick: () => onNotRelevant(item) }, "Not relevant")));
}
const TONE_CLASSES = {
  default: "border-white/10 bg-white/[0.05] text-slate-200",
  slate: "border-white/10 bg-white/[0.05] text-slate-300",
  sky: "border-sky-300/20 bg-sky-400/10 text-sky-100",
  emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
  amber: "border-amber-300/20 bg-amber-400/10 text-amber-100",
  rose: "border-rose-300/20 bg-rose-400/10 text-rose-100"
};
function WorldSuggestionReasonPills({ reasons = [] }) {
  if (!Array.isArray(reasons) || reasons.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, reasons.map((reason) => /* @__PURE__ */ React.createElement(
    "span",
    {
      key: `${reason.label}-${reason.tone || "default"}`,
      className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${TONE_CLASSES[reason.tone] || TONE_CLASSES.default}`
    },
    reason.label
  )));
}
function TinyBadge({ children, tone = "default" }) {
  const tones2 = {
    default: "border-white/10 bg-white/[0.05] text-slate-200",
    sky: "border-sky-300/20 bg-sky-400/10 text-sky-100",
    emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
    amber: "border-amber-300/20 bg-amber-400/10 text-amber-100",
    rose: "border-rose-300/20 bg-rose-400/10 text-rose-100"
  };
  return /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${tones2[tone] || tones2.default}` }, children);
}
function WorldSuggestionCard({ item, busyKey, onAddFeatured, onAddSection, onPin, onDismiss, onNotRelevant, onRestore }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-24 w-24 shrink-0 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "h-full w-full object-cover" }) : null, !item.image && !item.avatar ? /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-stars" })) : null, item.avatar && item.image ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "absolute bottom-2 left-2 h-9 w-9 rounded-xl border border-white/10 object-cover" }) : null), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, item.entity_label ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "sky" }, item.entity_label) : null, item.category_label ? /* @__PURE__ */ React.createElement(TinyBadge, null, item.category_label) : null, item.signals?.challenge_linked ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "sky" }, "Challenge-linked") : null, item.signals?.community_submission ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "emerald" }, "Community signal") : null, item.signals?.recurring_history_informed ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "default" }, "Recurring signal") : null, item.signals?.analytics_informed ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "amber" }, "Analytics cue") : null, item.state?.status === "pinned" ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "amber" }, "Pinned") : null, item.state?.status === "dismissed" ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "default" }, "Dismissed") : null, item.state?.status === "not_relevant" ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "rose" }, "Not relevant") : null, item.score_label ? /* @__PURE__ */ React.createElement(TinyBadge, { tone: "emerald" }, item.score_label) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-200" }, "Score ", item.score)), item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null, item.context_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm font-medium text-sky-100" }, item.context_label) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-xs text-slate-500" }, item.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry }, entry))) : null, /* @__PURE__ */ React.createElement(WorldSuggestionReasonPills, { reasons: item.reasons }), item.url ? /* @__PURE__ */ React.createElement("a", { href: item.url, target: "_blank", rel: "noreferrer", className: "mt-4 inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300 hover:text-white" }, "Open source entity ", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-up-right-from-square" })) : null, /* @__PURE__ */ React.createElement(
    WorldSuggestionActions,
    {
      item,
      busyKey,
      onAddFeatured,
      onAddSection,
      onPin,
      onDismiss,
      onNotRelevant,
      onRestore
    }
  ))));
}
function WorldChallengeSuggestionPanel({ group, busyKey, onAddFeatured, onAddSection, onPin, onDismiss, onNotRelevant, onRestore }) {
  if (!group) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/15 bg-sky-400/[0.06] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Challenge-aware suggestions"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, group.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-300" }, group.description)), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, group.count, " ready")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4" }, group.items.map((item) => /* @__PURE__ */ React.createElement(
    WorldSuggestionCard,
    {
      key: item.key,
      item,
      busyKey: busyKey === item.key ? busyKey : "",
      onAddFeatured,
      onAddSection,
      onPin,
      onDismiss,
      onNotRelevant,
      onRestore
    }
  ))));
}
function FilterSelect({ label, value, onChange, options = [] }) {
  const novaOptions = [{ value: "", label: "All" }, ...options.map((o) => ({ value: o.value, label: typeof o.count === "number" ? `${o.label} (${o.count})` : o.label }))];
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement(NovaSelect, { value: value || "", onChange, options: novaOptions, searchable: false }));
}
function WorldSuggestionFilters({ filters, value, onChange }) {
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 rounded-[24px] border border-white/10 bg-black/20 p-4 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement(FilterSelect, { label: "Category", value: value.category, onChange: (nextValue) => onChange({ ...value, category: nextValue }), options: filters?.category_options || [] }), /* @__PURE__ */ React.createElement(FilterSelect, { label: "Entity type", value: value.type, onChange: (nextValue) => onChange({ ...value, type: nextValue }), options: filters?.type_options || [] }), /* @__PURE__ */ React.createElement(FilterSelect, { label: "Section target", value: value.section, onChange: (nextValue) => onChange({ ...value, section: nextValue }), options: filters?.section_options || [] }), /* @__PURE__ */ React.createElement(FilterSelect, { label: "Sort", value: value.sort, onChange: (nextValue) => onChange({ ...value, sort: nextValue }), options: filters?.sort_options || [] }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: value.challengeOnly, onChange: (event) => onChange({ ...value, challengeOnly: event.target.checked }), label: "Challenge-linked only" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: value.communityOnly, onChange: (event) => onChange({ ...value, communityOnly: event.target.checked }), label: "Community submissions only" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: value.recurringOnly, onChange: (event) => onChange({ ...value, recurringOnly: event.target.checked }), label: "Recurring-history informed" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: value.analyticsOnly, onChange: (event) => onChange({ ...value, analyticsOnly: event.target.checked }), label: "Analytics-informed only" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: value.showSuppressed, onChange: (event) => onChange({ ...value, showSuppressed: event.target.checked }), label: "Show suppressed" })));
}
function SummaryPill({ label, value, tone = "default" }) {
  const tones2 = {
    default: "border-white/10 bg-white/[0.04] text-slate-200",
    sky: "border-sky-300/20 bg-sky-400/10 text-sky-100",
    emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
    amber: "border-amber-300/20 bg-amber-400/10 text-amber-100"
  };
  return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border px-4 py-3 ${tones2[tone] || tones2.default}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] opacity-80" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold" }, value));
}
function matchesFilters(item, filters) {
  if (filters.category && item.category_key !== filters.category) {
    return false;
  }
  if (filters.type && item.entity_type !== filters.type) {
    return false;
  }
  if (filters.section && !item.section_targets?.some((target) => target.value === filters.section)) {
    return false;
  }
  if (filters.challengeOnly && !item.signals?.challenge_linked) {
    return false;
  }
  if (filters.communityOnly && !item.signals?.community_submission) {
    return false;
  }
  if (filters.recurringOnly && !item.signals?.recurring_history_informed) {
    return false;
  }
  if (filters.analyticsOnly && !item.signals?.analytics_informed) {
    return false;
  }
  return true;
}
function sortItems(items, sortMode) {
  const list2 = Array.isArray(items) ? [...items] : [];
  return list2.sort((left, right) => {
    if (sortMode === "newest") {
      return Number(right?.ranking?.freshness_timestamp || 0) - Number(left?.ranking?.freshness_timestamp || 0);
    }
    if (sortMode === "performance") {
      return Number(right?.ranking?.performance_value || 0) - Number(left?.ranking?.performance_value || 0);
    }
    return Number(right?.score || 0) - Number(left?.score || 0);
  });
}
function WorldSuggestionsPanel({ suggestions, notice = null, worldExists = false, busyKey = "", onAddFeatured, onAddSection, onPin, onDismiss, onNotRelevant, onRestore }) {
  const [filters, setFilters] = reactExports.useState({
    category: "",
    type: "",
    section: "",
    sort: "relevance",
    challengeOnly: false,
    communityOnly: false,
    recurringOnly: false,
    analyticsOnly: false,
    showSuppressed: false
  });
  const groups = Array.isArray(suggestions?.groups) ? suggestions.groups : [];
  const pinnedItems = Array.isArray(suggestions?.pinned_items) ? suggestions.pinned_items : [];
  const suppressedItems = Array.isArray(suggestions?.suppressed_items) ? suggestions.suppressed_items : [];
  const visibleGroups = reactExports.useMemo(() => groups.map((group) => ({
    ...group,
    items: sortItems((Array.isArray(group.items) ? group.items : []).filter((item) => matchesFilters(item, filters)), filters.sort)
  })).filter((group) => group.items.length > 0 || filters.category === group.key), [filters, groups]);
  const visiblePinned = reactExports.useMemo(() => sortItems(pinnedItems.filter((item) => matchesFilters(item, filters)), filters.sort), [filters, pinnedItems]);
  const visibleSuppressed = reactExports.useMemo(() => sortItems(suppressedItems.filter((item) => matchesFilters(item, filters)), filters.sort), [filters, suppressedItems]);
  if (!worldExists) {
    return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm leading-6 text-slate-300" }, "Save the world once to unlock editorial suggestions. The suggestion service uses real world metadata, submissions, linked challenge context, and recurring-family signals, so it needs a persisted edition to score against.");
  }
  return /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "World editorial suggestions"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-3xl text-sm leading-6 text-slate-400" }, "Review scored candidate artworks, creators, collections, groups, stories, and challenge standouts without auto-publishing anything into the world.")), suggestions?.generated_at ? /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, "Refreshed ", new Date(suggestions.generated_at).toLocaleString()) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(SummaryPill, { label: "Ready now", value: suggestions?.summary?.available_count || 0, tone: "emerald" }), /* @__PURE__ */ React.createElement(SummaryPill, { label: "Pinned", value: suggestions?.summary?.pinned_count || 0, tone: "amber" }), /* @__PURE__ */ React.createElement(SummaryPill, { label: "Suppressed", value: suggestions?.summary?.suppressed_count || 0 }), /* @__PURE__ */ React.createElement(SummaryPill, { label: "Community signal", value: suggestions?.summary?.community_submission_count || 0, tone: "sky" }), /* @__PURE__ */ React.createElement(SummaryPill, { label: "Analytics cues", value: suggestions?.summary?.analytics_signal_count || 0, tone: "amber" })), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[20px] border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm text-sky-100" }, notice) : null), /* @__PURE__ */ React.createElement(WorldSuggestionFilters, { filters: suggestions?.filters || {}, value: filters, onChange: setFilters }), visiblePinned.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-amber-300/15 bg-amber-400/[0.05] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Pinned for later"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-300" }, "These suggestions stay separate from the public world until you explicitly attach them.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, visiblePinned.length, " pinned")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4" }, visiblePinned.map((item) => /* @__PURE__ */ React.createElement(
    WorldSuggestionCard,
    {
      key: item.key,
      item,
      busyKey: busyKey === item.key ? busyKey : "",
      onAddFeatured,
      onAddSection,
      onPin,
      onDismiss,
      onNotRelevant,
      onRestore
    }
  )))) : null, visibleGroups.length > 0 ? visibleGroups.map((group) => group.key === "challenge" ? /* @__PURE__ */ React.createElement(
    WorldChallengeSuggestionPanel,
    {
      key: group.key,
      group,
      busyKey,
      onAddFeatured,
      onAddSection,
      onPin,
      onDismiss,
      onNotRelevant,
      onRestore
    }
  ) : /* @__PURE__ */ React.createElement("div", { key: group.key, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, group.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, group.description)), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, group.items.length, " ready")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4" }, group.items.length > 0 ? group.items.map((item) => /* @__PURE__ */ React.createElement(
    WorldSuggestionCard,
    {
      key: item.key,
      item,
      busyKey: busyKey === item.key ? busyKey : "",
      onAddFeatured,
      onAddSection,
      onPin,
      onDismiss,
      onNotRelevant,
      onRestore
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, group.empty_label)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm leading-6 text-slate-300" }, "No suggestions match the current filters. Change the filters or save new world metadata to refresh the candidate pool."), filters.showSuppressed ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Suppressed suggestions"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Dismissed and not-relevant items stay out of the active queue until you restore them.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, visibleSuppressed.length, " hidden")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4" }, visibleSuppressed.length > 0 ? visibleSuppressed.map((item) => /* @__PURE__ */ React.createElement(
    WorldSuggestionCard,
    {
      key: item.key,
      item,
      busyKey: busyKey === item.key ? busyKey : "",
      onAddFeatured,
      onAddSection,
      onPin,
      onDismiss,
      onNotRelevant,
      onRestore
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No suppressed suggestions match the current filters."))) : null);
}
function formatDateTime(value) {
  if (!value) return "Not set";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "Not set";
  return new Intl.DateTimeFormat("en", { dateStyle: "medium", timeStyle: "short" }).format(date);
}
function typeLabel(value) {
  const labels = {
    seasonal: "Seasonal",
    event: "Event",
    campaign: "Campaign",
    tribute: "Tribute"
  };
  return labels[value] || value || "Seasonal";
}
function promotionState(world, state) {
  if (!world?.is_active_campaign) {
    return {
      label: "Public page only",
      message: "This world will live at its own URL, but it is not currently marked as an active campaign for stronger discovery surfaces.",
      tone: "slate"
    };
  }
  if (world?.is_homepage_featured && state.label === "Live") {
    return {
      label: "Homepage spotlight ready",
      message: "This campaign is active and flagged for homepage spotlight, so it is eligible for the strongest public placement.",
      tone: "emerald"
    };
  }
  if (state.label === "Live") {
    return {
      label: "Active campaign",
      message: "Campaign activation is enabled and the world is currently live across promotion-aware surfaces.",
      tone: "emerald"
    };
  }
  return {
    label: world?.is_homepage_featured ? "Homepage promotion queued" : "Campaign promotion queued",
    message: world?.is_homepage_featured ? "Homepage spotlight is enabled. Once the campaign goes live, it can occupy the main homepage promotion slot." : "Campaign activation is enabled. Once the world goes live, upload and worlds surfaces can prioritize it.",
    tone: "sky"
  };
}
function workflowState(world) {
  const now = Date.now();
  const publishedAt = world?.published_at ? new Date(world.published_at).getTime() : null;
  const startsAt = world?.starts_at ? new Date(world.starts_at).getTime() : null;
  const endsAt = world?.ends_at ? new Date(world.ends_at).getTime() : null;
  if (world?.status === "archived") {
    return { label: "Archived", message: "This world has ended and is no longer part of the active campaign cycle.", tone: "amber" };
  }
  if (world?.status !== "published") {
    return { label: "Draft", message: "Editors can keep refining this world before it becomes publicly visible.", tone: "slate" };
  }
  if (publishedAt && publishedAt > now) {
    return { label: "Scheduled", message: `This world will publish automatically on ${formatDateTime(world.published_at)}.`, tone: "sky" };
  }
  if (startsAt && startsAt > now) {
    return { label: "Scheduled", message: `This world is published and will go live automatically on ${formatDateTime(world.starts_at)}.`, tone: "sky" };
  }
  if (endsAt && endsAt < now) {
    return { label: "Ended", message: "The campaign window has passed. Archive it or create a new edition to continue the lineage.", tone: "amber" };
  }
  return { label: "Live", message: "This world is currently active on public surfaces.", tone: "emerald" };
}
const tones = {
  slate: "border-white/10 bg-white/[0.04] text-slate-100",
  sky: "border-sky-300/20 bg-sky-400/10 text-sky-100",
  emerald: "border-emerald-300/20 bg-emerald-400/10 text-emerald-100",
  amber: "border-amber-300/20 bg-amber-400/10 text-amber-100"
};
function WorldSummaryCard({ world, themeLabel, relationCount, enabledSectionsCount }) {
  const state = workflowState(world);
  const promotion = promotionState(world, state);
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Campaign summary"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "See the world lifecycle, promotion state, and editorial readiness without parsing the whole form.")), /* @__PURE__ */ React.createElement("div", { className: `rounded-full border px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] ${tones[state.tone]}` }, state.label)), /* @__PURE__ */ React.createElement("div", { className: `mt-4 rounded-[24px] border px-4 py-4 text-sm leading-6 ${tones[state.tone]}` }, state.message), /* @__PURE__ */ React.createElement("div", { className: `mt-3 rounded-[24px] border px-4 py-4 text-sm leading-6 ${tones[promotion.tone]}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] opacity-80" }, "Promotion scope"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold" }, promotion.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1" }, promotion.message)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, typeLabel(world?.type))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Theme preset"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, themeLabel || "No preset")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Campaign window"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, world?.starts_at || world?.ends_at ? `${formatDateTime(world?.starts_at)} to ${formatDateTime(world?.ends_at)}` : "Open ended")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Publish at"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, formatDateTime(world?.published_at))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Promotion window"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, world?.promotion_starts_at || world?.promotion_ends_at ? `${formatDateTime(world?.promotion_starts_at)} to ${formatDateTime(world?.promotion_ends_at)}` : "Uses campaign window")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Activation"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, world?.is_active_campaign ? world?.is_homepage_featured ? "Active + homepage featured" : "Active campaign" : "Standalone public page")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recurrence"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, world?.is_recurring ? `${world?.recurrence_key || "recurring"} ${world?.edition_year || ""}`.trim() : "One-off world")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Editorial setup"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, relationCount, " relations · ", enabledSectionsCount, " enabled sections"))));
}
function Pill({ children }) {
  return /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.06] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, children);
}
function ColorSwatch({ label, value }) {
  if (!value) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 rounded-full border border-white/10 bg-black/20 px-3 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "h-3 w-3 rounded-full border border-white/15", style: { backgroundColor: value } }), /* @__PURE__ */ React.createElement("span", null, label));
}
function WorldThemePresetHelper({ theme, onApply }) {
  if (!theme) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, theme.label, " preset"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Preset suggestions fill the campaign basics fast. You can still override every field manually afterwards.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onApply, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-sky-100" }, "Apply suggestions")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(ColorSwatch, { label: theme.accent_color || "accent", value: theme.accent_color }), /* @__PURE__ */ React.createElement(ColorSwatch, { label: theme.accent_color_secondary || "secondary", value: theme.accent_color_secondary }), theme.background_motif ? /* @__PURE__ */ React.createElement(Pill, null, theme.background_motif) : null, theme.icon_name ? /* @__PURE__ */ React.createElement(Pill, null, theme.icon_name.replace("fa-solid ", "")) : null, theme.suggested_badge_label ? /* @__PURE__ */ React.createElement(Pill, null, theme.suggested_badge_label) : null, theme.suggested_cta_label ? /* @__PURE__ */ React.createElement(Pill, null, theme.suggested_cta_label) : null), Array.isArray(theme.related_tags_json) && theme.related_tags_json.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Suggested related tags"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-slate-400" }, theme.related_tags_json.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full bg-white/[0.04] px-3 py-1.5" }, "#", tag)))) : null);
}
function toDateTimeLocal(value) {
  if (!value) return "";
  return String(value).slice(0, 16);
}
function arraysEqual(left, right) {
  if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
    return false;
  }
  return left.every((entry, index2) => entry === right[index2]);
}
function normalizeRelations(relations) {
  return (Array.isArray(relations) ? relations : []).map((relation, index2) => ({
    ...relation,
    sort_order: index2
  }));
}
function relationForEditor(relation) {
  return {
    ...relation,
    sort_order: Number(relation?.sort_order || 0),
    is_featured: Boolean(relation?.is_featured),
    preview: relation?.preview || null,
    query: relation?.query || relation?.preview?.title || ""
  };
}
function upsertRelation(relations, nextRelation) {
  const items = Array.isArray(relations) ? relations : [];
  const normalized = relationForEditor(nextRelation);
  const existingIndex = items.findIndex((relation) => relation.related_type === normalized.related_type && Number(relation.related_id) === Number(normalized.related_id));
  if (existingIndex === -1) {
    return normalizeRelations([...items, normalized]);
  }
  return normalizeRelations(items.map((relation, index2) => index2 === existingIndex ? relationForEditor({ ...relation, ...normalized }) : relation));
}
function initialSectionVisibility(sectionOptions, worldVisibility) {
  const defaults2 = Object.fromEntries((Array.isArray(sectionOptions) ? sectionOptions : []).map((option) => [option.value, true]));
  return { ...defaults2, ...worldVisibility || {} };
}
function buildDefaultRelation(sectionOptions, relationTypeOptions, existingCount = 0) {
  const firstSection = sectionOptions?.[0];
  return {
    section_key: firstSection?.value || "featured_artworks",
    related_type: firstSection?.relation_types?.[0] || relationTypeOptions?.[0]?.value || "artwork",
    related_id: "",
    context_label: "",
    sort_order: existingCount,
    is_featured: false,
    preview: null,
    query: ""
  };
}
function resolveMediaUrl(path, fallbackUrl = "", filesBaseUrl = "") {
  if (!path) return fallbackUrl || "";
  if (String(path).startsWith("http://") || String(path).startsWith("https://") || String(path).startsWith("/")) {
    return path;
  }
  if (fallbackUrl) {
    return fallbackUrl;
  }
  if (filesBaseUrl) {
    return `${String(filesBaseUrl).replace(/\/$/, "")}/${String(path).replace(/^\//, "")}`;
  }
  return path;
}
function formatCompactNumber(value) {
  const number2 = Number(value || 0);
  if (!Number.isFinite(number2)) {
    return "0";
  }
  return new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }).format(number2);
}
const DEFAULT_ACTION_CONFIRM = {
  open: false,
  url: "",
  title: "Please confirm",
  message: "",
  confirmLabel: "Confirm",
  cancelLabel: "Cancel",
  confirmTone: "danger",
  noteEnabled: false,
  copyModeEnabled: false,
  copyModeOptions: [],
  defaultCopyMode: "with_relations",
  preserveScroll: true
};
function buildPreviewWorld(formData, world, themeOptions, typeOptions, filesBaseUrl) {
  const theme = (themeOptions || []).find((item) => item.value === formData.theme_key) || null;
  const type2 = (typeOptions || []).find((item) => item.value === formData.type);
  return {
    title: formData.title,
    tagline: formData.tagline,
    summary: formData.summary,
    description: formData.description,
    cover_url: resolveMediaUrl(formData.cover_path, world?.cover_path === formData.cover_path ? world?.cover_url || "" : "", filesBaseUrl),
    teaser_image_url: resolveMediaUrl(formData.teaser_image_path, world?.teaser_image_path === formData.teaser_image_path ? world?.teaser_image_url || "" : "", filesBaseUrl),
    type: type2?.label || formData.type || "Seasonal",
    badge_label: formData.badge_label,
    campaign_label: formData.campaign_label,
    badge_description: formData.badge_description,
    cta_label: formData.cta_label,
    accent_color: formData.accent_color || theme?.accent_color || "#38bdf8",
    accent_color_secondary: formData.accent_color_secondary || theme?.accent_color_secondary || "#0f172a",
    background_motif: formData.background_motif || theme?.background_motif || "atmosphere",
    icon_name: formData.icon_name || theme?.icon_name || "fa-solid fa-sparkles",
    is_featured: Boolean(formData.is_featured),
    is_active_campaign: Boolean(formData.is_active_campaign),
    is_homepage_featured: Boolean(formData.is_homepage_featured)
  };
}
const WORLD_EDITOR_TABS = [
  {
    id: "basics",
    label: "Basics",
    icon: "fa-solid fa-pen-ruler",
    description: "Core editorial copy, title, and public story framing for the world."
  },
  {
    id: "structure",
    label: "Structure",
    icon: "fa-solid fa-diagram-project",
    description: "Curated relations and section ordering that shape the public world composition."
  },
  {
    id: "suggestions",
    label: "Suggestions",
    icon: "fa-solid fa-wand-magic-sparkles",
    description: "Editorial assist candidates scored from theme, submissions, challenge context, and recurring-world signals."
  },
  {
    id: "community",
    label: "Community",
    icon: "fa-solid fa-people-group",
    description: "Submission settings and the moderation queue for creator participation."
  },
  {
    id: "publishing",
    label: "Publishing",
    icon: "fa-solid fa-calendar-check",
    description: "Status, schedule, recurrence, and edition management controls."
  },
  {
    id: "presentation",
    label: "Presentation",
    icon: "fa-solid fa-swatchbook",
    description: "Theme preset, visual identity, media assets, CTA, and badge surface copy."
  },
  {
    id: "recap",
    label: "Recap",
    icon: "fa-solid fa-stars",
    description: "Shape the archive-facing recap with editorial framing, linked recap story, and publish-ready summary state."
  },
  {
    id: "seo",
    label: "SEO",
    icon: "fa-solid fa-magnifying-glass-chart",
    description: "Search and social metadata that ships with the world page."
  },
  {
    id: "analytics",
    label: "Analytics",
    icon: "fa-solid fa-chart-column",
    description: "Traffic, source surfaces, engagement, participation, challenge energy, and recurring-edition comparison."
  }
];
const WORLD_EDITOR_TAB_FIELDS = {
  basics: ["title", "slug", "tagline", "summary", "description"],
  structure: ["relations", "section_order_json", "section_visibility_json", "linked_challenge_id", "show_linked_challenge_section", "show_linked_challenge_entries", "show_linked_challenge_winners", "show_linked_challenge_finalists", "auto_grant_challenge_world_rewards", "challenge_teaser_override", "hidden_linked_challenge_artwork_ids_json"],
  suggestions: [],
  community: ["accepts_submissions", "participation_mode", "submission_starts_at", "submission_ends_at", "submission_note_enabled", "community_section_enabled", "allow_readd_after_removal", "submission_guidelines"],
  publishing: ["type", "status", "published_at", "starts_at", "ends_at", "promotion_starts_at", "promotion_ends_at", "is_featured", "is_active_campaign", "is_homepage_featured", "campaign_priority", "is_recurring", "recurrence_key", "recurrence_rule", "edition_year"],
  presentation: ["theme_key", "accent_color", "accent_color_secondary", "background_motif", "icon_name", "cover_path", "teaser_image_path", "og_image_path", "teaser_title", "teaser_summary", "cta_label", "cta_url", "badge_label", "campaign_label", "badge_description", "badge_url", "related_tags_json"],
  recap: ["recap_status", "recap_title", "recap_summary", "recap_intro", "recap_editor_note", "recap_cover_path", "recap_article_id"],
  seo: ["seo_title", "seo_description"],
  analytics: []
};
const PARTICIPATION_MODE_OPTIONS = [
  { value: "manual_approval", label: "Manual approval", description: "Creators can add artworks, but each one starts pending until a moderator approves it." },
  { value: "auto_add", label: "Auto add", description: "Eligible artworks go live in the community section immediately." },
  { value: "closed", label: "Closed", description: "Hide this world from creator participation surfaces." }
];
function errorBelongsToTab(tabId, errorKey) {
  const prefixes = WORLD_EDITOR_TAB_FIELDS[tabId] || [];
  return prefixes.some((prefix) => errorKey === prefix || errorKey.startsWith(`${prefix}.`) || errorKey.startsWith(`${prefix}[`));
}
function WorldEditorSection({ title, description, actions = null, children }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, description) : null), actions), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children));
}
function LinkedChallengeCard({ challenge, onChange, onClear }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, challenge ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-16 w-16 shrink-0 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, challenge.image ? /* @__PURE__ */ React.createElement("img", { src: challenge.image, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, challenge.title), challenge.entity_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, challenge.entity_label) : null), challenge.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, challenge.subtitle) : null, challenge.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-400" }, challenge.description) : null, Array.isArray(challenge.meta) && challenge.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs text-slate-500" }, challenge.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry }, entry))) : null)), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onChange, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Change"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClear, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-slate-200" }, "Clear"))) : /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "No primary challenge linked"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Link one group challenge when this world should automatically surface challenge status, entries, and winner context.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onChange, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Select challenge")));
}
function WorldEditorActionPanel({ formProcessing, isEditing, publishUrl, publishRecapUrl, canPublishRecap, recapStatusLabel, archiveUrl, publicUrl }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Campaign actions"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Keep save, publish, archive, and public-page actions reachable while reviewing the campaign summary.")), /* @__PURE__ */ React.createElement("div", { className: "hidden rounded-full border border-white/10 bg-black/20 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400 xl:inline-flex" }, "Sticky")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: formProcessing, className: "inline-flex items-center justify-center gap-2 rounded-2xl bg-white px-5 py-3 text-sm font-semibold text-slate-950 transition hover:bg-sky-100 disabled:opacity-60" }, formProcessing ? "Saving…" : isEditing ? "Save world" : "Create world"), publishUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(publishUrl), className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-5 py-3 text-sm font-semibold text-emerald-100" }, "Publish") : null, publishRecapUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(publishRecapUrl), disabled: !canPublishRecap, className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 disabled:cursor-not-allowed disabled:opacity-50" }, recapStatusLabel === "Published recap" ? "Refresh recap snapshot" : "Publish recap") : null, archiveUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(archiveUrl), className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 py-3 text-sm font-semibold text-amber-100" }, "Archive") : null, publicUrl ? /* @__PURE__ */ React.createElement("a", { href: publicUrl, className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Public page") : null));
}
function LinkedChallengeEntryVisibilityManager({ challenge, hiddenIds, onToggle, error = "" }) {
  const items = Array.isArray(challenge?.entry_preview_items) ? challenge.entry_preview_items : [];
  if (!challenge || items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-2 md:flex-row md:items-end md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Entry visibility overrides"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Hide specific linked challenge entries from the derived world feed when moderation or editorial context requires it.")), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, hiddenIds.length, " hidden")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => {
    const hidden = hiddenIds.includes(item.id);
    const statusLabel2 = item.status === "winner" ? "Winner" : item.status === "finalist" ? "Finalist" : "Entry";
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: item.id,
        type: "button",
        onClick: () => onToggle(item.id),
        className: `flex items-center gap-3 rounded-[20px] border px-3 py-3 text-left transition ${hidden ? "border-amber-300/25 bg-amber-400/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.05]"}`
      },
      /* @__PURE__ */ React.createElement("div", { className: "h-14 w-14 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-slate-950" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" }))),
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] uppercase tracking-[0.16em] text-slate-500" }, statusLabel2), /* @__PURE__ */ React.createElement("div", { className: `mt-2 text-xs font-semibold ${hidden ? "text-amber-100" : "text-emerald-100"}` }, hidden ? "Hidden from world entries" : "Visible on world page"))
    );
  })), error ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-rose-300" }, error) : null);
}
function StudioWorldEditor() {
  const { props } = X$1();
  const world = props.world || null;
  const filesBaseUrl = props.mediaSupport?.files_base_url || "";
  const sectionOptions = props.sectionOptions || [];
  const relationTypeOptions = props.relationTypeOptions || [];
  const themeOptions = props.themeOptions || [];
  const typeOptions = props.typeOptions || [];
  const duplicateActions = props.duplicateActions || null;
  const suggestions = props.suggestions || null;
  const reviewQueue = world?.submission_review_queue || { counts: { pending: 0, live: 0, removed: 0, blocked: 0, featured: 0 }, items: [] };
  const initialRelations = Array.isArray(world?.relations) ? normalizeRelations(world.relations.map((relation) => relationForEditor({
    section_key: relation.section_key || sectionOptions?.[0]?.value || "featured_artworks",
    related_type: relation.related_type || relationTypeOptions?.[0]?.value || "artwork",
    related_id: relation.related_id || "",
    context_label: relation.context_label || "",
    sort_order: relation.sort_order || 0,
    is_featured: Boolean(relation.is_featured),
    preview: relation.preview || null
  }))) : [];
  const form = G$1({
    title: world?.title || "",
    slug: world?.slug || "",
    tagline: world?.tagline || "",
    summary: world?.summary || "",
    teaser_title: world?.teaser_title || "",
    teaser_summary: world?.teaser_summary || "",
    description: world?.description || "",
    cover_path: world?.cover_path || "",
    teaser_image_path: world?.teaser_image_path || "",
    theme_key: world?.theme_key ?? "",
    accent_color: world?.accent_color || "",
    accent_color_secondary: world?.accent_color_secondary || "",
    background_motif: world?.background_motif || "",
    icon_name: world?.icon_name || "",
    status: world?.status || "draft",
    type: world?.type || "seasonal",
    published_at: toDateTimeLocal(world?.published_at),
    starts_at: toDateTimeLocal(world?.starts_at),
    ends_at: toDateTimeLocal(world?.ends_at),
    promotion_starts_at: toDateTimeLocal(world?.promotion_starts_at),
    promotion_ends_at: toDateTimeLocal(world?.promotion_ends_at),
    accepts_submissions: Boolean(world?.accepts_submissions),
    participation_mode: world?.participation_mode || (world?.accepts_submissions ? "manual_approval" : "closed"),
    submission_starts_at: toDateTimeLocal(world?.submission_starts_at),
    submission_ends_at: toDateTimeLocal(world?.submission_ends_at),
    submission_note_enabled: world?.submission_note_enabled !== false,
    community_section_enabled: world?.community_section_enabled !== false,
    allow_readd_after_removal: world?.allow_readd_after_removal !== false,
    is_featured: Boolean(world?.is_featured),
    is_active_campaign: Boolean(world?.is_active_campaign),
    is_homepage_featured: Boolean(world?.is_homepage_featured),
    campaign_priority: world?.campaign_priority ?? "",
    is_recurring: Boolean(world?.is_recurring),
    recurrence_key: world?.recurrence_key || "",
    recurrence_rule: world?.recurrence_rule || "",
    edition_year: world?.edition_year || "",
    cta_label: world?.cta_label || "",
    cta_url: world?.cta_url || "",
    badge_label: world?.badge_label || "",
    campaign_label: world?.campaign_label || "",
    badge_description: world?.badge_description || "",
    submission_guidelines: world?.submission_guidelines || "",
    badge_url: world?.badge_url || "",
    seo_title: world?.seo_title || "",
    seo_description: world?.seo_description || "",
    og_image_path: world?.og_image_path || "",
    recap_status: world?.recap_status || "draft",
    recap_title: world?.recap_title || "",
    recap_summary: world?.recap_summary || "",
    recap_intro: world?.recap_intro || "",
    recap_editor_note: world?.recap_editor_note || "",
    recap_cover_path: world?.recap_cover_path || "",
    recap_article_id: world?.recap_article_id || "",
    linked_challenge_id: world?.linked_challenge_id || "",
    show_linked_challenge_section: world?.show_linked_challenge_section !== false,
    show_linked_challenge_entries: world?.show_linked_challenge_entries !== false,
    show_linked_challenge_winners: world?.show_linked_challenge_winners !== false,
    show_linked_challenge_finalists: world?.show_linked_challenge_finalists !== false,
    auto_grant_challenge_world_rewards: world?.auto_grant_challenge_world_rewards !== false,
    challenge_teaser_override: world?.challenge_teaser_override || "",
    hidden_linked_challenge_artwork_ids_json: Array.isArray(world?.hidden_linked_challenge_artwork_ids_json) ? world.hidden_linked_challenge_artwork_ids_json : [],
    related_tags_json: Array.isArray(world?.related_tags_json) ? world.related_tags_json : [],
    section_order_json: Array.isArray(world?.section_order_json) && world.section_order_json.length > 0 ? world.section_order_json : sectionOptions.map((option) => option.value),
    section_visibility_json: initialSectionVisibility(sectionOptions, world?.section_visibility_json),
    relations: initialRelations
  });
  const [pickerState, setPickerState] = reactExports.useState({ open: false, index: null });
  const [linkedChallengePickerOpen, setLinkedChallengePickerOpen] = reactExports.useState(false);
  const [linkedChallengePreview, setLinkedChallengePreview] = reactExports.useState(world?.linked_challenge || null);
  const [recapArticlePickerOpen, setRecapArticlePickerOpen] = reactExports.useState(false);
  const [recapArticlePreview, setRecapArticlePreview] = reactExports.useState(world?.recap_article || null);
  const [activeTab, setActiveTab] = reactExports.useState("basics");
  const [temporaryMediaPaths, setTemporaryMediaPaths] = reactExports.useState({
    cover: "",
    teaser: "",
    og: "",
    recap: ""
  });
  const themeMap = reactExports.useMemo(() => Object.fromEntries(themeOptions.map((option) => [option.value, option])), [themeOptions]);
  const sectionMap = reactExports.useMemo(() => Object.fromEntries(sectionOptions.map((option) => [option.value, option])), [sectionOptions]);
  const tagString = reactExports.useMemo(() => Array.isArray(form.data.related_tags_json) ? form.data.related_tags_json.join(", ") : "", [form.data.related_tags_json]);
  const linkedChallengeEntryPreviewItems = reactExports.useMemo(() => Array.isArray(linkedChallengePreview?.entry_preview_items) ? linkedChallengePreview.entry_preview_items : [], [linkedChallengePreview]);
  const selectedTheme = form.data.theme_key ? themeMap[form.data.theme_key] : null;
  const previewWorld = reactExports.useMemo(() => buildPreviewWorld(form.data, world, themeOptions, typeOptions, filesBaseUrl), [filesBaseUrl, form.data, world, themeOptions, typeOptions]);
  const recapCoverPreviewUrl = reactExports.useMemo(() => resolveMediaUrl(form.data.recap_cover_path, world?.recap_cover_path === form.data.recap_cover_path ? world?.recap_cover_url || "" : "", filesBaseUrl), [filesBaseUrl, form.data.recap_cover_path, world?.recap_cover_path, world?.recap_cover_url]);
  const relationCounts = reactExports.useMemo(() => form.data.relations.reduce((counts, relation) => ({ ...counts, [relation.section_key]: (counts[relation.section_key] || 0) + 1 }), {}), [form.data.relations]);
  const enabledSectionsCount = reactExports.useMemo(() => Object.values(form.data.section_visibility_json || {}).filter(Boolean).length, [form.data.section_visibility_json]);
  const defaultAnalyticsRange = world?.analytics?.default_range || "30d";
  const analyticsSummary = world?.analytics?.ranges?.[defaultAnalyticsRange]?.summary || null;
  const previewSections = reactExports.useMemo(() => {
    const visibleKeys = (form.data.section_order_json || []).filter((key) => form.data.section_visibility_json?.[key] !== false);
    return visibleKeys.map((key) => ({
      key,
      label: sectionMap[key]?.label || key,
      count: form.data.relations.filter((relation) => relation.section_key === key).length,
      items: form.data.relations.filter((relation) => relation.section_key === key).map((relation) => relation.preview).filter(Boolean).slice(0, 3)
    }));
  }, [form.data.section_order_json, form.data.section_visibility_json, form.data.relations, sectionMap]);
  const recapStatsSnapshot = world?.recap_stats_snapshot || null;
  const recapStatsSummary = recapStatsSnapshot?.summary || null;
  const canPublishRecap = Boolean(world && (world.status === "archived" || world.ends_at && new Date(world.ends_at) < /* @__PURE__ */ new Date()));
  const errorEntries = Object.entries(form.errors || {});
  const tabErrorCounts = reactExports.useMemo(() => WORLD_EDITOR_TABS.reduce((counts, tab2) => ({
    ...counts,
    [tab2.id]: errorEntries.filter(([key]) => errorBelongsToTab(tab2.id, key)).length
  }), {}), [errorEntries]);
  const editorTabs = reactExports.useMemo(() => WORLD_EDITOR_TABS.map((tab2) => {
    let meta = "";
    switch (tab2.id) {
      case "basics":
        meta = form.data.title ? "Named and writable" : "Needs title";
        break;
      case "structure":
        meta = form.data.relations.length > 0 ? `${form.data.relations.length} relation${form.data.relations.length === 1 ? "" : "s"}` : "No relations yet";
        break;
      case "suggestions":
        meta = !world ? "Save to unlock" : `${suggestions?.summary?.available_count || 0} ready · ${suggestions?.summary?.pinned_count || 0} pinned`;
        break;
      case "community":
        meta = form.data.participation_mode === "closed" ? "Closed to creators" : form.data.participation_mode === "auto_add" ? `${reviewQueue?.counts?.live || 0} live now` : `${reviewQueue?.counts?.pending || 0} pending review`;
        break;
      case "publishing":
        meta = form.data.is_recurring ? "Recurring workflow" : "Single edition";
        break;
      case "presentation":
        meta = selectedTheme?.label || "Custom identity";
        break;
      case "recap":
        meta = form.data.recap_title || recapArticlePreview?.title ? `${form.data.recap_status === "published" ? "Published" : "Draft"} recap` : "Optional archive layer";
        break;
      case "seo":
        meta = form.data.seo_title || form.data.seo_description ? "Configured" : "Optional metadata";
        break;
      case "analytics":
        meta = analyticsSummary?.views > 0 ? `${analyticsSummary.views} tracked views` : world ? "Ready for measurement" : "Available after create";
        break;
      default:
        meta = "";
    }
    return {
      ...tab2,
      meta,
      errorCount: tabErrorCounts[tab2.id] || 0
    };
  }), [analyticsSummary?.views, form.data.participation_mode, form.data.recap_status, form.data.recap_title, form.data.title, form.data.relations.length, form.data.is_recurring, form.data.seo_description, form.data.seo_title, recapArticlePreview?.title, reviewQueue?.counts?.live, reviewQueue?.counts?.pending, selectedTheme?.label, suggestions?.summary?.available_count, suggestions?.summary?.pinned_count, tabErrorCounts, world]);
  const firstErrorTab = reactExports.useMemo(() => editorTabs.find((tab2) => tab2.errorCount > 0) || null, [editorTabs]);
  const currentTab = editorTabs.find((tab2) => tab2.id === activeTab) || editorTabs[0];
  const editingRelation = pickerState.index === null ? buildDefaultRelation(sectionOptions, relationTypeOptions, form.data.relations.length) : form.data.relations[pickerState.index];
  const [actionConfirm, setActionConfirm] = reactExports.useState(DEFAULT_ACTION_CONFIRM);
  const [actionReviewNote, setActionReviewNote] = reactExports.useState("");
  const [actionCopyMode, setActionCopyMode] = reactExports.useState(DEFAULT_ACTION_CONFIRM.defaultCopyMode);
  const [actionBusy, setActionBusy] = reactExports.useState(false);
  const [suggestionBusyKey, setSuggestionBusyKey] = reactExports.useState("");
  const [suggestionNotice, setSuggestionNotice] = reactExports.useState("");
  reactExports.useEffect(() => {
    if (firstErrorTab && firstErrorTab.id !== activeTab) {
      setActiveTab(firstErrorTab.id);
    }
  }, [activeTab, firstErrorTab]);
  const searchEntities = async (type2, query) => {
    const url = new URL(props.entitySearchUrl, window.location.origin);
    url.searchParams.set("type", type2);
    url.searchParams.set("q", query);
    const response = await fetch(url.toString(), {
      headers: { Accept: "application/json" },
      credentials: "same-origin"
    });
    if (!response.ok) {
      return [];
    }
    const payload = await response.json();
    return Array.isArray(payload.items) ? payload.items : [];
  };
  const submit = (event) => {
    event.preventDefault();
    const options = {
      onSuccess: () => {
        setTemporaryMediaPaths({ cover: "", teaser: "", og: "", recap: "" });
      }
    };
    if (props.updateUrl) {
      form.patch(props.updateUrl, options);
      return;
    }
    form.post(props.storeUrl, options);
  };
  const deleteTemporaryMediaPath = async (path) => {
    if (!props.mediaSupport?.delete_url || !path) return;
    await fetch(props.mediaSupport.delete_url, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
        Accept: "application/json"
      },
      credentials: "same-origin",
      body: JSON.stringify({
        path,
        world_id: world?.id || void 0
      })
    });
  };
  const applyCoverToOg = async () => {
    if (!form.data.cover_path) return;
    const currentOgPath = form.data.og_image_path;
    const shouldDeleteTemporaryOg = temporaryMediaPaths.og !== "" && temporaryMediaPaths.og === currentOgPath && currentOgPath !== form.data.cover_path;
    if (shouldDeleteTemporaryOg) {
      try {
        await deleteTemporaryMediaPath(currentOgPath);
      } catch {
      }
    }
    form.setData("og_image_path", form.data.cover_path);
    setTemporaryMediaPaths((current) => ({ ...current, og: "" }));
  };
  const handleThemeChange = (nextThemeKey, force = false) => {
    const nextTheme = themeMap[nextThemeKey];
    const previousTheme = themeMap[form.data.theme_key];
    const currentTags = Array.isArray(form.data.related_tags_json) ? form.data.related_tags_json : [];
    const shouldReplace = (currentValue, nextValue, previousValue) => {
      if (!nextValue) return currentValue;
      if (force || !currentValue || currentValue === previousValue) return nextValue;
      return currentValue;
    };
    const nextData = {
      ...form.data,
      theme_key: String(nextThemeKey || ""),
      accent_color: shouldReplace(form.data.accent_color, nextTheme?.accent_color || "", previousTheme?.accent_color || ""),
      accent_color_secondary: shouldReplace(form.data.accent_color_secondary, nextTheme?.accent_color_secondary || "", previousTheme?.accent_color_secondary || ""),
      background_motif: shouldReplace(form.data.background_motif, nextTheme?.background_motif || "", previousTheme?.background_motif || ""),
      icon_name: shouldReplace(form.data.icon_name, nextTheme?.icon_name || "", previousTheme?.icon_name || ""),
      badge_label: shouldReplace(form.data.badge_label, nextTheme?.suggested_badge_label || "", previousTheme?.suggested_badge_label || ""),
      cta_label: shouldReplace(form.data.cta_label, nextTheme?.suggested_cta_label || "", previousTheme?.suggested_cta_label || ""),
      related_tags_json: force || currentTags.length === 0 || arraysEqual(currentTags, previousTheme?.related_tags_json || []) ? [...nextTheme?.related_tags_json || []] : currentTags
    };
    form.setData(nextData);
  };
  const openRelationPicker = (index2 = null) => setPickerState({ open: true, index: index2 });
  const closeRelationPicker = () => setPickerState({ open: false, index: null });
  const saveRelation = (relation) => {
    const nextRelations = pickerState.index === null ? normalizeRelations([...form.data.relations, relation]) : normalizeRelations(form.data.relations.map((item, index2) => index2 === pickerState.index ? relation : item));
    form.setData("relations", nextRelations);
    closeRelationPicker();
  };
  const removeRelation = (index2) => form.setData("relations", normalizeRelations(form.data.relations.filter((_2, relationIndex) => relationIndex !== index2)));
  const moveRelation = (index2, delta) => {
    const nextIndex = index2 + delta;
    if (nextIndex < 0 || nextIndex >= form.data.relations.length) return;
    const next = [...form.data.relations];
    const [entry] = next.splice(index2, 1);
    next.splice(nextIndex, 0, entry);
    form.setData("relations", normalizeRelations(next));
  };
  const updateSectionControls = (nextOrder, nextVisibility) => {
    form.setData({
      ...form.data,
      section_order_json: nextOrder,
      section_visibility_json: nextVisibility
    });
  };
  const closeActionConfirm = () => {
    if (actionBusy) return;
    setActionConfirm(DEFAULT_ACTION_CONFIRM);
    setActionReviewNote("");
    setActionCopyMode(DEFAULT_ACTION_CONFIRM.defaultCopyMode);
  };
  const saveLinkedChallenge = (challenge) => {
    setLinkedChallengePreview(challenge);
    form.setData({
      ...form.data,
      linked_challenge_id: challenge?.id || "",
      hidden_linked_challenge_artwork_ids_json: []
    });
    setLinkedChallengePickerOpen(false);
  };
  const saveRecapArticle = (article) => {
    setRecapArticlePreview(article);
    form.setData({
      ...form.data,
      recap_article_id: article?.id || ""
    });
    setRecapArticlePickerOpen(false);
  };
  const clearRecapArticle = () => {
    setRecapArticlePreview(null);
    form.setData("recap_article_id", "");
  };
  const clearLinkedChallenge = () => {
    setLinkedChallengePreview(null);
    form.setData({
      ...form.data,
      linked_challenge_id: "",
      challenge_teaser_override: "",
      hidden_linked_challenge_artwork_ids_json: []
    });
  };
  const toggleHiddenLinkedChallengeEntry = (artworkId) => {
    const currentIds = Array.isArray(form.data.hidden_linked_challenge_artwork_ids_json) ? form.data.hidden_linked_challenge_artwork_ids_json : [];
    const nextIds = currentIds.includes(artworkId) ? currentIds.filter((id) => id !== artworkId) : [...currentIds, artworkId];
    form.setData("hidden_linked_challenge_artwork_ids_json", nextIds);
  };
  const openActionConfirm = (config) => {
    if (!config?.url) return;
    setActionReviewNote("");
    setActionCopyMode(config.defaultCopyMode || DEFAULT_ACTION_CONFIRM.defaultCopyMode);
    setActionConfirm({
      ...DEFAULT_ACTION_CONFIRM,
      ...config,
      open: true
    });
  };
  const confirmAction = () => {
    if (!actionConfirm.url || actionBusy) return;
    const payload = {
      ...actionConfirm.noteEnabled ? { review_note: actionReviewNote } : {},
      ...actionConfirm.copyModeEnabled ? { copy_mode: actionCopyMode } : {}
    };
    setActionBusy(true);
    At.post(actionConfirm.url, payload, {
      preserveScroll: actionConfirm.preserveScroll,
      onSuccess: () => {
        setActionConfirm(DEFAULT_ACTION_CONFIRM);
        setActionReviewNote("");
      },
      onFinish: () => {
        setActionBusy(false);
      }
    });
  };
  const runDuplicateAction = (url, promptText, copyModeOptions = []) => {
    openActionConfirm({
      url,
      title: "Duplicate world?",
      message: promptText,
      confirmLabel: "Continue",
      cancelLabel: "Cancel",
      confirmTone: "accent",
      copyModeEnabled: copyModeOptions.length > 0,
      copyModeOptions,
      defaultCopyMode: copyModeOptions.find((option) => option.value === "with_relations")?.value || copyModeOptions[0]?.value || "with_relations",
      preserveScroll: false
    });
  };
  const runSubmissionAction = (url, promptText, options = {}) => {
    const {
      title = "Confirm submission action",
      confirmLabel = "Confirm",
      cancelLabel = "Cancel",
      confirmTone = "accent",
      noteEnabled = false
    } = options;
    openActionConfirm({
      url,
      title,
      message: promptText,
      confirmLabel,
      cancelLabel,
      confirmTone,
      noteEnabled,
      preserveScroll: true
    });
  };
  const postSuggestionAction = async (url, payload) => {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || "",
        Accept: "application/json"
      },
      credentials: "same-origin",
      body: JSON.stringify(payload)
    });
    const data = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(data?.message || "Suggestion action failed.");
    }
    return data;
  };
  const refreshSuggestions = () => {
    if (!world) return;
    At.reload({
      only: ["suggestions"],
      preserveScroll: true,
      preserveState: true
    });
  };
  const handleSuggestionAction = async (item, action, payload = {}, afterSuccess = null) => {
    const url = props.suggestionActions?.[action];
    if (!url || !item) return;
    setSuggestionBusyKey(item.key);
    try {
      const response = await postSuggestionAction(url, {
        related_type: item.entity_type,
        related_id: item.entity_id,
        ...payload
      });
      if (typeof afterSuccess === "function") {
        afterSuccess(response);
      }
      setSuggestionNotice(response?.message || "Suggestion updated.");
      refreshSuggestions();
    } catch (error) {
      setSuggestionNotice(error?.message || "Suggestion action failed.");
    } finally {
      setSuggestionBusyKey("");
    }
  };
  const addSuggestionRelation = (item, sectionKey, isFeatured) => handleSuggestionAction(item, "add", {
    section_key: sectionKey,
    is_featured: isFeatured
  }, (response) => {
    if (response?.relation) {
      form.setData("relations", upsertRelation(form.data.relations, response.relation));
    }
  });
  const pinSuggestion = (item, sectionKey) => handleSuggestionAction(item, "pin", {
    section_key: sectionKey
  });
  const dismissSuggestion = (item) => handleSuggestionAction(item, "dismiss");
  const markSuggestionNotRelevant = (item) => handleSuggestionAction(item, "notRelevant");
  const restoreSuggestion = (item) => handleSuggestionAction(item, "restore");
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1.04fr)_minmax(360px,0.96fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "space-y-6" }, errorEntries.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-rose-300/20 bg-rose-400/10 p-5 text-sm text-rose-100" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, "Fix the highlighted editor issues before publishing."), firstErrorTab ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-rose-100/90" }, "The first blocked section is ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold" }, firstErrorTab.label), ".") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-1 text-sm leading-6" }, errorEntries.slice(0, 8).map(([key, message]) => /* @__PURE__ */ React.createElement("div", { key }, message)))) : null, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 md:grid-cols-2 2xl:grid-cols-3" }, editorTabs.map((tab2) => {
    const isActive = activeTab === tab2.id;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: tab2.id,
        type: "button",
        onClick: () => setActiveTab(tab2.id),
        role: "tab",
        "aria-selected": isActive,
        className: [
          "rounded-[22px] border px-4 py-3 text-left transition",
          isActive ? "border-sky-300/30 bg-sky-400/12 text-white shadow-[0_16px_40px_rgba(14,165,233,0.12)]" : "border-white/10 bg-black/20 text-slate-300 hover:border-white/15 hover:bg-white/[0.05]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: `${tab2.icon} text-[11px] ${isActive ? "text-sky-100" : "text-slate-500"}`, "aria-hidden": "true" }), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold" }, tab2.label)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, tab2.meta)), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 items-center gap-2" }, tab2.errorCount > 0 ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/12 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-rose-100" }, tab2.errorCount) : null, isActive ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/25 bg-sky-400/12 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, "Active") : null))
    );
  }))), activeTab === "basics" ? /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "World basics", description: "Shape the title, summary, and long-form story before you worry about composition or scheduling." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Use a campaign-ready title that will still read clearly in homepage spotlight, preview, and archive contexts.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.data.slug, onChange: (event) => form.setData("slug", event.target.value), placeholder: "optional-manual-slug", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Keep this short and durable. It becomes the public world URL and should survive future editorial updates."))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Tagline"), /* @__PURE__ */ React.createElement("input", { value: form.data.tagline, onChange: (event) => form.setData("tagline", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Summary"), /* @__PURE__ */ React.createElement("input", { value: form.data.summary, onChange: (event) => form.setData("summary", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Description"), /* @__PURE__ */ React.createElement(
    RichTextEditor,
    {
      content: form.data.description,
      onChange: (nextValue) => form.setData("description", nextValue),
      placeholder: "Build the world story with rich formatting, links, emoji, and campaign callouts.",
      error: form.errors.description,
      minHeight: 18,
      autofocus: false
    }
  )))) : null, activeTab === "structure" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(
    WorldEditorSection,
    {
      title: "Curated relations",
      description: "Attach explicit artworks, collections, creators, groups, news, challenges, events, releases, and cards as editorial composition blocks.",
      actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => openRelationPicker(null), className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Add relation")
    },
    /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, form.data.relations.length > 0 ? form.data.relations.map((relation, index2) => /* @__PURE__ */ React.createElement(
      WorldRelationCard,
      {
        key: `${relation.related_type}-${relation.related_id || index2}-${index2}`,
        relation,
        index: index2,
        total: form.data.relations.length,
        sectionLabel: sectionMap[relation.section_key]?.label || relation.section_key,
        onEdit: () => openRelationPicker(index2),
        onRemove: () => removeRelation(index2),
        onMove: moveRelation
      }
    )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No curated relations attached yet. Add relations to turn the world into a real campaign hub instead of a static shell."), activeTab === "suggestions" ? /* @__PURE__ */ React.createElement(
      WorldSuggestionsPanel,
      {
        suggestions,
        notice: suggestionNotice,
        worldExists: Boolean(world),
        busyKey: suggestionBusyKey,
        onAddFeatured: (item, sectionKey) => addSuggestionRelation(item, sectionKey, true),
        onAddSection: (item, sectionKey, isFeatured = false) => addSuggestionRelation(item, sectionKey, isFeatured),
        onPin: pinSuggestion,
        onDismiss: dismissSuggestion,
        onNotRelevant: markSuggestionNotRelevant,
        onRestore: restoreSuggestion
      }
    ) : null)
  ), /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Linked challenge automation", description: "Use one primary challenge to drive a dedicated challenge panel, entry rail, winner carry-over, and campaign freshness across public surfaces." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement(LinkedChallengeCard, { challenge: linkedChallengePreview, onChange: () => setLinkedChallengePickerOpen(true), onClear: clearLinkedChallenge }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.show_linked_challenge_section, onChange: (event) => form.setData("show_linked_challenge_section", event.target.checked), label: "Show challenge panel on the world page", size: 20, variant: "accent" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.show_linked_challenge_entries, onChange: (event) => form.setData("show_linked_challenge_entries", event.target.checked), label: "Show linked challenge entries rail", size: 20, variant: "accent" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.show_linked_challenge_winners, onChange: (event) => form.setData("show_linked_challenge_winners", event.target.checked), label: "Show linked challenge winner section", size: 20, variant: "accent" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.auto_grant_challenge_world_rewards, onChange: (event) => form.setData("auto_grant_challenge_world_rewards", event.target.checked), label: "Auto-grant winner and finalist rewards from the linked challenge", size: 20, variant: "accent" }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.show_linked_challenge_finalists, onChange: (event) => form.setData("show_linked_challenge_finalists", event.target.checked), label: "Show linked challenge finalists when they exist", size: 20, variant: "accent" }), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Finalists now come from structured challenge outcomes, so worlds can surface them automatically without waiting for manual recap edits.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Challenge teaser override"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.challenge_teaser_override, onChange: (event) => form.setData("challenge_teaser_override", event.target.value), rows: 4, placeholder: "Optional world-specific framing for the linked challenge panel.", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Leave this blank to reuse the challenge summary automatically. Use it when the world needs a more editorial campaign voice than the raw challenge copy.")), /* @__PURE__ */ React.createElement(
    LinkedChallengeEntryVisibilityManager,
    {
      challenge: linkedChallengePreview,
      hiddenIds: Array.isArray(form.data.hidden_linked_challenge_artwork_ids_json) ? form.data.hidden_linked_challenge_artwork_ids_json : [],
      onToggle: toggleHiddenLinkedChallengeEntry,
      error: form.errors.hidden_linked_challenge_artwork_ids_json
    }
  ), linkedChallengePreview && linkedChallengeEntryPreviewItems.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-400" }, "No visible challenge entries are available yet for per-entry overrides.") : null)), /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Sections", description: "Reorder and hide public sections without losing their underlying data or editorial intent." }, /* @__PURE__ */ React.createElement(
    WorldSectionToggleList,
    {
      sectionOptions,
      order: form.data.section_order_json,
      visibility: form.data.section_visibility_json,
      relationCounts,
      onChange: updateSectionControls
    }
  ))) : null, activeTab === "suggestions" ? /* @__PURE__ */ React.createElement(
    WorldSuggestionsPanel,
    {
      suggestions,
      notice: suggestionNotice,
      worldExists: Boolean(world),
      busyKey: suggestionBusyKey,
      onAddFeatured: (item, sectionKey) => addSuggestionRelation(item, sectionKey, true),
      onAddSection: (item, sectionKey, isFeatured = false) => addSuggestionRelation(item, sectionKey, isFeatured),
      onPin: pinSuggestion,
      onDismiss: dismissSuggestion,
      onNotRelevant: markSuggestionNotRelevant,
      onRestore: restoreSuggestion
    }
  ) : null, activeTab === "publishing" ? /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Publishing and timing", description: "Control the public state, campaign dates, and recurrence lifecycle without mixing in community settings." }, /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Type", value: form.data.type || null, onChange: (nextValue) => form.setData("type", String(nextValue || "")), options: typeOptions, searchable: false, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(NovaSelect, { label: "Workflow status", value: form.data.status || null, onChange: (nextValue) => form.setData("status", String(nextValue || "")), options: props.statusOptions || [], searchable: false, className: "bg-black/20" })), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Publish at", value: form.data.published_at, onChange: (nextValue) => form.setData("published_at", nextValue), placeholder: "Pick an automatic publish date", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement("div", { className: "-mt-1 text-xs leading-5 text-slate-500" }, "A future publish date keeps the world in the editorial pipeline until the release moment arrives automatically."), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Starts at", value: form.data.starts_at, onChange: (nextValue) => form.setData("starts_at", nextValue), placeholder: "Pick the campaign start", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Ends at", value: form.data.ends_at, onChange: (nextValue) => form.setData("ends_at", nextValue), placeholder: "Pick the campaign end", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "-mt-1 text-xs leading-5 text-slate-500" }, "The campaign window drives whether the world reads as upcoming, active, or finished on public surfaces."), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Activation and promotion"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Use campaign activation for platform-level surfacing. Homepage feature is a stronger spotlight signal on top of that base state."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: form.data.is_active_campaign,
      onChange: (event) => form.setData({
        ...form.data,
        is_active_campaign: event.target.checked,
        is_homepage_featured: event.target.checked ? form.data.is_homepage_featured : false
      }),
      label: "Mark as active campaign",
      size: 20,
      variant: "accent"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Active campaigns become eligible for stronger public surfacing on homepage, upload, and promoted worlds views.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: form.data.is_homepage_featured,
      onChange: (event) => form.setData({
        ...form.data,
        is_homepage_featured: event.target.checked,
        is_active_campaign: event.target.checked ? true : form.data.is_active_campaign
      }),
      label: "Feature on homepage spotlight",
      size: 20,
      variant: "accent"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Use this when the campaign should compete for the primary homepage spotlight position."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Campaign priority"), /* @__PURE__ */ React.createElement("input", { type: "number", min: "0", max: "9999", value: form.data.campaign_priority, onChange: (event) => form.setData("campaign_priority", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Higher values win when multiple campaigns are active at once.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Campaign label"), /* @__PURE__ */ React.createElement("input", { value: form.data.campaign_label, onChange: (event) => form.setData("campaign_label", event.target.value), placeholder: "Spring campaign, Returning seasonal world", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Promotion starts", value: form.data.promotion_starts_at, onChange: (nextValue) => form.setData("promotion_starts_at", nextValue), placeholder: "Optional promotion start", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Promotion ends", value: form.data.promotion_ends_at, onChange: (nextValue) => form.setData("promotion_ends_at", nextValue), placeholder: "Optional promotion end", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Promotion dates control when the world is highlighted beyond its own page. Leave them blank to use the main campaign window.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_featured, onChange: (event) => form.setData("is_featured", event.target.checked), label: "Feature on Worlds lists and supporting rails", size: 20, variant: "accent" }), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Keep this for secondary featured placement on worlds surfaces. Homepage spotlighting is controlled separately by active campaign and homepage feature.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_recurring, onChange: (event) => form.setData("is_recurring", event.target.checked), label: "Recurring world", size: 20, variant: "accent" }), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Use recurrence for annual or repeatable campaigns so new editions can be rolled forward cleanly."))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recurrence key"), /* @__PURE__ */ React.createElement("input", { value: form.data.recurrence_key, onChange: (event) => form.setData("recurrence_key", event.target.value), placeholder: "halloween, retro-month", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Edition year"), /* @__PURE__ */ React.createElement("input", { type: "number", min: "2000", max: "2100", value: form.data.edition_year, onChange: (event) => form.setData("edition_year", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recurrence rule"), /* @__PURE__ */ React.createElement("input", { value: form.data.recurrence_rule, onChange: (event) => form.setData("recurrence_rule", event.target.value), placeholder: "annual:10, annual:12, campaign-window", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(
    WorldRecurrenceHelper,
    {
      enabled: form.data.is_recurring,
      recurrenceKey: form.data.recurrence_key,
      editionYear: form.data.edition_year,
      recurrenceKeyError: form.errors.recurrence_key,
      editionYearError: form.errors.edition_year
    }
  ), world?.is_recurring ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Recurring family status"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-2xl leading-6 text-slate-400" }, "Track whether this editor is pointing at the canonical family edition, an archived edition, or a sibling inside the same recurrence group.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, world.family_title || world.recurrence_key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, "Edition ", world.edition_year || "Draft"), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${world.is_canonical_edition ? "border-emerald-300/20 bg-emerald-400/12 text-emerald-100" : "border-amber-300/20 bg-amber-400/12 text-amber-100"}` }, world.is_canonical_edition ? "Canonical family edition" : "Archive or sibling edition"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Family key"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 font-semibold text-white" }, world.recurrence_key)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Editions"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 font-semibold text-white" }, world.family_edition_count || 1)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Archive count"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 font-semibold text-white" }, world.archive_edition_count || 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Current public edition"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 font-semibold text-white" }, world.current_edition?.title || "None published yet"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("a", { href: world.family_url || "#", className: `rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 ${world.family_url ? "text-white" : "pointer-events-none text-slate-500"}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Family route"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold" }, world.family_url ? "Open canonical family page" : "Unavailable")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Previous edition"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, world.previous_edition?.title || "None")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Next edition"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm font-semibold text-white" }, world.next_edition?.title || "None yet")))) : null, /* @__PURE__ */ React.createElement(
    WorldDuplicateActionMenu,
    {
      duplicateUrl: duplicateActions?.duplicateUrl,
      newEditionUrl: duplicateActions?.newEditionUrl,
      canCreateEdition: Boolean(duplicateActions?.canCreateEdition),
      copyModeCount: Math.max(duplicateActions?.duplicateModeOptions?.length || 0, duplicateActions?.newEditionModeOptions?.length || 0),
      onDuplicate: () => runDuplicateAction(duplicateActions?.duplicateUrl, "Duplicate this world into a new draft?", duplicateActions?.duplicateModeOptions || []),
      onCreateEdition: () => runDuplicateAction(duplicateActions?.newEditionUrl, "Create the next edition draft from this world?", duplicateActions?.newEditionModeOptions || [])
    }
  ))) : null, activeTab === "community" ? /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Community participation", description: "Choose how creators can join the world, define the participation window, and moderate community placements without touching curated relations." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Participation mode"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Pick whether creator artworks need approval, go live automatically, or stay hidden from creator participation surfaces.")), /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Creator participation",
      value: form.data.participation_mode || "closed",
      onChange: (nextValue) => {
        const nextMode = String(nextValue || "closed");
        form.setData({
          ...form.data,
          participation_mode: nextMode,
          accepts_submissions: nextMode !== "closed"
        });
      },
      options: PARTICIPATION_MODE_OPTIONS,
      searchable: false,
      className: "bg-black/20"
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.submission_note_enabled, onChange: (event) => form.setData("submission_note_enabled", event.target.checked), label: "Allow creator notes", size: 20, variant: "accent" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.community_section_enabled, onChange: (event) => form.setData("community_section_enabled", event.target.checked), label: "Show community section on the public world page", size: 20, variant: "accent" }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.allow_readd_after_removal, onChange: (event) => form.setData("allow_readd_after_removal", event.target.checked), label: "Allow creators to re-add artworks after removal", size: 20, variant: "accent" }), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "Blocked artworks still stay locked until a moderator unblocks them."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Submission opens", value: form.data.submission_starts_at, onChange: (nextValue) => form.setData("submission_starts_at", nextValue), placeholder: "Optional submission start", clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(DateTimePicker, { label: "Submission closes", value: form.data.submission_ends_at, onChange: (nextValue) => form.setData("submission_ends_at", nextValue), placeholder: "Optional submission end", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("label", { className: "mt-4 grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Creator guidelines"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.submission_guidelines, onChange: (event) => form.setData("submission_guidelines", event.target.value), rows: 5, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", placeholder: "Explain what qualifies, what you want creators to submit, and any world-specific expectations." }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "These notes are shown to creators in upload and artwork-edit submission surfaces."))), world ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Submission review queue"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Moderate creator participation without converting those artworks into curated world relations.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-xs" }, [
    ["Pending", reviewQueue?.counts?.pending || 0, "border-sky-300/25 bg-sky-400/10 text-sky-100"],
    ["Live", reviewQueue?.counts?.live || 0, "border-emerald-300/25 bg-emerald-400/10 text-emerald-100"],
    ["Featured", reviewQueue?.counts?.featured || 0, "border-amber-300/25 bg-amber-400/10 text-amber-100"],
    ["Removed", reviewQueue?.counts?.removed || 0, "border-orange-300/25 bg-orange-400/10 text-orange-100"],
    ["Blocked", reviewQueue?.counts?.blocked || 0, "border-rose-300/25 bg-rose-400/10 text-rose-100"]
  ].map(([label, count, tone]) => /* @__PURE__ */ React.createElement("span", { key: label, className: `rounded-full border px-3 py-1 font-semibold uppercase tracking-[0.14em] ${tone}` }, label, ": ", count)))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, Array.isArray(reviewQueue?.items) && reviewQueue.items.length > 0 ? reviewQueue.items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row" }, /* @__PURE__ */ React.createElement("div", { className: "h-24 w-24 shrink-0 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950/80" }, item.artwork?.thumbnail_url ? /* @__PURE__ */ React.createElement("img", { src: item.artwork.thumbnail_url, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.artwork?.edit_url || item.artwork?.url || "#", className: "text-base font-semibold text-white hover:text-sky-100" }, item.artwork?.title || "Untitled artwork"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, item.status_label)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.submitted_by?.name || item.artwork?.creator_name || "Unknown creator"), Array.isArray(item.artwork?.meta) && item.artwork.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, item.artwork.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry, className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-xs text-slate-300" }, entry))) : null, Array.isArray(item.world_rewards) && item.world_rewards.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, item.world_rewards.map((reward) => /* @__PURE__ */ React.createElement("span", { key: reward.id, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100" }, reward.reward_label))) : null, item.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Creator note"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, item.note)) : null, item.reviewer_note ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm leading-6 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Moderator note"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, item.reviewer_note)) : null), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-wrap gap-2 xl:w-[220px] xl:flex-col" }, item.status === "pending" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.approve, "Approve this submission and make it live?", { title: "Approve submission?", confirmLabel: "Approve" }), className: "rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve") : null, item.status === "removed" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.restore, "Restore this submission to the live community section?", { title: "Restore submission?", confirmLabel: "Restore" }), className: "rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Restore") : null, item.status === "blocked" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.unblock, "Unblock this artwork so it can be restored or re-added later?", { title: "Unblock artwork?", confirmLabel: "Unblock", confirmTone: "accent" }), className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Unblock") : null, item.status !== "blocked" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.is_featured ? item.actions?.unfeature : item.actions?.feature, item.is_featured ? "Remove this artwork from featured community placement?" : "Feature this artwork in the public community section?", { title: item.is_featured ? "Unfeature artwork?" : "Feature artwork?", confirmLabel: item.is_featured ? "Unfeature" : "Feature" }), className: "rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-sm font-semibold text-amber-100" }, item.is_featured ? "Unfeature" : "Feature") : null, item.status !== "pending" && item.status !== "blocked" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.pending, "Return this submission to pending review?", { title: "Return to pending?", confirmLabel: "Set pending" }), className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Set pending") : null, item.can_grant_manual_rewards ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.grant_rewards?.winner, "Grant winner recognition to this creator for this world edition?", { title: "Grant winner reward?", confirmLabel: "Grant winner", noteEnabled: true }), className: "rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Winner") : null, item.can_grant_manual_rewards ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.grant_rewards?.finalist, "Grant finalist recognition to this creator for this world edition?", { title: "Grant finalist reward?", confirmLabel: "Grant finalist", noteEnabled: true }), className: "rounded-2xl border border-violet-300/20 bg-violet-400/10 px-4 py-2 text-sm font-semibold text-violet-100" }, "Finalist") : null, item.can_grant_manual_rewards ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.grant_rewards?.spotlight, "Grant spotlight recognition to this creator for this world edition?", { title: "Grant spotlight reward?", confirmLabel: "Grant spotlight", noteEnabled: true }), className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Spotlight") : null, Array.isArray(item.world_rewards) && item.world_rewards.some((reward) => reward.reward_type === "winner") ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.revoke_rewards?.winner, "Revoke winner recognition for this creator in this world edition?", { title: "Revoke winner reward?", confirmLabel: "Revoke winner", confirmTone: "danger" }), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-slate-200" }, "Revoke winner") : null, Array.isArray(item.world_rewards) && item.world_rewards.some((reward) => reward.reward_type === "finalist") ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.revoke_rewards?.finalist, "Revoke finalist recognition for this creator in this world edition?", { title: "Revoke finalist reward?", confirmLabel: "Revoke finalist", confirmTone: "danger" }), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-slate-200" }, "Revoke finalist") : null, Array.isArray(item.world_rewards) && item.world_rewards.some((reward) => reward.reward_type === "spotlight") ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.revoke_rewards?.spotlight, "Revoke spotlight recognition for this creator in this world edition?", { title: "Revoke spotlight reward?", confirmLabel: "Revoke spotlight", confirmTone: "danger" }), className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-slate-200" }, "Revoke spotlight") : null, item.status !== "removed" && item.status !== "blocked" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.remove, "Remove this artwork from community participation for this world?", { title: "Remove artwork?", confirmLabel: "Remove", cancelLabel: "Keep live", confirmTone: "danger", noteEnabled: true }), className: "rounded-2xl border border-orange-300/20 bg-orange-400/10 px-4 py-2 text-sm font-semibold text-orange-100" }, "Remove") : null, item.status !== "blocked" ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runSubmissionAction(item.actions?.block, "Block this artwork from re-adding to this world until a moderator clears it?", { title: "Block artwork?", confirmLabel: "Block", cancelLabel: "Cancel", confirmTone: "danger", noteEnabled: true }), className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Block") : null)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No submissions have been attached to this world yet."))) : null)) : null, activeTab === "presentation" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Theme and identity", description: "Apply theme presets and tune the visual language that drives the world’s mood and recognition." }, /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Theme preset",
      value: form.data.theme_key || null,
      onChange: (nextValue) => handleThemeChange(String(nextValue || "")),
      options: [{ value: "", label: "No preset" }, ...themeOptions],
      searchable: false,
      className: "bg-black/20"
    }
  ), /* @__PURE__ */ React.createElement(WorldThemePresetHelper, { theme: selectedTheme, onApply: () => handleThemeChange(form.data.theme_key, true) }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Accent color"), /* @__PURE__ */ React.createElement("input", { value: form.data.accent_color, onChange: (event) => form.setData("accent_color", event.target.value), placeholder: "#f97316", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Secondary accent"), /* @__PURE__ */ React.createElement("input", { value: form.data.accent_color_secondary, onChange: (event) => form.setData("accent_color_secondary", event.target.value), placeholder: "#0f172a", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Background motif"), /* @__PURE__ */ React.createElement("input", { value: form.data.background_motif, onChange: (event) => form.setData("background_motif", event.target.value), placeholder: "embers, frost, scanlines", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Icon class"), /* @__PURE__ */ React.createElement("input", { value: form.data.icon_name, onChange: (event) => form.setData("icon_name", event.target.value), placeholder: "fa-solid fa-ghost", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))))), /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Media assets", description: props.mediaSupport?.helper_text }, /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Cover image",
      slot: "cover",
      value: form.data.cover_path,
      previewUrl: resolveMediaUrl(form.data.cover_path, world?.cover_path === form.data.cover_path ? world?.cover_url || "" : "", filesBaseUrl),
      emptyLabel: "No cover selected",
      helperText: "Use the strongest hero asset you have so the world reads clearly in spotlight, cards, and preview states.",
      uploadUrl: props.mediaSupport?.upload_url,
      deleteUrl: props.mediaSupport?.delete_url,
      worldId: world?.id || null,
      isTemporaryValue: temporaryMediaPaths.cover !== "" && temporaryMediaPaths.cover === form.data.cover_path,
      accept: (props.mediaSupport?.accepted_mime_types || []).join(",") || "image/jpeg,image/png,image/webp",
      maxFileSizeMb: props.mediaSupport?.max_file_size_mb || 6,
      onChange: ({ path }) => {
        form.setData("cover_path", path);
        setTemporaryMediaPaths((current) => ({ ...current, cover: path || "" }));
      }
    }
  ), /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Teaser image",
      slot: "teaser",
      value: form.data.teaser_image_path,
      previewUrl: resolveMediaUrl(form.data.teaser_image_path, world?.teaser_image_path === form.data.teaser_image_path ? world?.teaser_image_url || "" : "", filesBaseUrl),
      emptyLabel: "Falls back to cover image when blank",
      helperText: "Use a promo-specific image when homepage, upload, or world index surfaces need a tighter campaign crop than the full world cover.",
      uploadUrl: props.mediaSupport?.upload_url,
      deleteUrl: props.mediaSupport?.delete_url,
      worldId: world?.id || null,
      isTemporaryValue: temporaryMediaPaths.teaser !== "" && temporaryMediaPaths.teaser === form.data.teaser_image_path,
      accept: (props.mediaSupport?.accepted_mime_types || []).join(",") || "image/jpeg,image/png,image/webp",
      maxFileSizeMb: props.mediaSupport?.max_file_size_mb || 6,
      onChange: ({ path }) => {
        form.setData("teaser_image_path", path);
        setTemporaryMediaPaths((current) => ({ ...current, teaser: path || "" }));
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "OG image",
      slot: "og",
      value: form.data.og_image_path,
      previewUrl: resolveMediaUrl(form.data.og_image_path, world?.og_image_path === form.data.og_image_path ? world?.og_image_url || "" : "", filesBaseUrl),
      emptyLabel: "Falls back to cover image when blank",
      helperText: "Upload a dedicated social share image, or leave it blank and use the cover image fallback.",
      uploadUrl: props.mediaSupport?.upload_url,
      deleteUrl: props.mediaSupport?.delete_url,
      worldId: world?.id || null,
      isTemporaryValue: temporaryMediaPaths.og !== "" && temporaryMediaPaths.og === form.data.og_image_path,
      accept: (props.mediaSupport?.accepted_mime_types || []).join(",") || "image/jpeg,image/png,image/webp",
      maxFileSizeMb: props.mediaSupport?.max_file_size_mb || 6,
      onChange: ({ path }) => {
        form.setData("og_image_path", path);
        setTemporaryMediaPaths((current) => ({ ...current, og: path || "" }));
      }
    }
  ), /* @__PURE__ */ React.createElement("div", { className: "flex justify-end" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: applyCoverToOg,
      disabled: !form.data.cover_path,
      className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white disabled:opacity-50"
    },
    "Use cover"
  ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Cover preview"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 h-40 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, previewWorld.cover_url ? /* @__PURE__ */ React.createElement("img", { src: previewWorld.cover_url, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-sm text-slate-500" }, "No cover selected"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "OG preview"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 h-40 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, form.data.og_image_path || previewWorld.cover_url ? /* @__PURE__ */ React.createElement("img", { src: resolveMediaUrl(form.data.og_image_path || form.data.cover_path, form.data.og_image_path ? world?.og_image_path === form.data.og_image_path ? world?.og_image_url || "" : "" : world?.cover_path === form.data.cover_path ? world?.cover_url || "" : "", filesBaseUrl), alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-sm text-slate-500" }, "Falls back to cover image when blank")))))), /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "CTA and badge", description: "Handle the promotional copy and campaign affordances that sit around the world, not inside its core story." }, /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Teaser title"), /* @__PURE__ */ React.createElement("input", { value: form.data.teaser_title, onChange: (event) => form.setData("teaser_title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Optional. Use this for homepage, upload, and world-card headlines without changing the canonical world title.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Teaser summary"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.teaser_summary, onChange: (event) => form.setData("teaser_summary", event.target.value), rows: 4, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "CTA label"), /* @__PURE__ */ React.createElement("input", { value: form.data.cta_label, onChange: (event) => form.setData("cta_label", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Keep this action specific to the campaign intent: explore, join, enter, submit, or discover.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "CTA URL"), /* @__PURE__ */ React.createElement("input", { value: form.data.cta_url, onChange: (event) => form.setData("cta_url", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Point this at the destination that matches the world, such as a challenge, collection, landing page, or participation flow."))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Badge label"), /* @__PURE__ */ React.createElement("input", { value: form.data.badge_label, onChange: (event) => form.setData("badge_label", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Use concise editorial language that still reads cleanly in the hero, cards, and spotlight surfaces.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Badge URL"), /* @__PURE__ */ React.createElement("input", { value: form.data.badge_url, onChange: (event) => form.setData("badge_url", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Optional. Use this when the badge should send visitors to a participation or explanation destination."))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Badge description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.badge_description, onChange: (event) => form.setData("badge_description", event.target.value), rows: 4, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Related tags"), /* @__PURE__ */ React.createElement("input", { value: tagString, onChange: (event) => form.setData("related_tags_json", event.target.value.split(",").map((tag) => tag.trim()).filter(Boolean)), placeholder: "halloween, spooky, demoscene", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Use these to reinforce the campaign identity and keep recurring presets consistent across editions."))))) : null, activeTab === "recap" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Recap framing", description: "Prepare the archive-facing editorial layer that turns an ended edition into a meaningful recap instead of a quiet archive shell." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recap workflow"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${form.data.recap_status === "published" ? "border-sky-300/25 bg-sky-400/10 text-sky-100" : "border-white/10 bg-white/[0.04] text-slate-200"}` }, form.data.recap_status === "published" ? "Published recap" : "Draft recap"), world?.recap_published_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, "Published ", new Date(world.recap_published_at).toLocaleDateString()) : null, canPublishRecap ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Ready to publish") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Publish after the edition ends")), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Recap stays editorial but data-backed. Curated world relations, challenge outcomes, community highlights, and analytics snapshots all flow into the public recap once you publish it.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Primary recap metrics"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-3" }, recapStatsSummary ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, formatCompactNumber(recapStatsSummary.views))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Submissions"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, formatCompactNumber(recapStatsSummary.submissions))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recognitions"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, formatCompactNumber(recapStatsSummary.reward_grants)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-400" }, "A recap snapshot will be captured when you publish the recap.")))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recap title"), /* @__PURE__ */ React.createElement("input", { value: form.data.recap_title, onChange: (event) => form.setData("recap_title", event.target.value), placeholder: "Halloween World 2026 recap", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Leave blank to fall back to “", form.data.title || "World", " recap”.")), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recap summary"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.recap_summary, onChange: (event) => form.setData("recap_summary", event.target.value), rows: 4, placeholder: "Short archive-facing summary for the recap hero.", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recap intro"), /* @__PURE__ */ React.createElement(
    RichTextEditor,
    {
      content: form.data.recap_intro,
      onChange: (nextValue) => form.setData("recap_intro", nextValue),
      placeholder: "Write the archive-facing intro that frames what made this edition memorable.",
      error: form.errors.recap_intro,
      minHeight: 14,
      autofocus: false
    }
  )), /* @__PURE__ */ React.createElement(
    WorldMediaUploadField,
    {
      label: "Recap cover",
      slot: "recap_cover",
      value: form.data.recap_cover_path,
      previewUrl: recapCoverPreviewUrl,
      emptyLabel: "Falls back to the main world cover when blank",
      helperText: "Optional. Use a calmer archive-facing image when the recap should feel distinct from the live campaign hero.",
      uploadUrl: props.mediaSupport?.upload_url,
      deleteUrl: props.mediaSupport?.delete_url,
      worldId: world?.id || null,
      isTemporaryValue: temporaryMediaPaths.recap !== "" && temporaryMediaPaths.recap === form.data.recap_cover_path,
      accept: (props.mediaSupport?.accepted_mime_types || []).join(",") || "image/jpeg,image/png,image/webp",
      maxFileSizeMb: props.mediaSupport?.max_file_size_mb || 6,
      onChange: ({ path }) => {
        form.setData("recap_cover_path", path);
        setTemporaryMediaPaths((current) => ({ ...current, recap: path || "" }));
      }
    }
  ), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Editor note"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.recap_editor_note, onChange: (event) => form.setData("recap_editor_note", event.target.value), rows: 4, placeholder: "Internal notes for editorial context, follow-up cleanup, or recap publishing reminders.", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Internal only. This note is stored with the recap draft but is not shown on the public recap page.")))), /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "Recap article and publish state", description: "Link one editorial story when the recap should point visitors toward a fuller write-up, results article, or reflective editorial piece." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, recapArticlePreview ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-start md:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-16 w-16 shrink-0 overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, recapArticlePreview.image ? /* @__PURE__ */ React.createElement("img", { src: recapArticlePreview.image, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-newspaper" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, recapArticlePreview.title), recapArticlePreview.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, recapArticlePreview.subtitle) : null, recapArticlePreview.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-slate-400" }, recapArticlePreview.description) : null)), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setRecapArticlePickerOpen(true), className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Change"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: clearRecapArticle, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-slate-200" }, "Clear"))) : /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "No recap article linked"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "Link an article when this recap should push visitors toward a fuller editorial recap, results post, or archive story.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setRecapArticlePickerOpen(true), className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Select article"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Publish behavior"), /* @__PURE__ */ React.createElement("p", { className: "mt-2" }, "Publishing recap captures a stats snapshot and makes the recap-first archive layout public for ended editions. You can keep refining the draft copy before that point."))))) : null, activeTab === "seo" ? /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "SEO", description: "Set metadata that travels with the world into search results, previews, and social cards." }, /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "SEO title"), /* @__PURE__ */ React.createElement("input", { value: form.data.seo_title, onChange: (event) => form.setData("seo_title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "SEO description"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.seo_description, onChange: (event) => form.setData("seo_description", event.target.value), rows: 4, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))) : null, activeTab === "analytics" ? /* @__PURE__ */ React.createElement(WorldEditorSection, { title: "World analytics", description: "Use campaign-useful metrics to judge traffic, editorial engagement, participation quality, challenge impact, and recurring-edition performance." }, /* @__PURE__ */ React.createElement(WorldAnalyticsPanel, { analytics: world?.analytics || null, world })) : null), /* @__PURE__ */ React.createElement("section", { className: "space-y-6 xl:sticky xl:top-6 xl:max-h-[calc(100vh-48px)] xl:self-start xl:overflow-y-auto xl:overscroll-contain xl:pr-1 nova-scrollbar" }, /* @__PURE__ */ React.createElement(
    WorldEditorActionPanel,
    {
      formProcessing: form.processing,
      isEditing: Boolean(props.updateUrl),
      publishUrl: props.publishUrl,
      publishRecapUrl: props.publishRecapUrl,
      canPublishRecap,
      recapStatusLabel: world?.recap_status_label || (form.data.recap_status === "published" ? "Published recap" : "Draft recap"),
      archiveUrl: props.archiveUrl,
      publicUrl: world?.urls?.public
    }
  ), /* @__PURE__ */ React.createElement(WorldSummaryCard, { world: form.data, themeLabel: selectedTheme?.label || "", relationCount: form.data.relations.length, enabledSectionsCount }), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Current focus"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center gap-2 text-white" }, /* @__PURE__ */ React.createElement("i", { className: `${currentTab?.icon || "fa-solid fa-pen-ruler"} text-[11px] text-sky-200`, "aria-hidden": "true" }), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold" }, currentTab?.label || "Editor")), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, currentTab?.description)), /* @__PURE__ */ React.createElement(WorldMiniPreviewPanel, { world: previewWorld, sections: previewSections, previewUrl: props.previewUrl }))), /* @__PURE__ */ React.createElement(
    WorldRelationPickerModal,
    {
      open: pickerState.open,
      onClose: closeRelationPicker,
      onSave: saveRelation,
      initialRelation: editingRelation,
      sectionOptions,
      relationTypeOptions,
      searchEntities
    }
  ), /* @__PURE__ */ React.createElement(
    WorldLinkedChallengePickerModal,
    {
      open: linkedChallengePickerOpen,
      onClose: () => setLinkedChallengePickerOpen(false),
      onSave: saveLinkedChallenge,
      initialChallenge: linkedChallengePreview,
      searchEntities
    }
  ), /* @__PURE__ */ React.createElement(
    WorldRecapArticlePickerModal,
    {
      open: recapArticlePickerOpen,
      onClose: () => setRecapArticlePickerOpen(false),
      onSave: saveRecapArticle,
      initialArticle: recapArticlePreview,
      searchEntities
    }
  ), /* @__PURE__ */ React.createElement(
    NovaConfirmDialog,
    {
      open: actionConfirm.open,
      title: actionConfirm.title,
      message: actionConfirm.message,
      confirmLabel: actionConfirm.confirmLabel,
      cancelLabel: actionConfirm.cancelLabel,
      confirmTone: actionConfirm.confirmTone,
      onConfirm: confirmAction,
      onClose: closeActionConfirm,
      busy: actionBusy
    },
    actionConfirm.copyModeEnabled ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Copy mode"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2" }, (actionConfirm.copyModeOptions || []).map((option) => /* @__PURE__ */ React.createElement("label", { key: option.value, className: "flex cursor-pointer items-start gap-3 rounded-[20px] border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(
      "input",
      {
        type: "radio",
        name: "world-copy-mode",
        value: option.value,
        checked: actionCopyMode === option.value,
        onChange: (event) => setActionCopyMode(event.target.value),
        className: "mt-1"
      }
    ), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, option.label), option.description ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, option.description) : null))))) : null,
    actionConfirm.noteEnabled ? /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Moderator note"), /* @__PURE__ */ React.createElement(
      "textarea",
      {
        value: actionReviewNote,
        onChange: (event) => setActionReviewNote(event.target.value),
        rows: 4,
        className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none",
        placeholder: "Explain the moderation decision so creators understand what changed."
      }
    )) : null
  ));
}
const __vite_glob_0_160 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioWorldEditor
}, Symbol.toStringTag, { value: "Module" }));
function formatNumber$1(value) {
  return new Intl.NumberFormat("en-US").format(Number(value || 0));
}
function formatPercent(value) {
  return `${Math.round(Number(value || 0) * 100)}%`;
}
function metricValue(row, key) {
  switch (key) {
    case "conversion":
      return formatPercent(row.view_to_submission_conversion);
    case "reward_grants":
      return `${formatNumber$1(row.reward_grants)} grants`;
    case "submissions":
      return `${formatNumber$1(row.submissions)} submissions`;
    case "unique_visitors":
      return `${formatNumber$1(row.unique_visitors)} visitors`;
    case "views":
    default:
      return `${formatNumber$1(row.views)} views`;
  }
}
function LeaderboardColumn({ title, rows = [], metricKey = "views" }) {
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, rows.length > 0 ? rows.map((row, index2) => /* @__PURE__ */ React.createElement("a", { key: `${metricKey}-${row.world_id}`, href: row.edit_url, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, "#", index2 + 1), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate text-sm font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, "/", row.slug, row.edition_year ? ` • ${row.edition_year}` : "")), /* @__PURE__ */ React.createElement("div", { className: "shrink-0 text-xs font-semibold uppercase tracking-[0.14em] text-sky-100" }, metricValue(row, metricKey))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] px-4 py-5 text-sm text-slate-400" }, "No activity recorded for this range yet.")));
}
function WorldAnalyticsPortfolioPanel({ analytics = null }) {
  const rangeOptions2 = Array.isArray(analytics?.range_options) ? analytics.range_options : [];
  const defaultRange = analytics?.default_range || rangeOptions2[0]?.value || "30d";
  const [selectedRange, setSelectedRange] = reactExports.useState(defaultRange);
  const range2 = reactExports.useMemo(() => analytics?.ranges?.[selectedRange] || {}, [analytics, selectedRange]);
  const summary = range2.summary || {};
  const leaderboards = range2.leaderboards || {};
  if (!analytics || rangeOptions2.length === 0) {
    return null;
  }
  const summaryCards2 = [
    {
      label: "Tracked Worlds",
      value: formatNumber$1(summary.tracked_worlds),
      hint: "Worlds with activity in this range."
    },
    {
      label: "Views",
      value: formatNumber$1(summary.views),
      hint: "Portfolio traffic across all worlds.",
      tone: "accent"
    },
    {
      label: "Promotion Impressions",
      value: formatNumber$1(summary.promotion_impressions),
      hint: "Observed spotlight, rail, and upload placements."
    },
    {
      label: "Submissions",
      value: formatNumber$1(summary.submissions),
      hint: `Rewards granted: ${formatNumber$1(summary.reward_grants)}`,
      tone: "emerald"
    }
  ];
  return /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Portfolio analytics"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Cross-world performance"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Use this snapshot to see which worlds are drawing traffic, driving participation, and converting attention into submissions.")), /* @__PURE__ */ React.createElement("div", { className: "inline-flex flex-wrap gap-2 rounded-full border border-white/10 bg-black/20 p-1" }, rangeOptions2.map((option) => {
    const active = option.value === selectedRange;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => setSelectedRange(option.value),
        className: `rounded-full px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition ${active ? "bg-sky-400/15 text-sky-100" : "text-slate-400 hover:text-white"}`
      },
      option.label
    );
  }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, summaryCards2.map((card) => /* @__PURE__ */ React.createElement(WorldAnalyticsSummaryCard, { key: card.label, ...card }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(LeaderboardColumn, { title: "Top by views", rows: leaderboards.views || [], metricKey: "views" }), /* @__PURE__ */ React.createElement(LeaderboardColumn, { title: "Top by unique visitors", rows: leaderboards.unique_visitors || [], metricKey: "unique_visitors" }), /* @__PURE__ */ React.createElement(LeaderboardColumn, { title: "Top by submissions", rows: leaderboards.submissions || [], metricKey: "submissions" }), /* @__PURE__ */ React.createElement(LeaderboardColumn, { title: "Best view-to-submit conversion", rows: leaderboards.conversion || [], metricKey: "conversion" })));
}
function StudioWorldsIndex() {
  const { props } = X$1();
  const listing = props.listing || {};
  const items = Array.isArray(listing.items) ? listing.items : [];
  const filters = listing.filters || {};
  const updateFilter = (name2, value) => {
    At.get("/studio/worlds", { ...filters, [name2]: value }, { preserveState: true, replace: true });
  };
  return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6" }, /* @__PURE__ */ React.createElement(WorldAnalyticsPortfolioPanel, { analytics: props.analytics }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_12rem_12rem_auto] lg:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilter("q", event.target.value), placeholder: "Search title, slug, or summary", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.status || "", onChange: (val) => updateFilter("status", val), options: [{ value: "", label: "All statuses" }, ...props.statusOptions || []], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "", onChange: (val) => updateFilter("type", val), options: [{ value: "", label: "All types" }, ...props.typeOptions || []], searchable: false })), /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "New world"))), /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 xl:grid-cols-2" }, items.length > 0 ? items.map((world) => /* @__PURE__ */ React.createElement("a", { key: world.id, href: world.edit_url, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 transition hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.status, tone: "slate" } }), /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.type, tone: "slate" } }), (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: `${world.id}-${badge.label}`, badge }))), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-2xl font-semibold tracking-[-0.03em] text-white" }, world.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-500" }, "/", world.slug), world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-6 text-slate-300" }, world.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 text-sm text-slate-400" }, world.timeframe_label ? /* @__PURE__ */ React.createElement("span", null, world.timeframe_label) : null, world.promotion_window_label ? /* @__PURE__ */ React.createElement("span", null, world.promotion_window_label) : null, /* @__PURE__ */ React.createElement("span", null, world.relation_count, " relations"), world.live_submission_count > 0 ? /* @__PURE__ */ React.createElement("span", null, world.live_submission_count, " live submissions") : null, world.theme_key ? /* @__PURE__ */ React.createElement("span", null, world.theme_key) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-sm font-semibold" }, /* @__PURE__ */ React.createElement("span", { className: "text-sky-100" }, "Edit"), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Preview"), world.public_url ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Public") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No worlds match this filter yet."))));
}
const __vite_glob_0_161 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: StudioWorldsIndex
}, Symbol.toStringTag, { value: "Module" }));
const DEFAULT_MIN_LENGTH = 2;
const DEFAULT_MAX_LENGTH = 32;
const DEBOUNCE_MS = 300;
const MAX_SUGGESTIONS = 8;
function normalizeTag(rawTag) {
  const raw = String(rawTag ?? "").trim().toLowerCase();
  if (!raw) return "";
  const noSpaces = raw.replace(/\s+/g, "-");
  const cleaned = noSpaces.replace(/[^a-z0-9_-]/g, "");
  const compact = cleaned.replace(/-+/g, "-").replace(/_+/g, "_").replace(/^[-_]+|[-_]+$/g, "");
  return compact.slice(0, DEFAULT_MAX_LENGTH);
}
function parseTagList(input) {
  if (Array.isArray(input)) return input;
  if (typeof input !== "string") return [];
  return input.split(/[\n,]+/).map((item) => item.trim()).filter(Boolean);
}
function analyzePastedTags(rawText, selectedTags, minLength, maxLength, maxTags) {
  const parts = parseTagList(rawText);
  const tagsToAdd = [];
  const skippedDuplicates = [];
  const skippedInvalid = [];
  const skippedOverflow = [];
  for (const part of parts) {
    const normalized = normalizeTag(part);
    if (!normalized) {
      skippedInvalid.push(String(part ?? "").trim());
      continue;
    }
    if (selectedTags.includes(normalized) || tagsToAdd.includes(normalized)) {
      skippedDuplicates.push(normalized);
      continue;
    }
    if (normalized.length < minLength || normalized.length > maxLength || !/^[a-z0-9_-]+$/.test(normalized)) {
      skippedInvalid.push(String(part ?? "").trim());
      continue;
    }
    if (selectedTags.length + tagsToAdd.length >= maxTags) {
      skippedOverflow.push(normalized);
      continue;
    }
    tagsToAdd.push(normalized);
  }
  return {
    parsedCount: parts.length,
    tagsToAdd,
    nextTags: [...selectedTags, ...tagsToAdd],
    skippedDuplicates,
    skippedInvalid,
    skippedOverflow
  };
}
function validateTag(tag, selectedTags, minLength, maxLength, maxTags) {
  if (selectedTags.length >= maxTags) return "Max tags reached";
  if (tag.length < minLength) return "Tag too short";
  if (tag.length > maxLength) return "Tag too long";
  if (!/^[a-z0-9_-]+$/.test(tag)) return "Invalid tag format";
  if (selectedTags.includes(tag)) return "Duplicate tag";
  return null;
}
function toSuggestionItems(raw) {
  if (!Array.isArray(raw)) return [];
  return raw.map((item) => {
    if (typeof item === "string") {
      return { key: item, label: item, tag: item, usageCount: null, isAi: false };
    }
    const tag = item?.slug || item?.name || item?.tag || "";
    if (!tag) return null;
    return {
      key: item?.id ?? tag,
      label: item?.name || item?.tag || item?.slug || tag,
      tag,
      usageCount: Number.isFinite(Number(item?.usage_count)) ? Number(item.usage_count) : null,
      recentClicks: Number.isFinite(Number(item?.recent_clicks)) ? Number(item.recent_clicks) : 0,
      isAi: Boolean(item?.is_ai || item?.source === "ai")
    };
  }).filter(Boolean);
}
function TagPillList({ tags, onRemove, disabled }) {
  return /* @__PURE__ */ React.createElement("div", { className: "min-h-[3rem] rounded-xl border border-white/10 bg-white/5 p-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, tags.length === 0 && /* @__PURE__ */ React.createElement("span", { className: "px-2 py-1 text-xs text-white/50" }, "No tags selected"), tags.map((tag) => /* @__PURE__ */ React.createElement(
    "span",
    {
      key: tag,
      className: "group inline-flex max-w-full items-center gap-2 rounded-full border border-white/20 bg-slate-900/80 px-3 py-1.5 text-xs text-slate-100 transition-all duration-150 ease-in-out",
      title: tag
    },
    /* @__PURE__ */ React.createElement("span", { className: "truncate" }, tag),
    /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => onRemove(tag),
        disabled,
        className: "rounded-full p-0.5 text-slate-300 transition-colors duration-150 ease-in-out hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-50",
        "aria-label": `Remove tag ${tag}`
      },
      "✕"
    )
  ))));
}
function SearchInput({
  inputValue,
  onInputChange,
  onKeyDown,
  onPaste,
  onFocus,
  disabled,
  expanded,
  listboxId,
  placeholder
}) {
  return /* @__PURE__ */ React.createElement(
    "input",
    {
      value: inputValue,
      onChange: (event) => onInputChange(event.target.value),
      onKeyDown,
      onPaste,
      onFocus,
      disabled,
      type: "text",
      role: "combobox",
      className: "w-full rounded-xl border border-white/10 bg-white/10 px-3 py-2 text-sm text-white placeholder:text-white/45 focus:border-sky-400 focus:outline-none disabled:cursor-not-allowed disabled:opacity-60",
      placeholder,
      "aria-label": "Tag input",
      "aria-autocomplete": "list",
      "aria-haspopup": "listbox",
      "aria-expanded": expanded,
      "aria-controls": listboxId
    }
  );
}
function HighlightedMatch({ label, query }) {
  if (!query) return /* @__PURE__ */ React.createElement(React.Fragment, null, label);
  const lowerLabel = label.toLowerCase();
  const lowerQuery = query.toLowerCase();
  const start = lowerLabel.indexOf(lowerQuery);
  if (start === -1) return /* @__PURE__ */ React.createElement(React.Fragment, null, label);
  const end = start + query.length;
  const before = label.slice(0, start);
  const match = label.slice(start, end);
  const after = label.slice(end);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, before, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-sky-300" }, match), after);
}
function SuggestionDropdown({
  isOpen,
  loading,
  error,
  suggestions,
  highlightedIndex,
  onSelect,
  query,
  listboxId
}) {
  if (!isOpen) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-xl ring-1 ring-white/10 bg-slate-950/98 shadow-xl shadow-black/50" }, /* @__PURE__ */ React.createElement("ul", { id: listboxId, role: "listbox", className: "max-h-56 overflow-auto py-1" }, loading && /* @__PURE__ */ React.createElement("li", { className: "px-3 py-2 text-xs text-white/60" }, "Searching tags…"), !loading && error && /* @__PURE__ */ React.createElement("li", { className: "px-3 py-2 text-xs text-amber-200" }, "Tag search unavailable"), !loading && !error && suggestions.length === 0 && /* @__PURE__ */ React.createElement("li", { className: "px-3 py-2 text-xs text-white/50" }, "No suggestions"), !loading && !error && suggestions.map((item, index2) => {
    const active = highlightedIndex === index2;
    const detailLabel = item.recentClicks > 0 ? `${item.recentClicks.toLocaleString()} recent` : typeof item.usageCount === "number" ? `${item.usageCount.toLocaleString()} uses` : null;
    return /* @__PURE__ */ React.createElement(
      "li",
      {
        key: item.key,
        role: "option",
        "aria-selected": active,
        className: `flex cursor-pointer items-center justify-between gap-2 px-3 py-2 text-sm transition-colors duration-150 ease-in-out ${active ? "bg-sky-500/20 text-white" : "text-white/85 hover:bg-white/10"}`,
        onMouseDown: (event) => {
          event.preventDefault();
          onSelect(item.tag);
        }
      },
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "truncate" }, /* @__PURE__ */ React.createElement(HighlightedMatch, { label: item.label, query })), item.isAi && /* @__PURE__ */ React.createElement("span", { className: "ml-2 rounded-full border border-purple-400/40 bg-purple-400/10 px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-purple-200" }, "AI")),
      detailLabel && /* @__PURE__ */ React.createElement("span", { className: "shrink-0 text-[11px] text-white/50" }, detailLabel)
    );
  })));
}
function SuggestedTagsPanel({ items, selectedTags, onAdd, disabled }) {
  const filtered = reactExports.useMemo(
    () => items.filter((item) => !selectedTags.includes(normalizeTag(item.tag))),
    [items, selectedTags]
  );
  if (filtered.length === 0) return null;
  return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-purple-400/20 bg-purple-500/5 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 text-xs uppercase tracking-wide text-purple-200" }, "AI Suggested tags"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, filtered.map((item) => /* @__PURE__ */ React.createElement(
    "button",
    {
      key: item.key,
      type: "button",
      onClick: () => onAdd(item.tag),
      disabled,
      className: "inline-flex items-center gap-1 rounded-full border border-purple-300/40 bg-purple-400/10 px-3 py-1.5 text-xs text-purple-100 transition-all duration-150 ease-in-out hover:bg-purple-400/20 disabled:cursor-not-allowed disabled:opacity-60"
    },
    item.label,
    /* @__PURE__ */ React.createElement("span", { className: "text-[11px]" }, "+")
  ))));
}
function StatusHints({ error, count, maxTags }) {
  return /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: error ? "text-amber-200" : "text-white/55", role: "status", "aria-live": "polite" }, error || "Type and press Enter, comma, or Tab to add. Paste a comma-separated list to review multiple tags."), /* @__PURE__ */ React.createElement("span", { className: "text-white/50" }, count, "/", maxTags));
}
function PastedTagsDialog({ open, preview, maxTags, onClose, onConfirm }) {
  const backdropRef = reactExports.useRef(null);
  const cancelButtonRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const timeoutId = window.setTimeout(() => cancelButtonRef.current?.focus(), 60);
    return () => window.clearTimeout(timeoutId);
  }, [open]);
  reactExports.useEffect(() => {
    if (!open) return void 0;
    const handleKeyDown2 = (event) => {
      if (event.key === "Escape") {
        onClose?.();
      }
    };
    window.addEventListener("keydown", handleKeyDown2);
    return () => window.removeEventListener("keydown", handleKeyDown2);
  }, [onClose, open]);
  if (!open || !preview) return null;
  const duplicateCount = preview.skippedDuplicates.length;
  const invalidCount = preview.skippedInvalid.length;
  const overflowCount = preview.skippedOverflow.length;
  return reactDomExports.createPortal(
    /* @__PURE__ */ React.createElement(
      "div",
      {
        ref: backdropRef,
        className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md",
        onClick: (event) => {
          if (event.target === backdropRef.current) {
            onClose?.();
          }
        },
        role: "presentation"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "dialog",
          "aria-modal": "true",
          "aria-labelledby": "tag-input-paste-title",
          className: "w-full max-w-lg overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]"
        },
        /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Tag Import"), /* @__PURE__ */ React.createElement("h3", { id: "tag-input-paste-title", className: "mt-2 text-lg font-semibold text-white" }, "Add ", preview.tagsToAdd.length, " pasted tag", preview.tagsToAdd.length === 1 ? "" : "s", "?"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Parsed ", preview.parsedCount, " item", preview.parsedCount === 1 ? "" : "s", " from your paste. Confirm before adding them to the artwork.")),
        /* @__PURE__ */ React.createElement("div", { className: "space-y-4 px-6 py-5" }, overflowCount > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-amber-300/25 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "Only ", preview.tagsToAdd.length, " tag", preview.tagsToAdd.length === 1 ? "" : "s", " can be added because the limit is ", maxTags, ". ", overflowCount, " pasted tag", overflowCount === 1 ? "" : "s", " will be skipped."), (duplicateCount > 0 || invalidCount > 0) && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-white/70" }, duplicateCount > 0 ? `${duplicateCount} duplicate tag${duplicateCount === 1 ? "" : "s"} ignored.` : "", duplicateCount > 0 && invalidCount > 0 ? " " : "", invalidCount > 0 ? `${invalidCount} invalid tag${invalidCount === 1 ? "" : "s"} ignored.` : ""), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-xs font-semibold uppercase tracking-[0.18em] text-white/40" }, "Tags to add"), /* @__PURE__ */ React.createElement("div", { className: "max-h-56 overflow-auto rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, preview.tagsToAdd.map((tag) => /* @__PURE__ */ React.createElement(
          "span",
          {
            key: tag,
            className: "inline-flex items-center rounded-full border border-sky-300/25 bg-sky-400/10 px-3 py-1.5 text-xs font-medium text-sky-100"
          },
          tag
        )))))),
        /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement(
          "button",
          {
            ref: cancelButtonRef,
            type: "button",
            onClick: () => onClose?.(),
            className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/20"
          },
          "Cancel"
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: () => onConfirm?.(),
            className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/40"
          },
          "Add tags"
        ))
      )
    ),
    document.body
  );
}
function TagInput({
  value,
  onChange,
  suggestedTags = [],
  disabled = false,
  maxTags = getMaxUserTags(),
  minLength = DEFAULT_MIN_LENGTH,
  maxLength = DEFAULT_MAX_LENGTH,
  placeholder = "Type tags…",
  searchEndpoint = "/api/tags/search",
  popularEndpoint = "/api/tags/popular"
}) {
  const selectedTags = reactExports.useMemo(() => parseTagList(value).map(normalizeTag).filter(Boolean), [value]);
  const [inputValue, setInputValue] = reactExports.useState("");
  const [suggestions, setSuggestions] = reactExports.useState([]);
  const [loading, setLoading] = reactExports.useState(false);
  const [error, setError] = reactExports.useState("");
  const [searchError, setSearchError] = reactExports.useState(false);
  const [isOpen, setIsOpen] = reactExports.useState(false);
  const [highlightedIndex, setHighlightedIndex] = reactExports.useState(-1);
  const [pastePreview, setPastePreview] = reactExports.useState(null);
  const queryCacheRef = reactExports.useRef(/* @__PURE__ */ new Map());
  const abortControllerRef = reactExports.useRef(null);
  const debounceTimerRef = reactExports.useRef(null);
  const hasFocusedRef = reactExports.useRef(false);
  const listboxId = reactExports.useMemo(() => `tag-input-listbox-${Math.random().toString(16).slice(2)}`, []);
  const aiSuggestedItems = reactExports.useMemo(() => toSuggestionItems(suggestedTags), [suggestedTags]);
  const updateTags = reactExports.useCallback((nextTags) => {
    const unique = Array.from(new Set(nextTags.map(normalizeTag).filter(Boolean)));
    onChange(unique);
  }, [onChange]);
  const addTag = reactExports.useCallback((rawTag) => {
    const normalized = normalizeTag(rawTag);
    const validation = validateTag(normalized, selectedTags, minLength, maxLength, maxTags);
    if (validation) {
      setError(validation);
      return false;
    }
    setError("");
    updateTags([...selectedTags, normalized]);
    setInputValue("");
    setIsOpen(false);
    setHighlightedIndex(-1);
    return true;
  }, [selectedTags, minLength, maxLength, maxTags, updateTags]);
  const removeTag = reactExports.useCallback((tagToRemove) => {
    setError("");
    updateTags(selectedTags.filter((tag) => tag !== tagToRemove));
  }, [selectedTags, updateTags]);
  const applyPastedTags = reactExports.useCallback((rawText) => {
    const preview = analyzePastedTags(rawText, selectedTags, minLength, maxLength, maxTags);
    if (preview.parsedCount === 0) return false;
    if (preview.tagsToAdd.length === 0) {
      if (selectedTags.length >= maxTags || preview.skippedOverflow.length > 0) {
        setError("Max tags reached");
      } else {
        setError("No new tags found in pasted text");
      }
      return false;
    }
    setError("");
    setIsOpen(false);
    setHighlightedIndex(-1);
    setPastePreview(preview);
    return true;
  }, [selectedTags, minLength, maxLength, maxTags]);
  const closePastePreview = reactExports.useCallback(() => {
    setPastePreview(null);
  }, []);
  const confirmPastePreview = reactExports.useCallback(() => {
    if (!pastePreview) return;
    updateTags(pastePreview.nextTags);
    setInputValue("");
    setError("");
    setPastePreview(null);
  }, [pastePreview, updateTags]);
  const runSearch = reactExports.useCallback(async (query) => {
    const normalizedQuery = normalizeTag(query);
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
    }
    const cacheKey = normalizedQuery || "__popular__";
    if (queryCacheRef.current.has(cacheKey)) {
      const cached = queryCacheRef.current.get(cacheKey);
      setSuggestions(cached);
      setSearchError(false);
      setIsOpen(true);
      return;
    }
    const controller = new AbortController();
    abortControllerRef.current = controller;
    setLoading(true);
    setSearchError(false);
    try {
      const url = normalizedQuery ? `${searchEndpoint}?q=${encodeURIComponent(normalizedQuery)}` : popularEndpoint;
      const res = await window.axios.get(url, { signal: controller.signal });
      const items = toSuggestionItems(res?.data?.data || []).filter((item) => !selectedTags.includes(normalizeTag(item.tag))).slice(0, MAX_SUGGESTIONS);
      queryCacheRef.current.set(cacheKey, items);
      setSuggestions(items);
      setHighlightedIndex(items.length > 0 ? 0 : -1);
      setIsOpen(true);
    } catch (requestError) {
      if (controller.signal.aborted) return;
      setSuggestions([]);
      setSearchError(true);
      setIsOpen(true);
    } finally {
      if (!controller.signal.aborted) {
        setLoading(false);
      }
    }
  }, [searchEndpoint, popularEndpoint, selectedTags]);
  reactExports.useEffect(() => {
    if (!hasFocusedRef.current) return;
    const query = inputValue.trim();
    if (debounceTimerRef.current) {
      window.clearTimeout(debounceTimerRef.current);
    }
    debounceTimerRef.current = window.setTimeout(() => {
      runSearch(query);
    }, DEBOUNCE_MS);
    return () => {
      if (debounceTimerRef.current) {
        window.clearTimeout(debounceTimerRef.current);
      }
    };
  }, [inputValue, runSearch]);
  reactExports.useEffect(() => {
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);
  const handleInputKeyDown = reactExports.useCallback((event) => {
    if (event.key === "Escape") {
      setIsOpen(false);
      setHighlightedIndex(-1);
      return;
    }
    if (event.key === "Backspace" && inputValue.length === 0 && selectedTags.length > 0) {
      removeTag(selectedTags[selectedTags.length - 1]);
      return;
    }
    if (event.key === "ArrowDown") {
      event.preventDefault();
      if (!isOpen || suggestions.length === 0) return;
      setHighlightedIndex((prev) => {
        if (prev < 0) return 0;
        return Math.min(prev + 1, suggestions.length - 1);
      });
      return;
    }
    if (event.key === "ArrowUp") {
      event.preventDefault();
      if (!isOpen || suggestions.length === 0) return;
      setHighlightedIndex((prev) => {
        if (prev <= 0) return 0;
        return prev - 1;
      });
      return;
    }
    const shouldCommit = event.key === "Enter" || event.key === "," || event.key === "Tab";
    if (!shouldCommit) return;
    if (event.key === "Tab" && !isOpen && inputValue.trim() === "") {
      return;
    }
    event.preventDefault();
    if ((event.key === "Enter" || event.key === "Tab") && isOpen && highlightedIndex >= 0 && suggestions[highlightedIndex]) {
      addTag(suggestions[highlightedIndex].tag);
      return;
    }
    const candidate = inputValue.trim().replace(/,$/, "");
    if (!candidate) return;
    addTag(candidate);
  }, [inputValue, selectedTags, removeTag, isOpen, suggestions, highlightedIndex, addTag]);
  const handlePaste = reactExports.useCallback((event) => {
    const raw = event.clipboardData?.getData("text");
    if (!raw) return;
    const parts = parseTagList(raw);
    if (parts.length <= 1) return;
    event.preventDefault();
    applyPastedTags(raw);
  }, [applyPastedTags]);
  const handleFocus = reactExports.useCallback(() => {
    hasFocusedRef.current = true;
    if (inputValue.trim() !== "") return;
    runSearch("");
  }, [inputValue, runSearch]);
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex h-full flex-col gap-3", "data-testid": "tag-input-root" }, /* @__PURE__ */ React.createElement(TagPillList, { tags: selectedTags, onRemove: removeTag, disabled }), /* @__PURE__ */ React.createElement(
    SearchInput,
    {
      inputValue,
      onInputChange: (next) => {
        setInputValue(next);
        setError("");
      },
      onKeyDown: handleInputKeyDown,
      onPaste: handlePaste,
      onFocus: handleFocus,
      disabled,
      expanded: isOpen,
      listboxId,
      placeholder
    }
  ), /* @__PURE__ */ React.createElement(
    SuggestionDropdown,
    {
      isOpen,
      loading,
      error: searchError,
      suggestions,
      highlightedIndex,
      onSelect: addTag,
      query: inputValue.trim(),
      listboxId
    }
  ), /* @__PURE__ */ React.createElement(
    SuggestedTagsPanel,
    {
      items: aiSuggestedItems,
      selectedTags,
      onAdd: addTag,
      disabled
    }
  ), /* @__PURE__ */ React.createElement(StatusHints, { error, count: selectedTags.length, maxTags })), /* @__PURE__ */ React.createElement(
    PastedTagsDialog,
    {
      open: Boolean(pastePreview),
      preview: pastePreview,
      maxTags,
      onClose: closePastePreview,
      onConfirm: confirmPastePreview
    }
  ));
}
function emitUploadEvent(eventName, payload = {}) {
  try {
    if (typeof window !== "undefined") {
      window.dispatchEvent(
        new CustomEvent("skinbase:upload-analytics", {
          detail: {
            event: eventName,
            payload,
            timestamp: Date.now()
          }
        })
      );
    }
    const endpoint = typeof window !== "undefined" ? window?.SKINBASE_UPLOAD_ANALYTICS_URL : null;
    if (endpoint && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
      const body2 = JSON.stringify({ event: eventName, payload, ts: Date.now() });
      const blob = new Blob([body2], { type: "application/json" });
      navigator.sendBeacon(endpoint, blob);
    }
  } catch {
  }
}
function init() {
  return "/api/uploads/init";
}
function chunk() {
  return "/api/uploads/chunk";
}
function finish() {
  return "/api/uploads/finish";
}
function status(id) {
  return `/api/uploads/status/${id}`;
}
function cancel() {
  return "/api/uploads/cancel";
}
function publish(id) {
  return `/api/uploads/${id}/publish`;
}
function submitReview(id) {
  return `/api/uploads/${id}/submit-review`;
}
const REASON_MAP = {
  duplicate_hash: {
    type: "error",
    message: "This file already exists in Skinbase. Please upload a different file."
  },
  validation_failed: {
    type: "error",
    message: "Upload validation failed. Please check the file and try again."
  },
  scan_failed: {
    type: "error",
    message: "Upload scan failed. Please try another file."
  },
  quota_exceeded: {
    type: "warning",
    message: "Upload limit reached. Please wait before uploading again."
  }
};
function normalizeType(value, fallback = "error") {
  const normalized = String(value || "").toLowerCase();
  if (normalized === "success" || normalized === "warning" || normalized === "error") return normalized;
  return fallback;
}
function firstValidationError(errors) {
  if (!errors || typeof errors !== "object") return "";
  for (const value of Object.values(errors)) {
    if (Array.isArray(value) && value[0]) return String(value[0]).trim();
    if (typeof value === "string" && value.trim()) return value.trim();
  }
  return "";
}
function mapUploadErrorNotice(error, fallback = "Upload failed.") {
  const status2 = Number(error?.response?.status || 0);
  const payload = error?.response?.data || {};
  const reason = String(payload?.reason || "").toLowerCase();
  const mapped = REASON_MAP[reason];
  const errorCode = String(error?.code || "").toUpperCase();
  const rawMessage = typeof error?.message === "string" ? error.message.trim() : "";
  const validationMessage = firstValidationError(payload?.errors);
  const timedOut = errorCode === "ECONNABORTED" || /timeout/i.test(rawMessage);
  const requestTooLarge = status2 === 413;
  const type2 = mapped?.type ? mapped.type : normalizeType(payload?.type || payload?.level, requestTooLarge ? "warning" : status2 >= 500 ? "error" : "warning");
  const message = (requestTooLarge ? "Server rejected this upload chunk as too large. Retrying with smaller chunks may help, or increase Nginx/PHP upload limits." : "") || (timedOut ? "Upload request timed out before the server responded. Check Nginx/PHP-FPM body handling and try again." : "") || mapped?.message || validationMessage || typeof payload?.message === "string" && payload.message.trim() || rawMessage || fallback;
  return {
    type: type2,
    message,
    reason,
    status: status2
  };
}
function mapUploadResultNotice(payload, options = {}) {
  const {
    fallbackType = "success",
    fallbackMessage = "Operation completed successfully."
  } = options;
  const reason = String(payload?.reason || "").toLowerCase();
  const mapped = REASON_MAP[reason];
  const type2 = mapped?.type || normalizeType(payload?.type || payload?.level, fallbackType);
  const message = mapped?.message || typeof payload?.message === "string" && payload.message.trim() || fallbackMessage;
  return {
    type: type2,
    message,
    reason,
    status: Number(payload?.status_code || 0)
  };
}
const DEFAULT_CHUNK_SIZE_BYTES = 5 * 1024 * 1024;
const DEFAULT_CHUNK_REQUEST_TIMEOUT_MS$1 = 45e3;
const MIN_CHUNK_SIZE_BYTES$1 = 256 * 1024;
const POLL_INTERVAL_MS = 2e3;
const machineStates = {
  idle: "idle",
  initializing: "initializing",
  uploading: "uploading",
  finishing: "finishing",
  processing: "processing",
  ready_to_publish: "ready_to_publish",
  publishing: "publishing",
  complete: "complete",
  error: "error",
  cancelled: "cancelled"
};
const initialMachineState = {
  state: machineStates.idle,
  progress: 0,
  sessionId: null,
  uploadToken: null,
  processingStatus: null,
  isCancelling: false,
  error: "",
  lastAction: null,
  slug: null
};
function machineReducer(state, action) {
  switch (action.type) {
    case "INIT_START":
      return { ...state, state: machineStates.initializing, progress: 0, error: "", isCancelling: false, lastAction: "start" };
    case "INIT_SUCCESS":
      return { ...state, sessionId: action.sessionId, uploadToken: action.uploadToken, error: "" };
    case "UPLOAD_START":
      return { ...state, state: machineStates.uploading, progress: 1, error: "" };
    case "UPLOAD_PROGRESS":
      return { ...state, progress: Math.max(1, Math.min(95, action.progress)), error: "" };
    case "FINISH_START":
      return { ...state, state: machineStates.finishing, progress: Math.max(state.progress, 96), error: "" };
    case "FINISH_SUCCESS":
      return { ...state, state: machineStates.processing, progress: 100, processingStatus: action.processingStatus ?? "processing", error: "" };
    case "PROCESSING_STATUS":
      return { ...state, processingStatus: action.processingStatus ?? state.processingStatus, error: "" };
    case "READY_TO_PUBLISH":
      return { ...state, state: machineStates.ready_to_publish, processingStatus: "ready", error: "" };
    case "PUBLISH_START":
      return { ...state, state: machineStates.publishing, error: "", lastAction: "publish" };
    case "PUBLISH_SUCCESS":
      return { ...state, state: machineStates.complete, error: "", slug: action.slug ?? state.slug };
    case "SCHEDULED":
      return { ...state, state: machineStates.complete, error: "", lastAction: "schedule", slug: action.slug ?? state.slug };
    case "CANCEL_START":
      return { ...state, isCancelling: true, error: "", lastAction: "cancel" };
    case "CANCELLED":
      return { ...state, state: machineStates.cancelled, isCancelling: false, error: "" };
    case "ERROR":
      return { ...state, state: machineStates.error, isCancelling: false, error: action.error || "Upload failed." };
    case "RESET_MACHINE":
      return { ...initialMachineState };
    default:
      return state;
  }
}
function toPercent(loaded, total) {
  if (!Number.isFinite(total) || total <= 0) return 0;
  return Math.max(0, Math.min(100, Math.round(loaded / total * 100)));
}
function formatChunkSize$1(bytes) {
  if (!Number.isFinite(bytes) || bytes <= 0) return "0 KB";
  if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(bytes % (1024 * 1024) === 0 ? 0 : 1)} MB`;
  return `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
function isRequestTooLarge$1(error) {
  return Number(error?.response?.status || 0) === 413;
}
function getProcessingValue(payload) {
  const direct = String(payload?.processing_state || payload?.status || "").toLowerCase();
  return direct || "processing";
}
function isReadyToPublishStatus(status2) {
  const normalized = String(status2 || "").toLowerCase();
  return ["ready", "processed", "publish_ready", "published", "complete"].includes(normalized);
}
function useUploadMachine$1({
  primaryFile,
  screenshots = [],
  selectedScreenshotIndex = 0,
  canStartUpload,
  primaryType,
  isArchive,
  initialDraftId = null,
  metadata,
  chunkSize = DEFAULT_CHUNK_SIZE_BYTES,
  chunkRequestTimeoutMs = DEFAULT_CHUNK_REQUEST_TIMEOUT_MS$1,
  onArtworkCreated,
  onNotice
}) {
  const [machine, dispatchMachine] = reactExports.useReducer(machineReducer, initialMachineState);
  const pollingTimerRef = reactExports.useRef(null);
  const requestControllersRef = reactExports.useRef(/* @__PURE__ */ new Set());
  const publishLockRef = reactExports.useRef(false);
  const archiveSessionRef = reactExports.useRef({ sessionId: null, uploadToken: null });
  const additionalScreenshotSessionsRef = reactExports.useRef([]);
  const resolvedArtworkIdRef = reactExports.useRef(
    (() => {
      const parsed = Number(initialDraftId);
      return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : null;
    })()
  );
  const effectiveChunkSize = (() => {
    const parsed = Number(chunkSize);
    return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : DEFAULT_CHUNK_SIZE_BYTES;
  })();
  const effectiveChunkRequestTimeoutMs = (() => {
    const parsed = Number(chunkRequestTimeoutMs);
    return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : DEFAULT_CHUNK_REQUEST_TIMEOUT_MS$1;
  })();
  const adaptiveChunkSizeRef = reactExports.useRef(effectiveChunkSize);
  const registerController = reactExports.useCallback(() => {
    const controller = new AbortController();
    requestControllersRef.current.add(controller);
    return controller;
  }, []);
  const unregisterController = reactExports.useCallback((controller) => {
    if (!controller) return;
    requestControllersRef.current.delete(controller);
  }, []);
  const abortAllRequests = reactExports.useCallback(() => {
    requestControllersRef.current.forEach((c) => c.abort());
    requestControllersRef.current.clear();
  }, []);
  const clearArchiveSession = reactExports.useCallback(() => {
    archiveSessionRef.current = { sessionId: null, uploadToken: null };
  }, []);
  const setArchiveSession = reactExports.useCallback((sessionId, uploadToken) => {
    archiveSessionRef.current = { sessionId, uploadToken };
  }, []);
  const clearAdditionalScreenshotSessions = reactExports.useCallback(() => {
    additionalScreenshotSessionsRef.current = [];
  }, []);
  const setAdditionalScreenshotSessions = reactExports.useCallback((sessions) => {
    additionalScreenshotSessionsRef.current = Array.isArray(sessions) ? sessions : [];
  }, []);
  const clearPolling = reactExports.useCallback(() => {
    if (pollingTimerRef.current) {
      window.clearInterval(pollingTimerRef.current);
      pollingTimerRef.current = null;
    }
  }, []);
  const fetchProcessingStatus = reactExports.useCallback(async (sessionId, uploadToken, signal) => {
    const response = await window.axios.get(status(sessionId), {
      signal,
      headers: uploadToken ? { "X-Upload-Token": uploadToken } : void 0,
      params: uploadToken ? { upload_token: uploadToken } : void 0
    });
    return response.data || {};
  }, []);
  const pollProcessing = reactExports.useCallback(async (sessionId, uploadToken) => {
    if (!sessionId) return;
    try {
      const statusController = registerController();
      const payload = await fetchProcessingStatus(sessionId, uploadToken, statusController.signal);
      unregisterController(statusController);
      const processingValue = getProcessingValue(payload);
      dispatchMachine({ type: "PROCESSING_STATUS", processingStatus: processingValue });
      if (isReadyToPublishStatus(processingValue)) {
        dispatchMachine({ type: "READY_TO_PUBLISH" });
        clearPolling();
      } else if (processingValue === "rejected" || processingValue === "error" || payload?.failure_reason) {
        const failureMessage = payload?.failure_reason || payload?.message || `Processing ended with status: ${processingValue}`;
        dispatchMachine({ type: "ERROR", error: failureMessage });
        onNotice?.({ type: "error", message: failureMessage });
        clearPolling();
      }
    } catch (error) {
      if (error?.name === "CanceledError" || error?.code === "ERR_CANCELED") return;
      const notice = mapUploadErrorNotice(error, "Processing status check failed.");
      dispatchMachine({ type: "ERROR", error: notice.message });
      onNotice?.(notice);
      emitUploadEvent("upload_error", { stage: "processing_poll", message: notice.message });
      clearPolling();
    }
  }, [fetchProcessingStatus, registerController, unregisterController, clearPolling, onNotice]);
  const startPolling = reactExports.useCallback((sessionId, uploadToken) => {
    clearPolling();
    pollProcessing(sessionId, uploadToken);
    pollingTimerRef.current = window.setInterval(() => {
      pollProcessing(sessionId, uploadToken);
    }, POLL_INTERVAL_MS);
  }, [clearPolling, pollProcessing]);
  const initUploadSession = reactExports.useCallback(async () => {
    const initController = registerController();
    try {
      const initResponse = await window.axios.post(
        init(),
        { client: "web" },
        { signal: initController.signal }
      );
      const sessionId = initResponse?.data?.session_id;
      const uploadToken = initResponse?.data?.upload_token;
      if (!sessionId || !uploadToken) {
        throw new Error("Upload session initialization returned an invalid payload.");
      }
      return { sessionId, uploadToken };
    } finally {
      unregisterController(initController);
    }
  }, [registerController, unregisterController]);
  const uploadSingleFile = reactExports.useCallback(async (sessionId, uploadToken, file, uploadedBaseBytes, combinedTotalBytes) => {
    let uploadedForFile = 0;
    const totalSize = file.size;
    while (uploadedForFile < totalSize) {
      const activeChunkSize = Math.max(MIN_CHUNK_SIZE_BYTES$1, Number(adaptiveChunkSizeRef.current || effectiveChunkSize));
      const nextOffset = Math.min(uploadedForFile + activeChunkSize, totalSize);
      const blob = file.slice(uploadedForFile, nextOffset);
      const payload = new FormData();
      payload.append("session_id", sessionId);
      payload.append("offset", String(uploadedForFile));
      payload.append("chunk_size", String(blob.size));
      payload.append("total_size", String(totalSize));
      payload.append("upload_token", uploadToken);
      payload.append("chunk", blob);
      const chunkController = registerController();
      try {
        await window.axios.post(chunk(), payload, {
          signal: chunkController.signal,
          timeout: effectiveChunkRequestTimeoutMs,
          headers: { "X-Upload-Token": uploadToken }
        });
      } catch (error) {
        if (isRequestTooLarge$1(error) && activeChunkSize > MIN_CHUNK_SIZE_BYTES$1) {
          const nextChunkSize = Math.max(MIN_CHUNK_SIZE_BYTES$1, Math.floor(activeChunkSize / 2));
          if (nextChunkSize < activeChunkSize) {
            adaptiveChunkSizeRef.current = nextChunkSize;
            onNotice?.({
              type: "warning",
              message: `Server rejected ${formatChunkSize$1(activeChunkSize)} chunks. Retrying with ${formatChunkSize$1(nextChunkSize)} chunks.`
            });
            continue;
          }
        }
        throw error;
      } finally {
        unregisterController(chunkController);
      }
      uploadedForFile = nextOffset;
      const totalUploaded = uploadedBaseBytes + uploadedForFile;
      const progress = Math.max(1, Math.min(95, toPercent(totalUploaded, combinedTotalBytes)));
      dispatchMachine({ type: "UPLOAD_PROGRESS", progress });
    }
    return uploadedBaseBytes + totalSize;
  }, [effectiveChunkRequestTimeoutMs, effectiveChunkSize, onNotice, registerController, unregisterController]);
  const cancelUploadSession = reactExports.useCallback(async (sessionId, uploadToken) => {
    if (!sessionId) return;
    await window.axios.post(
      cancel(),
      { session_id: sessionId, upload_token: uploadToken || void 0 },
      { headers: uploadToken ? { "X-Upload-Token": uploadToken } : void 0 }
    );
  }, []);
  const runUploadFlow = reactExports.useCallback(async () => {
    if (!primaryFile || !canStartUpload) return;
    const normalizedScreenshotIndex = Number.isFinite(selectedScreenshotIndex) ? Math.max(0, Math.floor(selectedScreenshotIndex)) : 0;
    const previewFile = isArchive ? screenshots[normalizedScreenshotIndex] || screenshots[0] || null : primaryFile;
    const archiveFile = isArchive ? primaryFile : null;
    const additionalScreenshotFiles = isArchive ? screenshots.filter((file, index2) => index2 !== normalizedScreenshotIndex && Boolean(file)) : [];
    if (!previewFile) {
      const message = isArchive ? "Archive uploads require at least one screenshot before upload can start." : "A preview image is required before upload can start.";
      dispatchMachine({ type: "ERROR", error: message });
      onNotice?.({ type: "error", message });
      return;
    }
    clearPolling();
    clearArchiveSession();
    clearAdditionalScreenshotSessions();
    dispatchMachine({ type: "INIT_START" });
    emitUploadEvent("upload_start", {
      file_name: primaryFile.name,
      file_size: primaryFile.size,
      file_type: primaryType,
      is_archive: isArchive
    });
    let activePrimarySessionId = null;
    let activePrimaryUploadToken = null;
    let activeArchiveSessionId = null;
    let activeArchiveUploadToken = null;
    let activeAdditionalScreenshotSessions = [];
    try {
      let artworkIdForUpload = resolvedArtworkIdRef.current;
      if (!artworkIdForUpload) {
        const titleSourceFile = archiveFile || primaryFile || previewFile;
        const derivedTitle = String(metadata.title || "").trim() || String(titleSourceFile?.name || "").replace(/\.[^.]+$/, "") || "Untitled upload";
        const draftResponse = await window.axios.post("/api/artworks", {
          title: derivedTitle,
          description: String(metadata.description || "").trim() || null,
          category: metadata.subCategoryId || metadata.rootCategoryId || null,
          tags: Array.isArray(metadata.tags) ? metadata.tags.join(", ") : "",
          license: Boolean(metadata.rightsAccepted),
          is_mature: Boolean(metadata.isMature),
          group: String(metadata.group || "").trim() || null
        });
        const draftIdCandidate = Number(draftResponse?.data?.artwork_id ?? draftResponse?.data?.id);
        if (!Number.isFinite(draftIdCandidate) || draftIdCandidate <= 0) {
          throw new Error("Unable to create upload draft before finishing upload.");
        }
        artworkIdForUpload = Math.floor(draftIdCandidate);
        resolvedArtworkIdRef.current = artworkIdForUpload;
        onArtworkCreated?.(artworkIdForUpload);
      }
      const { sessionId, uploadToken } = await initUploadSession();
      activePrimarySessionId = sessionId;
      activePrimaryUploadToken = uploadToken;
      dispatchMachine({ type: "INIT_SUCCESS", sessionId, uploadToken });
      dispatchMachine({ type: "UPLOAD_START" });
      const combinedTotalBytes = previewFile.size + (archiveFile?.size || 0) + additionalScreenshotFiles.reduce((sum, file) => sum + (file?.size || 0), 0);
      let uploadedBytes = await uploadSingleFile(sessionId, uploadToken, previewFile, 0, combinedTotalBytes);
      let archiveSessionId = null;
      let archiveUploadToken = null;
      if (archiveFile) {
        const archiveSession = await initUploadSession();
        archiveSessionId = archiveSession.sessionId;
        archiveUploadToken = archiveSession.uploadToken;
        activeArchiveSessionId = archiveSessionId;
        activeArchiveUploadToken = archiveUploadToken;
        setArchiveSession(archiveSessionId, archiveUploadToken);
        uploadedBytes = await uploadSingleFile(archiveSessionId, archiveUploadToken, archiveFile, uploadedBytes, combinedTotalBytes);
      }
      const additionalScreenshotSessions = [];
      for (const screenshotFile of additionalScreenshotFiles) {
        const screenshotSession = await initUploadSession();
        additionalScreenshotSessions.push({
          sessionId: screenshotSession.sessionId,
          uploadToken: screenshotSession.uploadToken,
          fileName: String(screenshotFile?.name || "")
        });
        activeAdditionalScreenshotSessions = additionalScreenshotSessions;
        setAdditionalScreenshotSessions(additionalScreenshotSessions);
        uploadedBytes = await uploadSingleFile(
          screenshotSession.sessionId,
          screenshotSession.uploadToken,
          screenshotFile,
          uploadedBytes,
          combinedTotalBytes
        );
      }
      dispatchMachine({ type: "FINISH_START" });
      const finishController = registerController();
      const finishResponse = await window.axios.post(
        finish(),
        {
          session_id: sessionId,
          upload_token: uploadToken,
          artwork_id: artworkIdForUpload,
          file_name: String(previewFile?.name || ""),
          archive_session_id: archiveSessionId,
          archive_file_name: archiveFile ? String(archiveFile?.name || "") : void 0,
          additional_screenshot_sessions: additionalScreenshotSessions.map((item) => ({
            session_id: item.sessionId,
            file_name: item.fileName
          }))
        },
        { signal: finishController.signal, headers: { "X-Upload-Token": uploadToken } }
      );
      unregisterController(finishController);
      const finishStatus = getProcessingValue(finishResponse?.data || {});
      dispatchMachine({ type: "FINISH_SUCCESS", processingStatus: finishStatus });
      const finishNotice = mapUploadResultNotice(finishResponse?.data || {}, {
        fallbackType: finishStatus === "queued" ? "warning" : "success",
        fallbackMessage: finishStatus === "queued" ? "Upload received. Processing is queued." : "Upload completed successfully."
      });
      onNotice?.(finishNotice);
      if (isReadyToPublishStatus(finishStatus)) {
        dispatchMachine({ type: "READY_TO_PUBLISH" });
      } else {
        startPolling(sessionId, uploadToken);
      }
      emitUploadEvent("upload_complete", { session_id: sessionId, artwork_id: artworkIdForUpload });
    } catch (error) {
      if (error?.name === "CanceledError" || error?.code === "ERR_CANCELED") return;
      await Promise.allSettled([
        cancelUploadSession(activePrimarySessionId, activePrimaryUploadToken),
        cancelUploadSession(activeArchiveSessionId, activeArchiveUploadToken),
        ...activeAdditionalScreenshotSessions.map((item) => cancelUploadSession(item.sessionId, item.uploadToken))
      ]);
      const notice = mapUploadErrorNotice(error, "Upload failed.");
      dispatchMachine({ type: "ERROR", error: notice.message });
      onNotice?.(notice);
      emitUploadEvent("upload_error", { stage: "upload_flow", message: notice.message });
    }
  }, [
    primaryFile,
    screenshots,
    selectedScreenshotIndex,
    canStartUpload,
    primaryType,
    isArchive,
    metadata,
    clearPolling,
    clearArchiveSession,
    startPolling,
    onArtworkCreated,
    onNotice,
    initUploadSession,
    uploadSingleFile,
    setArchiveSession,
    cancelUploadSession
  ]);
  const handleCancel = reactExports.useCallback(async () => {
    dispatchMachine({ type: "CANCEL_START" });
    clearPolling();
    abortAllRequests();
    try {
      const { sessionId, uploadToken } = machine;
      const archiveSessionId = archiveSessionRef.current.sessionId;
      const archiveUploadToken = archiveSessionRef.current.uploadToken;
      const additionalScreenshotSessions = additionalScreenshotSessionsRef.current;
      await Promise.allSettled([
        cancelUploadSession(sessionId, uploadToken),
        cancelUploadSession(archiveSessionId, archiveUploadToken),
        ...additionalScreenshotSessions.map((item) => cancelUploadSession(item.sessionId, item.uploadToken))
      ]);
      clearArchiveSession();
      clearAdditionalScreenshotSessions();
      dispatchMachine({ type: "CANCELLED" });
      onNotice?.({ type: "warning", message: "Upload cancelled." });
      emitUploadEvent("upload_cancel", { session_id: machine.sessionId || null });
    } catch (error) {
      const notice = mapUploadErrorNotice(error, "Cancel failed.");
      dispatchMachine({ type: "ERROR", error: notice.message });
      onNotice?.(notice);
      emitUploadEvent("upload_error", { stage: "cancel", message: notice.message });
    }
  }, [machine, abortAllRequests, clearPolling, onNotice, cancelUploadSession, clearArchiveSession, clearAdditionalScreenshotSessions]);
  const handlePublish = reactExports.useCallback(async (canPublish, opts = {}) => {
    if (!canPublish || publishLockRef.current) return;
    publishLockRef.current = true;
    dispatchMachine({ type: "PUBLISH_START" });
    const { mode = "now", publishAt = null, timezone = null, visibility = "public", action = "publish" } = opts;
    const resolvedCategoryId = metadata.subCategoryId || metadata.rootCategoryId || null;
    const buildPayload2 = () => ({
      title: String(metadata.title || "").trim() || void 0,
      description: String(metadata.description || "").trim() || null,
      category: resolvedCategoryId ? String(resolvedCategoryId) : null,
      tags: Array.isArray(metadata.tags) ? metadata.tags : [],
      is_mature: Boolean(metadata.isMature),
      group: String(metadata.group || "").trim() || null,
      primary_author_user_id: metadata.primaryAuthorUserId ? Number(metadata.primaryAuthorUserId) : null,
      contributor_user_ids: Array.isArray(metadata.contributorUserIds) ? metadata.contributorUserIds.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0) : [],
      contributor_credits: Array.isArray(metadata.contributorUserIds) ? metadata.contributorUserIds.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0).map((id) => {
        const creditMeta = metadata.contributorCredits?.[id] || metadata.contributorCredits?.[String(id)] || {};
        return {
          user_id: id,
          credit_role: typeof creditMeta.creditRole === "string" && creditMeta.creditRole.trim() !== "" ? creditMeta.creditRole.trim() : null,
          is_primary: Boolean(creditMeta.isPrimary)
        };
      }) : [],
      mode,
      ...mode === "schedule" && publishAt ? { publish_at: publishAt } : {},
      ...timezone ? { timezone } : {},
      visibility,
      world_submissions: Array.isArray(metadata.worldSubmissions) ? metadata.worldSubmissions.filter((world) => Boolean(world?.selected)).map((world) => ({
        world_id: Number(world.id),
        note: typeof world.note === "string" ? world.note : "",
        source_surface: "upload_flow"
      })).filter((entry) => Number.isFinite(entry.world_id) && entry.world_id > 0) : []
    });
    try {
      const publishTargetId = resolvedArtworkIdRef.current || initialDraftId || machine.sessionId;
      if (resolvedArtworkIdRef.current && resolvedArtworkIdRef.current > 0) {
        const publishController2 = registerController();
        const publishRes = await window.axios.post(
          action === "submit_review" ? submitReview(String(resolvedArtworkIdRef.current)) : publish(String(resolvedArtworkIdRef.current)),
          buildPayload2(),
          { signal: publishController2.signal }
        );
        unregisterController(publishController2);
        const publishedSlug = publishRes?.data?.slug ?? null;
        dispatchMachine({ type: mode === "schedule" ? "SCHEDULED" : "PUBLISH_SUCCESS", slug: publishedSlug });
        onNotice?.(mapUploadResultNotice(publishRes?.data || {}, {
          fallbackType: "success",
          fallbackMessage: action === "submit_review" ? "Artwork submitted for group review." : mode === "schedule" ? "Artwork scheduled successfully." : "Artwork published successfully."
        }));
        emitUploadEvent(action === "submit_review" ? "upload_submit_review" : "upload_publish", { id: publishTargetId, mode });
        return;
      }
      if (!publishTargetId) throw new Error("Missing publish id.");
      const publishController = registerController();
      const publishRes2 = await window.axios.post(
        action === "submit_review" ? submitReview(publishTargetId) : publish(publishTargetId),
        buildPayload2(),
        { signal: publishController.signal }
      );
      unregisterController(publishController);
      const publishedSlug2 = publishRes2?.data?.slug ?? null;
      dispatchMachine({ type: mode === "schedule" ? "SCHEDULED" : "PUBLISH_SUCCESS", slug: publishedSlug2 });
      onNotice?.(mapUploadResultNotice(publishRes2?.data || {}, {
        fallbackType: "success",
        fallbackMessage: action === "submit_review" ? "Artwork submitted for group review." : mode === "schedule" ? "Artwork scheduled successfully." : "Artwork published successfully."
      }));
      emitUploadEvent(action === "submit_review" ? "upload_submit_review" : "upload_publish", { id: publishTargetId, mode });
    } catch (error) {
      if (error?.name === "CanceledError" || error?.code === "ERR_CANCELED") return;
      const notice = mapUploadErrorNotice(error, "Publish failed.");
      dispatchMachine({ type: "ERROR", error: notice.message });
      onNotice?.(notice);
      emitUploadEvent("upload_error", { stage: "publish", message: notice.message });
    } finally {
      publishLockRef.current = false;
    }
  }, [machine, initialDraftId, metadata, registerController, unregisterController, onNotice]);
  const resetMachine = reactExports.useCallback(() => {
    clearPolling();
    abortAllRequests();
    resolvedArtworkIdRef.current = (() => {
      const parsed = Number(initialDraftId);
      return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : null;
    })();
    clearArchiveSession();
    clearAdditionalScreenshotSessions();
    publishLockRef.current = false;
    dispatchMachine({ type: "RESET_MACHINE" });
  }, [clearPolling, abortAllRequests, initialDraftId, clearArchiveSession, clearAdditionalScreenshotSessions]);
  const handleRetry = reactExports.useCallback((canPublish, opts = {}) => {
    clearPolling();
    abortAllRequests();
    if (machine.lastAction === "publish") {
      handlePublish(canPublish, opts);
      return;
    }
    runUploadFlow();
  }, [machine.lastAction, handlePublish, runUploadFlow, clearPolling, abortAllRequests]);
  return {
    machine,
    dispatchMachine,
    resolvedArtworkId: resolvedArtworkIdRef.current,
    runUploadFlow,
    handleCancel,
    handlePublish,
    handleRetry,
    resetMachine,
    clearPolling,
    abortAllRequests,
    startPolling
  };
}
const IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["jpg", "jpeg", "png", "webp"]);
const IMAGE_MIME = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);
const ARCHIVE_EXTENSIONS = /* @__PURE__ */ new Set(["zip", "rar", "7z", "tar", "gz"]);
const ARCHIVE_MIME = /* @__PURE__ */ new Set([
  "application/zip",
  "application/x-zip-compressed",
  "application/x-rar-compressed",
  "application/vnd.rar",
  "application/x-7z-compressed",
  "application/x-tar",
  "application/gzip",
  "application/x-gzip",
  "application/octet-stream"
]);
const PRIMARY_IMAGE_MAX_BYTES = 50 * 1024 * 1024;
const PRIMARY_ARCHIVE_MAX_BYTES = 200 * 1024 * 1024;
const SCREENSHOT_MAX_BYTES = 10 * 1024 * 1024;
function getExtension$1(fileName = "") {
  const parts = String(fileName).toLowerCase().split(".");
  return parts.length > 1 ? parts.pop() : "";
}
function detectFileType(file) {
  if (!file) return "unknown";
  const extension2 = getExtension$1(file.name);
  const mime = String(file.type || "").toLowerCase();
  if (IMAGE_MIME.has(mime) || IMAGE_EXTENSIONS.has(extension2)) return "image";
  if (ARCHIVE_MIME.has(mime) || ARCHIVE_EXTENSIONS.has(extension2)) return "archive";
  return "unsupported";
}
function formatBytes(bytes) {
  if (!Number.isFinite(bytes) || bytes <= 0) return "—";
  if (bytes < 1024) return `${bytes} B`;
  const kb = bytes / 1024;
  if (kb < 1024) return `${kb.toFixed(1)} KB`;
  const mb = kb / 1024;
  if (mb < 1024) return `${mb.toFixed(1)} MB`;
  return `${(mb / 1024).toFixed(2)} GB`;
}
function readImageDimensions(file) {
  return new Promise((resolve, reject) => {
    const blobUrl = URL.createObjectURL(file);
    const img = new Image();
    img.onload = () => {
      resolve({ width: img.naturalWidth, height: img.naturalHeight });
      URL.revokeObjectURL(blobUrl);
    };
    img.onerror = () => {
      reject(new Error("image_read_failed"));
      URL.revokeObjectURL(blobUrl);
    };
    img.src = blobUrl;
  });
}
function buildCategoryTree(contentTypes = []) {
  const rootsById = /* @__PURE__ */ new Map();
  contentTypes.forEach((type2) => {
    const categories = Array.isArray(type2?.categories) ? type2.categories : [];
    categories.forEach((category) => {
      if (!category?.id) return;
      const key = String(category.id);
      if (!rootsById.has(key)) {
        rootsById.set(key, {
          id: key,
          name: category.name || `Category ${category.id}`,
          children: []
        });
      }
      const root2 = rootsById.get(key);
      const children = Array.isArray(category?.children) ? category.children : [];
      children.forEach((child) => {
        if (!child?.id) return;
        const exists = root2.children.some((item) => String(item.id) === String(child.id));
        if (!exists) {
          root2.children.push({ id: String(child.id), name: child.name || `Subcategory ${child.id}` });
        }
      });
    });
  });
  return Array.from(rootsById.values());
}
function getContentTypeValue(type2) {
  if (!type2) return "";
  return String(type2.id ?? type2.key ?? type2.slug ?? type2.name ?? "");
}
function getContentTypeVisualKey(type2) {
  const raw = String(type2?.slug || type2?.name || type2?.key || "").toLowerCase();
  const normalized = raw.replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "");
  if (normalized.includes("wallpaper")) return "wallpapers";
  if (normalized.includes("skin")) return "skins";
  if (normalized.includes("photo")) return "photography";
  return "other";
}
function getProcessingTransparencyLabel(processingStatus, machineState) {
  if (!["processing", "finishing", "publishing"].includes(machineState)) return "";
  const normalized = String(processingStatus || "").toLowerCase();
  if (normalized === "generating_preview") return "Generating preview";
  if (["processed", "ready", "published", "queued", "publish_ready"].includes(normalized)) {
    return "Preparing for publish";
  }
  return "Analyzing content";
}
async function validatePrimaryFile(file) {
  const errors = [];
  const warnings = [];
  const type2 = detectFileType(file);
  if (!file) {
    return {
      type: "unknown",
      errors: [],
      warnings,
      metadata: { resolution: "—", size: "—", type: "—" },
      previewUrl: ""
    };
  }
  const metadata = {
    resolution: "—",
    size: formatBytes(file.size),
    type: file.type || getExtension$1(file.name) || "unknown"
  };
  if (type2 === "unsupported") {
    errors.push("Unsupported file type. Use image (jpg/jpeg/png/webp) or archive (zip/rar/7z/tar/gz).");
  }
  if (type2 === "image") {
    if (file.size > PRIMARY_IMAGE_MAX_BYTES) {
      errors.push("Image exceeds 50MB maximum size.");
    }
    try {
      const dimensions = await readImageDimensions(file);
      metadata.resolution = `${dimensions.width} × ${dimensions.height}`;
      if (dimensions.width < 800 || dimensions.height < 600) {
        errors.push("Image resolution must be at least 800×600.");
      }
    } catch {
      errors.push("Unable to read image resolution.");
    }
  }
  if (type2 === "archive") {
    metadata.resolution = "n/a";
    if (file.size > PRIMARY_ARCHIVE_MAX_BYTES) {
      errors.push("Archive exceeds 200MB maximum size.");
    }
    warnings.push("Archive upload requires at least one valid screenshot.");
  }
  const previewUrl = type2 === "image" ? URL.createObjectURL(file) : "";
  return { type: type2, errors, warnings, metadata, previewUrl };
}
async function validateScreenshots(files, isArchive) {
  if (!isArchive) return { errors: [], perFileErrors: [] };
  const errors = [];
  const perFileErrors = Array.from({ length: files.length }, () => "");
  if (files.length < 1) errors.push("At least one screenshot is required for archives.");
  if (files.length > 5) errors.push("Maximum 5 screenshots are allowed.");
  await Promise.all(
    files.map(async (file, index2) => {
      const typeErrors = [];
      const extension2 = getExtension$1(file.name);
      const mime = String(file.type || "").toLowerCase();
      if (!IMAGE_MIME.has(mime) && !IMAGE_EXTENSIONS.has(extension2)) {
        typeErrors.push("Must be JPG, PNG, or WEBP.");
      }
      if (file.size > SCREENSHOT_MAX_BYTES) {
        typeErrors.push("Must be 10MB or less.");
      }
      if (typeErrors.length === 0) {
        try {
          const dimensions = await readImageDimensions(file);
          if (dimensions.width < 1280 || dimensions.height < 720) {
            typeErrors.push("Minimum resolution is 1280×720.");
          }
        } catch {
          typeErrors.push("Could not read screenshot resolution.");
        }
      }
      if (typeErrors.length > 0) {
        perFileErrors[index2] = typeErrors.join(" ");
      }
    })
  );
  if (perFileErrors.some(Boolean)) {
    errors.push("One or more screenshots are invalid.");
  }
  return { errors, perFileErrors };
}
function useFileValidation(primaryFile, screenshots, isArchive) {
  const [primaryType, setPrimaryType] = reactExports.useState("unknown");
  const [primaryErrors, setPrimaryErrors] = reactExports.useState([]);
  const [primaryWarnings, setPrimaryWarnings] = reactExports.useState([]);
  const [fileMetadata, setFileMetadata] = reactExports.useState({ resolution: "—", size: "—", type: "—" });
  const [primaryPreviewUrl, setPrimaryPreviewUrl] = reactExports.useState("");
  const [screenshotErrors, setScreenshotErrors] = reactExports.useState([]);
  const [screenshotPerFileErrors, setScreenshotPerFileErrors] = reactExports.useState([]);
  const primaryRunRef = reactExports.useRef(0);
  const screenshotRunRef = reactExports.useRef(0);
  const effectiveIsArchive = detectFileType(primaryFile) === "archive";
  reactExports.useEffect(() => {
    primaryRunRef.current += 1;
    const runId = primaryRunRef.current;
    let cancelled = false;
    (async () => {
      const result = await validatePrimaryFile(primaryFile);
      if (cancelled || runId !== primaryRunRef.current) return;
      setPrimaryType(result.type);
      setPrimaryWarnings(result.warnings);
      setPrimaryErrors(result.errors);
      setFileMetadata(result.metadata);
      setPrimaryPreviewUrl((current) => {
        if (current) URL.revokeObjectURL(current);
        return result.previewUrl;
      });
    })();
    return () => {
      cancelled = true;
    };
  }, [primaryFile]);
  reactExports.useEffect(() => {
    screenshotRunRef.current += 1;
    const runId = screenshotRunRef.current;
    let cancelled = false;
    (async () => {
      const result = await validateScreenshots(screenshots, effectiveIsArchive);
      if (cancelled || runId !== screenshotRunRef.current) return;
      setScreenshotErrors(result.errors);
      setScreenshotPerFileErrors(result.perFileErrors);
    })();
    return () => {
      cancelled = true;
    };
  }, [screenshots, effectiveIsArchive]);
  reactExports.useEffect(() => {
    if (!effectiveIsArchive) {
      setScreenshotErrors([]);
      setScreenshotPerFileErrors([]);
    }
  }, [effectiveIsArchive]);
  reactExports.useEffect(() => {
    return () => {
      if (primaryPreviewUrl) URL.revokeObjectURL(primaryPreviewUrl);
    };
  }, []);
  return {
    primaryType,
    primaryErrors,
    primaryWarnings,
    fileMetadata,
    primaryPreviewUrl,
    screenshotErrors,
    screenshotPerFileErrors
  };
}
const VISION_POLL_INTERVAL_MS = 5e3;
const VISION_DEBOUNCE_MS = 3e3;
const initialDebug = {
  enabled: null,
  queueConnection: "",
  queuedJobs: 0,
  failedJobs: 0,
  triggered: false,
  aiTagCount: 0,
  totalTagCount: 0,
  syncDone: false,
  lastError: ""
};
function useVisionTags(artworkId, uploadReady) {
  const [visionSuggestedTags, setVisionSuggestedTags] = reactExports.useState([]);
  const [visionDebug, setVisionDebug] = reactExports.useState(initialDebug);
  const syncDoneRef = reactExports.useRef(false);
  const lastPollAtRef = reactExports.useRef(0);
  const abortRef = reactExports.useRef(null);
  const mergeTags = reactExports.useCallback((incoming) => {
    setVisionSuggestedTags((prev) => {
      if (!incoming.length) return prev;
      const seen = new Set(prev.map((t) => t?.slug || t?.name || t));
      const next = [...prev];
      for (const tag of incoming) {
        const key = tag?.slug || tag?.name || tag;
        if (!seen.has(key)) {
          seen.add(key);
          next.push(tag);
        }
      }
      return next;
    });
  }, []);
  const callGatewaySync = reactExports.useCallback(async () => {
    if (!artworkId || artworkId <= 0 || syncDoneRef.current) return;
    syncDoneRef.current = true;
    if (abortRef.current) abortRef.current.abort();
    abortRef.current = new AbortController();
    try {
      const response = await window.axios.post(
        `/api/uploads/${artworkId}/vision-suggest`,
        {},
        { signal: abortRef.current.signal }
      );
      const payload = response?.data || {};
      if (payload?.vision_enabled === false) {
        setVisionDebug((prev) => ({ ...prev, enabled: false, syncDone: true }));
        return;
      }
      const tags = Array.isArray(payload?.tags) ? payload.tags : [];
      mergeTags(tags);
      setVisionDebug((prev) => ({
        ...prev,
        enabled: true,
        syncDone: true,
        aiTagCount: Math.max(prev.aiTagCount, tags.length)
      }));
      window.console?.debug?.("[upload][vision-tags][sync]", {
        artworkId,
        count: tags.length,
        source: payload?.source
      });
    } catch (err) {
      if (err?.code === "ERR_CANCELED") return;
      setVisionDebug((prev) => ({
        ...prev,
        syncDone: true,
        lastError: err?.response?.data?.reason || err?.message || ""
      }));
    }
  }, [artworkId, mergeTags]);
  const pollDbTags = reactExports.useCallback(async () => {
    if (!artworkId || artworkId <= 0) return;
    const now = Date.now();
    if (now - lastPollAtRef.current < VISION_DEBOUNCE_MS) return;
    lastPollAtRef.current = now;
    try {
      const response = await window.axios.get(`/api/artworks/${artworkId}/tags`, {
        params: { trigger: 1 }
      });
      const payload = response?.data || {};
      if (payload?.vision_enabled === false) {
        setVisionDebug((prev) => ({ ...prev, enabled: false }));
        return;
      }
      const aiTags = Array.isArray(payload?.ai_tags) ? payload.ai_tags : [];
      mergeTags(aiTags);
      const debug = payload?.debug || {};
      setVisionDebug((prev) => ({
        ...prev,
        enabled: Boolean(payload?.vision_enabled),
        queueConnection: String(debug?.queue_connection || prev.queueConnection),
        queuedJobs: Number(debug?.queued_jobs ?? prev.queuedJobs),
        failedJobs: Number(debug?.failed_jobs ?? prev.failedJobs),
        triggered: Boolean(debug?.triggered),
        aiTagCount: Math.max(prev.aiTagCount, Number(debug?.ai_tag_count || aiTags.length || 0)),
        totalTagCount: Number(debug?.total_tag_count || 0),
        lastError: ""
      }));
      window.console?.debug?.("[upload][vision-tags][poll]", {
        artworkId,
        aiTags: aiTags.map((t) => t?.slug || t?.name || t)
      });
    } catch (err) {
      if (err?.response?.status === 404 || err?.response?.status === 403) return;
      setVisionDebug((prev) => ({
        ...prev,
        lastError: err?.response?.data?.message || err?.message || ""
      }));
    }
  }, [artworkId, mergeTags]);
  reactExports.useEffect(() => {
    if (!artworkId || !uploadReady) return;
    callGatewaySync();
    pollDbTags();
    const timer = window.setInterval(pollDbTags, VISION_POLL_INTERVAL_MS);
    return () => {
      window.clearInterval(timer);
      abortRef.current?.abort();
    };
  }, [artworkId, uploadReady, callGatewaySync, pollDbTags]);
  reactExports.useEffect(() => {
    syncDoneRef.current = false;
    lastPollAtRef.current = 0;
    setVisionSuggestedTags([]);
    setVisionDebug(initialDebug);
  }, [artworkId]);
  return { visionSuggestedTags, visionDebug };
}
const STATE_LABELS = {
  idle: null,
  initializing: "Initializing…",
  uploading: "Uploading",
  finishing: "Finishing…",
  processing: "Processing",
  ready_to_publish: "Ready",
  publishing: "Publishing…",
  complete: "Published",
  error: "Error",
  cancelled: "Cancelled"
};
const STATE_COLORS = {
  idle: "",
  initializing: "bg-sky-500/20 text-sky-200 border-sky-300/30",
  uploading: "bg-sky-500/25 text-sky-100 border-sky-300/40",
  finishing: "bg-sky-400/20 text-sky-200 border-sky-300/30",
  processing: "bg-amber-500/20 text-amber-100 border-amber-300/30",
  ready_to_publish: "bg-emerald-500/20 text-emerald-100 border-emerald-300/35",
  publishing: "bg-sky-500/25 text-sky-100 border-sky-300/40",
  complete: "bg-emerald-500/25 text-emerald-100 border-emerald-300/50",
  error: "bg-red-500/20 text-red-200 border-red-300/30",
  cancelled: "bg-white/8 text-white/50 border-white/15"
};
function StudioStatusBar({
  steps = [],
  activeStep = 1,
  highestUnlockedStep = 1,
  machineState = "idle",
  progress = 0,
  showProgress = false,
  onStepClick
}) {
  const prefersReducedMotion = useReducedMotion();
  const transition = prefersReducedMotion ? { duration: 0 } : { duration: 0.3, ease: "easeOut" };
  const stateLabel = STATE_LABELS[machineState] ?? machineState;
  const stateColor = STATE_COLORS[machineState] ?? "bg-white/8 text-white/50 border-white/15";
  return /* @__PURE__ */ React.createElement("div", { className: "sticky top-0 z-20 -mx-4 px-4 pb-0 pt-2 sm:-mx-6 sm:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-slate-950/80 backdrop-blur-md", "aria-hidden": "true" }), /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[24px] border border-white/8 bg-[linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.02))] px-3 shadow-[0_14px_44px_rgba(2,8,23,0.24)] sm:px-4" }, /* @__PURE__ */ React.createElement("nav", { "aria-label": "Upload steps" }, /* @__PURE__ */ React.createElement("ol", { className: "flex flex-nowrap items-center gap-2 overflow-x-auto py-3 pr-1 sm:gap-3" }, steps.map((step, index2) => {
    const number2 = index2 + 1;
    const isActive = number2 === activeStep;
    const isComplete = number2 < activeStep;
    const isLocked = number2 > highestUnlockedStep;
    const canNavigate = !isLocked && number2 < activeStep;
    const btnClass = [
      "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] sm:text-xs transition",
      isActive ? "border-sky-300/70 bg-sky-500/25 text-white shadow-[0_10px_30px_rgba(14,165,233,0.14)]" : isComplete ? "border-emerald-300/30 bg-emerald-500/15 text-emerald-100 hover:bg-emerald-500/25 cursor-pointer" : isLocked ? "cursor-default border-white/10 bg-white/5 text-white/35 pointer-events-none" : "border-white/15 bg-white/6 text-white/70 hover:bg-white/12 cursor-pointer"
    ].join(" ");
    const circleClass = isComplete ? "border-emerald-300/50 bg-emerald-500/20 text-emerald-100" : isActive ? "border-sky-300/50 bg-sky-500/25 text-white" : "border-white/20 bg-white/6 text-white/60";
    return /* @__PURE__ */ React.createElement("li", { key: step.key, className: "flex shrink-0 items-center gap-2" }, /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => canNavigate && onStepClick?.(number2),
        disabled: isLocked,
        "aria-disabled": isLocked,
        "aria-current": isActive ? "step" : void 0,
        className: btnClass
      },
      /* @__PURE__ */ React.createElement("span", { className: `grid h-4 w-4 place-items-center rounded-full border text-[10px] shrink-0 ${circleClass}` }, isComplete ? "✓" : number2),
      /* @__PURE__ */ React.createElement("span", { className: "whitespace-nowrap" }, step.label)
    ), index2 < steps.length - 1 && /* @__PURE__ */ React.createElement("span", { className: "text-white/30 select-none text-xs", "aria-hidden": "true" }, "›"));
  }), /* @__PURE__ */ React.createElement("li", { className: "flex-1", "aria-hidden": "true" }), stateLabel && /* @__PURE__ */ React.createElement("li", { className: "shrink-0" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] ${stateColor}` }, ["uploading", "initializing", "finishing", "processing", "publishing"].includes(machineState) && /* @__PURE__ */ React.createElement("span", { className: "relative flex h-2 w-2 shrink-0", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("span", { className: "absolute inline-flex h-full w-full animate-ping rounded-full bg-sky-300 opacity-60" }), /* @__PURE__ */ React.createElement("span", { className: "relative inline-flex h-2 w-2 rounded-full bg-sky-300" })), stateLabel)))), showProgress && /* @__PURE__ */ React.createElement("div", { className: "mb-2 h-1 w-full overflow-hidden rounded-full bg-white/8" }, /* @__PURE__ */ React.createElement(
    motion.div,
    {
      className: "h-full rounded-full bg-gradient-to-r from-sky-400 via-cyan-300 to-emerald-300",
      animate: { width: `${progress}%` },
      transition
    }
  ))));
}
const ACTIVE_STATES = /* @__PURE__ */ new Set([
  "initializing",
  "uploading",
  "finishing",
  "processing"
]);
const STATE_META = {
  initializing: {
    label: "Initializing",
    sublabel: "Preparing your upload…",
    color: "text-sky-300",
    barColor: "from-sky-500 via-sky-400 to-cyan-300",
    icon: /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0 animate-spin", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("circle", { className: "opacity-20", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3" }), /* @__PURE__ */ React.createElement("path", { className: "opacity-80", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" }))
  },
  uploading: {
    label: "Uploading",
    sublabel: "Sending your file to the server…",
    color: "text-sky-300",
    barColor: "from-sky-500 via-cyan-400 to-teal-300",
    icon: /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M10 3a1 1 0 011 1v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 111.414-1.414L9 11.586V4a1 1 0 011-1zM3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z", clipRule: "evenodd" }))
  },
  finishing: {
    label: "Finishing",
    sublabel: "Wrapping up the transfer…",
    color: "text-cyan-300",
    barColor: "from-cyan-500 via-teal-400 to-emerald-300",
    icon: /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0 animate-spin", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("circle", { className: "opacity-20", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "3" }), /* @__PURE__ */ React.createElement("path", { className: "opacity-80", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" }))
  },
  processing: {
    label: "Processing",
    sublabel: "Analyzing your artwork…",
    color: "text-amber-300",
    barColor: "from-amber-500 via-yellow-400 to-lime-300",
    icon: /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z", clipRule: "evenodd" }))
  },
  error: {
    label: "Upload failed",
    sublabel: null,
    color: "text-rose-300",
    barColor: "from-rose-600 via-rose-500 to-rose-400",
    icon: /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z", clipRule: "evenodd" }))
  }
};
function UploadOverlay({
  machineState = "idle",
  progress = 0,
  processingLabel = null,
  error = null,
  onRetry,
  onReset
}) {
  const prefersReducedMotion = useReducedMotion();
  const isVisible = ACTIVE_STATES.has(machineState) || machineState === "error";
  const meta = STATE_META[machineState] ?? STATE_META.uploading;
  const barTransition = prefersReducedMotion ? { duration: 0 } : { duration: 0.4, ease: "easeOut" };
  const overlayTransition = prefersReducedMotion ? { duration: 0 } : { duration: 0.25, ease: [0.32, 0.72, 0, 1] };
  const displayLabel = processingLabel || meta.sublabel;
  return /* @__PURE__ */ React.createElement(AnimatePresence, { initial: false }, isVisible && /* @__PURE__ */ React.createElement(
    motion.div,
    {
      key: "upload-overlay",
      initial: prefersReducedMotion ? false : { opacity: 0 },
      animate: { opacity: 1 },
      exit: prefersReducedMotion ? {} : { opacity: 0 },
      transition: overlayTransition,
      className: "fixed inset-0 z-[80] flex items-center justify-center p-4 sm:p-6"
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-slate-950/72 backdrop-blur-sm", "aria-hidden": "true" }),
    /* @__PURE__ */ React.createElement(
      motion.div,
      {
        role: "dialog",
        "aria-modal": "true",
        "aria-labelledby": "upload-overlay-title",
        "aria-describedby": "upload-overlay-description",
        initial: prefersReducedMotion ? false : { opacity: 0, y: 18, scale: 0.97 },
        animate: { opacity: 1, y: 0, scale: 1 },
        exit: prefersReducedMotion ? {} : { opacity: 0, y: 12, scale: 0.98 },
        transition: overlayTransition,
        className: "relative w-full max-w-xl overflow-hidden rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(6,14,24,0.96),rgba(2,8,23,0.92))] px-5 pb-5 pt-5 shadow-[0_30px_120px_rgba(2,8,23,0.72)] ring-1 ring-inset ring-white/8 backdrop-blur-xl sm:px-6 sm:pb-6 sm:pt-6"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          role: "status",
          "aria-live": "polite",
          "aria-label": `${meta.label}${progress > 0 ? ` — ${progress}%` : ""}`
        },
        /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: `flex items-center gap-2 ${meta.color}` }, meta.icon, /* @__PURE__ */ React.createElement("span", { id: "upload-overlay-title", className: "text-xl font-semibold tracking-tight" }, meta.label), machineState !== "error" && /* @__PURE__ */ React.createElement("span", { className: "relative flex h-2.5 w-2.5 shrink-0", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("span", { className: "absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-50" }), /* @__PURE__ */ React.createElement("span", { className: "relative inline-flex h-2.5 w-2.5 rounded-full bg-current opacity-80" }))), /* @__PURE__ */ React.createElement("p", { id: "upload-overlay-description", className: "mt-2 text-sm text-white/60" }, machineState === "error" ? "The upload was interrupted. You can retry safely or start over." : "Keep this tab open while we finish the upload and process your artwork.")), machineState !== "error" && /* @__PURE__ */ React.createElement("span", { className: `shrink-0 tabular-nums text-2xl font-bold ${meta.color}` }, progress, "%")),
        /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/20 p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `text-lg font-semibold ${meta.color}` }, meta.label), machineState !== "error" && /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/45" }, "Secure pipeline active")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-3 w-full overflow-hidden rounded-full bg-white/8" }, /* @__PURE__ */ React.createElement(
          motion.div,
          {
            className: `h-full rounded-full bg-gradient-to-r ${meta.barColor}`,
            animate: { width: machineState === "error" ? "100%" : `${progress}%` },
            transition: barTransition,
            style: machineState === "error" ? { opacity: 0.35 } : {}
          }
        )), /* @__PURE__ */ React.createElement(AnimatePresence, { mode: "wait", initial: false }, machineState !== "error" && displayLabel && /* @__PURE__ */ React.createElement(
          motion.p,
          {
            key: displayLabel,
            initial: prefersReducedMotion ? false : { opacity: 0, y: 4 },
            animate: { opacity: 1, y: 0 },
            exit: prefersReducedMotion ? {} : { opacity: 0, y: -4 },
            transition: { duration: 0.2 },
            className: "mt-4 text-sm text-white/60"
          },
          displayLabel
        )), machineState !== "error" && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.2em] text-white/30" }, "Progress updates are live")),
        /* @__PURE__ */ React.createElement(AnimatePresence, { initial: false }, machineState === "error" && /* @__PURE__ */ React.createElement(
          motion.div,
          {
            key: "error-block",
            initial: prefersReducedMotion ? false : { opacity: 0, height: 0 },
            animate: { opacity: 1, height: "auto" },
            exit: prefersReducedMotion ? {} : { opacity: 0, height: 0 },
            transition: { duration: 0.2 },
            className: "overflow-hidden"
          },
          /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-400/20 bg-rose-500/10 px-4 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-relaxed text-rose-100" }, error || "Something went wrong. You can retry safely."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(
            "button",
            {
              type: "button",
              onClick: onRetry,
              className: "rounded-lg border border-rose-300/30 bg-rose-400/15 px-3.5 py-2 text-sm font-medium text-rose-100 transition hover:bg-rose-400/25 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rose-300/60"
            },
            "Retry upload"
          ), /* @__PURE__ */ React.createElement(
            "button",
            {
              type: "button",
              onClick: onReset,
              className: "rounded-lg border border-white/20 bg-white/8 px-3.5 py-2 text-sm font-medium text-white/70 transition hover:bg-white/14 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/40"
            },
            "Start over"
          )))
        ))
      )
    )
  ));
}
function UploadActions({
  step = 1,
  canStart = false,
  canContinue = false,
  canPublish = false,
  canGoBack = false,
  canReset = true,
  canCancel = false,
  canRetry = false,
  isUploading = false,
  isProcessing = false,
  isPublishing = false,
  isCancelling = false,
  disableReason = "Complete required fields",
  onStart,
  onContinue,
  onPublish,
  onBack,
  onCancel,
  onReset,
  onRetry,
  onSaveDraft,
  showSaveDraft = false,
  mobileSticky = true,
  resetLabel = "Reset",
  publishLabel = "Publish"
}) {
  const [confirmCancel, setConfirmCancel] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (!confirmCancel) return;
    const timer = window.setTimeout(() => setConfirmCancel(false), 3200);
    return () => window.clearTimeout(timer);
  }, [confirmCancel]);
  const handleCancel = () => {
    if (!canCancel || isCancelling) return;
    if (!confirmCancel) {
      setConfirmCancel(true);
      return;
    }
    setConfirmCancel(false);
    onCancel?.();
  };
  const renderPrimary = () => {
    if (step === 1) {
      const disabled2 = !canStart || isUploading || isProcessing || isCancelling;
      const label = isUploading ? "Uploading…" : isProcessing ? "Processing…" : "Start upload";
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          disabled: disabled2,
          title: disabled2 ? disableReason : "Start upload",
          onClick: () => onStart?.(),
          className: `btn-primary text-sm ${disabled2 ? "cursor-not-allowed opacity-60" : ""}`
        },
        label
      );
    }
    if (step === 2) {
      const disabled2 = !canContinue;
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          disabled: disabled2,
          title: disabled2 ? disableReason : "Continue to Publish",
          onClick: () => onContinue?.(),
          className: `btn-primary text-sm ${disabled2 ? "cursor-not-allowed opacity-60" : ""}`
        },
        "Continue to Publish"
      );
    }
    const disabled = !canPublish || isPublishing;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        disabled,
        title: disabled ? disableReason : publishLabel,
        onClick: () => onPublish?.(),
        className: `btn-primary text-sm ${disabled ? "cursor-not-allowed opacity-60" : ""}`
      },
      isPublishing ? `${publishLabel}…` : publishLabel
    );
  };
  return /* @__PURE__ */ React.createElement("footer", { "data-testid": "wizard-action-bar", className: `${mobileSticky ? "pointer-events-none fixed inset-x-0 bottom-0 z-[70] px-4 pb-4 pt-3" : ""}` }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-auto mx-auto w-full max-w-7xl rounded-[24px] border border-white/10 bg-[#08111c]/92 p-3 shadow-[0_-12px_32px_rgba(2,8,23,0.65)] backdrop-blur-sm sm:p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-white/35" }, step === 1 ? "Step 1 of 3" : step === 2 ? "Step 2 of 3" : "Step 3 of 3"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-end gap-2.5" }, canGoBack && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onBack?.(),
      className: "btn-secondary text-sm"
    },
    "Back"
  ), showSaveDraft && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onSaveDraft?.(),
      className: "btn-secondary text-sm"
    },
    "Save draft"
  ), step === 1 && canCancel && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: handleCancel,
      disabled: isCancelling,
      title: confirmCancel ? "Click again to confirm cancel" : "Cancel current upload",
      className: "btn-secondary text-sm disabled:cursor-not-allowed disabled:opacity-60"
    },
    isCancelling ? "Cancelling…" : confirmCancel ? "Cancel upload?" : "Cancel"
  ), canRetry && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onRetry?.(),
      className: "btn-secondary text-sm"
    },
    "Retry"
  ), canReset && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => onReset?.(),
      className: "btn-secondary text-sm"
    },
    resetLabel
  ), renderPrimary()))));
}
function getScreenshotName(item, fallbackIndex) {
  if (item && typeof item === "object" && typeof item.name === "string" && item.name.trim()) {
    return item.name.trim();
  }
  return `Screenshot ${fallbackIndex + 1}`;
}
function resolveScreenshotSource(item) {
  if (!item) return { src: null, revoke: null };
  if (typeof item === "string") {
    return { src: item, revoke: null };
  }
  if (typeof item === "object") {
    if (typeof item.preview === "string" && item.preview) {
      return { src: item.preview, revoke: null };
    }
    if (typeof item.src === "string" && item.src) {
      return { src: item.src, revoke: null };
    }
    if (typeof item.url === "string" && item.url) {
      return { src: item.url, revoke: null };
    }
    if (typeof File !== "undefined" && item instanceof File) {
      const objectUrl = URL.createObjectURL(item);
      return {
        src: objectUrl,
        revoke: () => URL.revokeObjectURL(objectUrl)
      };
    }
  }
  return { src: null, revoke: null };
}
function ArchiveScreenshotPicker({
  screenshots = [],
  selectedIndex = 0,
  onSelect,
  compact = false,
  title = "Screenshots",
  description = "Choose which screenshot should be used as the default preview."
}) {
  const [resolvedScreenshots, setResolvedScreenshots] = reactExports.useState([]);
  reactExports.useEffect(() => {
    const cleanup = [];
    const next = (Array.isArray(screenshots) ? screenshots : []).map((item, index2) => {
      const { src: src2, revoke } = resolveScreenshotSource(item);
      if (revoke) cleanup.push(revoke);
      return {
        src: src2,
        alt: getScreenshotName(item, index2)
      };
    }).filter((item) => Boolean(item.src));
    setResolvedScreenshots(next);
    return () => {
      cleanup.forEach((revoke) => revoke());
    };
  }, [screenshots]);
  const normalizedIndex = reactExports.useMemo(() => {
    if (resolvedScreenshots.length === 0) return 0;
    if (!Number.isFinite(selectedIndex)) return 0;
    return Math.min(Math.max(0, Math.floor(selectedIndex)), resolvedScreenshots.length - 1);
  }, [resolvedScreenshots.length, selectedIndex]);
  const selectedScreenshot = resolvedScreenshots[normalizedIndex] ?? null;
  if (!selectedScreenshot) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: compact ? "space-y-3" : "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-white/45" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/55" }, description)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/30 bg-emerald-400/10 px-2.5 py-1 text-[11px] text-emerald-100" }, "Default preview")), /* @__PURE__ */ React.createElement("div", { className: compact ? "overflow-hidden rounded-2xl border border-white/10 bg-black/25" : "overflow-hidden rounded-3xl border border-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: selectedScreenshot.src,
      alt: selectedScreenshot.alt,
      className: compact ? "h-40 w-full object-cover" : "h-56 w-full object-cover sm:h-72",
      loading: "lazy",
      decoding: "async"
    }
  )), /* @__PURE__ */ React.createElement("div", { className: compact ? "grid grid-cols-4 gap-2" : "grid grid-cols-2 gap-3 sm:grid-cols-4" }, resolvedScreenshots.map((item, index2) => {
    const isSelected = index2 === normalizedIndex;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: `${item.src}-${index2}`,
        type: "button",
        onClick: () => onSelect?.(index2),
        "aria-label": `Use ${item.alt} as default screenshot`,
        className: [
          "group relative overflow-hidden rounded-2xl border text-left transition",
          isSelected ? "border-emerald-300/45 bg-emerald-400/10 shadow-[0_0_0_1px_rgba(52,211,153,0.22)]" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"
        ].join(" "),
        "aria-pressed": isSelected
      },
      /* @__PURE__ */ React.createElement(
        "img",
        {
          src: item.src,
          alt: item.alt,
          className: compact ? "h-16 w-full object-cover" : "h-20 w-full object-cover",
          loading: "lazy",
          decoding: "async"
        }
      ),
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-2 px-2.5 py-2" }, /* @__PURE__ */ React.createElement("span", { className: "truncate text-[11px] text-white/70" }, item.alt), /* @__PURE__ */ React.createElement("span", { className: [
        "shrink-0 rounded-full px-2 py-0.5 text-[10px]",
        isSelected ? "bg-emerald-300/20 text-emerald-100" : "bg-white/10 text-white/45"
      ].join(" ") }, isSelected ? "Default" : "Use"))
    );
  })));
}
function ReadinessChecklist({ items = [] }) {
  const allOk = items.every((item) => item.ok);
  return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 text-[10px] uppercase tracking-wider text-white/40" }, "Readiness"), /* @__PURE__ */ React.createElement("ul", { className: "space-y-1", role: "list" }, items.map((item) => /* @__PURE__ */ React.createElement("li", { key: item.label, className: "flex items-center gap-2 text-xs" }, /* @__PURE__ */ React.createElement(
    "span",
    {
      className: [
        "flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-[9px] font-bold",
        item.ok ? "bg-emerald-500/25 text-emerald-300" : "bg-white/8 text-white/30"
      ].join(" "),
      "aria-hidden": "true"
    },
    item.ok ? "✓" : "○"
  ), /* @__PURE__ */ React.createElement("span", { className: item.ok ? "text-white/70" : "text-white/40" }, (item.onClick || item.href) && !item.ok ? /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: item.onClick,
      className: "text-sky-400 hover:underline focus-visible:outline-none focus-visible:underline"
    },
    item.label
  ) : item.label), item.optional && !item.ok && /* @__PURE__ */ React.createElement("span", { className: "ml-auto text-[9px] text-white/25 italic" }, "optional")))), allOk && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-[11px] text-emerald-300/80" }, "All requirements met."));
}
const STATUS_PILL = {
  idle: null,
  initializing: { label: "Uploading", cls: "bg-sky-500/20 text-sky-200 border-sky-300/30" },
  uploading: { label: "Uploading", cls: "bg-sky-500/25 text-sky-100 border-sky-300/40" },
  finishing: { label: "Processing", cls: "bg-amber-500/20 text-amber-200 border-amber-300/30" },
  processing: { label: "Processing", cls: "bg-amber-500/20 text-amber-200 border-amber-300/30" },
  ready_to_publish: { label: "Ready", cls: "bg-emerald-500/20 text-emerald-100 border-emerald-300/35" },
  publishing: { label: "Publishing…", cls: "bg-sky-500/25 text-sky-100 border-sky-300/40" },
  complete: { label: "Published", cls: "bg-emerald-500/25 text-emerald-100 border-emerald-300/50" },
  scheduled: { label: "Scheduled", cls: "bg-violet-500/20 text-violet-200 border-violet-300/30" },
  error: { label: "Error", cls: "bg-red-500/20 text-red-200 border-red-300/30" },
  cancelled: { label: "Cancelled", cls: "bg-white/8 text-white/40 border-white/10" }
};
function PublishPanel({
  // Asset
  primaryPreviewUrl = null,
  isArchive = false,
  screenshots = [],
  selectedScreenshotIndex = 0,
  onSelectedScreenshotChange,
  // Metadata
  metadata = {},
  // Readiness
  machineState = "idle",
  uploadReady = false,
  canPublish = false,
  isPublishing = false,
  isArchiveRequiresScreenshot = false,
  // Publish options
  publishMode = "now",
  // 'now' | 'schedule'
  scheduledAt = null,
  timezone = Intl.DateTimeFormat().resolvedOptions().timeZone,
  visibility = "public",
  // 'public' | 'unlisted' | 'private'
  showRightsConfirmation = true,
  showVisibility = false,
  onPublishModeChange,
  onScheduleAt,
  onVisibilityChange,
  onToggleRights,
  // Actions
  onPublish,
  onCancel,
  // Navigation helpers (for checklist quick-links)
  onGoToStep,
  allRootCategoryOptions = [],
  actionLabel = "Publish now",
  showScheduleControls = true,
  publishActionEnabled = true,
  publishActionTitle = "Complete all requirements first"
}) {
  const pill = STATUS_PILL[machineState] ?? null;
  const hasPreview = Boolean(primaryPreviewUrl && !isArchive);
  const title = String(metadata.title || "").trim();
  const hasTitle = Boolean(title);
  const selectedRoot = allRootCategoryOptions.find(
    (item) => String(item.id) === String(metadata.rootCategoryId || "")
  ) ?? null;
  const requiresSubCategory = Boolean(selectedRoot?.children?.length);
  const hasCompleteCategory = Boolean(
    metadata.rootCategoryId && (!requiresSubCategory || metadata.subCategoryId)
  );
  const hasTag = Array.isArray(metadata.tags) && metadata.tags.length > 0;
  const hasRights = Boolean(metadata.rightsAccepted);
  const hasScreenshot = !isArchiveRequiresScreenshot || screenshots.length > 0;
  const checklist = [
    { label: "File uploaded & processed", ok: uploadReady },
    { label: "Title", ok: hasTitle, onClick: () => onGoToStep?.(2) },
    { label: "Category", ok: hasCompleteCategory, onClick: () => onGoToStep?.(2) },
    { label: "Rights confirmed", ok: hasRights, onClick: () => onGoToStep?.(2) },
    ...isArchiveRequiresScreenshot ? [{ label: "Screenshot (required for pack)", ok: hasScreenshot, onClick: () => onGoToStep?.(1) }] : [],
    { label: "At least 1 tag", ok: hasTag, onClick: () => onGoToStep?.(2) }
  ];
  const publishLabel = reactExports.useCallback(() => {
    if (isPublishing) return `${actionLabel}…`;
    if (!showScheduleControls) return actionLabel;
    if (publishMode === "schedule") return "Schedule publish";
    return actionLabel;
  }, [isPublishing, publishMode, actionLabel, showScheduleControls]);
  const canSchedulePublish = publishMode === "schedule" ? Boolean(scheduledAt) && canPublish : canPublish;
  const canTriggerPublish = publishActionEnabled && canSchedulePublish;
  const rightsError = uploadReady && !hasRights ? "Rights confirmation is required." : null;
  const visibilityOptions = [
    {
      value: "public",
      label: "Public",
      hint: "Visible to everyone"
    },
    {
      value: "unlisted",
      label: "Unlisted",
      hint: "Available by direct link"
    },
    {
      value: "private",
      label: "Private",
      hint: "Keep as draft visibility"
    }
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "h-fit space-y-5 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-5 shadow-[0_24px_90px_rgba(2,8,23,0.28)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "shrink-0 h-[72px] w-[72px] overflow-hidden rounded-xl ring-1 ring-white/10 bg-black/30 flex items-center justify-center" }, hasPreview ? /* @__PURE__ */ React.createElement(
    "img",
    {
      src: primaryPreviewUrl,
      alt: "Artwork preview",
      className: "max-h-full max-w-full object-contain",
      loading: "lazy",
      decoding: "async",
      width: 72,
      height: 72
    }
  ) : /* @__PURE__ */ React.createElement("svg", { className: "h-6 w-6 text-white/25", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 pt-0.5" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-semibold text-white leading-snug" }, hasTitle ? title : /* @__PURE__ */ React.createElement("span", { className: "italic text-white/35" }, "Untitled artwork")), pill && /* @__PURE__ */ React.createElement("span", { className: `mt-1 inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] ${pill.cls}` }, ["uploading", "initializing", "finishing", "processing", "publishing"].includes(machineState) && /* @__PURE__ */ React.createElement("span", { className: "relative flex h-1.5 w-1.5 shrink-0", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("span", { className: "absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-60" }), /* @__PURE__ */ React.createElement("span", { className: "relative inline-flex h-1.5 w-1.5 rounded-full bg-current" })), pill.label))), isArchive && screenshots.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement(
    ArchiveScreenshotPicker,
    {
      screenshots,
      selectedIndex: selectedScreenshotIndex,
      onSelect: onSelectedScreenshotChange,
      compact: true,
      title: "Preview screenshot",
      description: "Choose which screenshot should represent this archive in the publish panel."
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/8" }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement(ReadinessChecklist, { items: checklist })), showVisibility && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("label", { className: "mb-2 block text-[10px] uppercase tracking-wider text-white/40", htmlFor: "publish-visibility" }, "Visibility"), /* @__PURE__ */ React.createElement("div", { id: "publish-visibility", className: "grid gap-2" }, visibilityOptions.map((option) => {
    const active = visibility === option.value;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => onVisibilityChange?.(option.value),
        disabled: !canPublish && machineState !== "ready_to_publish",
        className: [
          "flex items-start justify-between gap-3 rounded-2xl border px-4 py-3 text-left transition disabled:opacity-50",
          active ? "border-sky-300/30 bg-sky-400/10 text-white" : "border-white/10 bg-white/[0.03] text-white/75 hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-white/50" }, option.hint)),
      /* @__PURE__ */ React.createElement("span", { className: [
        "mt-0.5 inline-flex h-5 w-5 items-center justify-center rounded-full border text-[10px]",
        active ? "border-sky-300/40 bg-sky-400/20 text-sky-100" : "border-white/10 bg-white/5 text-white/35"
      ].join(" ") }, active ? "✓" : "")
    );
  }))), showVisibility && showScheduleControls && uploadReady && machineState !== "complete" && /* @__PURE__ */ React.createElement(
    SchedulePublishPicker,
    {
      mode: publishMode,
      scheduledAt,
      timezone,
      onModeChange: onPublishModeChange,
      onScheduleAt,
      disabled: !canPublish || isPublishing
    }
  ), showRightsConfirmation && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      id: "publish-rights-confirm",
      checked: Boolean(metadata.rightsAccepted),
      onChange: (event) => onToggleRights?.(event.target.checked),
      variant: "emerald",
      size: 18,
      label: /* @__PURE__ */ React.createElement("span", { className: "text-xs text-white/85" }, "I confirm I own the rights to this content."),
      hint: /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/50" }, "Required before publishing."),
      error: rightsError,
      required: true
    }
  )), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      disabled: !canTriggerPublish || isPublishing,
      onClick: () => onPublish?.(),
      title: !publishActionEnabled ? publishActionTitle : !canPublish ? "Complete all requirements first" : void 0,
      className: [
        "w-full rounded-2xl py-3 text-sm font-semibold transition",
        canTriggerPublish && !isPublishing ? publishMode === "schedule" ? "bg-violet-500/80 text-white hover:bg-violet-500 shadow-[0_4px_16px_rgba(139,92,246,0.25)]" : "btn-primary" : "cursor-not-allowed bg-white/8 text-white/35 ring-1 ring-white/10"
      ].join(" ")
    },
    publishLabel()
  ), onCancel && machineState !== "idle" && machineState !== "complete" && /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: onCancel,
      className: "w-full text-center text-xs text-white/35 hover:text-white/70 transition"
    },
    "Cancel upload"
  ));
}
function getExtension(fileName = "") {
  const parts = String(fileName).toLowerCase().split(".");
  return parts.length > 1 ? parts.pop() : "";
}
function detectPrimaryType(file) {
  if (!file) return "unknown";
  const extension2 = getExtension(file.name);
  const mime = String(file.type || "").toLowerCase();
  const imageExt = /* @__PURE__ */ new Set(["jpg", "jpeg", "png", "webp"]);
  const archiveExt = /* @__PURE__ */ new Set(["zip", "rar", "7z", "tar", "gz"]);
  const imageMime = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);
  const archiveMime = /* @__PURE__ */ new Set([
    "application/zip",
    "application/x-zip-compressed",
    "application/x-rar-compressed",
    "application/vnd.rar",
    "application/x-7z-compressed",
    "application/x-tar",
    "application/gzip",
    "application/x-gzip",
    "application/octet-stream"
  ]);
  if (imageMime.has(mime) || imageExt.has(extension2)) return "image";
  if (archiveMime.has(mime) || archiveExt.has(extension2)) return "archive";
  return "unsupported";
}
function UploadDropzone({
  title = "Upload file",
  description = "Drop file here or click to browse",
  fileName = "",
  fileHint = "No file selected yet",
  previewUrl = "",
  fileMeta = null,
  errors = [],
  invalid = false,
  showLooksGood = false,
  looksGoodText = "Looks good",
  locked = false,
  onPrimaryFileChange,
  onValidationResult
}) {
  const [dragging, setDragging] = reactExports.useState(false);
  const inputRef = reactExports.useRef(null);
  const prefersReducedMotion = useReducedMotion();
  const dragTransition = prefersReducedMotion ? { duration: 0 } : { duration: 0.2, ease: "easeOut" };
  const emitFile = (file) => {
    const detectedType = detectPrimaryType(file);
    if (typeof onPrimaryFileChange === "function") {
      onPrimaryFileChange(file, { detectedType });
    }
    if (typeof onValidationResult === "function") {
      onValidationResult({ file, detectedType });
    }
  };
  return /* @__PURE__ */ React.createElement("section", { className: `rounded-[28px] bg-gradient-to-br p-0 shadow-[0_20px_60px_rgba(0,0,0,0.30)] transition-colors ${invalid ? "ring-1 ring-red-400/40 from-red-500/10 to-slate-900/45" : "ring-1 ring-white/10 from-slate-900/80 to-slate-900/50"}` }, /* @__PURE__ */ React.createElement(
    motion.div,
    {
      "data-testid": "upload-dropzone",
      role: "button",
      "aria-disabled": locked ? "true" : "false",
      tabIndex: locked ? -1 : 0,
      onClick: () => {
        if (locked) return;
        inputRef.current?.click();
      },
      onKeyDown: (event) => {
        if (locked) return;
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          inputRef.current?.click();
        }
      },
      onDragOver: (event) => {
        if (locked) return;
        event.preventDefault();
        setDragging(true);
      },
      onDragLeave: () => setDragging(false),
      onDrop: (event) => {
        if (locked) return;
        event.preventDefault();
        setDragging(false);
        const droppedFile = event.dataTransfer?.files?.[0];
        if (droppedFile) emitFile(droppedFile);
      },
      animate: prefersReducedMotion ? void 0 : { scale: dragging ? 1.01 : 1 },
      transition: dragTransition,
      className: `group rounded-[26px] border-2 border-dashed border-white/15 px-5 py-7 text-center transition hover:border-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70 sm:px-6 ${locked ? "cursor-default bg-white/5 opacity-75" : "cursor-pointer"} ${invalid ? "border-red-300/70 bg-red-500/10 shadow-[0_0_0_1px_rgba(248,113,113,0.2)]" : dragging ? "border-cyan-300 bg-cyan-500/20 shadow-[0_0_0_1px_rgba(103,232,249,0.35)]" : locked ? "bg-white/5" : "bg-[linear-gradient(180deg,rgba(14,165,233,0.08),rgba(255,255,255,0.02))] hover:bg-sky-500/12"}`
    },
    /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-sm font-semibold text-white" }, title),
    /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-soft" }, description),
    previewUrl ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 w-full flex flex-col items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-52 w-64 items-center justify-center overflow-hidden rounded-lg bg-black/40 ring-1 ring-white/10" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: previewUrl,
        alt: "Selected preview",
        className: "h-full w-full object-contain object-center",
        loading: "lazy",
        decoding: "async",
        width: "250",
        height: "208"
      }
    )), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-white/70" }, "Click to replace")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex h-16 w-16 items-center justify-center rounded-2xl border border-sky-400/40 bg-sky-500/12 text-sky-100 shadow-[0_14px_40px_rgba(14,165,233,0.18)]" }, /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", className: "h-7 w-7", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15v4a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-4" }), /* @__PURE__ */ React.createElement("path", { d: "M7 10l5-5 5 5" }), /* @__PURE__ */ React.createElement("path", { d: "M12 5v10" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap items-center justify-center gap-2 text-[11px] text-white/65" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-2.5 py-1" }, "JPG, PNG, WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-2.5 py-1" }, "ZIP, RAR, 7Z"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-2.5 py-1" }, "50MB images"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/5 px-2.5 py-1" }, "200MB archives")), /* @__PURE__ */ React.createElement("span", { className: `btn-secondary mt-4 inline-flex text-sm ${locked ? "opacity-80" : "group-focus-visible:bg-white/15"}` }, "Click to browse files")),
    /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: inputRef,
        type: "file",
        className: "hidden",
        "aria-label": "Upload file input",
        disabled: locked,
        accept: ".jpg,.jpeg,.png,.webp,.zip,.rar,.7z,.tar,.gz,image/jpeg,image/png,image/webp",
        onChange: (event) => {
          const selectedFile = event.target.files?.[0];
          if (selectedFile) {
            emitFile(selectedFile);
          }
        }
      }
    ),
    (previewUrl || fileMeta && String(fileMeta.type || "").startsWith("image/")) && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl ring-1 ring-white/10 bg-black/25 px-4 py-3 text-left text-xs text-white/80" }, /* @__PURE__ */ React.createElement("div", { className: "font-medium text-white/85" }, "Selected file"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate" }, fileName || fileHint), fileMeta && /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-2 text-xs text-white/60" }, /* @__PURE__ */ React.createElement("span", null, "Type: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, fileMeta.type || "—")), /* @__PURE__ */ React.createElement("span", null, "·"), /* @__PURE__ */ React.createElement("span", null, "Size: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, fileMeta.size || "—")), /* @__PURE__ */ React.createElement("span", null, "·"), /* @__PURE__ */ React.createElement("span", null, "Resolution: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, fileMeta.resolution || "—")))),
    showLooksGood && /* @__PURE__ */ React.createElement("div", { className: "mt-3 inline-flex items-center gap-1.5 rounded-full border border-emerald-300/35 bg-emerald-500/15 px-3 py-1 text-xs text-emerald-100" }, /* @__PURE__ */ React.createElement("span", { "aria-hidden": "true" }, "✓"), /* @__PURE__ */ React.createElement("span", null, looksGoodText)),
    /* @__PURE__ */ React.createElement(AnimatePresence, { initial: false }, errors.length > 0 && /* @__PURE__ */ React.createElement(
      motion.div,
      {
        key: "dropzone-errors",
        initial: prefersReducedMotion ? false : { opacity: 0, y: 4 },
        animate: prefersReducedMotion ? {} : { opacity: 1, y: 0 },
        exit: prefersReducedMotion ? {} : { opacity: 0, y: -4 },
        transition: dragTransition,
        className: "mt-4 rounded-lg border border-red-300/40 bg-red-500/10 p-3 text-left"
      },
      /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-wide text-red-100" }, "Please fix the following"),
      /* @__PURE__ */ React.createElement("ul", { className: "mt-2 space-y-1 text-xs text-red-100", role: "status", "aria-live": "polite" }, errors.map((error, index2) => /* @__PURE__ */ React.createElement("li", { key: `${error}-${index2}`, className: "rounded-md border border-red-300/35 bg-red-500/10 px-2 py-1" }, error)))
    ))
  ));
}
function ScreenshotUploader({
  title = "Archive screenshots",
  description = "Screenshot requirement placeholder for archive uploads",
  visible = false,
  files = [],
  perFileErrors = [],
  errors = [],
  invalid = false,
  showLooksGood = false,
  looksGoodText = "Looks good",
  onFilesChange,
  min: min2 = 1,
  max: max2 = 5
}) {
  const inputRef = reactExports.useRef(null);
  const prefersReducedMotion = useReducedMotion();
  const quickTransition = prefersReducedMotion ? { duration: 0 } : { duration: 0.2, ease: "easeOut" };
  const previewItems = reactExports.useMemo(() => files.map((file) => ({
    file,
    url: URL.createObjectURL(file)
  })), [files]);
  reactExports.useEffect(() => {
    return () => {
      previewItems.forEach((item) => URL.revokeObjectURL(item.url));
    };
  }, [previewItems]);
  if (!visible) return null;
  const emitFiles = (fileList, merge2 = false) => {
    const incoming = Array.from(fileList || []);
    const next = merge2 ? [...files, ...incoming] : incoming;
    if (typeof onFilesChange === "function") {
      onFilesChange(next.slice(0, max2));
    }
  };
  const removeAt = (index2) => {
    const next = files.filter((_2, idx) => idx !== index2);
    if (typeof onFilesChange === "function") {
      onFilesChange(next);
    }
  };
  return /* @__PURE__ */ React.createElement("section", { className: `rounded-xl border bg-gradient-to-br p-5 shadow-[0_12px_28px_rgba(0,0,0,0.3)] transition-colors sm:p-6 ${invalid ? "border-red-400/45 from-red-500/10 to-slate-900/40" : "border-amber-300/25 from-amber-500/10 to-slate-900/40"}` }, /* @__PURE__ */ React.createElement("div", { className: `rounded-lg border p-4 transition-colors ${invalid ? "border-red-300/45 bg-red-500/5" : "border-amber-300/30 bg-black/20"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-amber-100" }, title, " ", /* @__PURE__ */ React.createElement("span", { className: "text-red-200" }, "(Required)")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-200/35 bg-amber-500/15 px-2.5 py-1 text-xs text-amber-100" }, Math.min(files.length, max2), "/", max2, " screenshots")), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-amber-100/85" }, description), /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-lg border border-amber-200/20 bg-amber-500/10 px-3 py-3 text-xs text-amber-50/90" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold" }, "Why we need screenshots"), /* @__PURE__ */ React.createElement("p", { className: "mt-1" }, "Screenshots provide a visual thumbnail and help AI analysis/moderation before archive contents are published."), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-amber-100/85" }, "Rules: JPG/PNG/WEBP · 1280×720 minimum · 10MB max each · ", min2, " to ", max2, " files.")), /* @__PURE__ */ React.createElement(
    "div",
    {
      className: `mt-3 rounded-lg border-2 border-dashed p-4 text-center transition-colors ${invalid ? "border-red-300/45 bg-red-500/10" : "border-white/20 bg-white/5 hover:border-amber-300/45 hover:bg-amber-500/5"}`,
      onDragOver: (event) => event.preventDefault(),
      onDrop: (event) => {
        event.preventDefault();
        emitFiles(event.dataTransfer?.files, true);
      }
    },
    /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/85" }, "Drop screenshots here or click to browse"),
    /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        className: "btn-secondary mt-2 text-xs",
        onClick: () => inputRef.current?.click()
      },
      "Browse screenshots"
    ),
    /* @__PURE__ */ React.createElement(
      "input",
      {
        ref: inputRef,
        type: "file",
        className: "hidden",
        "aria-label": "Screenshot file input",
        multiple: true,
        accept: ".jpg,.jpeg,.png,.webp,image/jpeg,image/png,image/webp",
        onChange: (event) => emitFiles(event.target.files, true)
      }
    )
  ), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-white/70" }, files.length, " selected · minimum ", min2, ", maximum ", max2), showLooksGood && /* @__PURE__ */ React.createElement("div", { className: "mt-2 inline-flex items-center gap-1.5 rounded-full border border-emerald-300/35 bg-emerald-500/15 px-3 py-1 text-xs text-emerald-100" }, /* @__PURE__ */ React.createElement("span", { "aria-hidden": "true" }, "✓"), /* @__PURE__ */ React.createElement("span", null, looksGoodText)), previewItems.length > 0 && /* @__PURE__ */ React.createElement("ul", { className: "mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement(AnimatePresence, { initial: false }, previewItems.map((item, index2) => /* @__PURE__ */ React.createElement(
    motion.li,
    {
      layout: !prefersReducedMotion,
      key: `${item.file.name}-${index2}`,
      initial: prefersReducedMotion ? false : { opacity: 0, scale: 0.96 },
      animate: prefersReducedMotion ? {} : { opacity: 1, scale: 1 },
      exit: prefersReducedMotion ? {} : { opacity: 0, scale: 0.96 },
      transition: quickTransition,
      className: "rounded-lg ring-1 ring-white/10 bg-white/5 p-2 text-xs"
    },
    /* @__PURE__ */ React.createElement("div", { className: "flex h-40 w-40 items-center justify-center overflow-hidden rounded-md ring-1 ring-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement(
      "img",
      {
        src: item.url,
        alt: `Screenshot ${index2 + 1}`,
        className: "max-h-full max-w-full object-contain",
        loading: "lazy",
        decoding: "async",
        width: "160",
        height: "160"
      }
    )),
    /* @__PURE__ */ React.createElement("div", { className: "mt-2 truncate text-white/90" }, item.file.name),
    /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-white/55" }, Math.round(item.file.size / 1024), " KB"),
    perFileErrors[index2] && /* @__PURE__ */ React.createElement("div", { className: "mt-1 rounded-md border border-red-300/35 bg-red-500/10 px-2 py-1 text-red-200" }, perFileErrors[index2]),
    /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => removeAt(index2),
        className: "mt-2 rounded-md border border-white/20 bg-white/5 px-2.5 py-1 text-[11px] text-white/80 transition hover:bg-white/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-300/70"
      },
      "Remove"
    )
  )))), errors.length > 0 && /* @__PURE__ */ React.createElement("ul", { className: "mt-3 space-y-1 text-xs text-red-100", role: "status", "aria-live": "polite" }, errors.map((error, index2) => /* @__PURE__ */ React.createElement("li", { key: `${error}-${index2}`, className: "rounded-md border border-red-300/35 bg-red-500/10 px-2 py-1" }, error))), invalid && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-red-200" }, "Continue is blocked until screenshot requirements are valid.")));
}
function Step1FileUpload({
  headingRef,
  // File state
  primaryFile,
  primaryPreviewUrl,
  primaryErrors,
  primaryWarnings,
  fileMetadata,
  fileSelectionLocked,
  onPrimaryFileChange,
  // Archive screenshots
  isArchive,
  screenshots,
  selectedScreenshotIndex,
  screenshotErrors,
  screenshotPerFileErrors,
  onScreenshotsChange,
  onSelectedScreenshotChange,
  // Machine state (passed for potential future use)
  machine
}) {
  const fileSelected = Boolean(primaryFile);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-6 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-6 shadow-[0_24px_90px_rgba(2,8,23,0.28)] backdrop-blur sm:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-sky-400/30 bg-sky-400/10 px-3 py-1 text-[11px] uppercase tracking-widest text-sky-300" }, "Step 1 of 3"), /* @__PURE__ */ React.createElement(
    "h2",
    {
      ref: headingRef,
      tabIndex: -1,
      className: "mt-4 text-2xl font-bold text-white focus:outline-none"
    },
    "Upload your artwork"
  ), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-2 max-w-md text-sm text-white/55" }, "Drop an image or an archive pack. We validate the file instantly so you can start uploading straight away.")), fileSelectionLocked && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2.5 rounded-2xl bg-amber-500/10 px-4 py-3 text-sm text-amber-100 ring-1 ring-amber-300/30" }, /* @__PURE__ */ React.createElement("svg", { className: "h-4 w-4 shrink-0", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M10 1a4.5 4.5 0 00-4.5 4.5V9H5a2 2 0 00-2 2v6a2 2 0 002 2h10a2 2 0 002-2v-6a2 2 0 00-2-2h-.5V5.5A4.5 4.5 0 0010 1zm3 8V5.5a3 3 0 10-6 0V9h6z", clipRule: "evenodd" })), "File is locked after upload starts. Reset to change the file."), /* @__PURE__ */ React.createElement(
    UploadDropzone,
    {
      title: "Drop your file here",
      description: "JPG, PNG, WEBP · ZIP, RAR, 7Z · Images up to 50 MB · Archives up to 200 MB",
      fileName: primaryFile?.name || "",
      previewUrl: primaryPreviewUrl,
      fileMeta: fileMetadata,
      fileHint: "No file selected",
      invalid: primaryErrors.length > 0,
      errors: primaryErrors,
      showLooksGood: fileSelected && primaryErrors.length === 0,
      looksGoodText: "File looks good — ready to upload",
      locked: fileSelectionLocked,
      onPrimaryFileChange: (file) => {
        if (fileSelectionLocked) return;
        onPrimaryFileChange(file || null);
      }
    }
  ), /* @__PURE__ */ React.createElement(
    ScreenshotUploader,
    {
      title: "Archive screenshots",
      description: "Add at least 1 screenshot so we can generate a thumbnail and analyze your content.",
      visible: isArchive,
      files: screenshots,
      min: 1,
      max: 5,
      perFileErrors: screenshotPerFileErrors,
      errors: screenshotErrors,
      invalid: isArchive && screenshotErrors.length > 0,
      showLooksGood: isArchive && screenshots.length > 0 && screenshotErrors.length === 0,
      looksGoodText: "Screenshots look good",
      onFilesChange: onScreenshotsChange
    }
  ), isArchive && screenshots.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4 sm:p-5" }, /* @__PURE__ */ React.createElement(
    ArchiveScreenshotPicker,
    {
      screenshots,
      selectedIndex: selectedScreenshotIndex,
      onSelect: onSelectedScreenshotChange,
      compact: true,
      title: "Choose default screenshot",
      description: "Pick the screenshot that should be uploaded as the archive preview before you start the upload."
    }
  )), !fileSelected && /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3" }, [
    {
      icon: /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5 text-sky-300", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15v4a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-4" }), /* @__PURE__ */ React.createElement("path", { d: "M7 10l5-5 5 5" }), /* @__PURE__ */ React.createElement("path", { d: "M12 5v10" })),
      label: "Add your file",
      hint: "Image or archive — drop it in or click to browse."
    },
    {
      icon: /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5 text-violet-300", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M9 12l2 2 4-4" }), /* @__PURE__ */ React.createElement("path", { d: "M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10-4.477 10-10 10z" })),
      label: "Instant validation",
      hint: "Format, size, and screenshot checks run immediately."
    },
    {
      icon: /* @__PURE__ */ React.createElement("svg", { className: "h-5 w-5 text-emerald-300", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { d: "M5 13l4 4L19 7" })),
      label: "Start upload",
      hint: "One click sends your file through the secure pipeline."
    }
  ].map((item) => /* @__PURE__ */ React.createElement("div", { key: item.label, className: "flex items-start gap-3 rounded-2xl border border-white/8 bg-white/[0.03] px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.05]" }, item.icon), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs leading-5 text-slate-400" }, item.hint))))));
}
function UploadSidebar({
  title = "Artwork details",
  description = "Complete metadata before publishing",
  showHeader = true,
  metadata,
  suggestedTags = [],
  errors = {},
  publishMode,
  scheduledAt,
  timezone,
  onPublishModeChange,
  onScheduleAt,
  onChangeTitle,
  onChangeTags,
  onChangeDescription,
  onToggleRights
}) {
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, showHeader && /* @__PURE__ */ React.createElement("div", { className: "mb-5 rounded-xl border border-white/8 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white/65" }, description)), /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Basics"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/60" }, "Add a clear title and short description.")), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/90" }, "Title ", /* @__PURE__ */ React.createElement("span", { className: "text-red-300" }, "*")), /* @__PURE__ */ React.createElement(
    "input",
    {
      id: "upload-sidebar-title",
      value: metadata.title,
      onChange: (event) => onChangeTitle?.(event.target.value),
      className: `mt-2 w-full rounded-xl border bg-white/10 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 ${errors.title ? "border-red-300/60 focus:ring-red-300/70" : "border-white/15 focus:ring-sky-300/70"}`,
      placeholder: "Give your artwork a clear title"
    }
  ), errors.title && /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-red-200" }, errors.title)), /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/90" }, "Description ", /* @__PURE__ */ React.createElement("span", { className: "text-red-300" }, "*")), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement(
    UploadDescriptionEditor,
    {
      id: "upload-sidebar-description",
      value: metadata.description,
      onChange: onChangeDescription,
      placeholder: "Describe your artwork, tools, inspiration...",
      error: Array.isArray(errors.description) ? errors.description[0] : errors.description,
      rows: 9
    }
  )), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-white/50" }, "This upload editor only allows safe formatting and emoji. Images, embeds, and raw HTML are blocked."), errors.description && /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-red-200" }, Array.isArray(errors.description) ? errors.description[0] : errors.description)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Tags"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/60" }, "Use keywords people would search for. Press Enter, comma, or Tab to add a tag.")), /* @__PURE__ */ React.createElement(
    TagPicker,
    {
      value: metadata.tags,
      onChange: (nextTags) => onChangeTags?.(nextTags),
      suggestedTags,
      searchEndpoint: "/api/tags/search",
      popularEndpoint: "/api/tags/popular",
      error: errors.tags
    }
  )), typeof publishMode === "string" && typeof onPublishModeChange === "function" && /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white" }, "Publish settings"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/60" }, "Choose whether this artwork should publish immediately or on a schedule.")), /* @__PURE__ */ React.createElement(
    SchedulePublishPicker,
    {
      mode: publishMode,
      scheduledAt,
      timezone,
      onModeChange: onPublishModeChange,
      onScheduleAt,
      disabled: false
    }
  )), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      id: "upload-sidebar-rights",
      checked: Boolean(metadata.rightsAccepted),
      onChange: (event) => onToggleRights?.(event.target.checked),
      variant: "emerald",
      size: 20,
      label: "I confirm I own the rights to this content.",
      hint: "Required before publishing.",
      error: errors.rights,
      required: true
    }
  ))));
}
function Step2Details({
  headingRef,
  // Asset summary
  primaryFile,
  primaryPreviewUrl,
  isArchive,
  fileMetadata,
  screenshots,
  selectedScreenshotIndex,
  onSelectedScreenshotChange,
  // Content type + category
  contentTypes,
  metadata,
  metadataErrors,
  filteredCategoryTree,
  allRootCategoryOptions,
  requiresSubCategory,
  onContentTypeChange,
  onRootCategoryChange,
  onSubCategoryChange,
  groupOptions,
  currentContributorOptions,
  onGroupChange,
  onPrimaryAuthorChange,
  onContributorToggle,
  onContributorRoleChange,
  onContributorPrimaryChange,
  // Sidebar (title / tags / description / rights)
  suggestedTags,
  publishMode,
  scheduledAt,
  timezone,
  onPublishModeChange,
  onScheduleAt,
  onChangeTitle,
  onChangeTags,
  onChangeDescription,
  onToggleRights
}) {
  const [isContentTypeChooserOpen, setIsContentTypeChooserOpen] = reactExports.useState(() => !metadata.contentType);
  const [isCategoryChooserOpen, setIsCategoryChooserOpen] = reactExports.useState(() => !metadata.rootCategoryId);
  const [isSubCategoryChooserOpen, setIsSubCategoryChooserOpen] = reactExports.useState(() => !metadata.subCategoryId);
  const [categorySearch, setCategorySearch] = reactExports.useState("");
  const [subCategorySearch, setSubCategorySearch] = reactExports.useState("");
  const contentTypeOptions = reactExports.useMemo(
    () => (Array.isArray(contentTypes) ? contentTypes : []).map((item) => {
      const normalizedName = String(item?.name || "").trim().toLowerCase();
      const normalizedSlug = String(item?.slug || "").trim().toLowerCase();
      if (normalizedName === "other" || normalizedSlug === "other") {
        return {
          ...item,
          name: "Others"
        };
      }
      return item;
    }),
    [contentTypes]
  );
  const selectedContentType = reactExports.useMemo(
    () => contentTypeOptions.find((item) => String(getContentTypeValue(item)) === String(metadata.contentType || "")) ?? null,
    [contentTypeOptions, metadata.contentType]
  );
  const selectedRoot = reactExports.useMemo(
    () => filteredCategoryTree.find((item) => String(item.id) === String(metadata.rootCategoryId || "")) ?? null,
    [filteredCategoryTree, metadata.rootCategoryId]
  );
  const subCategories = selectedRoot?.children || [];
  const selectedSubCategory = reactExports.useMemo(
    () => subCategories.find((item) => String(item.id) === String(metadata.subCategoryId || "")) ?? null,
    [subCategories, metadata.subCategoryId]
  );
  const sortedFilteredCategories = reactExports.useMemo(() => {
    const sorted = [...filteredCategoryTree].sort((a, b2) => a.name.localeCompare(b2.name));
    const q2 = categorySearch.trim().toLowerCase();
    return q2 ? sorted.filter((c) => c.name.toLowerCase().includes(q2)) : sorted;
  }, [filteredCategoryTree, categorySearch]);
  const sortedFilteredSubCategories = reactExports.useMemo(() => {
    const sorted = [...subCategories].sort((a, b2) => a.name.localeCompare(b2.name));
    const q2 = subCategorySearch.trim().toLowerCase();
    return q2 ? sorted.filter((s2) => s2.name.toLowerCase().includes(q2)) : sorted;
  }, [subCategories, subCategorySearch]);
  const contributorCredits = metadata.contributorCredits || {};
  reactExports.useEffect(() => {
    if (!metadata.contentType) {
      setIsContentTypeChooserOpen(true);
    }
  }, [metadata.contentType]);
  reactExports.useEffect(() => {
    if (!metadata.rootCategoryId) {
      setIsCategoryChooserOpen(true);
    }
  }, [metadata.rootCategoryId]);
  reactExports.useEffect(() => {
    if (!metadata.subCategoryId) {
      setIsSubCategoryChooserOpen(true);
    }
  }, [metadata.subCategoryId]);
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-5 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-6 shadow-[0_24px_90px_rgba(2,8,23,0.28)] backdrop-blur sm:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-white/[0.04] px-5 py-4" }, /* @__PURE__ */ React.createElement(
    "h2",
    {
      ref: headingRef,
      tabIndex: -1,
      className: "text-lg font-semibold text-white focus:outline-none"
    },
    "Artwork details"
  ), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white/60" }, "Complete required metadata and rights confirmation before publishing.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl ring-1 ring-white/8 bg-white/[0.025] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-[11px] uppercase tracking-wide text-white/45" }, "Uploaded asset"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center" }, primaryPreviewUrl && !isArchive ? /* @__PURE__ */ React.createElement("div", { className: "flex h-[120px] w-[120px] items-center justify-center overflow-hidden rounded-xl ring-1 ring-white/10 bg-black/30 shrink-0" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: primaryPreviewUrl,
      alt: "Uploaded artwork thumbnail",
      className: "max-h-full max-w-full object-contain",
      loading: "lazy",
      decoding: "async",
      width: 120,
      height: 120
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "grid h-[120px] w-[120px] place-items-center rounded-xl ring-1 ring-white/10 bg-white/5 shrink-0" }, /* @__PURE__ */ React.createElement("svg", { className: "h-8 w-8 text-white/30", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" }))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-medium text-white" }, primaryFile?.name || "Primary file"), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/50" }, isArchive ? `Archive · ${screenshots.length} screenshot${screenshots.length !== 1 ? "s" : ""}` : fileMetadata.resolution !== "—" ? `${fileMetadata.resolution} · ${fileMetadata.size}` : fileMetadata.size), /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] ${isArchive ? "border-amber-400/40 bg-amber-400/10 text-amber-200" : "border-sky-400/40 bg-sky-400/10 text-sky-200"}` }, isArchive ? "Archive" : "Image"))), isArchive && screenshots.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-5 border-t border-white/8 pt-5" }, /* @__PURE__ */ React.createElement(
    ArchiveScreenshotPicker,
    {
      screenshots,
      selectedIndex: selectedScreenshotIndex,
      onSelect: onSelectedScreenshotChange,
      title: "Archive screenshots",
      description: "All selected screenshots are shown here. Pick the one that should become the main preview thumbnail."
    }
  ))), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-[radial-gradient(ellipse_at_top_left,_rgba(14,165,233,0.07),_transparent_45%),radial-gradient(ellipse_at_bottom_right,_rgba(168,85,247,0.07),_transparent_45%)] p-5 sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap items-start justify-between gap-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, "Content type & category"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/55" }, "Choose the content family, then narrow down to a category and subcategory.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-400/30 bg-sky-400/10 px-2.5 py-0.5 text-[11px] uppercase tracking-widest text-sky-300" }, "Step 2")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Content type"), contentTypeOptions.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-400" }, "No content types are available right now."), selectedContentType && !isContentTypeChooserOpen && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-400/25 bg-emerald-400/[0.08] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-emerald-400/30 bg-emerald-400/10" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: `/gfx/mascot_${getContentTypeVisualKey(selectedContentType)}.webp`,
      alt: "",
      className: "h-7 w-7 object-contain",
      onError: (e) => {
        e.currentTarget.style.display = "none";
      }
    }
  )), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-200/70" }, "Selected"), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-base font-semibold text-white" }, selectedContentType.name))), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => setIsContentTypeChooserOpen(true),
      className: "inline-flex items-center justify-center rounded-xl border border-white/10 bg-white/[0.05] px-3 py-2 text-sm font-medium text-slate-200 transition hover:border-white/20 hover:bg-white/[0.08] hover:text-white"
    },
    "Change"
  ))), (!selectedContentType || isContentTypeChooserOpen) && /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-2" }, contentTypeOptions.map((ct) => {
    const typeValue = String(getContentTypeValue(ct));
    const isActive = typeValue === String(metadata.contentType || "");
    const visualKey = getContentTypeVisualKey(ct);
    const categoryCount = Array.isArray(ct.categories) ? ct.categories.length : 0;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: typeValue || ct.name,
        type: "button",
        onClick: () => {
          setIsContentTypeChooserOpen(false);
          setIsCategoryChooserOpen(true);
          onContentTypeChange(typeValue);
        },
        className: [
          "group flex w-full items-center gap-3 rounded-2xl border px-3 py-3 text-left transition-all",
          isActive ? "border-emerald-400/40 bg-emerald-400/10 shadow-[0_0_0_1px_rgba(52,211,153,0.18)]" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" "),
        "aria-pressed": isActive
      },
      /* @__PURE__ */ React.createElement("div", { className: `flex h-12 w-12 items-center justify-center rounded-2xl border ${isActive ? "border-emerald-400/30 bg-emerald-400/10" : "border-white/10 bg-white/[0.04]"}` }, /* @__PURE__ */ React.createElement(
        "img",
        {
          src: `/gfx/mascot_${visualKey}.webp`,
          alt: "",
          className: "h-8 w-8 object-contain",
          onError: (e) => {
            e.currentTarget.style.display = "none";
          }
        }
      )),
      /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: `text-sm font-semibold ${isActive ? "text-emerald-200" : "text-white"}` }, ct.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-slate-500" }, categoryCount, " ", categoryCount === 1 ? "category" : "categories")),
      /* @__PURE__ */ React.createElement("div", { className: `text-xs ${isActive ? "text-emerald-300" : "text-slate-500 group-hover:text-slate-300"}` }, isActive ? "Selected" : "Open")
    );
  })), metadataErrors.contentType && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-red-300" }, metadataErrors.contentType)), selectedContentType && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "my-5 border-t border-white/8" }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Category"), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-slate-600" }, filteredCategoryTree.length, " available")), selectedRoot && !isCategoryChooserOpen && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-purple-400/25 bg-purple-400/[0.07] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-purple-200/70" }, "Selected"), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-base font-semibold text-white" }, selectedRoot.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, subCategories.length > 0 ? `${subCategories.length} subcategories available` : "No subcategory required")), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        setCategorySearch("");
        setIsCategoryChooserOpen(true);
      },
      className: "inline-flex items-center justify-center rounded-xl border border-white/10 bg-white/[0.05] px-3 py-2 text-sm font-medium text-slate-200 transition hover:border-white/20 hover:bg-white/[0.08] hover:text-white"
    },
    "Change"
  ))), (!selectedRoot || isCategoryChooserOpen) && /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("svg", { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z", clipRule: "evenodd" })), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: categorySearch,
      onChange: (e) => setCategorySearch(e.target.value),
      placeholder: "Search categories…",
      className: "w-full rounded-xl border border-white/10 bg-white/[0.04] py-2.5 pl-9 pr-4 text-sm text-white placeholder:text-slate-500 focus:border-purple-400/40 focus:outline-none focus:ring-1 focus:ring-purple-400/30"
    }
  )), sortedFilteredCategories.length === 0 && /* @__PURE__ */ React.createElement("p", { className: "py-4 text-center text-sm text-slate-500" }, "No categories match “", categorySearch, "”"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-2" }, sortedFilteredCategories.map((cat) => {
    const isActive = String(metadata.rootCategoryId || "") === String(cat.id);
    const childCount = cat.children?.length || 0;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: cat.id,
        type: "button",
        onClick: () => {
          setIsCategoryChooserOpen(false);
          onRootCategoryChange(String(cat.id));
        },
        className: [
          "rounded-2xl border px-4 py-4 text-left transition-all",
          isActive ? "border-purple-400/40 bg-purple-400/12 shadow-[0_0_0_1px_rgba(192,132,252,0.15)]" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: `text-sm font-semibold ${isActive ? "text-purple-200" : "text-white"}` }, cat.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-slate-500" }, childCount > 0 ? `${childCount} subcategories` : "Standalone")), /* @__PURE__ */ React.createElement("span", { className: `rounded-full px-2 py-1 text-[11px] ${isActive ? "bg-purple-300/15 text-purple-200" : "bg-white/[0.05] text-slate-500"}` }, isActive ? "Selected" : "Choose"))
    );
  }))), metadataErrors.category && /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-red-300" }, metadataErrors.category))), selectedRoot && subCategories.length > 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "my-5 border-t border-white/8" }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mb-3 flex items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Subcategory"), /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-slate-600" }, subCategories.length, " available")), !metadata.subCategoryId && requiresSubCategory && /* @__PURE__ */ React.createElement("div", { className: "mb-3 rounded-xl border border-amber-400/20 bg-amber-400/10 px-3 py-2 text-sm text-amber-100" }, "Subcategory still needs to be selected."), selectedSubCategory && !isSubCategoryChooserOpen && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-cyan-400/25 bg-cyan-400/[0.07] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-cyan-200/70" }, "Selected"), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-base font-semibold text-white" }, selectedSubCategory.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Path: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-300" }, selectedRoot.name), " / ", /* @__PURE__ */ React.createElement("span", { className: "text-cyan-200" }, selectedSubCategory.name))), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        setSubCategorySearch("");
        setIsSubCategoryChooserOpen(true);
      },
      className: "inline-flex items-center justify-center rounded-xl border border-white/10 bg-white/[0.05] px-3 py-2 text-sm font-medium text-slate-200 transition hover:border-white/20 hover:bg-white/[0.08] hover:text-white"
    },
    "Change"
  ))), (!selectedSubCategory || isSubCategoryChooserOpen) && /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("svg", { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-500", viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M9 3.5a5.5 5.5 0 100 11 5.5 5.5 0 000-11zM2 9a7 7 0 1112.452 4.391l3.328 3.329a.75.75 0 11-1.06 1.06l-3.329-3.328A7 7 0 012 9z", clipRule: "evenodd" })), /* @__PURE__ */ React.createElement(
    "input",
    {
      type: "search",
      value: subCategorySearch,
      onChange: (e) => setSubCategorySearch(e.target.value),
      placeholder: "Search subcategories…",
      className: "w-full rounded-xl border border-white/10 bg-white/[0.04] py-2.5 pl-9 pr-4 text-sm text-white placeholder:text-slate-500 focus:border-cyan-400/40 focus:outline-none focus:ring-1 focus:ring-cyan-400/30"
    }
  )), sortedFilteredSubCategories.length === 0 && /* @__PURE__ */ React.createElement("p", { className: "py-4 text-center text-sm text-slate-500" }, "No subcategories match “", subCategorySearch, "”"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, sortedFilteredSubCategories.map((sub) => {
    const isActive = String(metadata.subCategoryId || "") === String(sub.id);
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: sub.id,
        type: "button",
        onClick: () => {
          setIsSubCategoryChooserOpen(false);
          onSubCategoryChange(String(sub.id));
        },
        className: [
          "group rounded-2xl border px-4 py-3 text-left transition-all",
          isActive ? "border-cyan-400/40 bg-cyan-400/[0.13] shadow-[0_0_0_1px_rgba(34,211,238,0.14)]" : "border-white/10 bg-white/[0.04] hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: ["text-sm font-semibold transition-colors", isActive ? "text-cyan-100" : "text-slate-100 group-hover:text-white"].join(" ") }, sub.name), /* @__PURE__ */ React.createElement("div", { className: ["mt-1 text-xs", isActive ? "text-cyan-200/80" : "text-slate-500 group-hover:text-slate-300"].join(" ") }, "Subcategory")), /* @__PURE__ */ React.createElement("span", { className: ["shrink-0 rounded-full px-2.5 py-1 text-[11px] font-medium", isActive ? "bg-cyan-300/15 text-cyan-100" : "bg-white/[0.05] text-slate-500 group-hover:text-slate-300"].join(" ") }, isActive ? "Selected" : "Choose"))
    );
  }))))), selectedRoot && subCategories.length === 0 && selectedRoot && /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-white/8 bg-white/[0.02] px-4 py-3 text-sm text-slate-500" }, /* @__PURE__ */ React.createElement("span", { className: "font-medium text-slate-300" }, selectedRoot.name), " has no subcategories — selecting it is enough.")), Array.isArray(groupOptions) && groupOptions.length > 0 && /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-[radial-gradient(ellipse_at_top_left,_rgba(56,189,248,0.08),_transparent_42%),linear-gradient(180deg,rgba(255,255,255,0.04),rgba(255,255,255,0.02))] p-5 sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, "Publisher attribution"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-white/55" }, "Publish personally or switch into a group identity while preserving author and contributor credits.")), metadata.group ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100" }, "Group publish") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, "Personal publish")), /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Publishing identity",
      value: metadata.group || "",
      onChange: (nextValue) => onGroupChange?.(String(nextValue || "")),
      options: [
        { value: "", label: "Personal profile" },
        ...groupOptions.map((group) => ({ value: group.slug, label: group.name }))
      ],
      searchable: false,
      className: "mt-2 bg-black/20"
    }
  )), metadata.group && /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-5 lg:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(
    NovaSelect,
    {
      label: "Primary author",
      value: metadata.primaryAuthorUserId || null,
      onChange: (nextValue) => onPrimaryAuthorChange?.(nextValue == null ? "" : String(nextValue)),
      options: currentContributorOptions.map((user) => ({
        value: user.id,
        label: user.name || user.username
      })),
      searchable: false,
      className: "mt-2 bg-black/20"
    }
  ), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-slate-400" }, "The primary author is shown as the lead creator for this group-published artwork.")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/90" }, "Contributors"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, "Optional")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 grid gap-2" }, currentContributorOptions.filter((user) => Number(user.id) !== Number(metadata.primaryAuthorUserId)).map((user) => {
    const active = Array.isArray(metadata.contributorUserIds) && metadata.contributorUserIds.some((id) => Number(id) === Number(user.id));
    const creditMeta = contributorCredits?.[user.id] || contributorCredits?.[String(user.id)] || { creditRole: "", isPrimary: false };
    return /* @__PURE__ */ React.createElement(
      "div",
      {
        key: user.id,
        className: [
          "rounded-2xl border px-3 py-3 transition",
          active ? "border-sky-300/30 bg-sky-300/10 text-white" : "border-white/10 bg-white/[0.03] text-slate-200 hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, user.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: user.avatar_url, alt: user.name || user.username, className: "h-10 w-10 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold" }, user.name || user.username), /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs text-slate-400" }, "@", user.username)), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => onContributorToggle?.(user.id),
          className: [
            "inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold transition",
            active ? "border-sky-300/40 bg-sky-300/20 text-sky-50" : "border-white/10 bg-white/[0.03] text-white/70 hover:border-white/20 hover:text-white"
          ].join(" ")
        },
        /* @__PURE__ */ React.createElement("span", { className: ["inline-flex h-4 w-4 items-center justify-center rounded-full border text-[10px]", active ? "border-sky-300/40 bg-sky-300/20 text-sky-50" : "border-white/10 bg-white/[0.03] text-white/35"].join(" ") }, active ? "✓" : ""),
        active ? "Added" : "Add credit"
      )),
      active ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium uppercase tracking-[0.16em] text-slate-300" }, "Credit role"), /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "text",
          value: creditMeta.creditRole || "",
          onChange: (event) => onContributorRoleChange?.(user.id, event.target.value),
          placeholder: "Colorist, concept support, layout...",
          "aria-label": `Credit role for ${user.name || user.username}`,
          className: "mt-2 w-full rounded-xl border border-white/15 bg-black/20 px-3 py-3 text-sm text-white outline-none transition focus:border-sky-300/40"
        }
      )), /* @__PURE__ */ React.createElement(
        "button",
        {
          type: "button",
          onClick: () => onContributorPrimaryChange?.(user.id),
          "aria-pressed": creditMeta.isPrimary ? "true" : "false",
          "aria-label": `Mark ${user.name || user.username} as lead supporting credit`,
          className: [
            "inline-flex items-center justify-center rounded-xl border px-3 py-3 text-sm font-medium transition",
            creditMeta.isPrimary ? "border-emerald-300/35 bg-emerald-400/12 text-emerald-100" : "border-white/10 bg-white/[0.03] text-slate-200 hover:border-white/20 hover:bg-white/[0.06] hover:text-white"
          ].join(" ")
        },
        creditMeta.isPrimary ? "Lead support" : "Set lead support"
      )) : null
    );
  }))))), /* @__PURE__ */ React.createElement(
    UploadSidebar,
    {
      showHeader: false,
      metadata,
      suggestedTags,
      errors: metadataErrors,
      publishMode,
      scheduledAt,
      timezone,
      onPublishModeChange,
      onScheduleAt,
      onChangeTitle,
      onChangeTags,
      onChangeDescription,
      onToggleRights
    }
  ));
}
function stripHtml(value) {
  return String(value || "").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();
}
function PublishCheckBadge({ label, ok: ok2 }) {
  return /* @__PURE__ */ React.createElement(
    "span",
    {
      className: [
        "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs",
        ok2 ? "border-emerald-300/40 bg-emerald-500/12 text-emerald-100" : "border-white/15 bg-white/5 text-white/55"
      ].join(" ")
    },
    /* @__PURE__ */ React.createElement("span", { "aria-hidden": "true" }, ok2 ? "✓" : "○"),
    label
  );
}
function Step3Publish({
  headingRef,
  // Asset
  primaryFile,
  primaryPreviewUrl,
  isArchive,
  screenshots,
  selectedScreenshotIndex,
  onSelectedScreenshotChange,
  fileMetadata,
  // Metadata
  metadata,
  eligibleWorlds = [],
  // Readiness
  canPublish,
  uploadReady,
  // Publish options (from wizard state, for summary display only)
  publishMode = "now",
  scheduledAt = null,
  timezone = null,
  visibility = "public",
  onVisibilityChange,
  selectedGroup = null,
  currentContributorOptions = [],
  actionLabel = "Publish now",
  showScheduleSummary = true,
  // Category tree (for label lookup)
  allRootCategoryOptions = [],
  filteredCategoryTree = [],
  onToggleWorldSubmission,
  onChangeWorldSubmissionNote
}) {
  const prefersReducedMotion = useReducedMotion();
  const quickTransition = prefersReducedMotion ? { duration: 0 } : { duration: 0.2, ease: "easeOut" };
  const hasPreview = Boolean(primaryPreviewUrl && !isArchive);
  const rootCategory = allRootCategoryOptions.find(
    (r) => String(r.id) === String(metadata.rootCategoryId)
  ) ?? null;
  const rootLabel = rootCategory?.name ?? null;
  const subCategory = rootCategory?.children?.find(
    (c) => String(c.id) === String(metadata.subCategoryId)
  ) ?? null;
  const subLabel = subCategory?.name ?? null;
  const descriptionPreview = stripHtml(metadata.description);
  const primaryAuthor = (Array.isArray(currentContributorOptions) ? currentContributorOptions : []).find(
    (user) => Number(user.id) === Number(metadata.primaryAuthorUserId)
  ) ?? null;
  const contributorCredits = metadata.contributorCredits || {};
  const contributors = (Array.isArray(currentContributorOptions) ? currentContributorOptions : []).filter((user) => Array.isArray(metadata.contributorUserIds) && metadata.contributorUserIds.some((id) => Number(id) === Number(user.id))).map((user) => {
    const creditMeta = contributorCredits?.[user.id] || contributorCredits?.[String(user.id)] || { creditRole: "", isPrimary: false };
    return {
      ...user,
      creditRole: creditMeta.creditRole || "",
      isPrimary: Boolean(creditMeta.isPrimary)
    };
  });
  const checks2 = [
    { label: "File uploaded", ok: uploadReady },
    { label: "Scan passed", ok: uploadReady },
    { label: "Preview ready", ok: hasPreview || isArchive && screenshots.length > 0 },
    { label: "Rights confirmed", ok: Boolean(metadata.rightsAccepted) },
    { label: "Tags added", ok: Array.isArray(metadata.tags) && metadata.tags.length > 0 }
  ];
  return /* @__PURE__ */ React.createElement("div", { className: "space-y-5 rounded-[28px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-6 shadow-[0_24px_90px_rgba(2,8,23,0.28)] backdrop-blur sm:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-white/[0.04] px-5 py-4" }, /* @__PURE__ */ React.createElement(
    "h2",
    {
      ref: headingRef,
      tabIndex: -1,
      className: "text-lg font-semibold text-white focus:outline-none"
    },
    "Review & publish"
  ), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white/60" }, "Everything looks good? Hit ", /* @__PURE__ */ React.createElement("span", { className: "text-white/85" }, "Publish"), " to make your artwork live.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl ring-1 ring-white/8 bg-white/[0.025] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row" }, /* @__PURE__ */ React.createElement("div", { className: "shrink-0" }, hasPreview ? /* @__PURE__ */ React.createElement("div", { className: "flex h-[140px] w-[140px] items-center justify-center overflow-hidden rounded-xl ring-1 ring-white/10 bg-black/30" }, /* @__PURE__ */ React.createElement(
    "img",
    {
      src: primaryPreviewUrl,
      alt: "Artwork preview",
      className: "max-h-full max-w-full object-contain",
      loading: "lazy",
      decoding: "async",
      width: 140,
      height: 140
    }
  )) : /* @__PURE__ */ React.createElement("div", { className: "grid h-[140px] w-[140px] place-items-center rounded-xl ring-1 ring-white/10 bg-white/5 text-white/40" }, /* @__PURE__ */ React.createElement("svg", { className: "h-8 w-8", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" })))), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1 space-y-2.5" }, /* @__PURE__ */ React.createElement("p", { className: "text-base font-semibold text-white leading-snug" }, metadata.title || /* @__PURE__ */ React.createElement("span", { className: "text-white/45 italic" }, "Untitled artwork")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/55" }, metadata.contentType && /* @__PURE__ */ React.createElement("span", { className: "capitalize" }, "Type: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, metadata.contentType)), rootLabel && /* @__PURE__ */ React.createElement("span", null, "Category: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, rootLabel)), subLabel && /* @__PURE__ */ React.createElement("span", null, "Sub: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, subLabel))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/55" }, /* @__PURE__ */ React.createElement("span", null, "Tags: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, (metadata.tags || []).length)), /* @__PURE__ */ React.createElement("span", null, "Audience: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, metadata.isMature ? "Mature" : "General")), selectedGroup ? /* @__PURE__ */ React.createElement("span", null, "Publisher: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, selectedGroup.name)) : /* @__PURE__ */ React.createElement("span", null, "Publisher: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, "Personal profile")), !isArchive && fileMetadata?.resolution && fileMetadata.resolution !== "—" && /* @__PURE__ */ React.createElement("span", null, "Resolution: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, fileMetadata.resolution)), isArchive && /* @__PURE__ */ React.createElement("span", null, "Screenshots: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, screenshots.length))), (selectedGroup || primaryAuthor || contributors.length > 0) && /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-xs text-white/55" }, primaryAuthor ? /* @__PURE__ */ React.createElement("span", null, "Primary author: ", /* @__PURE__ */ React.createElement("span", { className: "text-white/75" }, primaryAuthor.name || primaryAuthor.username)) : null, contributors.length > 0 ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", null, "Contributors:"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-2" }, contributors.map((user) => /* @__PURE__ */ React.createElement("span", { key: user.id, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white/80" }, /* @__PURE__ */ React.createElement("span", null, user.name || user.username), user.creditRole ? /* @__PURE__ */ React.createElement("span", { className: "text-white/50" }, user.creditRole) : null, user.isPrimary ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/30 bg-emerald-400/12 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Lead support") : null)))) : null), descriptionPreview && /* @__PURE__ */ React.createElement("p", { className: "line-clamp-2 text-xs text-white/50" }, descriptionPreview))), isArchive && screenshots.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-5 border-t border-white/8 pt-5" }, /* @__PURE__ */ React.createElement(
    ArchiveScreenshotPicker,
    {
      screenshots,
      selectedIndex: selectedScreenshotIndex,
      onSelect: onSelectedScreenshotChange,
      title: "Archive preview",
      description: "This screenshot will be used as the default preview once the archive is published."
    }
  ))), /* @__PURE__ */ React.createElement(
    WorldSubmissionSelector,
    {
      title: "Add to Worlds",
      description: "Attach this artwork to active worlds for creator participation. These placements stay separate from editorial curated relations.",
      options: eligibleWorlds,
      onToggle: onToggleWorldSubmission,
      onNoteChange: onChangeWorldSubmissionNote,
      analyticsContext: { sourceSurface: "upload_flow", sourceDetail: "publish_step" }
    }
  ), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "mb-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Visibility"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 sm:grid-cols-3" }, [
    { value: "public", label: "Public", hint: "Visible to everyone" },
    { value: "unlisted", label: "Unlisted", hint: "Available by direct link" },
    { value: "private", label: "Private", hint: "Keep as draft visibility" }
  ].map((option) => {
    const active = visibility === option.value;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: option.value,
        type: "button",
        onClick: () => onVisibilityChange?.(option.value),
        className: [
          "flex items-start justify-between gap-3 rounded-2xl border px-4 py-3 text-left transition",
          active ? "border-sky-300/30 bg-sky-400/10 text-white shadow-[0_0_0_1px_rgba(56,189,248,0.12)]" : "border-white/10 bg-white/[0.03] text-white/75 hover:border-white/20 hover:bg-white/[0.06]"
        ].join(" ")
      },
      /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-white/45" }, option.hint)),
      /* @__PURE__ */ React.createElement("span", { className: [
        "mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border text-[10px]",
        active ? "border-sky-300/40 bg-sky-400/20 text-sky-100" : "border-white/10 bg-white/5 text-white/30"
      ].join(" ") }, active ? "✓" : "")
    );
  }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-white/15 bg-white/6 px-2.5 py-1 text-xs text-white/60" }, "👁 ", visibility === "public" ? "Public" : visibility === "unlisted" ? "Unlisted" : "Private"), showScheduleSummary && publishMode === "schedule" && scheduledAt ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-violet-300/30 bg-violet-500/15 px-2.5 py-1 text-xs text-violet-200" }, "🕐 Scheduled", timezone && /* @__PURE__ */ React.createElement("span", { className: "text-violet-300/70" }, " ", "·", " ", new Intl.DateTimeFormat("en-GB", {
    timeZone: timezone,
    weekday: "short",
    day: "numeric",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false
  }).format(new Date(scheduledAt)))) : /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1.5 rounded-full border border-emerald-300/30 bg-emerald-500/12 px-2.5 py-1 text-xs text-emerald-200" }, "⚡ ", actionLabel)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2.5 text-xs uppercase tracking-wide text-white/40" }, "Readiness checks"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, checks2.map((check) => /* @__PURE__ */ React.createElement(PublishCheckBadge, { key: check.label, label: check.label, ok: check.ok })))), !canPublish && /* @__PURE__ */ React.createElement(
    motion.div,
    {
      initial: prefersReducedMotion ? false : { opacity: 0, y: 4 },
      animate: { opacity: 1, y: 0 },
      transition: quickTransition,
      className: "rounded-lg ring-1 ring-amber-300/25 bg-amber-500/8 px-4 py-3 text-sm text-amber-100/85"
    },
    !uploadReady ? "Waiting for upload processing to complete…" : !metadata.rightsAccepted ? "Please confirm rights in the Details step to enable publishing." : "Complete all required fields to enable publishing."
  ));
}
const wizardSteps = [
  { key: "upload", label: "Upload" },
  { key: "details", label: "Details" },
  { key: "publish", label: "Publish" }
];
function createInitialMetadata(initialGroupSlug = "", currentUserId = null, contributorOptionsByGroup = {}, eligibleWorlds = []) {
  const normalizedGroupSlug = String(initialGroupSlug || "").trim();
  const contributors = Array.isArray(contributorOptionsByGroup?.[normalizedGroupSlug]) ? contributorOptionsByGroup[normalizedGroupSlug] : [];
  const defaultPrimaryAuthor = contributors.some((user) => Number(user.id) === Number(currentUserId)) ? Number(currentUserId) : Number(contributors[0]?.id || 0) || null;
  return {
    title: "",
    rootCategoryId: "",
    subCategoryId: "",
    tags: [],
    description: "",
    isMature: false,
    rightsAccepted: false,
    contentType: "",
    group: normalizedGroupSlug,
    primaryAuthorUserId: defaultPrimaryAuthor,
    contributorUserIds: [],
    contributorCredits: {},
    worldSubmissions: Array.isArray(eligibleWorlds) ? eligibleWorlds.map((world) => ({ ...world, selected: Boolean(world.selected), note: world.note || "" })) : []
  };
}
function normalizeContributorCredits(contributorIds = [], contributorCredits = {}) {
  const normalized = {};
  const ids = Array.isArray(contributorIds) ? contributorIds.map((id) => Number(id)).filter((id) => Number.isFinite(id) && id > 0) : [];
  ids.forEach((id) => {
    const current = contributorCredits?.[id] || contributorCredits?.[String(id)] || {};
    normalized[id] = {
      creditRole: typeof current.creditRole === "string" ? current.creditRole : "",
      isPrimary: Boolean(current.isPrimary)
    };
  });
  const leadIds = Object.entries(normalized).filter(([, value]) => value.isPrimary).map(([id]) => Number(id));
  if (leadIds.length > 1) {
    leadIds.slice(1).forEach((id) => {
      normalized[id] = {
        ...normalized[id],
        isPrimary: false
      };
    });
  }
  return normalized;
}
function isValidForUpload(primaryFile, primaryErrors, isArchive, screenshotErrors) {
  if (!primaryFile) return false;
  if (primaryErrors.length > 0) return false;
  if (isArchive && screenshotErrors.length > 0) return false;
  return true;
}
function UploadWizard({
  onValidationStateChange,
  initialDraftId = null,
  chunkSize,
  chunkRequestTimeoutMs,
  contentTypes = [],
  suggestedTags = [],
  eligibleWorlds = [],
  groupOptions = [],
  contributorOptionsByGroup = {},
  initialGroupSlug = "",
  currentUserId = null
}) {
  const [notices, setNotices] = reactExports.useState([]);
  const [activeStep, setActiveStep] = reactExports.useState(1);
  const [showRestoredBanner, setShowRestoredBanner] = reactExports.useState(Boolean(initialDraftId));
  const [isUploadLocked, setIsUploadLocked] = reactExports.useState(false);
  const [resolvedArtworkId, setResolvedArtworkId] = reactExports.useState(() => {
    const parsed = Number(initialDraftId);
    return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : null;
  });
  const [publishMode, setPublishMode] = reactExports.useState("now");
  const [scheduledAt, setScheduledAt] = reactExports.useState(null);
  const [visibility, setVisibility] = reactExports.useState("public");
  const userTimezone = reactExports.useMemo(() => {
    try {
      return Intl.DateTimeFormat().resolvedOptions().timeZone;
    } catch {
      return "UTC";
    }
  }, []);
  const [primaryFile, setPrimaryFile] = reactExports.useState(null);
  const [screenshots, setScreenshots] = reactExports.useState([]);
  const [selectedScreenshotIndex, setSelectedScreenshotIndex] = reactExports.useState(0);
  const [metadata, setMetadata] = reactExports.useState(() => createInitialMetadata(initialGroupSlug, currentUserId, contributorOptionsByGroup, eligibleWorlds));
  const prefersReducedMotion = useReducedMotion();
  const stepContentRef = reactExports.useRef(null);
  const stepHeadingRef = reactExports.useRef(null);
  const hasAutoAdvancedRef = reactExports.useRef(false);
  const quickTransition = prefersReducedMotion ? { duration: 0 } : { duration: 0.2, ease: "easeOut" };
  const {
    primaryType,
    primaryErrors,
    primaryWarnings,
    fileMetadata,
    primaryPreviewUrl,
    screenshotErrors,
    screenshotPerFileErrors
  } = useFileValidation(primaryFile, screenshots);
  const isArchive = primaryType === "archive";
  const canStartUpload = isValidForUpload(primaryFile, primaryErrors, isArchive, screenshotErrors);
  reactExports.useEffect(() => {
    if (!Array.isArray(screenshots) || screenshots.length === 0) {
      setSelectedScreenshotIndex(0);
      return;
    }
    setSelectedScreenshotIndex((prev) => {
      if (!Number.isFinite(prev) || prev < 0) return 0;
      return Math.min(prev, screenshots.length - 1);
    });
  }, [screenshots]);
  const {
    machine,
    runUploadFlow,
    handleCancel,
    handlePublish,
    handleRetry,
    resetMachine,
    abortAllRequests,
    clearPolling
  } = useUploadMachine$1({
    primaryFile,
    screenshots,
    selectedScreenshotIndex,
    canStartUpload,
    primaryType,
    isArchive,
    initialDraftId,
    metadata,
    chunkSize,
    chunkRequestTimeoutMs,
    onArtworkCreated: (id) => setResolvedArtworkId(id),
    onNotice: (notice) => {
      if (!notice?.message) return;
      const normalizedType = ["success", "warning", "error"].includes(String(notice.type || "").toLowerCase()) ? String(notice.type).toLowerCase() : "error";
      const id = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
      setNotices((prev) => [...prev, { id, type: normalizedType, message: String(notice.message) }]);
      window.setTimeout(() => {
        setNotices((prev) => prev.filter((item) => item.id !== id));
      }, 4500);
    }
  });
  const uploadReady = machine.state === machineStates.ready_to_publish || machine.processingStatus === "ready" || machine.state === machineStates.complete;
  const { visionSuggestedTags } = useVisionTags(resolvedArtworkId, uploadReady);
  const categoryTreeByType = reactExports.useMemo(() => {
    const result = {};
    const list2 = Array.isArray(contentTypes) ? contentTypes : [];
    list2.forEach((type2) => {
      const value = getContentTypeValue(type2);
      if (!value) return;
      result[value] = buildCategoryTree([type2]);
    });
    return result;
  }, [contentTypes]);
  const filteredCategoryTree = reactExports.useMemo(() => {
    const selected = String(metadata.contentType || "");
    if (!selected) return [];
    return categoryTreeByType[selected] || [];
  }, [categoryTreeByType, metadata.contentType]);
  const selectedGroupOption = reactExports.useMemo(() => {
    const selectedSlug = String(metadata.group || "");
    if (!selectedSlug) return null;
    return (Array.isArray(groupOptions) ? groupOptions : []).find((group) => String(group.slug || "") === selectedSlug) || null;
  }, [groupOptions, metadata.group]);
  const reviewSubmissionMode = Boolean(
    selectedGroupOption && !selectedGroupOption?.permissions?.can_publish_artworks && selectedGroupOption?.permissions?.can_submit_artwork_for_review
  );
  const publishActionLabel = reviewSubmissionMode ? "Submit for review" : publishMode === "schedule" ? "Schedule publish" : "Publish now";
  const currentContributorOptions = reactExports.useMemo(() => {
    const selectedSlug = String(metadata.group || "");
    return Array.isArray(contributorOptionsByGroup?.[selectedSlug]) ? contributorOptionsByGroup[selectedSlug] : [];
  }, [contributorOptionsByGroup, metadata.group]);
  const allRootCategoryOptions = reactExports.useMemo(() => {
    const items = [];
    Object.entries(categoryTreeByType).forEach(([contentTypeValue, roots]) => {
      roots.forEach((root2) => items.push({ ...root2, contentTypeValue }));
    });
    return items;
  }, [categoryTreeByType]);
  const selectedRootCategory = reactExports.useMemo(() => {
    const id = String(metadata.rootCategoryId || "");
    if (!id) return null;
    return filteredCategoryTree.find((r) => String(r.id) === id) || allRootCategoryOptions.find((r) => String(r.id) === id) || null;
  }, [filteredCategoryTree, allRootCategoryOptions, metadata.rootCategoryId]);
  const requiresSubCategory = Boolean(
    selectedRootCategory && Array.isArray(selectedRootCategory.children) && selectedRootCategory.children.length > 0
  );
  reactExports.useEffect(() => {
    const selectedSlug = String(metadata.group || "");
    if (!selectedSlug) {
      if (metadata.primaryAuthorUserId || metadata.contributorUserIds.length > 0 || Object.keys(metadata.contributorCredits || {}).length > 0) {
        setMetadata((current) => ({ ...current, primaryAuthorUserId: null, contributorUserIds: [], contributorCredits: {} }));
      }
      return;
    }
    const validGroup = (Array.isArray(groupOptions) ? groupOptions : []).some((group) => String(group.slug || "") === selectedSlug);
    if (!validGroup) {
      setMetadata((current) => ({ ...current, group: "", primaryAuthorUserId: null, contributorUserIds: [], contributorCredits: {} }));
      return;
    }
    const validContributorIds = currentContributorOptions.map((user) => Number(user.id)).filter((id) => Number.isFinite(id) && id > 0);
    const nextPrimaryAuthorId = validContributorIds.includes(Number(metadata.primaryAuthorUserId)) ? Number(metadata.primaryAuthorUserId) : validContributorIds.includes(Number(currentUserId)) ? Number(currentUserId) : validContributorIds[0] || null;
    const nextContributorIds = (Array.isArray(metadata.contributorUserIds) ? metadata.contributorUserIds : []).map((id) => Number(id)).filter((id) => validContributorIds.includes(id) && id !== nextPrimaryAuthorId);
    const nextContributorCredits = normalizeContributorCredits(nextContributorIds, metadata.contributorCredits);
    const currentPrimary = metadata.primaryAuthorUserId ? Number(metadata.primaryAuthorUserId) : null;
    const currentContributors = (Array.isArray(metadata.contributorUserIds) ? metadata.contributorUserIds : []).map((id) => Number(id));
    const contributorsChanged = nextContributorIds.length !== currentContributors.length || nextContributorIds.some((id, index2) => id !== currentContributors[index2]);
    const contributorCreditsChanged = JSON.stringify(nextContributorCredits) !== JSON.stringify(normalizeContributorCredits(currentContributors, metadata.contributorCredits));
    if (currentPrimary !== nextPrimaryAuthorId || contributorsChanged || contributorCreditsChanged) {
      setMetadata((current) => ({
        ...current,
        primaryAuthorUserId: nextPrimaryAuthorId,
        contributorUserIds: nextContributorIds,
        contributorCredits: nextContributorCredits
      }));
    }
  }, [groupOptions, currentContributorOptions, currentUserId, metadata.group, metadata.primaryAuthorUserId, metadata.contributorUserIds, metadata.contributorCredits]);
  const metadataErrors = reactExports.useMemo(() => {
    const errors = {};
    if (!String(metadata.title || "").trim()) errors.title = "Title is required.";
    if (!metadata.contentType) errors.contentType = "Content type is required.";
    if (!metadata.rootCategoryId) errors.category = "Root category is required.";
    if (metadata.rootCategoryId && requiresSubCategory && !metadata.subCategoryId) {
      errors.category = "Subcategory is required for the selected category.";
    }
    if (!Array.isArray(metadata.tags) || metadata.tags.length === 0) errors.tags = "Add at least one tag.";
    if (!String(metadata.description || "").trim()) {
      errors.description = "Description is required.";
    } else {
      const descriptionErrors = validateMarkdownLiteContent(metadata.description);
      if (descriptionErrors.length > 0) {
        errors.description = descriptionErrors[0];
      }
    }
    if (!metadata.rightsAccepted) errors.rights = "Rights confirmation is required.";
    return errors;
  }, [metadata, requiresSubCategory]);
  const detailsValid = Object.keys(metadataErrors).length === 0;
  const mergedSuggestedTags = reactExports.useMemo(() => {
    const map = /* @__PURE__ */ new Map();
    const addTag = (item) => {
      if (!item) return;
      const key = String(item?.slug || item?.tag || item?.name || item).trim().toLowerCase();
      if (!key || map.has(key)) return;
      map.set(key, typeof item === "string" ? item : {
        id: item.id ?? key,
        name: item.name || item.tag || item.slug || key,
        slug: item.slug || item.tag || key,
        usage_count: Number(item.usage_count || 0),
        is_ai: Boolean(item.is_ai || item.source === "ai"),
        source: item.source || (item.is_ai ? "ai" : "manual")
      });
    };
    (Array.isArray(suggestedTags) ? suggestedTags : []).forEach(addTag);
    (Array.isArray(visionSuggestedTags) ? visionSuggestedTags : []).forEach(addTag);
    return Array.from(map.values());
  }, [suggestedTags, visionSuggestedTags]);
  const highestUnlockedStep = uploadReady ? detailsValid ? 3 : 2 : 1;
  const showProgress = ![machineStates.idle, machineStates.cancelled].includes(machine.state);
  const processingLabel = getProcessingTransparencyLabel(machine.processingStatus, machine.state);
  ["initializing", "uploading", "finishing", "processing", "error"].includes(machine.state);
  const hasTitle = Boolean(String(metadata.title || "").trim());
  const hasCompleteCategory = Boolean(
    metadata.rootCategoryId && (!requiresSubCategory || metadata.subCategoryId)
  );
  const hasTag = Array.isArray(metadata.tags) && metadata.tags.length > 0;
  const hasRequiredScreenshot = !isArchive || screenshots.length > 0;
  const canPublish = reactExports.useMemo(() => uploadReady && hasTitle && hasCompleteCategory && hasTag && hasRequiredScreenshot && String(metadata.description || "").trim() && !metadataErrors.description && metadata.rightsAccepted && machine.state !== machineStates.publishing, [uploadReady, hasTitle, hasCompleteCategory, hasTag, hasRequiredScreenshot, metadata.description, metadata.rightsAccepted, metadataErrors.description, machine.state]);
  const canScheduleSubmit = reactExports.useMemo(() => {
    if (!canPublish) return false;
    if (reviewSubmissionMode) return true;
    if (publishMode === "schedule") return Boolean(scheduledAt);
    return true;
  }, [canPublish, reviewSubmissionMode, publishMode, scheduledAt]);
  const publishActionEnabled = activeStep === 3 && canScheduleSubmit;
  const validationErrors = reactExports.useMemo(
    () => [...primaryErrors, ...screenshotErrors],
    [primaryErrors, screenshotErrors]
  );
  reactExports.useEffect(() => {
    if (typeof onValidationStateChange === "function") {
      onValidationStateChange({ isValid: canStartUpload, validationErrors, isArchive });
    }
  }, [canStartUpload, validationErrors, isArchive, onValidationStateChange]);
  reactExports.useEffect(() => {
    if (uploadReady && activeStep === 1 && !hasAutoAdvancedRef.current) {
      hasAutoAdvancedRef.current = true;
      setIsUploadLocked(true);
      setActiveStep(2);
    }
  }, [uploadReady, activeStep]);
  reactExports.useEffect(() => {
    if (uploadReady) setIsUploadLocked(true);
  }, [uploadReady]);
  reactExports.useEffect(() => {
    if (!stepContentRef.current) return;
    stepContentRef.current.scrollIntoView({
      behavior: prefersReducedMotion ? "auto" : "smooth",
      block: "start"
    });
    window.setTimeout(() => {
      stepHeadingRef.current?.focus?.({ preventScroll: true });
    }, 0);
  }, [activeStep, prefersReducedMotion]);
  reactExports.useEffect(() => {
    return () => {
      abortAllRequests();
      clearPolling();
    };
  }, [abortAllRequests, clearPolling]);
  const setMeta = reactExports.useCallback((patch2) => setMetadata((prev) => ({ ...prev, ...patch2 })), []);
  const handleReset = reactExports.useCallback(() => {
    resetMachine();
    setPrimaryFile(null);
    setScreenshots([]);
    setSelectedScreenshotIndex(0);
    setMetadata(createInitialMetadata(initialGroupSlug, currentUserId, contributorOptionsByGroup, eligibleWorlds));
    setIsUploadLocked(false);
    hasAutoAdvancedRef.current = false;
    setPublishMode("now");
    setScheduledAt(null);
    setVisibility("public");
    setResolvedArtworkId(() => {
      const parsed = Number(initialDraftId);
      return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : null;
    });
    setActiveStep(1);
  }, [resetMachine, initialDraftId, initialGroupSlug, currentUserId, contributorOptionsByGroup, eligibleWorlds]);
  const goToStep = reactExports.useCallback((step) => {
    if (step >= 1 && step <= highestUnlockedStep) setActiveStep(step);
  }, [highestUnlockedStep]);
  const renderStepContent = () => {
    if (machine.state === machineStates.complete) {
      const wasScheduled = machine.lastAction === "schedule";
      const studioArtworksUrl = "/studio/artworks";
      const artworkUrl = resolvedArtworkId ? `/art/${resolvedArtworkId}${machine.slug ? `/${machine.slug}` : ""}` : "/";
      const studioArtworkUrl = resolvedArtworkId ? `/studio/artworks/${resolvedArtworkId}/edit` : studioArtworksUrl;
      return /* @__PURE__ */ React.createElement(
        motion.div,
        {
          initial: prefersReducedMotion ? false : { opacity: 0, scale: 0.98 },
          animate: { opacity: 1, scale: 1 },
          transition: prefersReducedMotion ? { duration: 0 } : { duration: 0.28, ease: "easeOut" },
          className: `rounded-2xl p-8 text-center ${wasScheduled ? "ring-1 ring-violet-300/25 bg-violet-500/8" : "ring-1 ring-emerald-300/25 bg-emerald-500/8"}`
        },
        /* @__PURE__ */ React.createElement(
          motion.div,
          {
            initial: prefersReducedMotion ? false : { scale: 0.7, opacity: 0 },
            animate: { scale: 1, opacity: 1 },
            transition: prefersReducedMotion ? { duration: 0 } : { delay: 0.1, duration: 0.26, ease: "backOut" },
            className: `mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full text-2xl`
          },
          wasScheduled ? "🕐" : "🎉"
        ),
        /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold text-white" }, wasScheduled ? "Artwork scheduled!" : "Your artwork is live!"),
        /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/65" }, wasScheduled ? scheduledAt ? `Will publish on ${new Intl.DateTimeFormat("en-GB", { timeZone: userTimezone, weekday: "short", day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit", hour12: false }).format(new Date(scheduledAt))}` : "Your artwork is scheduled for future publishing." : "It has been published and is now visible to the community."),
        /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap justify-center gap-3" }, !wasScheduled && /* @__PURE__ */ React.createElement(
          "a",
          {
            href: artworkUrl,
            className: "rounded-lg ring-1 ring-emerald-300/45 bg-emerald-400/20 px-4 py-2 text-sm font-medium text-emerald-50 hover:bg-emerald-400/30 transition"
          },
          "View artwork"
        ), /* @__PURE__ */ React.createElement(
          "a",
          {
            href: studioArtworksUrl,
            className: "rounded-lg ring-1 ring-sky-300/35 bg-sky-400/12 px-4 py-2 text-sm font-medium text-sky-50 hover:bg-sky-400/20 transition"
          },
          "View in studio"
        ), /* @__PURE__ */ React.createElement(
          "a",
          {
            href: studioArtworkUrl,
            className: "rounded-lg ring-1 ring-white/20 bg-white/8 px-4 py-2 text-sm font-medium text-white hover:bg-white/15 transition"
          },
          "Edit artwork in studio"
        ), /* @__PURE__ */ React.createElement(
          "button",
          {
            type: "button",
            onClick: handleReset,
            className: "rounded-lg ring-1 ring-white/20 bg-white/8 px-4 py-2 text-sm text-white hover:bg-white/15 transition"
          },
          "Upload another"
        ))
      );
    }
    if (activeStep === 1) {
      return /* @__PURE__ */ React.createElement(
        Step1FileUpload,
        {
          headingRef: stepHeadingRef,
          primaryFile,
          primaryPreviewUrl,
          primaryErrors,
          primaryWarnings,
          fileMetadata,
          fileSelectionLocked: isUploadLocked,
          onPrimaryFileChange: setPrimaryFile,
          isArchive,
          screenshots,
          selectedScreenshotIndex,
          screenshotErrors,
          screenshotPerFileErrors,
          onScreenshotsChange: setScreenshots,
          onSelectedScreenshotChange: setSelectedScreenshotIndex,
          machine
        }
      );
    }
    if (activeStep === 2) {
      return /* @__PURE__ */ React.createElement(
        Step2Details,
        {
          headingRef: stepHeadingRef,
          primaryFile,
          primaryPreviewUrl,
          isArchive,
          fileMetadata,
          screenshots,
          selectedScreenshotIndex,
          onSelectedScreenshotChange: setSelectedScreenshotIndex,
          contentTypes,
          metadata,
          metadataErrors,
          filteredCategoryTree,
          allRootCategoryOptions,
          requiresSubCategory,
          onContentTypeChange: (value) => setMeta({ contentType: value, rootCategoryId: "", subCategoryId: "" }),
          onRootCategoryChange: (rootId) => setMeta({ rootCategoryId: rootId, subCategoryId: "" }),
          onSubCategoryChange: (subId) => setMeta({ subCategoryId: subId }),
          groupOptions,
          currentContributorOptions,
          onGroupChange: (groupSlug) => setMeta({ group: groupSlug }),
          onPrimaryAuthorChange: (authorId) => setMeta({ primaryAuthorUserId: authorId ? Number(authorId) : null }),
          onContributorToggle: (contributorId) => setMetadata((current) => {
            const normalizedId = Number(contributorId);
            const nextIds = new Set((Array.isArray(current.contributorUserIds) ? current.contributorUserIds : []).map((id) => Number(id)).filter((id) => id !== Number(current.primaryAuthorUserId)));
            if (nextIds.has(normalizedId)) {
              nextIds.delete(normalizedId);
            } else {
              nextIds.add(normalizedId);
            }
            const contributorUserIds = Array.from(nextIds).filter((id) => id !== Number(current.primaryAuthorUserId));
            return {
              ...current,
              contributorUserIds,
              contributorCredits: normalizeContributorCredits(contributorUserIds, current.contributorCredits)
            };
          }),
          onContributorRoleChange: (contributorId, creditRole) => setMetadata((current) => {
            const contributorUserIds = (Array.isArray(current.contributorUserIds) ? current.contributorUserIds : []).map((id) => Number(id));
            if (!contributorUserIds.includes(Number(contributorId))) return current;
            const contributorCredits = normalizeContributorCredits(contributorUserIds, current.contributorCredits);
            return {
              ...current,
              contributorCredits: {
                ...contributorCredits,
                [Number(contributorId)]: {
                  ...contributorCredits[Number(contributorId)] || { isPrimary: false },
                  creditRole
                }
              }
            };
          }),
          onContributorPrimaryChange: (contributorId) => setMetadata((current) => {
            const contributorUserIds = (Array.isArray(current.contributorUserIds) ? current.contributorUserIds : []).map((id) => Number(id));
            const contributorCredits = normalizeContributorCredits(contributorUserIds, current.contributorCredits);
            contributorUserIds.forEach((id) => {
              contributorCredits[id] = {
                ...contributorCredits[id] || { creditRole: "" },
                isPrimary: id === Number(contributorId)
              };
            });
            return {
              ...current,
              contributorCredits
            };
          }),
          suggestedTags: mergedSuggestedTags,
          publishMode,
          scheduledAt,
          timezone: userTimezone,
          onPublishModeChange: setPublishMode,
          onScheduleAt: setScheduledAt,
          onChangeTitle: (value) => setMeta({ title: value }),
          onChangeTags: (value) => setMeta({ tags: value }),
          onChangeDescription: (value) => setMeta({ description: value }),
          onToggleRights: (value) => setMeta({ rightsAccepted: Boolean(value) })
        }
      );
    }
    return /* @__PURE__ */ React.createElement(
      Step3Publish,
      {
        headingRef: stepHeadingRef,
        primaryFile,
        primaryPreviewUrl,
        isArchive,
        screenshots,
        selectedScreenshotIndex,
        onSelectedScreenshotChange: setSelectedScreenshotIndex,
        fileMetadata,
        metadata,
        eligibleWorlds: Array.isArray(metadata.worldSubmissions) ? metadata.worldSubmissions : [],
        canPublish,
        uploadReady,
        publishMode,
        scheduledAt,
        timezone: userTimezone,
        visibility,
        actionLabel: publishActionLabel,
        showScheduleSummary: !reviewSubmissionMode,
        onVisibilityChange: setVisibility,
        selectedGroup: selectedGroupOption,
        currentContributorOptions,
        allRootCategoryOptions,
        filteredCategoryTree,
        onToggleWorldSubmission: (worldId) => setMetadata((current) => ({
          ...current,
          worldSubmissions: (Array.isArray(current.worldSubmissions) ? current.worldSubmissions : []).map((world) => Number(world.id) === Number(worldId) && !world.selection_locked ? { ...world, selected: !world.selected } : world)
        })),
        onChangeWorldSubmissionNote: (worldId, note) => setMetadata((current) => ({
          ...current,
          worldSubmissions: (Array.isArray(current.worldSubmissions) ? current.worldSubmissions : []).map((world) => Number(world.id) === Number(worldId) ? { ...world, note } : world)
        }))
      }
    );
  };
  const disableReason = (() => {
    if (activeStep === 1) return validationErrors[0] || machine.error || "Complete upload requirements first.";
    if (activeStep === 2) return metadataErrors.title || metadataErrors.contentType || metadataErrors.category || metadataErrors.rights || metadataErrors.tags || "Complete required metadata.";
    return machine.error || "Publish is available when upload is ready and rights are confirmed.";
  })();
  const publishActionTitle = activeStep < 3 ? "Continue to the final publish step to choose Worlds and publish." : disableReason;
  return /* @__PURE__ */ React.createElement(
    "section",
    {
      ref: stepContentRef,
      className: "space-y-5 pb-40 text-white lg:pb-40",
      "data-is-archive": isArchive ? "true" : "false"
    },
    notices.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "fixed right-4 top-4 z-[70] w-[min(92vw,420px)] space-y-2" }, notices.map((notice) => /* @__PURE__ */ React.createElement(
      "div",
      {
        key: notice.id,
        role: "alert",
        "aria-live": "polite",
        className: [
          "rounded-xl border px-4 py-3 text-sm shadow-lg backdrop-blur",
          notice.type === "success" ? "border-emerald-400/45 bg-emerald-500/12 text-emerald-100" : notice.type === "warning" ? "border-amber-400/45 bg-amber-500/12 text-amber-100" : "border-red-400/45 bg-red-500/12 text-red-100"
        ].join(" ")
      },
      notice.message
    ))),
    showRestoredBanner && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-sky-300/20 bg-sky-500/10 px-4 py-3 text-sm text-sky-100 shadow-[0_14px_44px_rgba(14,165,233,0.10)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", null, "Draft restored. Continue from your previous upload session."), /* @__PURE__ */ React.createElement(
      "button",
      {
        type: "button",
        onClick: () => setShowRestoredBanner(false),
        className: "shrink-0 rounded-md ring-1 ring-sky-200/35 bg-sky-500/15 px-2 py-1 text-xs text-sky-100 hover:bg-sky-500/25 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70"
      },
      "Dismiss"
    ))),
    /* @__PURE__ */ React.createElement(
      StudioStatusBar,
      {
        steps: wizardSteps,
        activeStep,
        highestUnlockedStep,
        machineState: machine.state,
        progress: machine.progress,
        showProgress,
        onStepClick: goToStep
      }
    ),
    /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-start lg:gap-8" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement(AnimatePresence, { mode: "wait", initial: false }, /* @__PURE__ */ React.createElement(
      motion.div,
      {
        key: `step-${activeStep}`,
        initial: prefersReducedMotion ? false : { opacity: 0, y: 8 },
        animate: { opacity: 1, y: 0 },
        exit: prefersReducedMotion ? {} : { opacity: 0, y: -8 },
        transition: quickTransition
      },
      renderStepContent()
    )), /* @__PURE__ */ React.createElement(
      UploadOverlay,
      {
        machineState: machine.state,
        progress: machine.progress,
        processingLabel,
        error: machine.error,
        onRetry: () => handleRetry(canPublish, { mode: publishMode, publishAt: scheduledAt, timezone: userTimezone, visibility }),
        onReset: handleReset
      }
    )), machine.state !== machineStates.complete && /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement(
      UploadActions,
      {
        step: activeStep,
        canStart: canStartUpload && [machineStates.idle, machineStates.error, machineStates.cancelled].includes(machine.state),
        canContinue: detailsValid,
        canPublish: publishActionEnabled,
        canGoBack: activeStep > 1 && machine.state !== machineStates.complete,
        canReset: Boolean(primaryFile || screenshots.length || metadata.title || metadata.description || metadata.tags.length),
        canCancel: activeStep === 1 && [
          machineStates.initializing,
          machineStates.uploading,
          machineStates.finishing,
          machineStates.processing
        ].includes(machine.state),
        canRetry: machine.state === machineStates.error,
        isUploading: [machineStates.uploading, machineStates.initializing].includes(machine.state),
        isProcessing: [machineStates.processing, machineStates.finishing].includes(machine.state),
        isPublishing: machine.state === machineStates.publishing,
        isCancelling: machine.isCancelling,
        disableReason,
        onStart: runUploadFlow,
        onContinue: () => detailsValid && setActiveStep(3),
        onPublish: () => publishActionEnabled && handlePublish(canPublish, { mode: reviewSubmissionMode ? "now" : publishMode, publishAt: reviewSubmissionMode ? null : scheduledAt, timezone: userTimezone, visibility, action: reviewSubmissionMode ? "submit_review" : "publish" }),
        onBack: () => setActiveStep((s2) => Math.max(1, s2 - 1)),
        onCancel: handleCancel,
        onReset: handleReset,
        onRetry: () => handleRetry(canPublish, { mode: reviewSubmissionMode ? "now" : publishMode, publishAt: reviewSubmissionMode ? null : scheduledAt, timezone: userTimezone, visibility, action: reviewSubmissionMode ? "submit_review" : "publish" }),
        onSaveDraft: () => {
        },
        showSaveDraft: activeStep === 2,
        resetLabel: isUploadLocked ? "Reset upload" : "Reset",
        publishLabel: publishActionLabel,
        mobileSticky: true
      }
    ))), (primaryFile || resolvedArtworkId) && machine.state !== machineStates.complete && activeStep > 1 && /* @__PURE__ */ React.createElement("div", { className: "hidden shrink-0 lg:block lg:w-80 xl:w-[22rem] lg:sticky lg:top-20 lg:self-start" }, /* @__PURE__ */ React.createElement(
      PublishPanel,
      {
        primaryPreviewUrl,
        isArchive,
        screenshots,
        selectedScreenshotIndex,
        onSelectedScreenshotChange: setSelectedScreenshotIndex,
        metadata,
        machineState: machine.state,
        uploadReady,
        canPublish,
        publishActionEnabled,
        publishActionTitle,
        isPublishing: machine.state === machineStates.publishing,
        isArchiveRequiresScreenshot: isArchive,
        publishMode,
        scheduledAt,
        timezone: userTimezone,
        visibility,
        actionLabel: publishActionLabel,
        showScheduleControls: !reviewSubmissionMode,
        showRightsConfirmation: activeStep === 3,
        showVisibility: false,
        onPublishModeChange: setPublishMode,
        onScheduleAt: setScheduledAt,
        onVisibilityChange: setVisibility,
        onToggleRights: (checked) => setMeta({ rightsAccepted: Boolean(checked) }),
        onPublish: () => handlePublish(canPublish, { mode: reviewSubmissionMode ? "now" : publishMode, publishAt: reviewSubmissionMode ? null : scheduledAt, timezone: userTimezone, visibility, action: reviewSubmissionMode ? "submit_review" : "publish" }),
        onCancel: handleCancel,
        onGoToStep: goToStep,
        allRootCategoryOptions
      }
    )))
  );
}
const phases = {
  idle: "idle",
  initializing: "initializing",
  ready: "ready",
  uploading: "uploading",
  finishing: "finishing",
  polling: "polling",
  cancelling: "cancelling",
  success: "success",
  error: "error"
};
const DEFAULT_CHUNK_REQUEST_TIMEOUT_MS = 45e3;
const MIN_CHUNK_SIZE_BYTES = 256 * 1024;
function formatChunkSize(bytes) {
  if (!Number.isFinite(bytes) || bytes <= 0) return "0 KB";
  if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(bytes % (1024 * 1024) === 0 ? 0 : 1)} MB`;
  return `${Math.max(1, Math.round(bytes / 1024))} KB`;
}
function isRequestTooLarge(error) {
  return Number(error?.response?.status || 0) === 413;
}
const initialState = {
  phase: phases.idle,
  sessionId: null,
  uploadToken: null,
  file: null,
  filePreviewUrl: null,
  previewUrl: null,
  progress: 0,
  pipelineStatus: null,
  failureReason: null,
  error: null,
  cancelledAt: null,
  notices: [],
  artworkId: null,
  draftId: null,
  metadata: {
    title: "",
    type: "",
    category: "",
    tags: "",
    description: "",
    isMature: false,
    licenseAccepted: false
  }
};
const STORAGE_VERSION = 1;
function storageKey(userId) {
  return `sb.upload.session.${userId}.v${STORAGE_VERSION}`;
}
function readStoredSession(userId) {
  try {
    const raw = window.localStorage.getItem(storageKey(userId));
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") return null;
    return parsed;
  } catch (error) {
    return null;
  }
}
function writeStoredSession(userId, payload) {
  try {
    window.localStorage.setItem(storageKey(userId), JSON.stringify(payload));
  } catch (error) {
  }
}
function clearStoredSession(userId) {
  try {
    window.localStorage.removeItem(storageKey(userId));
  } catch (error) {
  }
}
function reducer(state, action) {
  switch (action.type) {
    case "SET_DRAFT":
      return { ...state, draftId: action.draftId, artworkId: action.artworkId ?? state.artworkId };
    case "SET_FILE":
      return { ...state, file: action.file, filePreviewUrl: action.previewUrl, error: null, cancelledAt: null };
    case "SET_METADATA":
      return { ...state, metadata: { ...state.metadata, ...action.payload } };
    case "INIT_START":
      return { ...state, phase: phases.initializing, error: null, cancelledAt: null };
    case "INIT_SUCCESS":
      return { ...state, phase: phases.ready, sessionId: action.sessionId, uploadToken: action.uploadToken, pipelineStatus: action.status };
    case "RESTORE_SESSION":
      return { ...state, phase: phases.ready, sessionId: action.sessionId, uploadToken: action.uploadToken, pipelineStatus: action.status ?? state.pipelineStatus };
    case "RESUME_SESSION":
      return { ...state, phase: phases.polling, sessionId: action.sessionId, pipelineStatus: action.status ?? state.pipelineStatus };
    case "INIT_ERROR":
      return { ...state, phase: phases.error, error: action.error };
    case "UPLOAD_START":
      return { ...state, phase: phases.uploading, progress: 0, error: null };
    case "UPLOAD_PROGRESS":
      return { ...state, progress: action.progress };
    case "UPLOAD_ERROR":
      return { ...state, phase: phases.error, error: action.error };
    case "FINISH_START":
      return { ...state, phase: phases.finishing, error: null };
    case "FINISH_SUCCESS":
      return { ...state, phase: phases.polling, pipelineStatus: action.status, previewUrl: action.previewUrl ?? null };
    case "FINISH_ERROR":
      return { ...state, phase: phases.error, error: action.error };
    case "CANCEL_START":
      return { ...state, phase: phases.cancelling, error: null };
    case "CANCEL_SUCCESS":
      return { ...state, phase: phases.idle, cancelledAt: Date.now() };
    case "CLEAR_CANCELLED":
      return { ...state, cancelledAt: null };
    case "CANCEL_ERROR":
      return { ...state, phase: phases.error, error: action.error };
    case "STATUS_UPDATE":
      return { ...state, pipelineStatus: action.status, progress: action.progress ?? state.progress, failureReason: action.failureReason ?? null };
    case "STATUS_ERROR":
      return { ...state, phase: phases.error, error: action.error };
    case "SUCCESS":
      return { ...state, phase: phases.success };
    case "RESET":
      return { ...initialState, draftId: state.draftId, cancelledAt: state.cancelledAt };
    case "PUSH_NOTICE":
      return { ...state, notices: [...state.notices, action.notice] };
    case "REMOVE_NOTICE":
      return { ...state, notices: state.notices.filter((notice) => notice.id !== action.id) };
    default:
      return state;
  }
}
const MAX_CHUNK_RETRIES = 3;
const RETRY_DELAY_MS = 900;
function normalizeUiTag(rawTag) {
  const raw = String(rawTag ?? "").trim().toLowerCase();
  if (!raw) return "";
  return raw.replace(/\s+/g, "-").replace(/[^a-z0-9_-]/g, "").replace(/-+/g, "-").replace(/_+/g, "_").replace(/^[-_]+|[-_]+$/g, "").slice(0, 32);
}
function parseUiTags(csvValue) {
  return String(csvValue ?? "").split(/[\n,]+/).map((item) => normalizeUiTag(item)).filter(Boolean);
}
function getTypeKey(ct) {
  if (!ct) return "default";
  if (ct.slug && typeof ct.slug === "string") {
    return ct.slug.toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "");
  }
  return String(ct.name || "").toLowerCase().replace(/\s+/g, "_").replace(/[^a-z0-9_]/g, "");
}
function useUploadMachine({ draftId = null, filesCdnUrl = "", chunkSize, chunkRequestTimeoutMs, userId = null } = {}) {
  const [state, dispatch] = reactExports.useReducer(reducer, { ...initialState, draftId });
  const pollRef = reactExports.useRef(null);
  const adaptiveChunkSizeRef = reactExports.useRef(Math.max(1, Number(chunkSize || 0)));
  const effectiveChunkRequestTimeoutMs = (() => {
    const parsed = Number(chunkRequestTimeoutMs);
    return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : DEFAULT_CHUNK_REQUEST_TIMEOUT_MS;
  })();
  reactExports.useCallback((error, fallback) => {
    const message = error?.response?.data?.message;
    if (message && typeof message === "string") return message;
    const errors = error?.response?.data?.errors;
    if (errors && typeof errors === "object") {
      const firstKey = Object.keys(errors)[0];
      if (firstKey && Array.isArray(errors[firstKey]) && errors[firstKey][0]) {
        return errors[firstKey][0];
      }
    }
    return fallback;
  }, []);
  const pushNotice = reactExports.useCallback((type2, message) => {
    const normalizedType = ["success", "warning", "error"].includes(String(type2 || "").toLowerCase()) ? String(type2).toLowerCase() : "error";
    const id = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
    dispatch({ type: "PUSH_NOTICE", notice: { id, type: normalizedType, message } });
    window.setTimeout(() => {
      dispatch({ type: "REMOVE_NOTICE", id });
    }, 4500);
  }, []);
  const pushMappedNotice = reactExports.useCallback((notice) => {
    if (!notice?.message) return;
    pushNotice(notice.type || "error", notice.message);
  }, [pushNotice]);
  const previewUrl = reactExports.useMemo(() => {
    if (state.previewUrl) return state.previewUrl;
    if (!state.filePreviewUrl) return null;
    return state.filePreviewUrl;
  }, [state.previewUrl, state.filePreviewUrl]);
  const stopPolling = reactExports.useCallback(() => {
    if (pollRef.current) {
      window.clearInterval(pollRef.current);
      pollRef.current = null;
    }
  }, []);
  const startPolling = reactExports.useCallback(() => {
    if (!state.sessionId) return;
    stopPolling();
    pollRef.current = window.setInterval(async () => {
      try {
        const res = await window.axios.get(`/api/uploads/status/${state.sessionId}`, {
          headers: state.uploadToken ? { "X-Upload-Token": state.uploadToken } : void 0,
          params: state.uploadToken ? { upload_token: state.uploadToken } : void 0
        });
        const data = res.data || {};
        dispatch({
          type: "STATUS_UPDATE",
          status: data.status,
          progress: typeof data.progress === "number" ? data.progress : state.progress,
          failureReason: data.failure_reason
        });
        if (data.status === "processed") {
          dispatch({ type: "SUCCESS" });
          stopPolling();
        }
        if (data.failure_reason) {
          dispatch({ type: "STATUS_ERROR", error: data.failure_reason });
          stopPolling();
        }
      } catch (error) {
        dispatch({ type: "STATUS_ERROR", error: "Status check failed." });
        stopPolling();
      }
    }, 2500);
  }, [state.sessionId, state.uploadToken, state.progress, stopPolling]);
  reactExports.useEffect(() => {
    if (draftId && !state.sessionId) {
      dispatch({ type: "RESUME_SESSION", sessionId: draftId, status: "resuming" });
    }
  }, [draftId, state.sessionId]);
  reactExports.useEffect(() => {
    if (state.phase === phases.polling) {
      startPolling();
    }
    return () => stopPolling();
  }, [state.phase, startPolling, stopPolling]);
  reactExports.useEffect(() => {
    return () => {
      if (state.filePreviewUrl) {
        URL.revokeObjectURL(state.filePreviewUrl);
      }
    };
  }, [state.filePreviewUrl]);
  const initSession = reactExports.useCallback(async () => {
    dispatch({ type: "INIT_START" });
    try {
      const res = await window.axios.post("/api/uploads/init", { client: "web" });
      const data = res.data || {};
      dispatch({
        type: "INIT_SUCCESS",
        sessionId: data.session_id,
        uploadToken: data.upload_token,
        status: data.status
      });
      if (userId && data.session_id && data.upload_token && state.file) {
        writeStoredSession(userId, {
          session_id: data.session_id,
          upload_token: data.upload_token,
          file_name: state.file.name,
          file_size: state.file.size,
          updated_at: Date.now()
        });
      }
      return { sessionId: data.session_id, uploadToken: data.upload_token };
    } catch (error) {
      const notice = mapUploadErrorNotice(error, "Failed to initialize upload session.");
      dispatch({ type: "INIT_ERROR", error: notice.message });
      pushMappedNotice(notice);
      return null;
    }
  }, [state.file, userId, pushMappedNotice]);
  const createDraft = reactExports.useCallback(async () => {
    if (state.artworkId) return state.artworkId;
    try {
      const res = await window.axios.post("/api/artworks", {
        title: state.metadata.title,
        category: state.metadata.category,
        tags: state.metadata.tags,
        description: state.metadata.description,
        is_mature: state.metadata.isMature,
        license: state.metadata.licenseAccepted
      });
      const data = res.data || {};
      const artworkId = data.artwork_id ?? data.id;
      if (artworkId) {
        dispatch({ type: "SET_DRAFT", draftId: state.draftId, artworkId });
        return artworkId;
      }
      throw new Error("missing_artwork_id");
    } catch (error) {
      const notice = mapUploadErrorNotice(error, "Unable to create draft metadata.");
      dispatch({ type: "FINISH_ERROR", error: notice.message });
      pushMappedNotice(notice);
      return null;
    }
  }, [state.artworkId, state.metadata, state.draftId, pushMappedNotice]);
  const syncArtworkTags = reactExports.useCallback(async (artworkId) => {
    const tags = Array.from(new Set(parseUiTags(state.metadata.tags)));
    if (tags.length === 0) {
      return true;
    }
    try {
      await window.axios.put(`/api/artworks/${artworkId}/tags`, { tags });
      return true;
    } catch (error) {
      const notice = mapUploadErrorNotice(error, "Tag sync failed. Upload will continue.");
      pushMappedNotice({ ...notice, type: "warning" });
      return false;
    }
  }, [state.metadata.tags, pushMappedNotice]);
  const fetchStatus = reactExports.useCallback(async (sessionId, uploadToken) => {
    const res = await window.axios.get(`/api/uploads/status/${sessionId}`, {
      headers: uploadToken ? { "X-Upload-Token": uploadToken } : void 0,
      params: uploadToken ? { upload_token: uploadToken } : void 0
    });
    return res.data || {};
  }, []);
  const validateStoredSession = reactExports.useCallback(async (file) => {
    if (!userId) return null;
    const stored = readStoredSession(userId);
    if (!stored) return null;
    if (stored.file_name !== file.name || stored.file_size !== file.size) {
      clearStoredSession(userId);
      return null;
    }
    try {
      const data = await fetchStatus(stored.session_id, stored.upload_token);
      if (!data || !data.session_id) {
        clearStoredSession(userId);
        return null;
      }
      dispatch({ type: "RESTORE_SESSION", sessionId: stored.session_id, uploadToken: stored.upload_token, status: data.status });
      return { sessionId: stored.session_id, uploadToken: stored.upload_token };
    } catch (error) {
      clearStoredSession(userId);
      return null;
    }
  }, [fetchStatus, userId]);
  const uploadChunk = reactExports.useCallback(async (sessionId, uploadToken, blob, offset, totalSize, attempt) => {
    const payload = new FormData();
    payload.append("session_id", sessionId);
    payload.append("offset", String(offset));
    payload.append("chunk_size", String(blob.size));
    payload.append("total_size", String(totalSize));
    payload.append("chunk", blob);
    payload.append("upload_token", uploadToken);
    try {
      const res = await window.axios.post("/api/uploads/chunk", payload, {
        timeout: effectiveChunkRequestTimeoutMs,
        headers: uploadToken ? { "X-Upload-Token": uploadToken } : void 0
      });
      const data = res.data || {};
      if (typeof data.progress === "number") {
        dispatch({ type: "UPLOAD_PROGRESS", progress: data.progress });
      }
      return data;
    } catch (error) {
      if (isRequestTooLarge(error)) {
        throw error;
      }
      if (attempt < MAX_CHUNK_RETRIES) {
        await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS * (attempt + 1)));
        return uploadChunk(sessionId, uploadToken, blob, offset, totalSize, attempt + 1);
      }
      throw error;
    }
  }, [effectiveChunkRequestTimeoutMs]);
  const uploadFile2 = reactExports.useCallback(async (sessionId, uploadToken, file) => {
    dispatch({ type: "UPLOAD_START" });
    let status2;
    try {
      status2 = await fetchStatus(sessionId, uploadToken);
    } catch (error) {
      const notice = mapUploadErrorNotice(error, "Unable to resume upload.");
      dispatch({ type: "UPLOAD_ERROR", error: notice.message });
      pushMappedNotice(notice);
      return false;
    }
    let offset = Number(status2.received_bytes || 0);
    const totalSize = file.size;
    if (offset > totalSize) offset = 0;
    while (offset < totalSize) {
      const activeChunkSize = Math.max(MIN_CHUNK_SIZE_BYTES, Number(adaptiveChunkSizeRef.current || chunkSize || MIN_CHUNK_SIZE_BYTES));
      const nextOffset = Math.min(offset + activeChunkSize, totalSize);
      const chunk2 = file.slice(offset, nextOffset);
      try {
        const data = await uploadChunk(sessionId, uploadToken, chunk2, offset, totalSize, 0);
        offset = Number(data.received_bytes ?? nextOffset);
        if (offset < nextOffset) {
          offset = nextOffset;
        }
      } catch (error) {
        if (isRequestTooLarge(error) && activeChunkSize > MIN_CHUNK_SIZE_BYTES) {
          const nextChunkSize = Math.max(MIN_CHUNK_SIZE_BYTES, Math.floor(activeChunkSize / 2));
          if (nextChunkSize < activeChunkSize) {
            adaptiveChunkSizeRef.current = nextChunkSize;
            pushNotice("warning", `Server rejected ${formatChunkSize(activeChunkSize)} chunks. Retrying with ${formatChunkSize(nextChunkSize)} chunks.`);
            continue;
          }
        }
        const notice = mapUploadErrorNotice(error, "File upload failed. Please retry.");
        dispatch({ type: "UPLOAD_ERROR", error: notice.message });
        pushMappedNotice(notice);
        return false;
      }
    }
    return true;
  }, [chunkSize, fetchStatus, uploadChunk, pushMappedNotice]);
  const finishUpload = reactExports.useCallback(async (sessionId, uploadToken, artworkId) => {
    dispatch({ type: "FINISH_START" });
    try {
      const res = await window.axios.post(
        "/api/uploads/finish",
        {
          session_id: sessionId,
          artwork_id: artworkId,
          upload_token: uploadToken,
          file_name: String(state.file?.name || "")
        },
        { headers: { "X-Upload-Token": uploadToken } }
      );
      const data = res.data || {};
      const previewPath = data.preview_path;
      const previewUrl2 = previewPath ? `${filesCdnUrl}/${previewPath}` : null;
      dispatch({ type: "FINISH_SUCCESS", status: data.status, previewUrl: previewUrl2 });
      const finishNotice = mapUploadResultNotice(data, {
        fallbackType: String(data.status || "").toLowerCase() === "queued" ? "warning" : "success",
        fallbackMessage: String(data.status || "").toLowerCase() === "queued" ? "Upload received. Processing is queued." : "Upload finalized successfully."
      });
      pushMappedNotice(finishNotice);
      if (userId) {
        clearStoredSession(userId);
      }
      return true;
    } catch (error) {
      const notice = mapUploadErrorNotice(error, "Upload finalization failed.");
      dispatch({ type: "FINISH_ERROR", error: notice.message });
      pushMappedNotice(notice);
      return false;
    }
  }, [filesCdnUrl, userId, pushMappedNotice]);
  const startUpload = reactExports.useCallback(async () => {
    if (!state.file) {
      const message = "Please select a file first.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    if (!state.metadata.title.trim()) {
      const message = "Title is required to start the upload.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    if (!state.metadata.type) {
      const message = "Please select a Type.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    if (!state.metadata.category) {
      const message = "Please select a Category.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    if (parseUiTags(state.metadata.tags).length === 0) {
      const message = "Please add at least one tag.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    if (!state.metadata.description.trim()) {
      const message = "Please provide a description.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    const descriptionErrors = validateMarkdownLiteContent(state.metadata.description);
    if (descriptionErrors.length > 0) {
      const message = descriptionErrors[0];
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    if (!state.metadata.licenseAccepted) {
      const message = "You must confirm ownership of the artwork.";
      dispatch({ type: "UPLOAD_ERROR", error: message });
      pushNotice("error", message);
      return;
    }
    let init2 = null;
    if (userId) {
      init2 = await validateStoredSession(state.file);
    }
    if (!init2) {
      init2 = await initSession();
    }
    if (!init2) return;
    const artworkId = await createDraft();
    if (!artworkId) return;
    await syncArtworkTags(artworkId);
    const ok2 = await uploadFile2(init2.sessionId, init2.uploadToken, state.file);
    if (!ok2) return;
    await finishUpload(init2.sessionId, init2.uploadToken, artworkId);
  }, [state.file, state.metadata, initSession, createDraft, syncArtworkTags, uploadFile2, finishUpload, validateStoredSession, userId, pushNotice]);
  const cancelUpload = reactExports.useCallback(async () => {
    dispatch({ type: "CANCEL_START" });
    if (!state.sessionId || !state.uploadToken) {
      if (userId) {
        clearStoredSession(userId);
      }
      dispatch({ type: "CANCEL_SUCCESS" });
      dispatch({ type: "RESET" });
      pushNotice("warning", "Upload cancelled.");
      return;
    }
    try {
      await window.axios.post(
        "/api/uploads/cancel",
        { session_id: state.sessionId, upload_token: state.uploadToken },
        { headers: { "X-Upload-Token": state.uploadToken } }
      );
    } catch (error) {
    }
    if (userId) {
      clearStoredSession(userId);
    }
    dispatch({ type: "CANCEL_SUCCESS" });
    dispatch({ type: "RESET" });
    pushNotice("warning", "Upload cancelled.");
  }, [state.sessionId, state.uploadToken, userId, pushNotice]);
  return {
    state,
    dispatch,
    previewUrl,
    startUpload,
    initSession,
    cancelUpload,
    pushNotice
  };
}
function UploadPage({ draftId = null, filesCdnUrl = "", chunkSize, chunkRequestTimeoutMs } = {}) {
  const { props } = X$1();
  const pageTitle = "Upload Artwork — Creator Studio";
  const pageDescription = "Submit a new artwork, complete the required metadata, and publish it from Skinbase Creator Studio.";
  const windowFlags = window?.SKINBASE_FLAGS || {};
  const propFlagRaw = props?.feature_flags?.uploads_v2;
  const windowFlagRaw = (windowFlags?.uploads && windowFlags.uploads.v2) ?? windowFlags?.uploads_v2;
  const toBooleanFlag = (value) => {
    if (typeof value === "boolean") return value;
    if (typeof value === "number") return value === 1;
    if (typeof value === "string") {
      const normalized = value.trim().toLowerCase();
      return ["1", "true", "yes", "on"].includes(normalized);
    }
    return false;
  };
  const uploadsV2Enabled = toBooleanFlag(propFlagRaw) || toBooleanFlag(windowFlagRaw);
  if (uploadsV2Enabled) {
    return /* @__PURE__ */ React.createElement("section", { className: "min-h-[calc(100vh-4rem)] bg-[#07111c] text-slate-100" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: { title: pageTitle, description: pageDescription, robots: "noindex, nofollow" } }), /* @__PURE__ */ React.createElement("div", { className: "relative isolate" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[420px] bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.22),_transparent_32%),radial-gradient(circle_at_top_right,_rgba(251,146,60,0.16),_transparent_30%),linear-gradient(180deg,_rgba(8,17,28,0.98),_rgba(7,17,28,1))]" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8 lg:py-8" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[32px] border border-white/10 bg-[#08111c]/92 shadow-[0_30px_120px_rgba(2,8,23,0.38)]" }, /* @__PURE__ */ React.createElement("div", { className: "px-4 py-5 sm:px-6 lg:px-8 lg:py-8" }, /* @__PURE__ */ React.createElement(
      UploadWizard,
      {
        initialDraftId: draftId ?? null,
        chunkSize,
        chunkRequestTimeoutMs,
        contentTypes: Array.isArray(props?.content_types) ? props.content_types : [],
        suggestedTags: Array.isArray(props?.suggested_tags) ? props.suggested_tags : [],
        eligibleWorlds: Array.isArray(props?.eligible_worlds) ? props.eligible_worlds : [],
        groupOptions: Array.isArray(props?.group_options) ? props.group_options : [],
        contributorOptionsByGroup: props?.contributor_options_by_group && typeof props.contributor_options_by_group === "object" ? props.contributor_options_by_group : {},
        initialGroupSlug: props?.initial_group || "",
        currentUserId: props?.auth?.user?.id ?? null
      }
    ))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-8 lg:grid-cols-[1.45fr_0.85fr] lg:items-start lg:gap-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] uppercase tracking-[0.28em] text-sky-200/50" }, "Skinbase Upload Studio"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 max-w-3xl text-xl font-semibold tracking-tight text-white/70 sm:text-2xl" }, "Upload artwork with less friction and better control."), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-2xl text-sm leading-7 text-slate-400" }, "The upload flow now stays focused on three steps: add the file, finish the metadata, then publish with confidence. The interface is simpler, but the secure processing pipeline stays intact."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-3" }, [
      {
        title: "Fast onboarding",
        description: "Clearer file requirements and a friendlier first step."
      },
      {
        title: "Safer publishing",
        description: "Processing state, rights, and readiness stay visible the whole time."
      },
      {
        title: "Cleaner review",
        description: "Metadata and publish options are easier to scan before going live."
      }
    ].map((item) => /* @__PURE__ */ React.createElement("div", { key: item.title, className: "rounded-2xl border border-white/6 bg-white/[0.02] p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white/70" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-500" }, item.description))))), /* @__PURE__ */ React.createElement("aside", { className: "rounded-[28px] border border-white/6 bg-white/[0.02] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] uppercase tracking-[0.24em] text-sky-200/50" }, "Before you start"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, [
      "Choose the final file you actually want published. Replacing after upload requires a reset.",
      "ZIP, RAR, and 7Z packs still need at least one screenshot for preview generation.",
      "You will confirm rights and visibility before the final publish step."
    ].map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: item, className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-white/10 bg-white/5 text-xs font-semibold text-slate-400" }, index2 + 1), /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-6 text-slate-500" }, item)))))))));
  }
  const userId = props?.auth?.user?.id ?? null;
  const suggestedTags = Array.isArray(props?.suggested_tags) ? props.suggested_tags : [];
  const safeChunkSize = Math.max(1, Number(chunkSize || 0));
  const { state, dispatch, previewUrl, startUpload, cancelUpload } = useUploadMachine({
    draftId,
    filesCdnUrl,
    chunkSize: safeChunkSize,
    chunkRequestTimeoutMs,
    userId
  });
  const fileInputRef = reactExports.useRef(null);
  const [confirmCancel, setConfirmCancel] = reactExports.useState(false);
  const [contentTypes, setContentTypes] = reactExports.useState([]);
  const [selectedParentCategory, setSelectedParentCategory] = reactExports.useState(null);
  const availableTypes = reactExports.useMemo(() => props?.content_types && Array.isArray(props.content_types) ? props.content_types : contentTypes, [props, contentTypes]);
  const selectedType = reactExports.useMemo(
    () => availableTypes.find((t) => String(t.id) === String(state.metadata.type)),
    [availableTypes, state.metadata.type]
  );
  const categoryOptions = reactExports.useMemo(() => selectedType?.categories || [], [selectedType]);
  const hasAtLeastOneTag = reactExports.useMemo(() => parseUiTags(state.metadata.tags).length > 0, [state.metadata.tags]);
  const descriptionErrors = reactExports.useMemo(() => validateMarkdownLiteContent(state.metadata.description), [state.metadata.description]);
  reactExports.useEffect(() => {
    if (props?.content_types && Array.isArray(props.content_types)) {
      setContentTypes(props.content_types);
      return;
    }
    let mounted = true;
    (async () => {
      try {
        const res = await window.axios.get("/api/content-types");
        if (!mounted) return;
        setContentTypes(res.data || []);
      } catch (e) {
      }
    })();
    return () => {
      mounted = false;
    };
  }, [props]);
  const onFileSelect = reactExports.useCallback((file) => {
    if (!file) return;
    const preview = URL.createObjectURL(file);
    dispatch({ type: "SET_FILE", file, previewUrl: preview });
  }, [dispatch]);
  const onDrop = reactExports.useCallback((event) => {
    event.preventDefault();
    const file = event.dataTransfer.files?.[0];
    onFileSelect(file);
  }, [onFileSelect]);
  const onBrowse = reactExports.useCallback(() => {
    fileInputRef.current?.click();
  }, []);
  const onChange = reactExports.useCallback((event) => {
    const file = event.target.files?.[0];
    onFileSelect(file);
  }, [onFileSelect]);
  const statusLabel2 = state.pipelineStatus || state.phase;
  reactExports.useEffect(() => {
    if (!confirmCancel) return;
    const timer = window.setTimeout(() => {
      setConfirmCancel(false);
    }, 5e3);
    return () => window.clearTimeout(timer);
  }, [confirmCancel]);
  reactExports.useEffect(() => {
    if (!state.cancelledAt) return;
    const timer = window.setTimeout(() => {
      dispatch({ type: "CLEAR_CANCELLED" });
    }, 3500);
    return () => window.clearTimeout(timer);
  }, [state.cancelledAt, dispatch]);
  return /* @__PURE__ */ React.createElement("section", { className: "min-h-[calc(100vh-4rem)] bg-gradient-to-b from-[#0d0f1b] via-[#111827] to-[#0b0c10] py-10 px-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-6xl mx-auto" }, state.notices.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mb-6 space-y-2" }, state.notices.map((notice) => /* @__PURE__ */ React.createElement(
    "div",
    {
      key: notice.id,
      role: "alert",
      "aria-live": "polite",
      className: `rounded-xl border px-4 py-3 text-sm ${notice.type === "error" ? "border-red-500/40 bg-red-500/10 text-red-100" : notice.type === "warning" ? "border-amber-400/40 bg-amber-400/10 text-amber-100" : "border-emerald-400/40 bg-emerald-400/10 text-emerald-100"}`
    },
    notice.message
  ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 lg:grid-cols-[1.1fr,0.9fr]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: { title: pageTitle, description: pageDescription, robots: "noindex, nofollow" } }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/5 p-6 shadow-[0_0_50px_rgba(59,130,246,0.15)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h1", { className: "text-3xl font-semibold tracking-tight" }, "Upload artwork"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.25em] text-sky-300" }, "Secure pipeline")), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/70" }, "All uploads are scanned, re-encoded, and published through the Skinbase pipeline."), /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "mt-6 rounded-2xl border border-dashed border-white/30 bg-white/5 p-6 text-center transition hover:border-sky-400/60",
      onDragOver: (e) => e.preventDefault(),
      onDrop
    },
    /* @__PURE__ */ React.createElement("div", { className: "mx-auto h-14 w-14 rounded-full bg-sky-500/20 grid place-items-center text-sky-200" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-cloud-arrow-up text-xl", "aria-hidden": "true" })),
    /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-lg font-medium" }, "Drag & drop your file"),
    /* @__PURE__ */ React.createElement("p", { className: "text-sm text-white/60" }, "JPG, PNG, or WebP. Up to 50MB."),
    /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onBrowse, className: "mt-4 inline-flex items-center gap-2 rounded-full bg-sky-500 px-4 py-2 text-sm font-semibold text-white shadow-lg shadow-sky-500/30" }, "Browse files"),
    /* @__PURE__ */ React.createElement("input", { ref: fileInputRef, type: "file", accept: "image/jpeg,image/png,image/webp", className: "hidden", onChange })
  ), state.file && /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex items-center gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-20 w-20 overflow-hidden rounded-xl border border-white/10" }, /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "Preview", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, state.file.name), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-white/60" }, (state.file.size / 1024 / 1024).toFixed(2), " MB"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "text-sm sm:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, "Title"), /* @__PURE__ */ React.createElement(
    "input",
    {
      value: state.metadata.title,
      onChange: (e) => dispatch({ type: "SET_METADATA", payload: { title: e.target.value } }),
      className: "mt-2 w-full rounded-xl border border-white/10 bg-white/10 px-3 py-2 text-white focus:border-sky-400 focus:outline-none",
      placeholder: "Name your artwork"
    }
  ))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 via-white/0 to-white/5 p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Choose a type"), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-white/60" }, "Step 1: Pick what kind of artwork this is.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-400/40 bg-sky-400/10 px-3 py-1 text-[11px] uppercase tracking-[0.2em] text-sky-200" }, "Type")), availableTypes.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/60" }, "No content types available.") : /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-3" }, availableTypes.map((ct) => {
    const active = String(ct.id) === String(state.metadata.type);
    const iconKey = getTypeKey(ct);
    const iconPath = ct?.mascot_url || `/gfx/mascot_${iconKey}.webp`;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: ct.id,
        type: "button",
        onClick: () => dispatch({ type: "SET_METADATA", payload: { type: String(ct.id), category: "" } }),
        className: `group rounded-2xl border px-4 py-3 text-left transition ${active ? "border-emerald-400/60 bg-emerald-500/10 shadow-[0_0_25px_rgba(16,185,129,0.25)]" : "border-white/10 bg-white/5 hover:border-sky-400/40 hover:bg-white/10"}`,
        "aria-pressed": active
      },
      /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("div", { className: `h-14 w-10 rounded-xl text-sm font-semibold overflow-hidden relative ${active ? "" : ""}` }, /* @__PURE__ */ React.createElement(
        "img",
        {
          src: iconPath,
          alt: `${ct.name} icon`,
          className: "absolute inset-0 h-full w-full object-contain object-center z-0",
          onLoad: (e) => {
            const letter = document.getElementById(`type-letter-${ct.id}`);
            if (letter) letter.style.display = "none";
          },
          onError: (e) => {
            e.currentTarget.style.display = "none";
            const letter = document.getElementById(`type-letter-${ct.id}`);
            if (letter) letter.style.display = "grid";
          }
        }
      ), /* @__PURE__ */ React.createElement("div", { id: `type-letter-${ct.id}`, className: `relative z-10 grid h-14 w-10 place-items-center ${active ? "text-emerald-200" : "text-white/70"}` }, ct.name?.slice(0, 1)?.toUpperCase() || "?")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, ct.name), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-white/60" }, "Select to reveal categories"))),
      /* @__PURE__ */ React.createElement("div", { className: `mt-3 h-1 w-full rounded-full ${active ? "bg-emerald-400/80" : "bg-white/10 group-hover:bg-sky-400/40"}` })
    );
  }))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-white/10 bg-white/5 p-4 sm:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Choose a category"), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-white/60" }, "Step 2: Pick a subcategory inside the type.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-purple-400/40 bg-purple-400/10 px-3 py-1 text-[11px] uppercase tracking-[0.2em] text-purple-200" }, "Category")), !selectedType ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/60" }, "Select a type first to see categories.") : categoryOptions.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-sm text-white/60" }, "No categories available for ", selectedType.name, ".") : /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, categoryOptions.map((cat) => {
    const isSelected = String(cat.id) === String(state.metadata.category);
    const isExpanded = String(cat.id) === String(selectedParentCategory);
    const hasChildren = Array.isArray(cat.children) && cat.children.length > 0;
    return /* @__PURE__ */ React.createElement(
      "button",
      {
        key: cat.id,
        type: "button",
        onClick: () => {
          if (hasChildren) {
            setSelectedParentCategory(String(cat.id));
            dispatch({ type: "SET_METADATA", payload: { category: "" } });
            return;
          }
          setSelectedParentCategory(null);
          dispatch({ type: "SET_METADATA", payload: { category: String(cat.id) } });
        },
        className: `rounded-full border px-4 py-2 text-sm transition ${isSelected || isExpanded ? "border-purple-300/60 bg-purple-400/20 text-purple-100" : "border-white/10 bg-white/5 text-white/70 hover:border-purple-300/50 hover:bg-purple-400/10"}`,
        "aria-pressed": isSelected || isExpanded
      },
      cat.name
    );
  })), selectedParentCategory && (() => {
    const parent = categoryOptions.find((c) => String(c.id) === String(selectedParentCategory));
    if (!parent || !Array.isArray(parent.children) || parent.children.length === 0) return null;
    return /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-xl border border-white/10 bg-white/5 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Subcategories for ", parent.name), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-white/60" }, "Choose a subcategory below")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setSelectedParentCategory(null), className: "text-sm text-white/60" }, "Back")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, parent.children.map((child) => {
      const activeChild = String(child.id) === String(state.metadata.category);
      return /* @__PURE__ */ React.createElement(
        "button",
        {
          key: child.id,
          type: "button",
          onClick: () => {
            dispatch({ type: "SET_METADATA", payload: { category: String(child.id) } });
          },
          className: `rounded-full border px-4 py-2 text-sm transition ${activeChild ? "border-purple-300/60 bg-purple-400/20 text-purple-100" : "border-white/10 bg-white/5 text-white/70 hover:border-purple-300/50 hover:bg-purple-400/10"}`,
          "aria-pressed": activeChild
        },
        child.name
      );
    })));
  })())), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/80" }, "Tags"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement(
    TagInput,
    {
      value: state.metadata.tags,
      onChange: (nextTags) => {
        dispatch({ type: "SET_METADATA", payload: { tags: nextTags.join(", ") } });
      },
      suggestedTags,
      minLength: 2,
      maxLength: 32,
      searchEndpoint: "/api/tags/search",
      popularEndpoint: "/api/tags/popular",
      placeholder: "Type tags (e.g. cyberpunk, city)"
    }
  ))), /* @__PURE__ */ React.createElement("label", { className: "mt-4 block text-sm" }, /* @__PURE__ */ React.createElement("span", { className: "text-white/80" }, "Description"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, /* @__PURE__ */ React.createElement(
    UploadDescriptionEditor,
    {
      id: "legacy-upload-description",
      value: state.metadata.description,
      onChange: (value) => dispatch({ type: "SET_METADATA", payload: { description: value } }),
      placeholder: "Tell the story behind this artwork.",
      error: descriptionErrors[0] || "",
      rows: 8
    }
  )), descriptionErrors.length > 0 && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-red-200" }, descriptionErrors[0])), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: state.metadata.isMature,
      onChange: (e) => dispatch({ type: "SET_METADATA", payload: { isMature: e.target.checked } }),
      size: 16,
      variant: "accent",
      label: "Mark this artwork as mature content."
    }
  )), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement(
    Checkbox,
    {
      checked: state.metadata.licenseAccepted,
      onChange: (e) => dispatch({ type: "SET_METADATA", payload: { licenseAccepted: e.target.checked } }),
      size: 16,
      variant: "emerald",
      label: "I confirm I own the rights to this artwork."
    }
  )), state.cancelledAt && /* @__PURE__ */ React.createElement("div", { role: "alert", "aria-live": "polite", className: "mt-4 rounded-xl border border-amber-400/40 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "Upload cancelled."), state.error && /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-xl border border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-100" }, state.error), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: startUpload,
      disabled: !state.file || !state.metadata.title.trim() || !state.metadata.type || !state.metadata.category || !hasAtLeastOneTag || !state.metadata.description.trim() || descriptionErrors.length > 0 || !state.metadata.licenseAccepted,
      className: `inline-flex items-center gap-2 rounded-full px-5 py-2 text-sm font-semibold text-white ${!state.file || !state.metadata.title.trim() || !state.metadata.type || !state.metadata.category || !hasAtLeastOneTag || !state.metadata.description.trim() || descriptionErrors.length > 0 || !state.metadata.licenseAccepted ? "bg-white/10 cursor-not-allowed" : "bg-emerald-500 shadow-lg shadow-emerald-500/30"}`
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket", "aria-hidden": "true" }),
    "Start upload"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        if (!confirmCancel) {
          setConfirmCancel(true);
          return;
        }
        setConfirmCancel(false);
        cancelUpload();
      },
      className: "inline-flex items-center gap-2 rounded-full border border-red-400/40 px-4 py-2 text-sm text-red-100",
      disabled: !state.sessionId || state.phase === phases.success,
      "aria-pressed": confirmCancel
    },
    /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-ban", "aria-hidden": "true" }),
    confirmCancel ? "Confirm cancel" : "Cancel"
  ), /* @__PURE__ */ React.createElement(
    "button",
    {
      type: "button",
      onClick: () => {
        if (userId) {
          clearStoredSession(userId);
        }
        dispatch({ type: "RESET" });
      },
      className: "inline-flex items-center gap-2 rounded-full border border-white/20 px-4 py-2 text-sm text-white/70"
    },
    "Reset"
  )))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/5 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold" }, "Pipeline status"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/60" }, "Stage: ", /* @__PURE__ */ React.createElement("span", { className: "text-white" }, statusLabel2)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-2 w-full overflow-hidden rounded-full bg-white/10" }, /* @__PURE__ */ React.createElement("div", { className: "h-full bg-sky-400 transition-all", style: { width: `${state.progress}%` } })), state.failureReason && /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-red-200" }, "Failure: ", state.failureReason), state.previewUrl && state.phase === phases.success && /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white/80" }, "CDN preview"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 overflow-hidden rounded-xl border border-white/10" }, /* @__PURE__ */ React.createElement("img", { src: state.previewUrl, alt: "CDN preview", className: "h-56 w-full object-cover" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-xs text-white/60" }, "Session: ", state.sessionId ?? "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/5 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold" }, "Draft resume"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/60" }, "Use the draft link to resume an interrupted upload."), draftId ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-white/80" }, "Draft ID: ", draftId) : /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-white/50" }, "No draft loaded."))))));
}
const __vite_glob_0_162 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: UploadPage
}, Symbol.toStringTag, { value: "Module" }));
function themeStyle$1(theme) {
  return {
    "--world-accent": theme?.accent_color || "#38bdf8",
    "--world-accent-secondary": theme?.accent_color_secondary || "#0f172a"
  };
}
function WorldCard({ world, compact = false, sourceSurface = "", sourceDetail = "" }) {
  const cardRef = reactExports.useRef(null);
  const href = world && sourceSurface ? withWorldSource(world.public_url, sourceSurface, sourceDetail) : world?.public_url;
  reactExports.useEffect(() => {
    if (!sourceSurface || !world?.id || typeof window === "undefined") {
      return void 0;
    }
    const node2 = cardRef.current;
    if (!node2) {
      return void 0;
    }
    if (typeof window.IntersectionObserver !== "function") {
      trackWorldSourceImpression({
        worldId: world.id,
        worldTitle: world.title,
        sourceSurface,
        sourceDetail,
        sectionKey: compact ? "compact_card" : "card"
      });
      return void 0;
    }
    const observer = new window.IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting || entry.intersectionRatio < 0.4) {
          return;
        }
        trackWorldSourceImpression({
          worldId: world.id,
          worldTitle: world.title,
          sourceSurface,
          sourceDetail,
          sectionKey: compact ? "compact_card" : "card"
        });
        observer.disconnect();
      });
    }, { threshold: [0.4] });
    observer.observe(node2);
    return () => observer.disconnect();
  }, [compact, sourceDetail, sourceSurface, world?.id, world?.title]);
  if (!world) {
    return null;
  }
  return /* @__PURE__ */ React.createElement(
    "a",
    {
      ref: cardRef,
      href,
      onClick: () => trackWorldSourceClick({ worldId: world.id, worldTitle: world.title, sourceSurface, sourceDetail }),
      className: `group relative block w-full overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/70 transition duration-300 hover:-translate-y-1 hover:border-white/20 ${compact ? "p-5" : "p-6"}`,
      style: themeStyle$1(world.theme)
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_42%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_94%,black),_rgba(2,6,23,0.94))] opacity-95" }),
    world.cover_url ? /* @__PURE__ */ React.createElement("img", { src: world.cover_url, alt: world.title, className: "absolute inset-0 h-full w-full object-cover opacity-20 transition duration-500 group-hover:scale-[1.03]" }) : null,
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/80 to-slate-950/10" }),
    /* @__PURE__ */ React.createElement("div", { className: "relative flex h-full min-h-[16rem] flex-col justify-between" }, /* @__PURE__ */ React.createElement("div", null, world.is_recurring ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, world.family_title || "Recurring family", world.edition_label ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 text-slate-300/70" }, world.edition_label) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), !Array.isArray(world.status_badges) || world.status_badges.length === 0 ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.phase || world.status, tone: "slate" } }) : null, world.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.campaign_label, tone: "slate" } }) : null, world.badge_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.badge_label, tone: "rose" } }) : null), world.teaser_title && world.teaser_title !== world.title ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, world.title) : null, /* @__PURE__ */ React.createElement("h3", { className: `mt-4 max-w-xl font-semibold tracking-[-0.03em] text-white ${compact ? "text-2xl" : "text-3xl"}` }, world.teaser_title || world.title), world.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm uppercase tracking-[0.18em] text-white/55" }, world.tagline) : null, world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-6 text-slate-200/85" }, world.summary) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world }), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-sm font-semibold text-white transition group-hover:bg-white/15" }, world.cta_label || world.challenge_cta_label || (world.is_recurring && !world.is_canonical_edition ? "Open edition" : "Open world"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))
  );
}
function ActiveWorldSpotlight({
  spotlight,
  secondary = [],
  indexUrl = "/worlds",
  eyebrow = "World spotlight",
  secondaryTitle = "Campaign rail",
  className = "",
  sourceSurface = "",
  sourceDetail = "",
  secondarySourceSurface = "",
  secondarySourceDetail = ""
}) {
  const spotlightRef = reactExports.useRef(null);
  const primaryHref = spotlight && sourceSurface ? withWorldSource(spotlight.public_url || spotlight.cta_url, sourceSurface, sourceDetail) : spotlight?.public_url || spotlight?.cta_url;
  reactExports.useEffect(() => {
    if (!spotlight?.id || !sourceSurface || typeof window === "undefined") {
      return void 0;
    }
    const node2 = spotlightRef.current;
    if (!node2) {
      return void 0;
    }
    if (typeof window.IntersectionObserver !== "function") {
      trackWorldSourceImpression({
        worldId: spotlight.id,
        worldTitle: spotlight.title || spotlight.headline,
        sourceSurface,
        sourceDetail,
        sectionKey: "spotlight"
      });
      return void 0;
    }
    const observer = new window.IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting || entry.intersectionRatio < 0.45) {
          return;
        }
        trackWorldSourceImpression({
          worldId: spotlight.id,
          worldTitle: spotlight.title || spotlight.headline,
          sourceSurface,
          sourceDetail,
          sectionKey: "spotlight"
        });
        observer.disconnect();
      });
    }, { threshold: [0.45] });
    observer.observe(node2);
    return () => observer.disconnect();
  }, [spotlight?.headline, spotlight?.id, spotlight?.title, sourceDetail, sourceSurface]);
  if (!spotlight) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className }, /* @__PURE__ */ React.createElement(
    "div",
    {
      ref: spotlightRef,
      className: "group relative overflow-hidden rounded-[32px] border border-white/10 bg-slate-950/70",
      style: {
        "--world-accent": spotlight.theme?.accent_color || "#f97316",
        "--world-accent-secondary": spotlight.theme?.accent_color_secondary || "#0f172a"
      }
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_36%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_92%,black),_rgba(2,6,23,0.98))]" }),
    spotlight.cover_url ? /* @__PURE__ */ React.createElement("img", { src: spotlight.cover_url, alt: spotlight.title || spotlight.headline, className: "absolute inset-0 h-full w-full object-cover opacity-20 transition duration-500 group-hover:scale-[1.03]" }) : null,
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-950/84 to-slate-950/28" }),
    /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-8 px-6 py-7 sm:px-8 lg:grid-cols-[minmax(0,1.2fr)_20rem] lg:px-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70" }, eyebrow), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, (Array.isArray(spotlight.status_badges) ? spotlight.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), spotlight.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: spotlight.campaign_label, tone: "slate" } }) : null), spotlight.title && spotlight.headline && spotlight.title !== spotlight.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-5 text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-100/70" }, spotlight.title) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white sm:text-4xl" }, spotlight.headline || spotlight.title), spotlight.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm uppercase tracking-[0.18em] text-white/55" }, spotlight.tagline) : null, spotlight.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-200/88" }, spotlight.summary) : null, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world: spotlight, className: "mt-6" }), spotlight.supporting_item ? /* @__PURE__ */ React.createElement("a", { href: spotlight.supporting_item.url, className: "mt-6 inline-flex max-w-xl items-center gap-3 rounded-[22px] border border-white/12 bg-black/25 px-4 py-3 text-left text-sm text-slate-100 transition hover:border-white/20 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, spotlight.supporting_item.entity_label || "Related item"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate font-semibold text-white" }, spotlight.supporting_item.title), spotlight.supporting_item.context_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-300/80" }, spotlight.supporting_item.context_label) : null), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right shrink-0 text-xs text-sky-100" })) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: primaryHref, onClick: () => trackWorldSourceClick({ worldId: spotlight.id, worldTitle: spotlight.title || spotlight.headline, sourceSurface, sourceDetail }), className: "inline-flex items-center gap-2 rounded-full bg-white px-4 py-2.5 text-sm font-semibold text-slate-950 transition group-hover:bg-sky-100" }, spotlight.cta_label || "Explore world", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })), /* @__PURE__ */ React.createElement("a", { href: indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse all worlds"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/12 bg-black/25 p-5 text-white backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Campaign state"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3 text-lg font-semibold" }, /* @__PURE__ */ React.createElement("i", { className: spotlight.icon_name || "fa-solid fa-globe" }), /* @__PURE__ */ React.createElement("span", null, spotlight.theme?.label || "Editorial world")), spotlight.timeframe_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-slate-300" }, spotlight.timeframe_label) : null, spotlight.promotion_window_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, spotlight.promotion_window_label) : null, Number(spotlight.live_submission_count || 0) > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-100" }, spotlight.live_submission_count, " live submissions are already part of this campaign.") : null))
  ), Array.isArray(secondary) && secondary.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, secondaryTitle), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "More live or upcoming worlds that are being actively surfaced right now.")), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, secondary.length, " worlds")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, secondary.map((world) => /* @__PURE__ */ React.createElement(WorldCard, { key: world.id, world, compact: true, sourceSurface: secondarySourceSurface || sourceSurface, sourceDetail: secondarySourceDetail || sourceDetail })))) : null);
}
function themeStyle(theme) {
  return {
    "--world-accent": theme?.accent_color || "#38bdf8",
    "--world-accent-secondary": theme?.accent_color_secondary || "#0f172a"
  };
}
function WorldFamilyCard({ family, sourceSurface = "", sourceDetail = "" }) {
  if (!family) {
    return null;
  }
  const currentWorld = family.current_world || null;
  const editionCount = Number(family.edition_count || 0);
  const archiveCount = Number(family.archive_count || 0);
  const familyHref = sourceSurface ? withWorldSource(family.public_url, sourceSurface, sourceDetail || "recurring_family") : family.public_url;
  return /* @__PURE__ */ React.createElement(
    "article",
    {
      className: "group relative overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/70 p-6",
      style: themeStyle(family.theme)
    },
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,_color-mix(in_srgb,var(--world-accent)_26%,transparent),_transparent_42%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_94%,black),_rgba(2,6,23,0.94))] opacity-95" }),
    family.cover_url ? /* @__PURE__ */ React.createElement("img", { src: family.cover_url, alt: family.title, className: "absolute inset-0 h-full w-full object-cover opacity-15" }) : null,
    /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/88 to-slate-950/15" }),
    /* @__PURE__ */ React.createElement("div", { className: "relative flex h-full min-h-[18rem] flex-col justify-between gap-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: "Recurring family", tone: "sky" } }), archiveCount > 0 ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: `${archiveCount} archived`, tone: "amber" } }) : null, currentWorld?.campaign_state_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: currentWorld.campaign_state_label, tone: currentWorld.campaign_state === "live_now" ? "emerald" : "slate" } }) : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-3xl font-semibold tracking-[-0.03em] text-white" }, family.title), family.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-6 text-slate-200/85" }, family.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-300/75" }, /* @__PURE__ */ React.createElement("span", null, editionCount, " editions"), Array.isArray(family.years) && family.years.length > 0 ? /* @__PURE__ */ React.createElement("span", null, family.years.join(" / ")) : null)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/25 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Current edition"), currentWorld ? /* @__PURE__ */ React.createElement("div", { className: "mt-3" }, /* @__PURE__ */ React.createElement("a", { href: sourceSurface ? withWorldSource(currentWorld.public_url, sourceSurface, "recurring_family_current") : currentWorld.public_url, onClick: () => trackWorldSourceClick({ worldId: currentWorld.id, worldTitle: currentWorld.title, sourceSurface, sourceDetail: "recurring_family_current" }), className: "text-lg font-semibold text-white transition hover:text-sky-200" }, currentWorld.title), currentWorld.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300/85" }, currentWorld.summary) : null) : /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300/75" }, "No public edition is currently available.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/25 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Archive"), Array.isArray(family.previous_editions) && family.previous_editions.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid gap-2" }, family.previous_editions.map((edition) => /* @__PURE__ */ React.createElement("a", { key: edition.id, href: sourceSurface ? withWorldSource(edition.public_url, sourceSurface, "recurring_family_archive") : edition.public_url, onClick: () => trackWorldSourceClick({ worldId: edition.id, worldTitle: edition.title, sourceSurface, sourceDetail: "recurring_family_archive" }), className: "inline-flex items-center justify-between gap-3 rounded-2xl border border-white/8 bg-white/[0.04] px-3 py-2 text-sm text-slate-200 transition hover:border-white/16 hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("span", null, edition.title), edition.edition_year ? /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.14em] text-slate-400" }, edition.edition_year) : null))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300/75" }, "The archive starts with the current edition."))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("a", { href: familyHref, onClick: () => trackWorldSourceClick({ worldId: family.current_world?.id || 0, worldTitle: family.title, sourceSurface, sourceDetail: sourceDetail || "recurring_family" }), className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-sm font-semibold text-white transition group-hover:bg-white/15" }, "Open family", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))
  );
}
function defaultRenderItem(item, sourceProps) {
  return /* @__PURE__ */ React.createElement(WorldCard, { key: item.id, world: item, compact: true, ...sourceProps });
}
function WorldsIndexSection({ title, description, items = [], emptyMessage = "", countLabel = "worlds", renderItem = defaultRenderItem, sourceSurface = "", sourceDetail = "" }) {
  if (!Array.isArray(items) || items.length === 0) {
    if (!emptyMessage) {
      return null;
    }
    return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, title), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, emptyMessage));
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, description) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, items.length, " ", countLabel)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, items.map((item) => renderItem(item, { sourceSurface, sourceDetail }))));
}
function WorldIndex() {
  const { props } = X$1();
  const hasSpotlight = Boolean(props.spotlightWorld);
  const featuredFallback = !hasSpotlight && Array.isArray(props.featuredWorlds) ? props.featuredWorlds : [];
  return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(249,115,22,0.12),_transparent_28%),radial-gradient(circle_at_top_right,_rgba(56,189,248,0.12),_transparent_32%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: "Worlds - Skinbase", description: props.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[36px] border border-white/10 bg-white/[0.03] p-6 sm:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-4xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/70" }, "Skinbase Worlds"), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold tracking-[-0.05em] text-white sm:text-5xl" }, "Curated spaces for seasonal culture, scene moments, and editorial campaigns."), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-3xl text-base leading-7 text-slate-300" }, "Worlds bundle together artworks, collections, creators, groups, cards, releases, events, challenges, and newsroom context into a single themed destination. They are not filters. They are editorial environments."))), hasSpotlight ? /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement(
    ActiveWorldSpotlight,
    {
      spotlight: props.spotlightWorld,
      secondary: Array.isArray(props.featuredWorlds) ? props.featuredWorlds.slice(0, 3) : [],
      indexUrl: "/worlds",
      eyebrow: "Active world spotlight",
      secondaryTitle: "Featured worlds",
      sourceSurface: "worlds_index",
      sourceDetail: "spotlight",
      secondarySourceSurface: "worlds_index",
      secondarySourceDetail: "featured"
    }
  )) : null, !hasSpotlight ? /* @__PURE__ */ React.createElement(
    WorldsIndexSection,
    {
      title: "Featured Worlds",
      description: "Editorially promoted worlds stay visible here even when there is no live campaign spotlighting the homepage moment.",
      items: featuredFallback,
      sourceSurface: "worlds_index",
      sourceDetail: "featured"
    }
  ) : null, /* @__PURE__ */ React.createElement(
    WorldsIndexSection,
    {
      title: "Active Worlds",
      description: "Live worlds and currently running campaign surfaces across Skinbase.",
      items: props.activeWorlds,
      emptyMessage: "No worlds are currently live. Check upcoming programming below.",
      sourceSurface: "worlds_index",
      sourceDetail: "active"
    }
  ), /* @__PURE__ */ React.createElement(
    WorldsIndexSection,
    {
      title: "Upcoming Worlds",
      description: "Scheduled campaign moments and future worlds lined up for the next launch window.",
      items: props.upcomingWorlds,
      emptyMessage: "No upcoming worlds are scheduled right now.",
      sourceSurface: "worlds_index",
      sourceDetail: "upcoming"
    }
  ), /* @__PURE__ */ React.createElement(
    WorldsIndexSection,
    {
      title: "Recurring Worlds",
      description: "Long-running campaign families keep a canonical current edition while preserving a browsable yearly archive.",
      items: props.recurringWorldFamilies,
      emptyMessage: "Recurring families will appear here as worlds begin building an archive across editions.",
      countLabel: "families",
      renderItem: (family, sourceProps) => /* @__PURE__ */ React.createElement(WorldFamilyCard, { key: family.id, family, ...sourceProps }),
      sourceSurface: "worlds_index",
      sourceDetail: "recurring"
    }
  ), /* @__PURE__ */ React.createElement(
    WorldsIndexSection,
    {
      title: "Archive Editions",
      description: "Past worlds stay available as browsable records of recurring culture and editorial programming.",
      items: props.archivedWorlds,
      emptyMessage: "Archived worlds will appear here as campaigns finish and move into the public record.",
      sourceSurface: "worlds_index",
      sourceDetail: "archive"
    }
  )));
}
const __vite_glob_0_163 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: WorldIndex
}, Symbol.toStringTag, { value: "Module" }));
function WorldArchiveNotice({ notice }) {
  if (!notice) {
    return null;
  }
  const currentEdition = notice.current_edition || null;
  return /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-amber-300/20 bg-amber-400/10 px-5 py-4 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, notice.eyebrow ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100/75" }, notice.eyebrow) : null, notice.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-base font-semibold text-white" }, notice.title) : null, notice.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 leading-6 text-amber-50/85" }, notice.description) : null), currentEdition?.public_url ? /* @__PURE__ */ React.createElement("a", { href: currentEdition.public_url, className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white" }, "Open current edition", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null));
}
function WorldChallengeEntriesRail({ section, challengeId = null }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title || "Challenge entries"), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement(WorldChallengeArtworkCard, { key: item.id, item, sectionKey: "challenge_entries", challengeId }))));
}
function WorldChallengeFinalistsGrid({ panel, section = null }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  if (items.length === 0 && (!panel?.show_finalists || panel?.supports_finalists)) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section?.title || "Challenge finalists"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section?.description || "Finalists from the linked challenge stay visible here so the world can carry the full result set forward as a public recap.")), items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement(WorldChallengeArtworkCard, { key: item.id, item, sectionKey: "challenge_finalists", challengeId: panel?.id || null }))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-black/20 p-5 text-sm leading-6 text-slate-400" }, "Finalists will appear here automatically once the linked challenge publishes them as structured outcomes."));
}
function WorldChallengeMeta({ items = [], className = "" }) {
  const filteredItems = Array.isArray(items) ? items.filter(Boolean) : [];
  if (filteredItems.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("div", { className: `flex flex-wrap gap-2 text-xs uppercase tracking-[0.16em] text-slate-400 ${className}`.trim() }, filteredItems.map((item) => /* @__PURE__ */ React.createElement("span", { key: item }, item)));
}
function WorldChallengePanel({ section }) {
  if (!section) {
    return null;
  }
  const storyMeta = Array.isArray(section.story?.meta) ? section.story.meta.filter(Boolean) : [];
  const metaItems2 = [
    section.timeframe_label,
    Number(section.entry_count || 0) > 0 ? `${section.entry_count} entries` : null,
    section.has_winner ? "Winner synced" : null
  ];
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03]" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_32%),linear-gradient(135deg,_rgba(15,23,42,0.94),_rgba(2,6,23,0.98))]" }), section.cover_url ? /* @__PURE__ */ React.createElement("img", { src: section.cover_url, alt: section.title, className: "absolute inset-0 h-full w-full object-cover opacity-20" }) : null, /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-6 p-6 lg:grid-cols-[minmax(0,1.25fr)_18rem] lg:p-8" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement(WorldChallengeStatusBadge, { label: section.state_label, tone: section.state_tone }), section.group?.name ? /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, section.group.name) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, section.title), section.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-200/86" }, section.summary) : null, /* @__PURE__ */ React.createElement(WorldChallengeMeta, { items: metaItems2, className: "mt-5" })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/25 p-5 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Linked challenge"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, section.show_entries ? /* @__PURE__ */ React.createElement("div", null, "Derived entries rail enabled") : null, section.show_winners ? /* @__PURE__ */ React.createElement("div", null, "Winner section enabled") : null, section.show_finalists ? /* @__PURE__ */ React.createElement("div", null, section.supports_finalists ? "Finalists section enabled" : "Finalists section unavailable") : null), section.story?.url ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[20px] border border-sky-300/15 bg-sky-400/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, section.story.eyebrow || section.story.context_label || "Challenge story"), /* @__PURE__ */ React.createElement("a", { href: section.story.url, "data-world-event": "world_challenge_cta_clicked", "data-world-section-key": "challenge", "data-world-cta-key": section.story.intent === "recap" ? "challenge_recap" : "challenge_story", "data-world-challenge-id": section.id, className: "mt-2 block text-base font-semibold text-white transition hover:text-sky-100" }, section.story.title), section.story.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-200/85" }, section.story.description) : null, storyMeta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2 text-[11px] uppercase tracking-[0.16em] text-slate-400" }, storyMeta.map((item) => /* @__PURE__ */ React.createElement("span", { key: item }, item))) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: section.cta_url || section.url, "data-world-event": "world_challenge_cta_clicked", "data-world-section-key": "challenge", "data-world-cta-key": section.story?.intent === "recap" && section.cta_url === section.story?.url ? "challenge_recap" : "challenge_primary", "data-world-challenge-id": section.id, className: "inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-sm font-semibold text-slate-950 transition hover:bg-sky-100" }, section.cta_label || "Open challenge", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })), section.story?.url && section.story.url !== section.cta_url ? /* @__PURE__ */ React.createElement("a", { href: section.story.url, "data-world-event": "world_challenge_cta_clicked", "data-world-section-key": "challenge", "data-world-cta-key": section.story.intent === "recap" ? "challenge_recap" : "challenge_story", "data-world-challenge-id": section.id, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, section.story.cta_label || "Read story") : null, section.challenge_url && section.challenge_url !== section.cta_url ? /* @__PURE__ */ React.createElement("a", { href: section.challenge_url, "data-world-event": "world_challenge_cta_clicked", "data-world-section-key": "challenge", "data-world-cta-key": "challenge_direct", "data-world-challenge-id": section.id, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Open challenge") : null, section.group?.url ? /* @__PURE__ */ React.createElement("a", { href: section.group.url, "data-world-event": "world_cta_clicked", "data-world-section-key": "challenge", "data-world-cta-key": "linked_group", "data-world-challenge-id": section.id, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Open group") : null)))));
}
function WorldChallengeWinnersPanel({ section, challengeId = null }) {
  const items = Array.isArray(section?.items) ? section.items : section?.item ? [section.item] : [];
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title || "Challenge winner"), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null), items.length === 1 ? /* @__PURE__ */ React.createElement(WorldChallengeArtworkCard, { item: items[0], featured: true, sectionKey: "challenge_winners", challengeId }) : /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement(WorldChallengeArtworkCard, { key: item.id, item, featured: true, sectionKey: "challenge_winners", challengeId }))));
}
function styleForWorld(world) {
  return {
    "--world-accent": world?.theme?.accent_color || "#38bdf8",
    "--world-accent-secondary": world?.theme?.accent_color_secondary || "#0f172a"
  };
}
function resolvedIconName(world) {
  const icon = String(world?.icon_name || "").trim();
  if (icon.startsWith("fa-")) {
    return icon;
  }
  const themeIcon = String(world?.theme?.icon_name || "").trim();
  return themeIcon.startsWith("fa-") ? themeIcon : "fa-solid fa-globe";
}
function WorldHero({ world, previewMode = false }) {
  if (!world) {
    return null;
  }
  const themeIconName = resolvedIconName(world);
  return /* @__PURE__ */ React.createElement("section", { className: "relative overflow-hidden rounded-[36px] border border-white/10", style: styleForWorld(world) }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_18%_16%,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_34%),radial-gradient(circle_at_82%_18%,_color-mix(in_srgb,var(--world-accent-secondary)_68%,transparent),_transparent_42%),linear-gradient(135deg,_rgba(2,6,23,0.92),_rgba(15,23,42,0.82)_45%,_rgba(2,6,23,0.95))]" }), world.cover_url ? /* @__PURE__ */ React.createElement("img", { src: world.cover_url, alt: world.title, className: "absolute inset-0 h-full w-full object-cover opacity-20" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-950/80 to-slate-950/20" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-10 px-6 py-8 sm:px-8 lg:grid-cols-[minmax(0,1.25fr)_20rem] lg:px-10 lg:py-10" }, /* @__PURE__ */ React.createElement("div", null, previewMode ? /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-amber-300/25 bg-amber-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.2em] text-amber-100" }, "Preview Mode") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2" }, (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.type, tone: "slate" } }), world.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.campaign_label, tone: "slate" } }) : null, world.badge_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.badge_label, tone: "rose" } }) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 max-w-4xl text-4xl font-semibold tracking-[-0.05em] text-white sm:text-5xl lg:text-6xl" }, world.title), world.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm uppercase tracking-[0.24em] text-white/55" }, world.tagline) : null, world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-6 max-w-none text-base leading-7 text-slate-200/86 sm:text-lg" }, world.summary) : null, world.description ? /* @__PURE__ */ React.createElement(
    "div",
    {
      className: "prose prose-invert prose-sm mt-5 max-w-none prose-p:text-slate-300/88 prose-p:leading-7 prose-headings:text-white prose-strong:text-white prose-a:text-sky-300 prose-blockquote:border-l-sky-500/40 prose-blockquote:text-slate-300 prose-code:text-amber-300 prose-code:bg-white/[0.06] prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-pre:border prose-pre:border-white/[0.06] prose-pre:bg-white/[0.04] prose-hr:border-white/10 prose-ul:text-slate-300/88 prose-ol:text-slate-300/88",
      dangerouslySetInnerHTML: { __html: world.description }
    }
  ) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex flex-wrap gap-3" }, world.cta_url || world.challenge_cta_url ? /* @__PURE__ */ React.createElement("a", { href: world.cta_url || world.challenge_cta_url, "data-world-event": "world_cta_clicked", "data-world-section-key": "hero", "data-world-cta-key": "main_world_cta", className: "inline-flex items-center gap-2 rounded-full bg-white px-5 py-3 text-sm font-semibold text-slate-950 transition hover:bg-sky-100" }, world.cta_label || world.challenge_cta_label || "Explore", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null), /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world, className: "mt-6" }), world.is_recurring ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3 text-sm text-slate-200/80" }, world.family_url ? /* @__PURE__ */ React.createElement("a", { href: world.family_url, "data-world-event": "world_cta_clicked", "data-world-section-key": "hero", "data-world-cta-key": "family_route", className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2 hover:bg-white/[0.08]" }, "Family route", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null, !world.is_canonical_edition && world.edition_url ? /* @__PURE__ */ React.createElement("a", { href: world.edition_url, "data-world-event": "world_cta_clicked", "data-world-section-key": "hero", "data-world-cta-key": "edition_archive", className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2 hover:bg-white/[0.08]" }, "Edition archive link", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null) : null, Array.isArray(world.related_tags) && world.related_tags.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex flex-wrap gap-2" }, world.related_tags.map((tag) => /* @__PURE__ */ React.createElement("span", { key: tag, className: "rounded-full border border-white/12 bg-black/25 px-3 py-1.5 text-xs font-medium uppercase tracking-[0.16em] text-slate-200/80" }, "#", tag))) : null), /* @__PURE__ */ React.createElement("aside", { className: "grid gap-4 self-end" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/12 bg-black/25 p-5 text-white shadow-2xl shadow-slate-950/30 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, themeIconName ? /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/12 bg-white/10 text-lg text-white" }, /* @__PURE__ */ React.createElement("i", { className: themeIconName })) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Theme"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold" }, world.theme?.label || world.type))), world.badge_description ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-6 text-slate-300" }, world.badge_description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 text-sm text-slate-200/90" }, world.timeframe_label ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-calendar" }), /* @__PURE__ */ React.createElement("span", null, world.timeframe_label)) : null, world.promotion_window_label ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bullhorn" }), /* @__PURE__ */ React.createElement("span", null, world.promotion_window_label)) : null, world.edition_label ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-repeat" }), /* @__PURE__ */ React.createElement("span", null, world.edition_label)) : null, world.is_recurring ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-clock-rotate-left" }), /* @__PURE__ */ React.createElement("span", null, world.is_canonical_edition ? "Canonical family edition" : "Archive edition in a recurring family")) : null, world.family_title ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-layer-group" }), /* @__PURE__ */ React.createElement("span", null, world.family_title)) : null, world.live_submission_count > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group" }), /* @__PURE__ */ React.createElement("span", null, world.live_submission_count, " live submissions")) : null), world.badge_url ? /* @__PURE__ */ React.createElement("a", { href: world.badge_url, "data-world-event": "world_cta_clicked", "data-world-section-key": "hero", "data-world-cta-key": "badge_cta", className: "mt-5 inline-flex items-center gap-2 text-sm font-semibold text-sky-100 hover:text-white" }, "View badge", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null))));
}
function statusTone(item) {
  return item?.status_label === "Featured" ? "border-amber-300/30 bg-amber-400/12 text-amber-100" : "border-emerald-300/25 bg-emerald-400/10 text-emerald-100";
}
function WorldCommunitySubmissionsSection({ section }) {
  if (!section || !Array.isArray(section.items) || section.items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, section.items.length, " artworks")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, section.items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, "data-world-event": "world_entity_clicked", "data-world-section-key": "community_submissions", "data-world-entity-type": "artwork", "data-world-entity-id": item.id, "data-world-entity-title": item.title || "", className: "group overflow-hidden rounded-[26px] border border-white/10 bg-white/[0.03] transition duration-300 hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden border-b border-white/10 bg-slate-950/80" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: item.title, className: "aspect-[16/10] w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/10] w-full bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_42%),linear-gradient(135deg,_rgba(15,23,42,0.96),_rgba(2,6,23,0.96))]" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 flex items-start justify-between gap-2 p-4" }, item.context_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/35 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-white/80" }, item.context_label) : null, item.status_label ? /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] ${statusTone(item)}` }, item.status_label) : null)), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold tracking-[-0.02em] text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry, className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-xs text-slate-300" }, entry))) : null)))));
}
function WorldRecapArticleCard({ article }) {
  if (!article?.url) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1.1fr)_16rem] lg:items-center" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, article.eyebrow || "Recap article"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, article.title), article.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, article.description) : null, Array.isArray(article.meta) && article.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, article.meta.map((item) => /* @__PURE__ */ React.createElement("span", { key: item }, item))) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:items-end" }, article.image ? /* @__PURE__ */ React.createElement("img", { src: article.image, alt: article.title, className: "h-32 w-full rounded-[24px] border border-white/10 object-cover lg:w-56" }) : null, /* @__PURE__ */ React.createElement("a", { href: article.url, "data-world-event": "world_cta_clicked", "data-world-section-key": "recap_article", "data-world-cta-key": "recap_article", className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, article.cta_label || "Read article", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })))));
}
function WorldRecapCommunityHighlights({ section }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title || "Community highlights"), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, items.length, " artworks")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, "data-world-event": "world_entity_clicked", "data-world-section-key": "recap_community", "data-world-entity-type": "artwork", "data-world-entity-id": item.id, "data-world-entity-title": item.title || "", className: "group overflow-hidden rounded-[26px] border border-white/10 bg-black/20 transition duration-300 hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden border-b border-white/10 bg-slate-950/80" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: item.title, className: "aspect-[16/10] w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/10] w-full bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_42%),linear-gradient(135deg,_rgba(15,23,42,0.96),_rgba(2,6,23,0.96))]" })), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, item.context_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-200" }, item.context_label) : null, item.status_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-amber-100" }, item.status_label) : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-lg font-semibold tracking-[-0.02em] text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null)))));
}
function EntityCard$1({ item, sectionKey }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.url, "data-world-event": "world_entity_clicked", "data-world-section-key": sectionKey, "data-world-entity-type": item.entity_type || "", "data-world-entity-id": item.id, "data-world-entity-title": item.title || "", className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/15 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "h-12 w-12 rounded-2xl border border-white/10 object-cover" }) : item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: "", className: "h-12 w-12 rounded-2xl border border-white/10 object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-group" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, item.context_label ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.context_label) : null, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null)), item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null);
}
function RewardedCard({ item }) {
  const creator = item?.creator || null;
  if (!creator) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("a", { href: creator.profile_url || "#", "data-world-event": "world_entity_clicked", "data-world-section-key": "recap_rewarded", "data-world-entity-type": "creator", "data-world-entity-id": creator.id || 0, "data-world-entity-title": creator.name || creator.username || "Creator", className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/15 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, creator.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: creator.avatar_url, alt: creator.username || creator.name, className: "h-12 w-12 rounded-2xl border border-white/10 object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, creator.name || creator.username || "Creator"), /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs uppercase tracking-[0.14em] text-slate-500" }, item.badge_label))), item.artwork?.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-300" }, item.artwork.title) : null);
}
function WorldRecapCreatorsPanel({ section }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  const rewarded = Array.isArray(section?.rewarded) ? section.rewarded.filter(Boolean) : [];
  if (items.length === 0 && rewarded.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title || "Creators and groups"), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null), items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, items.map((item) => /* @__PURE__ */ React.createElement(EntityCard$1, { key: `${item.entity_type}-${item.id}`, item, sectionKey: "recap_creators" }))) : null, rewarded.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Rewarded contributors"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, rewarded.map((item) => /* @__PURE__ */ React.createElement(RewardedCard, { key: item.id, item })))) : null);
}
function ArtworkCard({ item }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.url, "data-world-event": "world_entity_clicked", "data-world-section-key": "recap_highlights", "data-world-entity-type": item.entity_type || "artwork", "data-world-entity-id": item.id, "data-world-entity-title": item.title || "", className: "group overflow-hidden rounded-[26px] border border-white/10 bg-white/[0.03] transition duration-300 hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden border-b border-white/10 bg-slate-950/80" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: item.title, className: "aspect-[16/10] w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/10] w-full bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_42%),linear-gradient(135deg,_rgba(15,23,42,0.96),_rgba(2,6,23,0.96))]" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 flex items-start justify-between gap-2 p-4" }, item.context_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/15 bg-black/35 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-white/80" }, item.context_label) : null, item.status_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-sky-100" }, item.status_label) : null)), /* @__PURE__ */ React.createElement("div", { className: "p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold tracking-[-0.02em] text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry, className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-xs text-slate-300" }, entry))) : null));
}
function WorldRecapFeaturedArtworks({ section }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { id: "world-recap-highlights", className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title || "Edition highlights"), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, items.length, " highlights")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, items.map((item) => /* @__PURE__ */ React.createElement(ArtworkCard, { key: item.id, item }))));
}
function WorldEndedBadge({ label = "Ended edition" }) {
  return /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/12 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag-checkered" }), label);
}
function recapStyle(world) {
  return {
    "--world-accent": world?.theme?.accent_color || "#38bdf8",
    "--world-accent-secondary": world?.theme?.accent_color_secondary || "#0f172a"
  };
}
function WorldRecapHero({ world, recap, previewMode = false }) {
  if (!world || !recap) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { id: "world-recap", className: "relative overflow-hidden rounded-[36px] border border-white/10", style: recapStyle(world) }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_15%_20%,_color-mix(in_srgb,var(--world-accent)_28%,transparent),_transparent_32%),radial-gradient(circle_at_85%_18%,_color-mix(in_srgb,var(--world-accent-secondary)_70%,transparent),_transparent_40%),linear-gradient(140deg,_rgba(2,6,23,0.95),_rgba(15,23,42,0.84)_48%,_rgba(2,6,23,0.98))]" }), recap.cover_url ? /* @__PURE__ */ React.createElement("img", { src: recap.cover_url, alt: recap.title || world.title, className: "absolute inset-0 h-full w-full object-cover opacity-20" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-950/75 to-slate-950/10" }), /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-8 px-6 py-8 sm:px-8 lg:grid-cols-[minmax(0,1.18fr)_21rem] lg:px-10 lg:py-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement(WorldEndedBadge, { label: previewMode && recap.status === "draft_preview" ? "Recap draft preview" : "Published recap" }), (Array.isArray(world.status_badges) ? world.status_badges : []).slice(0, 3).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge }))), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 max-w-4xl text-4xl font-semibold tracking-[-0.05em] text-white sm:text-5xl lg:text-6xl" }, recap.title), world.title ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs uppercase tracking-[0.24em] text-white/55" }, world.title) : null, recap.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-6 max-w-3xl text-base leading-7 text-slate-200/90 sm:text-lg" }, recap.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex flex-wrap gap-3" }, world.cta_url ? /* @__PURE__ */ React.createElement("a", { href: world.cta_url, "data-world-event": "world_cta_clicked", "data-world-section-key": "recap_hero", "data-world-cta-key": "recap_primary", className: "inline-flex items-center gap-2 rounded-full bg-white px-5 py-3 text-sm font-semibold text-slate-950 transition hover:bg-sky-100" }, world.cta_label || "Browse recap highlights", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })) : null, world.public_url ? /* @__PURE__ */ React.createElement("a", { href: `${world.public_url}#world-recap-highlights`, "data-world-event": "world_cta_clicked", "data-world-section-key": "recap_hero", "data-world-cta-key": "recap_jump_highlights", className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Edition highlights") : null)), /* @__PURE__ */ React.createElement("aside", { className: "rounded-[28px] border border-white/12 bg-black/25 p-5 text-sm text-slate-200 shadow-2xl shadow-slate-950/30 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Recap status"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, "Edition state"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-base font-semibold text-white" }, "Archive-facing recap")), recap.published_at ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, "Published"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-base font-semibold text-white" }, new Date(recap.published_at).toLocaleDateString())) : null, world.edition_label ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, "Edition"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-base font-semibold text-white" }, world.edition_label)) : null, world.family_title ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-500" }, "Family"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-base font-semibold text-white" }, world.family_title)) : null))));
}
function formatNumber(value) {
  return new Intl.NumberFormat("en", { notation: value >= 1e3 ? "compact" : "standard", maximumFractionDigits: 1 }).format(Number(value || 0));
}
function WorldRecapStatsGrid({ stats }) {
  const items = Array.isArray(stats?.items) ? stats.items : [];
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, "Key stats"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "A compact snapshot of how the edition performed before it settled into the archive.")), stats?.captured_at ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, stats.source === "snapshot" ? "Snapshot captured" : "Live draft metrics", " ", new Date(stats.captured_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, formatNumber(item.value)), item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, item.description) : null))));
}
function WorldRecapSummaryCard({ recap }) {
  if (!recap?.intro) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Recap summary"), /* @__PURE__ */ React.createElement("div", { className: "prose prose-invert prose-sm mt-4 max-w-4xl prose-p:text-slate-300 prose-p:leading-7 prose-headings:text-white prose-strong:text-white prose-a:text-sky-300", dangerouslySetInnerHTML: { __html: recap.intro } }));
}
function EntityCard({ item, sectionKey }) {
  return /* @__PURE__ */ React.createElement("a", { href: item.url, "data-world-event": "world_entity_clicked", "data-world-section-key": sectionKey, "data-world-entity-type": item.entity_type || "", "data-world-entity-id": item.id, "data-world-entity-title": item.title || "", className: "group rounded-[26px] border border-white/10 bg-white/[0.03] p-4 transition duration-300 hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[22px] border border-white/10 bg-slate-950/70" }, item.image ? /* @__PURE__ */ React.createElement("img", { src: item.image, alt: item.title, className: "aspect-[16/10] w-full object-cover transition duration-500 group-hover:scale-[1.04]" }) : /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/10] w-full bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.18),_transparent_42%),linear-gradient(135deg,_rgba(15,23,42,0.96),_rgba(2,6,23,0.96))]" }), item.avatar ? /* @__PURE__ */ React.createElement("img", { src: item.avatar, alt: "", className: "absolute bottom-3 left-3 h-12 w-12 rounded-2xl border border-white/15 object-cover shadow-lg shadow-black/40" }) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, item.context_label ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/70" }, item.context_label) : null, /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold tracking-[-0.02em] text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.description) : null, Array.isArray(item.meta) && item.meta.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.meta.map((entry) => /* @__PURE__ */ React.createElement("span", { key: entry, className: "rounded-full border border-white/10 bg-black/20 px-3 py-1 text-xs text-slate-300" }, entry))) : null));
}
function WorldSection({ section }) {
  if (!section || !Array.isArray(section.items) || section.items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, section.title), section.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, section.description) : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, section.items.length, " items")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, section.items.map((item) => /* @__PURE__ */ React.createElement(EntityCard, { key: `${item.entity_type}-${item.id}`, item, sectionKey: section.key || "" }))));
}
function SupportingRail({ title, description, items, sourceDetail = "navigation_rail" }) {
  if (!Array.isArray(items) || items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, description) : null)), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement(WorldCard, { key: item.id, world: item, compact: true, sourceSurface: "navigation", sourceDetail }))));
}
function EditionNavigation({ previousEdition, nextEdition }) {
  if (!previousEdition && !nextEdition) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, "Edition Navigation"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Move through adjacent editions in this recurring world family without losing the archive context.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("a", { href: previousEdition ? withWorldSource(previousEdition.public_url, "navigation", "previous_edition") : "#", onClick: () => previousEdition && trackWorldSourceClick({ worldId: previousEdition.id, worldTitle: previousEdition.title, sourceSurface: "navigation", sourceDetail: "previous_edition" }), className: `rounded-[24px] border border-white/10 bg-black/20 p-4 ${previousEdition ? "text-white hover:bg-white/[0.06]" : "pointer-events-none text-slate-500"}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Previous edition"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold" }, previousEdition?.title || "No earlier edition"), previousEdition?.edition_year ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-300" }, previousEdition.edition_year) : null), /* @__PURE__ */ React.createElement("a", { href: nextEdition ? withWorldSource(nextEdition.public_url, "navigation", "next_edition") : "#", onClick: () => nextEdition && trackWorldSourceClick({ worldId: nextEdition.id, worldTitle: nextEdition.title, sourceSurface: "navigation", sourceDetail: "next_edition" }), className: `rounded-[24px] border border-white/10 bg-black/20 p-4 ${nextEdition ? "text-white hover:bg-white/[0.06]" : "pointer-events-none text-slate-500"}` }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Next edition"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold" }, nextEdition?.title || "No newer archive edition"), nextEdition?.edition_year ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-300" }, nextEdition.edition_year) : null)));
}
function RewardedContributors({ section, world }) {
  const items = Array.isArray(section?.items) ? section.items : [];
  const counts = section?.counts || {};
  const summaryChips = [
    section?.creator_count ? `${section.creator_count} rewarded creators` : null,
    world?.live_submission_count ? `${world.live_submission_count} live submissions` : null,
    world?.featured_submission_count ? `${world.featured_submission_count} featured artworks` : null
  ].filter(Boolean);
  const rewardTypeChips = [
    counts.winner ? `${counts.winner} winner${counts.winner === 1 ? "" : "s"}` : null,
    counts.finalist ? `${counts.finalist} finalist${counts.finalist === 1 ? "" : "s"}` : null,
    counts.spotlight ? `${counts.spotlight} spotlight` : null,
    counts.featured ? `${counts.featured} featured` : null,
    counts.participant ? `${counts.participant} participant` : null
  ].filter(Boolean);
  if (items.length === 0) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, "Rewarded Contributors"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Creators who earned visible recognition in this edition. Live participation builds history here, while featured and editorial selections raise the level of recognition.")), summaryChips.length > 0 || rewardTypeChips.length > 0 || world?.cta_url ? /* @__PURE__ */ React.createElement("div", { className: "mb-5 rounded-[24px] border border-white/10 bg-black/20 p-4" }, summaryChips.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, summaryChips.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-200" }, item))) : null, rewardTypeChips.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, rewardTypeChips.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-sky-100" }, item))) : null, world?.cta_url ? /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("a", { href: world.cta_url, "data-world-event": "world_cta_clicked", "data-world-section-key": "rewards", "data-world-cta-key": "rewards_join_world", className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.06] px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.1]" }, world.cta_label || "Join this world", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("p", { className: "max-w-3xl text-sm leading-6 text-slate-400" }, "This edition’s rewards are edition-aware, so recognition here remains part of each creator’s recurring world history.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.creator?.profile_url || item.world?.url || "#", "data-world-event": "world_entity_clicked", "data-world-section-key": "rewards", "data-world-entity-type": "creator", "data-world-entity-id": item.creator?.id || 0, "data-world-entity-title": item.creator?.name || item.creator?.username || "Creator", className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/15 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, item.creator?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.creator.avatar_url, alt: item.creator.username || item.creator.name, className: "h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.04] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.creator?.name || item.creator?.username || "Creator"), /* @__PURE__ */ React.createElement("div", { className: "truncate text-xs uppercase tracking-[0.16em] text-slate-500" }, item.badge_label))), item.artwork?.title ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-300" }, item.artwork.title) : null))));
}
function WebStoryCard({ story, worldTitle }) {
  if (!story) {
    return null;
  }
  return /* @__PURE__ */ React.createElement("section", { className: "mt-10 rounded-[28px] border border-sky-300/18 bg-[linear-gradient(135deg,rgba(14,165,233,0.12),rgba(15,23,42,0.85))] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[220px,1fr] lg:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 aspect-[3/4] max-w-[220px]" }, story.poster_portrait_url ? /* @__PURE__ */ React.createElement("img", { src: story.poster_portrait_url, alt: story.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open-reader text-4xl" }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Web Story"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, "Experience this World as a Web Story"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-200" }, "Swipe through a cinematic visual preview of ", worldTitle, "."), story.excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-slate-300" }, story.excerpt) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement("a", { href: story.url, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.08] px-5 py-2.5 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.14]" }, "View Web Story", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))));
}
function WorldShow() {
  const { props } = X$1();
  const world = props.world;
  const recap = props.recap || null;
  const sections = Array.isArray(props.sections) ? props.sections : [];
  const linkedChallenge = props.linkedChallenge || null;
  const linkedChallengeEntries = props.linkedChallengeEntries || null;
  const linkedChallengeWinners = props.linkedChallengeWinners || null;
  const linkedChallengeFinalists = props.linkedChallengeFinalists || null;
  const communitySubmissions = props.communitySubmissions || null;
  const rewardedContributors = props.rewardedContributors || null;
  const previewMode = Boolean(props.previewMode);
  const archiveNotice = props.archiveNotice || null;
  const familySummary = props.familySummary || null;
  const currentEdition = props.currentEdition || null;
  const previousEdition = props.previousEdition || null;
  const nextEdition = props.nextEdition || null;
  const webStory = props.webStory || world?.published_web_story || null;
  const archiveTitle = currentEdition ? "Previous Editions" : "Archive Editions";
  const archiveDescription = currentEdition ? "Earlier editions remain public so the recurring family keeps its full history accessible." : "Past iterations remain accessible so recurring worlds can build continuity over time.";
  const rootRef = reactExports.useRef(null);
  reactExports.useEffect(() => {
    if (previewMode || !world?.id) {
      return;
    }
    const landing = resolveWorldLandingSource();
    trackWorldAnalytics("world_viewed", {
      world_id: world.id,
      source_surface: landing.sourceSurface,
      source_detail: landing.sourceDetail
    });
  }, [previewMode, world?.id]);
  reactExports.useEffect(() => {
    if (previewMode || !world?.id || !rootRef.current) {
      return;
    }
    const landing = resolveWorldLandingSource();
    const container = rootRef.current;
    const clickHandler = (event) => {
      const target = event.target.closest("[data-world-event], [data-world-section-key]");
      if (!target || !container.contains(target)) {
        return;
      }
      const sectionKey = target.dataset.worldSectionKey || "";
      const challengeId = Number(target.dataset.worldChallengeId || 0);
      const entityId = Number(target.dataset.worldEntityId || 0);
      const payload = {
        world_id: world.id,
        source_surface: landing.sourceSurface,
        source_detail: landing.sourceDetail,
        ...sectionKey ? { section_key: sectionKey } : {},
        ...target.dataset.worldCtaKey ? { cta_key: target.dataset.worldCtaKey } : {},
        ...target.dataset.worldEntityType ? { entity_type: target.dataset.worldEntityType } : {},
        ...entityId > 0 ? { entity_id: entityId } : {},
        ...target.dataset.worldEntityTitle ? { entity_title: target.dataset.worldEntityTitle } : {},
        ...challengeId > 0 ? { challenge_id: challengeId } : {}
      };
      if (sectionKey) {
        trackWorldAnalytics("world_section_clicked", payload);
      }
      if (target.dataset.worldEvent) {
        trackWorldAnalytics(target.dataset.worldEvent, payload);
      }
    };
    container.addEventListener("click", clickHandler);
    return () => {
      container.removeEventListener("click", clickHandler);
    };
  }, [previewMode, world?.id]);
  return /* @__PURE__ */ React.createElement("main", { ref: rootRef, className: "min-h-screen bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${world?.title || "World"} - Skinbase`, description: world?.summary }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl" }, previewMode ? /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-amber-300/20 bg-amber-400/10 px-5 py-4 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100/75" }, "Studio preview"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, "You are viewing the editorial preview version of this world before or alongside public release.")), world?.public_url ? /* @__PURE__ */ React.createElement("a", { href: world.public_url, className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white" }, "Open canonical page ", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-up-right-from-square" })) : null)) : null, /* @__PURE__ */ React.createElement(WorldArchiveNotice, { notice: archiveNotice }), recap ? /* @__PURE__ */ React.createElement(WorldRecapHero, { world, recap, previewMode }) : /* @__PURE__ */ React.createElement(WorldHero, { world, previewMode }), recap ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(WorldRecapSummaryCard, { recap }), /* @__PURE__ */ React.createElement(WorldRecapStatsGrid, { stats: recap.stats }), /* @__PURE__ */ React.createElement(WorldRecapArticleCard, { article: recap.article }), /* @__PURE__ */ React.createElement(WorldRecapFeaturedArtworks, { section: recap.featured_artworks }), /* @__PURE__ */ React.createElement(WorldChallengePanel, { section: linkedChallenge })) : /* @__PURE__ */ React.createElement(WorldChallengePanel, { section: linkedChallenge }), familySummary ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.03em] text-white" }, "Recurring Family"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Each edition stays public, but the family route always resolves to the canonical current or latest edition.")), /* @__PURE__ */ React.createElement(WorldFamilyCard, { family: familySummary, sourceSurface: "navigation", sourceDetail: "family_summary" })) : null, /* @__PURE__ */ React.createElement(WebStoryCard, { story: webStory, worldTitle: world?.title || "this World" }), sections.length > 0 ? sections.map((section) => /* @__PURE__ */ React.createElement(WorldSection, { key: section.key, section })) : null, /* @__PURE__ */ React.createElement(WorldChallengeEntriesRail, { section: linkedChallengeEntries, challengeId: linkedChallenge?.id || null }), /* @__PURE__ */ React.createElement(WorldChallengeWinnersPanel, { section: linkedChallengeWinners, challengeId: linkedChallenge?.id || null }), /* @__PURE__ */ React.createElement(WorldChallengeFinalistsGrid, { panel: linkedChallenge, section: linkedChallengeFinalists }), recap ? /* @__PURE__ */ React.createElement(WorldRecapCommunityHighlights, { section: recap.community_highlights }) : /* @__PURE__ */ React.createElement(RewardedContributors, { section: rewardedContributors, world }), recap ? /* @__PURE__ */ React.createElement(WorldRecapCreatorsPanel, { section: recap.creators }) : /* @__PURE__ */ React.createElement(WorldCommunitySubmissionsSection, { section: communitySubmissions }), currentEdition ? /* @__PURE__ */ React.createElement(
    SupportingRail,
    {
      title: "Current Edition",
      description: "This recurring family has a newer public edition. Use the family route to follow the current canonical page.",
      items: [currentEdition],
      sourceDetail: "current_edition"
    }
  ) : null, /* @__PURE__ */ React.createElement(EditionNavigation, { previousEdition, nextEdition }), /* @__PURE__ */ React.createElement(
    SupportingRail,
    {
      title: archiveTitle,
      description: archiveDescription,
      items: props.archiveEditions,
      sourceDetail: "archive_editions"
    }
  ), /* @__PURE__ */ React.createElement(
    SupportingRail,
    {
      title: "Related Worlds",
      description: "Other worlds with adjacent themes, related editorial mood, or connected programming context.",
      items: props.relatedWorlds,
      sourceDetail: "related_worlds"
    }
  )));
}
const __vite_glob_0_164 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  default: WorldShow
}, Symbol.toStringTag, { value: "Module" }));
var g = (t) => new Promise((o, n) => {
  let r = "";
  t.on("data", (e) => r += e), t.on("end", () => o(r)), t.on("error", (e) => n(e));
}), d = (t, o) => {
  let n = 13714, r = { "/health": async () => ({ status: "OK", timestamp: Date.now() }), "/shutdown": () => s.exit(), "/render": async (e) => t(JSON.parse(await g(e))), "/404": async () => ({ status: "NOT_FOUND", timestamp: Date.now() }) };
  createServer(async (e, a) => {
    let i = r[e.url] || r["/404"];
    try {
      a.writeHead(200, { "Content-Type": "application/json", Server: "Inertia.js SSR" }), a.write(JSON.stringify(await i(e)));
    } catch (p) {
      console.error(p);
    }
    a.end();
  }).listen(n, () => console.log("Inertia SSR server started.")), console.log(`Starting SSR server on port ${n}...`);
};
var server_node = {};
var reactDomServerLegacy_node_production = {};
var hasRequiredReactDomServerLegacy_node_production;
function requireReactDomServerLegacy_node_production() {
  if (hasRequiredReactDomServerLegacy_node_production) return reactDomServerLegacy_node_production;
  hasRequiredReactDomServerLegacy_node_production = 1;
  var React2 = requireReact(), ReactDOM = requireReactDom(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_SCOPE_TYPE = /* @__PURE__ */ Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = /* @__PURE__ */ Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  function getIteratorFn(maybeIterable) {
    if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
    maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
    return "function" === typeof maybeIterable ? maybeIterable : null;
  }
  var isArrayImpl = Array.isArray;
  function murmurhash3_32_gc(key, seed) {
    var remainder = key.length & 3;
    var bytes = key.length - remainder;
    var h1 = seed;
    for (seed = 0; seed < bytes; ) {
      var k1 = key.charCodeAt(seed) & 255 | (key.charCodeAt(++seed) & 255) << 8 | (key.charCodeAt(++seed) & 255) << 16 | (key.charCodeAt(++seed) & 255) << 24;
      ++seed;
      k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295;
      k1 = k1 << 15 | k1 >>> 17;
      k1 = 461845907 * (k1 & 65535) + ((461845907 * (k1 >>> 16) & 65535) << 16) & 4294967295;
      h1 ^= k1;
      h1 = h1 << 13 | h1 >>> 19;
      h1 = 5 * (h1 & 65535) + ((5 * (h1 >>> 16) & 65535) << 16) & 4294967295;
      h1 = (h1 & 65535) + 27492 + (((h1 >>> 16) + 58964 & 65535) << 16);
    }
    k1 = 0;
    switch (remainder) {
      case 3:
        k1 ^= (key.charCodeAt(seed + 2) & 255) << 16;
      case 2:
        k1 ^= (key.charCodeAt(seed + 1) & 255) << 8;
      case 1:
        k1 ^= key.charCodeAt(seed) & 255, k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295, k1 = k1 << 15 | k1 >>> 17, h1 ^= 461845907 * (k1 & 65535) + ((461845907 * (k1 >>> 16) & 65535) << 16) & 4294967295;
    }
    h1 ^= key.length;
    h1 ^= h1 >>> 16;
    h1 = 2246822507 * (h1 & 65535) + ((2246822507 * (h1 >>> 16) & 65535) << 16) & 4294967295;
    h1 ^= h1 >>> 13;
    h1 = 3266489909 * (h1 & 65535) + ((3266489909 * (h1 >>> 16) & 65535) << 16) & 4294967295;
    return (h1 ^ h1 >>> 16) >>> 0;
  }
  var assign = Object.assign, hasOwnProperty2 = Object.prototype.hasOwnProperty, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
    "^[: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]*$"
  ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {};
  function isAttributeNameSafe(attributeName) {
    if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
      return true;
    if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName)) return false;
    if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
      return validatedAttributeNameCache[attributeName] = true;
    illegalAttributeNameCache[attributeName] = true;
    return false;
  }
  var unitlessNumbers = new Set(
    "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
      " "
    )
  ), aliases = /* @__PURE__ */ new Map([
    ["acceptCharset", "accept-charset"],
    ["htmlFor", "for"],
    ["httpEquiv", "http-equiv"],
    ["crossOrigin", "crossorigin"],
    ["accentHeight", "accent-height"],
    ["alignmentBaseline", "alignment-baseline"],
    ["arabicForm", "arabic-form"],
    ["baselineShift", "baseline-shift"],
    ["capHeight", "cap-height"],
    ["clipPath", "clip-path"],
    ["clipRule", "clip-rule"],
    ["colorInterpolation", "color-interpolation"],
    ["colorInterpolationFilters", "color-interpolation-filters"],
    ["colorProfile", "color-profile"],
    ["colorRendering", "color-rendering"],
    ["dominantBaseline", "dominant-baseline"],
    ["enableBackground", "enable-background"],
    ["fillOpacity", "fill-opacity"],
    ["fillRule", "fill-rule"],
    ["floodColor", "flood-color"],
    ["floodOpacity", "flood-opacity"],
    ["fontFamily", "font-family"],
    ["fontSize", "font-size"],
    ["fontSizeAdjust", "font-size-adjust"],
    ["fontStretch", "font-stretch"],
    ["fontStyle", "font-style"],
    ["fontVariant", "font-variant"],
    ["fontWeight", "font-weight"],
    ["glyphName", "glyph-name"],
    ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
    ["glyphOrientationVertical", "glyph-orientation-vertical"],
    ["horizAdvX", "horiz-adv-x"],
    ["horizOriginX", "horiz-origin-x"],
    ["imageRendering", "image-rendering"],
    ["letterSpacing", "letter-spacing"],
    ["lightingColor", "lighting-color"],
    ["markerEnd", "marker-end"],
    ["markerMid", "marker-mid"],
    ["markerStart", "marker-start"],
    ["overlinePosition", "overline-position"],
    ["overlineThickness", "overline-thickness"],
    ["paintOrder", "paint-order"],
    ["panose-1", "panose-1"],
    ["pointerEvents", "pointer-events"],
    ["renderingIntent", "rendering-intent"],
    ["shapeRendering", "shape-rendering"],
    ["stopColor", "stop-color"],
    ["stopOpacity", "stop-opacity"],
    ["strikethroughPosition", "strikethrough-position"],
    ["strikethroughThickness", "strikethrough-thickness"],
    ["strokeDasharray", "stroke-dasharray"],
    ["strokeDashoffset", "stroke-dashoffset"],
    ["strokeLinecap", "stroke-linecap"],
    ["strokeLinejoin", "stroke-linejoin"],
    ["strokeMiterlimit", "stroke-miterlimit"],
    ["strokeOpacity", "stroke-opacity"],
    ["strokeWidth", "stroke-width"],
    ["textAnchor", "text-anchor"],
    ["textDecoration", "text-decoration"],
    ["textRendering", "text-rendering"],
    ["transformOrigin", "transform-origin"],
    ["underlinePosition", "underline-position"],
    ["underlineThickness", "underline-thickness"],
    ["unicodeBidi", "unicode-bidi"],
    ["unicodeRange", "unicode-range"],
    ["unitsPerEm", "units-per-em"],
    ["vAlphabetic", "v-alphabetic"],
    ["vHanging", "v-hanging"],
    ["vIdeographic", "v-ideographic"],
    ["vMathematical", "v-mathematical"],
    ["vectorEffect", "vector-effect"],
    ["vertAdvY", "vert-adv-y"],
    ["vertOriginX", "vert-origin-x"],
    ["vertOriginY", "vert-origin-y"],
    ["wordSpacing", "word-spacing"],
    ["writingMode", "writing-mode"],
    ["xmlnsXlink", "xmlns:xlink"],
    ["xHeight", "x-height"]
  ]), matchHtmlRegExp = /["'&<>]/;
  function escapeTextForBrowser(text2) {
    if ("boolean" === typeof text2 || "number" === typeof text2 || "bigint" === typeof text2)
      return "" + text2;
    text2 = "" + text2;
    var match = matchHtmlRegExp.exec(text2);
    if (match) {
      var html2 = "", index2, lastIndex = 0;
      for (index2 = match.index; index2 < text2.length; index2++) {
        switch (text2.charCodeAt(index2)) {
          case 34:
            match = "&quot;";
            break;
          case 38:
            match = "&amp;";
            break;
          case 39:
            match = "&#x27;";
            break;
          case 60:
            match = "&lt;";
            break;
          case 62:
            match = "&gt;";
            break;
          default:
            continue;
        }
        lastIndex !== index2 && (html2 += text2.slice(lastIndex, index2));
        lastIndex = index2 + 1;
        html2 += match;
      }
      text2 = lastIndex !== index2 ? html2 + text2.slice(lastIndex, index2) : html2;
    }
    return text2;
  }
  var uppercasePattern = /([A-Z])/g, msPattern = /^ms-/, isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
  function sanitizeURL(url) {
    return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
  }
  var ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, sharedNotPendingObject = {
    pending: false,
    data: null,
    method: null,
    action: null
  }, previousDispatcher = ReactDOMSharedInternals.d;
  ReactDOMSharedInternals.d = {
    f: previousDispatcher.f,
    r: previousDispatcher.r,
    D: prefetchDNS,
    C: preconnect,
    L: preload,
    m: preloadModule,
    X: preinitScript,
    S: preinitStyle,
    M: preinitModuleScript
  };
  var PRELOAD_NO_CREDS = [], currentlyFlushingRenderState = null, scriptRegex = /(<\/|<)(s)(cript)/gi;
  function scriptReplacer(match, prefix2, s2, suffix2) {
    return "" + prefix2 + ("s" === s2 ? "\\u0073" : "\\u0053") + suffix2;
  }
  function createResumableState(identifierPrefix, externalRuntimeConfig, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
    return {
      idPrefix: void 0 === identifierPrefix ? "" : identifierPrefix,
      nextFormID: 0,
      streamingFormat: 0,
      bootstrapScriptContent,
      bootstrapScripts,
      bootstrapModules,
      instructions: 0,
      hasBody: false,
      hasHtml: false,
      unknownResources: {},
      dnsResources: {},
      connectResources: { default: {}, anonymous: {}, credentials: {} },
      imageResources: {},
      styleResources: {},
      scriptResources: {},
      moduleUnknownResources: {},
      moduleScriptResources: {}
    };
  }
  function createFormatContext(insertionMode, selectedValue, tagScope, viewTransition) {
    return {
      insertionMode,
      selectedValue,
      tagScope,
      viewTransition
    };
  }
  function getChildFormatContext(parentContext, type2, props) {
    var subtreeScope = parentContext.tagScope & -25;
    switch (type2) {
      case "noscript":
        return createFormatContext(2, null, subtreeScope | 1, null);
      case "select":
        return createFormatContext(
          2,
          null != props.value ? props.value : props.defaultValue,
          subtreeScope,
          null
        );
      case "svg":
        return createFormatContext(4, null, subtreeScope, null);
      case "picture":
        return createFormatContext(2, null, subtreeScope | 2, null);
      case "math":
        return createFormatContext(5, null, subtreeScope, null);
      case "foreignObject":
        return createFormatContext(2, null, subtreeScope, null);
      case "table":
        return createFormatContext(6, null, subtreeScope, null);
      case "thead":
      case "tbody":
      case "tfoot":
        return createFormatContext(7, null, subtreeScope, null);
      case "colgroup":
        return createFormatContext(9, null, subtreeScope, null);
      case "tr":
        return createFormatContext(8, null, subtreeScope, null);
      case "head":
        if (2 > parentContext.insertionMode)
          return createFormatContext(3, null, subtreeScope, null);
        break;
      case "html":
        if (0 === parentContext.insertionMode)
          return createFormatContext(1, null, subtreeScope, null);
    }
    return 6 <= parentContext.insertionMode || 2 > parentContext.insertionMode ? createFormatContext(2, null, subtreeScope, null) : parentContext.tagScope !== subtreeScope ? createFormatContext(
      parentContext.insertionMode,
      parentContext.selectedValue,
      subtreeScope,
      null
    ) : parentContext;
  }
  function getSuspenseViewTransition(parentViewTransition) {
    return null === parentViewTransition ? null : {
      update: parentViewTransition.update,
      enter: "none",
      exit: "none",
      share: parentViewTransition.update,
      name: parentViewTransition.autoName,
      autoName: parentViewTransition.autoName,
      nameIdx: 0
    };
  }
  function getSuspenseFallbackFormatContext(resumableState, parentContext) {
    parentContext.tagScope & 32 && (resumableState.instructions |= 128);
    return createFormatContext(
      parentContext.insertionMode,
      parentContext.selectedValue,
      parentContext.tagScope | 12,
      getSuspenseViewTransition(parentContext.viewTransition)
    );
  }
  function getSuspenseContentFormatContext(resumableState, parentContext) {
    resumableState = getSuspenseViewTransition(parentContext.viewTransition);
    var subtreeScope = parentContext.tagScope | 16;
    null !== resumableState && "none" !== resumableState.share && (subtreeScope |= 64);
    return createFormatContext(
      parentContext.insertionMode,
      parentContext.selectedValue,
      subtreeScope,
      resumableState
    );
  }
  var styleNameCache = /* @__PURE__ */ new Map();
  function pushStyleAttribute(target, style) {
    if ("object" !== typeof style)
      throw Error(
        "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
      );
    var isFirst = true, styleName;
    for (styleName in style)
      if (hasOwnProperty2.call(style, styleName)) {
        var styleValue = style[styleName];
        if (null != styleValue && "boolean" !== typeof styleValue && "" !== styleValue) {
          if (0 === styleName.indexOf("--")) {
            var nameChunk = escapeTextForBrowser(styleName);
            styleValue = escapeTextForBrowser(("" + styleValue).trim());
          } else
            nameChunk = styleNameCache.get(styleName), void 0 === nameChunk && (nameChunk = escapeTextForBrowser(
              styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-")
            ), styleNameCache.set(styleName, nameChunk)), styleValue = "number" === typeof styleValue ? 0 === styleValue || unitlessNumbers.has(styleName) ? "" + styleValue : styleValue + "px" : escapeTextForBrowser(("" + styleValue).trim());
          isFirst ? (isFirst = false, target.push(' style="', nameChunk, ":", styleValue)) : target.push(";", nameChunk, ":", styleValue);
        }
      }
    isFirst || target.push('"');
  }
  function pushBooleanAttribute(target, name2, value) {
    value && "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name2, '=""');
  }
  function pushStringAttribute(target, name2, value) {
    "function" !== typeof value && "symbol" !== typeof value && "boolean" !== typeof value && target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
  }
  var actionJavaScriptURL = escapeTextForBrowser(
    "javascript:throw new Error('React form unexpectedly submitted.')"
  );
  function pushAdditionalFormField(value, key) {
    this.push('<input type="hidden"');
    validateAdditionalFormField(value);
    pushStringAttribute(this, "name", key);
    pushStringAttribute(this, "value", value);
    this.push("/>");
  }
  function validateAdditionalFormField(value) {
    if ("string" !== typeof value)
      throw Error(
        "File/Blob fields are not yet supported in progressive forms. Will fallback to client hydration."
      );
  }
  function getCustomFormFields(resumableState, formAction) {
    if ("function" === typeof formAction.$$FORM_ACTION) {
      var id = resumableState.nextFormID++;
      resumableState = resumableState.idPrefix + id;
      try {
        var customFields = formAction.$$FORM_ACTION(resumableState);
        if (customFields) {
          var formData = customFields.data;
          null != formData && formData.forEach(validateAdditionalFormField);
        }
        return customFields;
      } catch (x2) {
        if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then)
          throw x2;
      }
    }
    return null;
  }
  function pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name2) {
    var formData = null;
    if ("function" === typeof formAction) {
      var customFields = getCustomFormFields(resumableState, formAction);
      null !== customFields ? (name2 = customFields.name, formAction = customFields.action || "", formEncType = customFields.encType, formMethod = customFields.method, formTarget = customFields.target, formData = customFields.data) : (target.push(" ", "formAction", '="', actionJavaScriptURL, '"'), formTarget = formMethod = formEncType = formAction = name2 = null, injectFormReplayingRuntime(resumableState, renderState));
    }
    null != name2 && pushAttribute(target, "name", name2);
    null != formAction && pushAttribute(target, "formAction", formAction);
    null != formEncType && pushAttribute(target, "formEncType", formEncType);
    null != formMethod && pushAttribute(target, "formMethod", formMethod);
    null != formTarget && pushAttribute(target, "formTarget", formTarget);
    return formData;
  }
  function pushAttribute(target, name2, value) {
    switch (name2) {
      case "className":
        pushStringAttribute(target, "class", value);
        break;
      case "tabIndex":
        pushStringAttribute(target, "tabindex", value);
        break;
      case "dir":
      case "role":
      case "viewBox":
      case "width":
      case "height":
        pushStringAttribute(target, name2, value);
        break;
      case "style":
        pushStyleAttribute(target, value);
        break;
      case "src":
      case "href":
        if ("" === value) break;
      case "action":
      case "formAction":
        if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
          break;
        value = sanitizeURL("" + value);
        target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
        break;
      case "defaultValue":
      case "defaultChecked":
      case "innerHTML":
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "ref":
        break;
      case "autoFocus":
      case "multiple":
      case "muted":
        pushBooleanAttribute(target, name2.toLowerCase(), value);
        break;
      case "xlinkHref":
        if ("function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
          break;
        value = sanitizeURL("" + value);
        target.push(" ", "xlink:href", '="', escapeTextForBrowser(value), '"');
        break;
      case "contentEditable":
      case "spellCheck":
      case "draggable":
      case "value":
      case "autoReverse":
      case "externalResourcesRequired":
      case "focusable":
      case "preserveAlpha":
        "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
        break;
      case "inert":
      case "allowFullScreen":
      case "async":
      case "autoPlay":
      case "controls":
      case "default":
      case "defer":
      case "disabled":
      case "disablePictureInPicture":
      case "disableRemotePlayback":
      case "formNoValidate":
      case "hidden":
      case "loop":
      case "noModule":
      case "noValidate":
      case "open":
      case "playsInline":
      case "readOnly":
      case "required":
      case "reversed":
      case "scoped":
      case "seamless":
      case "itemScope":
        value && "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name2, '=""');
        break;
      case "capture":
      case "download":
        true === value ? target.push(" ", name2, '=""') : false !== value && "function" !== typeof value && "symbol" !== typeof value && target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
        break;
      case "cols":
      case "rows":
      case "size":
      case "span":
        "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value && target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
        break;
      case "rowSpan":
      case "start":
        "function" === typeof value || "symbol" === typeof value || isNaN(value) || target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
        break;
      case "xlinkActuate":
        pushStringAttribute(target, "xlink:actuate", value);
        break;
      case "xlinkArcrole":
        pushStringAttribute(target, "xlink:arcrole", value);
        break;
      case "xlinkRole":
        pushStringAttribute(target, "xlink:role", value);
        break;
      case "xlinkShow":
        pushStringAttribute(target, "xlink:show", value);
        break;
      case "xlinkTitle":
        pushStringAttribute(target, "xlink:title", value);
        break;
      case "xlinkType":
        pushStringAttribute(target, "xlink:type", value);
        break;
      case "xmlBase":
        pushStringAttribute(target, "xml:base", value);
        break;
      case "xmlLang":
        pushStringAttribute(target, "xml:lang", value);
        break;
      case "xmlSpace":
        pushStringAttribute(target, "xml:space", value);
        break;
      default:
        if (!(2 < name2.length) || "o" !== name2[0] && "O" !== name2[0] || "n" !== name2[1] && "N" !== name2[1]) {
          if (name2 = aliases.get(name2) || name2, isAttributeNameSafe(name2)) {
            switch (typeof value) {
              case "function":
              case "symbol":
                return;
              case "boolean":
                var prefix$8 = name2.toLowerCase().slice(0, 5);
                if ("data-" !== prefix$8 && "aria-" !== prefix$8) return;
            }
            target.push(" ", name2, '="', escapeTextForBrowser(value), '"');
          }
        }
    }
  }
  function pushInnerHTML(target, innerHTML, children) {
    if (null != innerHTML) {
      if (null != children)
        throw Error(
          "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
        );
      if ("object" !== typeof innerHTML || !("__html" in innerHTML))
        throw Error(
          "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
        );
      innerHTML = innerHTML.__html;
      null !== innerHTML && void 0 !== innerHTML && target.push("" + innerHTML);
    }
  }
  function flattenOptionChildren(children) {
    var content2 = "";
    React2.Children.forEach(children, function(child) {
      null != child && (content2 += child);
    });
    return content2;
  }
  function injectFormReplayingRuntime(resumableState, renderState) {
    if (0 === (resumableState.instructions & 16)) {
      resumableState.instructions |= 16;
      var preamble = renderState.preamble, bootstrapChunks = renderState.bootstrapChunks;
      (preamble.htmlChunks || preamble.headChunks) && 0 === bootstrapChunks.length ? (bootstrapChunks.push(renderState.startInlineScript), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
        ">",
        `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`,
        "<\/script>"
      )) : bootstrapChunks.unshift(
        renderState.startInlineScript,
        ">",
        `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`,
        "<\/script>"
      );
    }
  }
  function pushLinkImpl(target, props) {
    target.push(startChunkForTag("link"));
    for (var propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
            case "dangerouslySetInnerHTML":
              throw Error(
                "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
              );
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push("/>");
    return null;
  }
  var styleRegex = /(<\/|<)(s)(tyle)/gi;
  function styleReplacer(match, prefix2, s2, suffix2) {
    return "" + prefix2 + ("s" === s2 ? "\\73 " : "\\53 ") + suffix2;
  }
  function pushSelfClosing(target, props, tag) {
    target.push(startChunkForTag(tag));
    for (var propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
            case "dangerouslySetInnerHTML":
              throw Error(
                tag + " is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
              );
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push("/>");
    return null;
  }
  function pushTitleImpl(target, props) {
    target.push(startChunkForTag("title"));
    var children = null, innerHTML = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              children = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(">");
    props = Array.isArray(children) ? 2 > children.length ? children[0] : null : children;
    "function" !== typeof props && "symbol" !== typeof props && null !== props && void 0 !== props && target.push(escapeTextForBrowser("" + props));
    pushInnerHTML(target, innerHTML, children);
    target.push(endChunkForTag("title"));
    return null;
  }
  function pushScriptImpl(target, props) {
    target.push(startChunkForTag("script"));
    var children = null, innerHTML = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              children = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(">");
    pushInnerHTML(target, innerHTML, children);
    "string" === typeof children && target.push(("" + children).replace(scriptRegex, scriptReplacer));
    target.push(endChunkForTag("script"));
    return null;
  }
  function pushStartSingletonElement(target, props, tag) {
    target.push(startChunkForTag(tag));
    var innerHTML = tag = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              tag = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(">");
    pushInnerHTML(target, innerHTML, tag);
    return tag;
  }
  function pushStartGenericElement(target, props, tag) {
    target.push(startChunkForTag(tag));
    var innerHTML = tag = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              tag = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(">");
    pushInnerHTML(target, innerHTML, tag);
    return "string" === typeof tag ? (target.push(escapeTextForBrowser(tag)), null) : tag;
  }
  var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = /* @__PURE__ */ new Map();
  function startChunkForTag(tag) {
    var tagStartChunk = validatedTagCache.get(tag);
    if (void 0 === tagStartChunk) {
      if (!VALID_TAG_REGEX.test(tag)) throw Error("Invalid tag: " + tag);
      tagStartChunk = "<" + tag;
      validatedTagCache.set(tag, tagStartChunk);
    }
    return tagStartChunk;
  }
  function pushStartInstance(target$jscomp$0, type2, props, resumableState, renderState, preambleState, hoistableState, formatContext, textEmbedded) {
    switch (type2) {
      case "div":
      case "span":
      case "svg":
      case "path":
        break;
      case "a":
        target$jscomp$0.push(startChunkForTag("a"));
        var children = null, innerHTML = null, propKey;
        for (propKey in props)
          if (hasOwnProperty2.call(props, propKey)) {
            var propValue = props[propKey];
            if (null != propValue)
              switch (propKey) {
                case "children":
                  children = propValue;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML = propValue;
                  break;
                case "href":
                  "" === propValue ? pushStringAttribute(target$jscomp$0, "href", "") : pushAttribute(target$jscomp$0, propKey, propValue);
                  break;
                default:
                  pushAttribute(target$jscomp$0, propKey, propValue);
              }
          }
        target$jscomp$0.push(">");
        pushInnerHTML(target$jscomp$0, innerHTML, children);
        if ("string" === typeof children) {
          target$jscomp$0.push(escapeTextForBrowser(children));
          var JSCompiler_inline_result = null;
        } else JSCompiler_inline_result = children;
        return JSCompiler_inline_result;
      case "g":
      case "p":
      case "li":
        break;
      case "select":
        target$jscomp$0.push(startChunkForTag("select"));
        var children$jscomp$0 = null, innerHTML$jscomp$0 = null, propKey$jscomp$0;
        for (propKey$jscomp$0 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$0)) {
            var propValue$jscomp$0 = props[propKey$jscomp$0];
            if (null != propValue$jscomp$0)
              switch (propKey$jscomp$0) {
                case "children":
                  children$jscomp$0 = propValue$jscomp$0;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$0 = propValue$jscomp$0;
                  break;
                case "defaultValue":
                case "value":
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$0,
                    propValue$jscomp$0
                  );
              }
          }
        target$jscomp$0.push(">");
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$0, children$jscomp$0);
        return children$jscomp$0;
      case "option":
        var selectedValue = formatContext.selectedValue;
        target$jscomp$0.push(startChunkForTag("option"));
        var children$jscomp$1 = null, value = null, selected = null, innerHTML$jscomp$1 = null, propKey$jscomp$1;
        for (propKey$jscomp$1 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$1)) {
            var propValue$jscomp$1 = props[propKey$jscomp$1];
            if (null != propValue$jscomp$1)
              switch (propKey$jscomp$1) {
                case "children":
                  children$jscomp$1 = propValue$jscomp$1;
                  break;
                case "selected":
                  selected = propValue$jscomp$1;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$1 = propValue$jscomp$1;
                  break;
                case "value":
                  value = propValue$jscomp$1;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$1,
                    propValue$jscomp$1
                  );
              }
          }
        if (null != selectedValue) {
          var stringValue = null !== value ? "" + value : flattenOptionChildren(children$jscomp$1);
          if (isArrayImpl(selectedValue))
            for (var i = 0; i < selectedValue.length; i++) {
              if ("" + selectedValue[i] === stringValue) {
                target$jscomp$0.push(' selected=""');
                break;
              }
            }
          else
            "" + selectedValue === stringValue && target$jscomp$0.push(' selected=""');
        } else selected && target$jscomp$0.push(' selected=""');
        target$jscomp$0.push(">");
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$1, children$jscomp$1);
        return children$jscomp$1;
      case "textarea":
        target$jscomp$0.push(startChunkForTag("textarea"));
        var value$jscomp$0 = null, defaultValue = null, children$jscomp$2 = null, propKey$jscomp$2;
        for (propKey$jscomp$2 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$2)) {
            var propValue$jscomp$2 = props[propKey$jscomp$2];
            if (null != propValue$jscomp$2)
              switch (propKey$jscomp$2) {
                case "children":
                  children$jscomp$2 = propValue$jscomp$2;
                  break;
                case "value":
                  value$jscomp$0 = propValue$jscomp$2;
                  break;
                case "defaultValue":
                  defaultValue = propValue$jscomp$2;
                  break;
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                  );
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$2,
                    propValue$jscomp$2
                  );
              }
          }
        null === value$jscomp$0 && null !== defaultValue && (value$jscomp$0 = defaultValue);
        target$jscomp$0.push(">");
        if (null != children$jscomp$2) {
          if (null != value$jscomp$0)
            throw Error(
              "If you supply `defaultValue` on a <textarea>, do not pass children."
            );
          if (isArrayImpl(children$jscomp$2)) {
            if (1 < children$jscomp$2.length)
              throw Error("<textarea> can only have at most one child.");
            value$jscomp$0 = "" + children$jscomp$2[0];
          }
          value$jscomp$0 = "" + children$jscomp$2;
        }
        "string" === typeof value$jscomp$0 && "\n" === value$jscomp$0[0] && target$jscomp$0.push("\n");
        null !== value$jscomp$0 && target$jscomp$0.push(escapeTextForBrowser("" + value$jscomp$0));
        return null;
      case "input":
        target$jscomp$0.push(startChunkForTag("input"));
        var name2 = null, formAction = null, formEncType = null, formMethod = null, formTarget = null, value$jscomp$1 = null, defaultValue$jscomp$0 = null, checked = null, defaultChecked = null, propKey$jscomp$3;
        for (propKey$jscomp$3 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$3)) {
            var propValue$jscomp$3 = props[propKey$jscomp$3];
            if (null != propValue$jscomp$3)
              switch (propKey$jscomp$3) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                  );
                case "name":
                  name2 = propValue$jscomp$3;
                  break;
                case "formAction":
                  formAction = propValue$jscomp$3;
                  break;
                case "formEncType":
                  formEncType = propValue$jscomp$3;
                  break;
                case "formMethod":
                  formMethod = propValue$jscomp$3;
                  break;
                case "formTarget":
                  formTarget = propValue$jscomp$3;
                  break;
                case "defaultChecked":
                  defaultChecked = propValue$jscomp$3;
                  break;
                case "defaultValue":
                  defaultValue$jscomp$0 = propValue$jscomp$3;
                  break;
                case "checked":
                  checked = propValue$jscomp$3;
                  break;
                case "value":
                  value$jscomp$1 = propValue$jscomp$3;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$3,
                    propValue$jscomp$3
                  );
              }
          }
        var formData = pushFormActionAttribute(
          target$jscomp$0,
          resumableState,
          renderState,
          formAction,
          formEncType,
          formMethod,
          formTarget,
          name2
        );
        null !== checked ? pushBooleanAttribute(target$jscomp$0, "checked", checked) : null !== defaultChecked && pushBooleanAttribute(target$jscomp$0, "checked", defaultChecked);
        null !== value$jscomp$1 ? pushAttribute(target$jscomp$0, "value", value$jscomp$1) : null !== defaultValue$jscomp$0 && pushAttribute(target$jscomp$0, "value", defaultValue$jscomp$0);
        target$jscomp$0.push("/>");
        null != formData && formData.forEach(pushAdditionalFormField, target$jscomp$0);
        return null;
      case "button":
        target$jscomp$0.push(startChunkForTag("button"));
        var children$jscomp$3 = null, innerHTML$jscomp$2 = null, name$jscomp$0 = null, formAction$jscomp$0 = null, formEncType$jscomp$0 = null, formMethod$jscomp$0 = null, formTarget$jscomp$0 = null, propKey$jscomp$4;
        for (propKey$jscomp$4 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$4)) {
            var propValue$jscomp$4 = props[propKey$jscomp$4];
            if (null != propValue$jscomp$4)
              switch (propKey$jscomp$4) {
                case "children":
                  children$jscomp$3 = propValue$jscomp$4;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$2 = propValue$jscomp$4;
                  break;
                case "name":
                  name$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formAction":
                  formAction$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formEncType":
                  formEncType$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formMethod":
                  formMethod$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formTarget":
                  formTarget$jscomp$0 = propValue$jscomp$4;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$4,
                    propValue$jscomp$4
                  );
              }
          }
        var formData$jscomp$0 = pushFormActionAttribute(
          target$jscomp$0,
          resumableState,
          renderState,
          formAction$jscomp$0,
          formEncType$jscomp$0,
          formMethod$jscomp$0,
          formTarget$jscomp$0,
          name$jscomp$0
        );
        target$jscomp$0.push(">");
        null != formData$jscomp$0 && formData$jscomp$0.forEach(pushAdditionalFormField, target$jscomp$0);
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$2, children$jscomp$3);
        if ("string" === typeof children$jscomp$3) {
          target$jscomp$0.push(escapeTextForBrowser(children$jscomp$3));
          var JSCompiler_inline_result$jscomp$0 = null;
        } else JSCompiler_inline_result$jscomp$0 = children$jscomp$3;
        return JSCompiler_inline_result$jscomp$0;
      case "form":
        target$jscomp$0.push(startChunkForTag("form"));
        var children$jscomp$4 = null, innerHTML$jscomp$3 = null, formAction$jscomp$1 = null, formEncType$jscomp$1 = null, formMethod$jscomp$1 = null, formTarget$jscomp$1 = null, propKey$jscomp$5;
        for (propKey$jscomp$5 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$5)) {
            var propValue$jscomp$5 = props[propKey$jscomp$5];
            if (null != propValue$jscomp$5)
              switch (propKey$jscomp$5) {
                case "children":
                  children$jscomp$4 = propValue$jscomp$5;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$3 = propValue$jscomp$5;
                  break;
                case "action":
                  formAction$jscomp$1 = propValue$jscomp$5;
                  break;
                case "encType":
                  formEncType$jscomp$1 = propValue$jscomp$5;
                  break;
                case "method":
                  formMethod$jscomp$1 = propValue$jscomp$5;
                  break;
                case "target":
                  formTarget$jscomp$1 = propValue$jscomp$5;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$5,
                    propValue$jscomp$5
                  );
              }
          }
        var formData$jscomp$1 = null, formActionName = null;
        if ("function" === typeof formAction$jscomp$1) {
          var customFields = getCustomFormFields(
            resumableState,
            formAction$jscomp$1
          );
          null !== customFields ? (formAction$jscomp$1 = customFields.action || "", formEncType$jscomp$1 = customFields.encType, formMethod$jscomp$1 = customFields.method, formTarget$jscomp$1 = customFields.target, formData$jscomp$1 = customFields.data, formActionName = customFields.name) : (target$jscomp$0.push(
            " ",
            "action",
            '="',
            actionJavaScriptURL,
            '"'
          ), formTarget$jscomp$1 = formMethod$jscomp$1 = formEncType$jscomp$1 = formAction$jscomp$1 = null, injectFormReplayingRuntime(resumableState, renderState));
        }
        null != formAction$jscomp$1 && pushAttribute(target$jscomp$0, "action", formAction$jscomp$1);
        null != formEncType$jscomp$1 && pushAttribute(target$jscomp$0, "encType", formEncType$jscomp$1);
        null != formMethod$jscomp$1 && pushAttribute(target$jscomp$0, "method", formMethod$jscomp$1);
        null != formTarget$jscomp$1 && pushAttribute(target$jscomp$0, "target", formTarget$jscomp$1);
        target$jscomp$0.push(">");
        null !== formActionName && (target$jscomp$0.push('<input type="hidden"'), pushStringAttribute(target$jscomp$0, "name", formActionName), target$jscomp$0.push("/>"), null != formData$jscomp$1 && formData$jscomp$1.forEach(pushAdditionalFormField, target$jscomp$0));
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$3, children$jscomp$4);
        if ("string" === typeof children$jscomp$4) {
          target$jscomp$0.push(escapeTextForBrowser(children$jscomp$4));
          var JSCompiler_inline_result$jscomp$1 = null;
        } else JSCompiler_inline_result$jscomp$1 = children$jscomp$4;
        return JSCompiler_inline_result$jscomp$1;
      case "menuitem":
        target$jscomp$0.push(startChunkForTag("menuitem"));
        for (var propKey$jscomp$6 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$6)) {
            var propValue$jscomp$6 = props[propKey$jscomp$6];
            if (null != propValue$jscomp$6)
              switch (propKey$jscomp$6) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "menuitems cannot have `children` nor `dangerouslySetInnerHTML`."
                  );
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$6,
                    propValue$jscomp$6
                  );
              }
          }
        target$jscomp$0.push(">");
        return null;
      case "object":
        target$jscomp$0.push(startChunkForTag("object"));
        var children$jscomp$5 = null, innerHTML$jscomp$4 = null, propKey$jscomp$7;
        for (propKey$jscomp$7 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$7)) {
            var propValue$jscomp$7 = props[propKey$jscomp$7];
            if (null != propValue$jscomp$7)
              switch (propKey$jscomp$7) {
                case "children":
                  children$jscomp$5 = propValue$jscomp$7;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$4 = propValue$jscomp$7;
                  break;
                case "data":
                  var sanitizedValue = sanitizeURL("" + propValue$jscomp$7);
                  if ("" === sanitizedValue) break;
                  target$jscomp$0.push(
                    " ",
                    "data",
                    '="',
                    escapeTextForBrowser(sanitizedValue),
                    '"'
                  );
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$7,
                    propValue$jscomp$7
                  );
              }
          }
        target$jscomp$0.push(">");
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$4, children$jscomp$5);
        if ("string" === typeof children$jscomp$5) {
          target$jscomp$0.push(escapeTextForBrowser(children$jscomp$5));
          var JSCompiler_inline_result$jscomp$2 = null;
        } else JSCompiler_inline_result$jscomp$2 = children$jscomp$5;
        return JSCompiler_inline_result$jscomp$2;
      case "title":
        var noscriptTagInScope = formatContext.tagScope & 1, isFallback = formatContext.tagScope & 4;
        if (4 === formatContext.insertionMode || noscriptTagInScope || null != props.itemProp)
          var JSCompiler_inline_result$jscomp$3 = pushTitleImpl(
            target$jscomp$0,
            props
          );
        else
          isFallback ? JSCompiler_inline_result$jscomp$3 = null : (pushTitleImpl(renderState.hoistableChunks, props), JSCompiler_inline_result$jscomp$3 = void 0);
        return JSCompiler_inline_result$jscomp$3;
      case "link":
        var noscriptTagInScope$jscomp$0 = formatContext.tagScope & 1, isFallback$jscomp$0 = formatContext.tagScope & 4, rel = props.rel, href = props.href, precedence = props.precedence;
        if (4 === formatContext.insertionMode || noscriptTagInScope$jscomp$0 || null != props.itemProp || "string" !== typeof rel || "string" !== typeof href || "" === href) {
          pushLinkImpl(target$jscomp$0, props);
          var JSCompiler_inline_result$jscomp$4 = null;
        } else if ("stylesheet" === props.rel)
          if ("string" !== typeof precedence || null != props.disabled || props.onLoad || props.onError)
            JSCompiler_inline_result$jscomp$4 = pushLinkImpl(
              target$jscomp$0,
              props
            );
          else {
            var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(href) ? resumableState.styleResources[href] : void 0;
            if (null !== resourceState) {
              resumableState.styleResources[href] = null;
              styleQueue || (styleQueue = {
                precedence: escapeTextForBrowser(precedence),
                rules: [],
                hrefs: [],
                sheets: /* @__PURE__ */ new Map()
              }, renderState.styles.set(precedence, styleQueue));
              var resource = {
                state: 0,
                props: assign({}, props, {
                  "data-precedence": props.precedence,
                  precedence: null
                })
              };
              if (resourceState) {
                2 === resourceState.length && adoptPreloadCredentials(resource.props, resourceState);
                var preloadResource = renderState.preloads.stylesheets.get(href);
                preloadResource && 0 < preloadResource.length ? preloadResource.length = 0 : resource.state = 1;
              }
              styleQueue.sheets.set(href, resource);
              hoistableState && hoistableState.stylesheets.add(resource);
            } else if (styleQueue) {
              var resource$9 = styleQueue.sheets.get(href);
              resource$9 && hoistableState && hoistableState.stylesheets.add(resource$9);
            }
            textEmbedded && target$jscomp$0.push("<!-- -->");
            JSCompiler_inline_result$jscomp$4 = null;
          }
        else
          props.onLoad || props.onError ? JSCompiler_inline_result$jscomp$4 = pushLinkImpl(
            target$jscomp$0,
            props
          ) : (textEmbedded && target$jscomp$0.push("<!-- -->"), JSCompiler_inline_result$jscomp$4 = isFallback$jscomp$0 ? null : pushLinkImpl(renderState.hoistableChunks, props));
        return JSCompiler_inline_result$jscomp$4;
      case "script":
        var noscriptTagInScope$jscomp$1 = formatContext.tagScope & 1, asyncProp = props.async;
        if ("string" !== typeof props.src || !props.src || !asyncProp || "function" === typeof asyncProp || "symbol" === typeof asyncProp || props.onLoad || props.onError || 4 === formatContext.insertionMode || noscriptTagInScope$jscomp$1 || null != props.itemProp)
          var JSCompiler_inline_result$jscomp$5 = pushScriptImpl(
            target$jscomp$0,
            props
          );
        else {
          var key = props.src;
          if ("module" === props.type) {
            var resources = resumableState.moduleScriptResources;
            var preloads = renderState.preloads.moduleScripts;
          } else
            resources = resumableState.scriptResources, preloads = renderState.preloads.scripts;
          var resourceState$jscomp$0 = resources.hasOwnProperty(key) ? resources[key] : void 0;
          if (null !== resourceState$jscomp$0) {
            resources[key] = null;
            var scriptProps = props;
            if (resourceState$jscomp$0) {
              2 === resourceState$jscomp$0.length && (scriptProps = assign({}, props), adoptPreloadCredentials(scriptProps, resourceState$jscomp$0));
              var preloadResource$jscomp$0 = preloads.get(key);
              preloadResource$jscomp$0 && (preloadResource$jscomp$0.length = 0);
            }
            var resource$jscomp$0 = [];
            renderState.scripts.add(resource$jscomp$0);
            pushScriptImpl(resource$jscomp$0, scriptProps);
          }
          textEmbedded && target$jscomp$0.push("<!-- -->");
          JSCompiler_inline_result$jscomp$5 = null;
        }
        return JSCompiler_inline_result$jscomp$5;
      case "style":
        var noscriptTagInScope$jscomp$2 = formatContext.tagScope & 1, precedence$jscomp$0 = props.precedence, href$jscomp$0 = props.href, nonce = props.nonce;
        if (4 === formatContext.insertionMode || noscriptTagInScope$jscomp$2 || null != props.itemProp || "string" !== typeof precedence$jscomp$0 || "string" !== typeof href$jscomp$0 || "" === href$jscomp$0) {
          target$jscomp$0.push(startChunkForTag("style"));
          var children$jscomp$6 = null, innerHTML$jscomp$5 = null, propKey$jscomp$8;
          for (propKey$jscomp$8 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$8)) {
              var propValue$jscomp$8 = props[propKey$jscomp$8];
              if (null != propValue$jscomp$8)
                switch (propKey$jscomp$8) {
                  case "children":
                    children$jscomp$6 = propValue$jscomp$8;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$5 = propValue$jscomp$8;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$8,
                      propValue$jscomp$8
                    );
                }
            }
          target$jscomp$0.push(">");
          var child = Array.isArray(children$jscomp$6) ? 2 > children$jscomp$6.length ? children$jscomp$6[0] : null : children$jscomp$6;
          "function" !== typeof child && "symbol" !== typeof child && null !== child && void 0 !== child && target$jscomp$0.push(("" + child).replace(styleRegex, styleReplacer));
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$5, children$jscomp$6);
          target$jscomp$0.push(endChunkForTag("style"));
          var JSCompiler_inline_result$jscomp$6 = null;
        } else {
          var styleQueue$jscomp$0 = renderState.styles.get(precedence$jscomp$0);
          if (null !== (resumableState.styleResources.hasOwnProperty(href$jscomp$0) ? resumableState.styleResources[href$jscomp$0] : void 0)) {
            resumableState.styleResources[href$jscomp$0] = null;
            styleQueue$jscomp$0 || (styleQueue$jscomp$0 = {
              precedence: escapeTextForBrowser(precedence$jscomp$0),
              rules: [],
              hrefs: [],
              sheets: /* @__PURE__ */ new Map()
            }, renderState.styles.set(precedence$jscomp$0, styleQueue$jscomp$0));
            var nonceStyle = renderState.nonce.style;
            if (!nonceStyle || nonceStyle === nonce) {
              styleQueue$jscomp$0.hrefs.push(escapeTextForBrowser(href$jscomp$0));
              var target = styleQueue$jscomp$0.rules, children$jscomp$7 = null, innerHTML$jscomp$6 = null, propKey$jscomp$9;
              for (propKey$jscomp$9 in props)
                if (hasOwnProperty2.call(props, propKey$jscomp$9)) {
                  var propValue$jscomp$9 = props[propKey$jscomp$9];
                  if (null != propValue$jscomp$9)
                    switch (propKey$jscomp$9) {
                      case "children":
                        children$jscomp$7 = propValue$jscomp$9;
                        break;
                      case "dangerouslySetInnerHTML":
                        innerHTML$jscomp$6 = propValue$jscomp$9;
                    }
                }
              var child$jscomp$0 = Array.isArray(children$jscomp$7) ? 2 > children$jscomp$7.length ? children$jscomp$7[0] : null : children$jscomp$7;
              "function" !== typeof child$jscomp$0 && "symbol" !== typeof child$jscomp$0 && null !== child$jscomp$0 && void 0 !== child$jscomp$0 && target.push(
                ("" + child$jscomp$0).replace(styleRegex, styleReplacer)
              );
              pushInnerHTML(target, innerHTML$jscomp$6, children$jscomp$7);
            }
          }
          styleQueue$jscomp$0 && hoistableState && hoistableState.styles.add(styleQueue$jscomp$0);
          textEmbedded && target$jscomp$0.push("<!-- -->");
          JSCompiler_inline_result$jscomp$6 = void 0;
        }
        return JSCompiler_inline_result$jscomp$6;
      case "meta":
        var noscriptTagInScope$jscomp$3 = formatContext.tagScope & 1, isFallback$jscomp$1 = formatContext.tagScope & 4;
        if (4 === formatContext.insertionMode || noscriptTagInScope$jscomp$3 || null != props.itemProp)
          var JSCompiler_inline_result$jscomp$7 = pushSelfClosing(
            target$jscomp$0,
            props,
            "meta"
          );
        else
          textEmbedded && target$jscomp$0.push("<!-- -->"), JSCompiler_inline_result$jscomp$7 = isFallback$jscomp$1 ? null : "string" === typeof props.charSet ? pushSelfClosing(renderState.charsetChunks, props, "meta") : "viewport" === props.name ? pushSelfClosing(renderState.viewportChunks, props, "meta") : pushSelfClosing(renderState.hoistableChunks, props, "meta");
        return JSCompiler_inline_result$jscomp$7;
      case "listing":
      case "pre":
        target$jscomp$0.push(startChunkForTag(type2));
        var children$jscomp$8 = null, innerHTML$jscomp$7 = null, propKey$jscomp$10;
        for (propKey$jscomp$10 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$10)) {
            var propValue$jscomp$10 = props[propKey$jscomp$10];
            if (null != propValue$jscomp$10)
              switch (propKey$jscomp$10) {
                case "children":
                  children$jscomp$8 = propValue$jscomp$10;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$7 = propValue$jscomp$10;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$10,
                    propValue$jscomp$10
                  );
              }
          }
        target$jscomp$0.push(">");
        if (null != innerHTML$jscomp$7) {
          if (null != children$jscomp$8)
            throw Error(
              "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
            );
          if ("object" !== typeof innerHTML$jscomp$7 || !("__html" in innerHTML$jscomp$7))
            throw Error(
              "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
            );
          var html2 = innerHTML$jscomp$7.__html;
          null !== html2 && void 0 !== html2 && ("string" === typeof html2 && 0 < html2.length && "\n" === html2[0] ? target$jscomp$0.push("\n", html2) : target$jscomp$0.push("" + html2));
        }
        "string" === typeof children$jscomp$8 && "\n" === children$jscomp$8[0] && target$jscomp$0.push("\n");
        return children$jscomp$8;
      case "img":
        var pictureOrNoScriptTagInScope = formatContext.tagScope & 3, src2 = props.src, srcSet = props.srcSet;
        if (!("lazy" === props.loading || !src2 && !srcSet || "string" !== typeof src2 && null != src2 || "string" !== typeof srcSet && null != srcSet || "low" === props.fetchPriority || pictureOrNoScriptTagInScope) && ("string" !== typeof src2 || ":" !== src2[4] || "d" !== src2[0] && "D" !== src2[0] || "a" !== src2[1] && "A" !== src2[1] || "t" !== src2[2] && "T" !== src2[2] || "a" !== src2[3] && "A" !== src2[3]) && ("string" !== typeof srcSet || ":" !== srcSet[4] || "d" !== srcSet[0] && "D" !== srcSet[0] || "a" !== srcSet[1] && "A" !== srcSet[1] || "t" !== srcSet[2] && "T" !== srcSet[2] || "a" !== srcSet[3] && "A" !== srcSet[3])) {
          null !== hoistableState && formatContext.tagScope & 64 && (hoistableState.suspenseyImages = true);
          var sizes = "string" === typeof props.sizes ? props.sizes : void 0, key$jscomp$0 = srcSet ? srcSet + "\n" + (sizes || "") : src2, promotablePreloads = renderState.preloads.images, resource$jscomp$1 = promotablePreloads.get(key$jscomp$0);
          if (resource$jscomp$1) {
            if ("high" === props.fetchPriority || 10 > renderState.highImagePreloads.size)
              promotablePreloads.delete(key$jscomp$0), renderState.highImagePreloads.add(resource$jscomp$1);
          } else if (!resumableState.imageResources.hasOwnProperty(key$jscomp$0)) {
            resumableState.imageResources[key$jscomp$0] = PRELOAD_NO_CREDS;
            var input = props.crossOrigin;
            var JSCompiler_inline_result$jscomp$8 = "string" === typeof input ? "use-credentials" === input ? input : "" : void 0;
            var headers = renderState.headers, header;
            headers && 0 < headers.remainingCapacity && "string" !== typeof props.srcSet && ("high" === props.fetchPriority || 500 > headers.highImagePreloads.length) && (header = getPreloadAsHeader(src2, "image", {
              imageSrcSet: props.srcSet,
              imageSizes: props.sizes,
              crossOrigin: JSCompiler_inline_result$jscomp$8,
              integrity: props.integrity,
              nonce: props.nonce,
              type: props.type,
              fetchPriority: props.fetchPriority,
              referrerPolicy: props.refererPolicy
            }), 0 <= (headers.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key$jscomp$0] = PRELOAD_NO_CREDS, headers.highImagePreloads && (headers.highImagePreloads += ", "), headers.highImagePreloads += header) : (resource$jscomp$1 = [], pushLinkImpl(resource$jscomp$1, {
              rel: "preload",
              as: "image",
              href: srcSet ? void 0 : src2,
              imageSrcSet: srcSet,
              imageSizes: sizes,
              crossOrigin: JSCompiler_inline_result$jscomp$8,
              integrity: props.integrity,
              type: props.type,
              fetchPriority: props.fetchPriority,
              referrerPolicy: props.referrerPolicy
            }), "high" === props.fetchPriority || 10 > renderState.highImagePreloads.size ? renderState.highImagePreloads.add(resource$jscomp$1) : (renderState.bulkPreloads.add(resource$jscomp$1), promotablePreloads.set(key$jscomp$0, resource$jscomp$1)));
          }
        }
        return pushSelfClosing(target$jscomp$0, props, "img");
      case "base":
      case "area":
      case "br":
      case "col":
      case "embed":
      case "hr":
      case "keygen":
      case "param":
      case "source":
      case "track":
      case "wbr":
        return pushSelfClosing(target$jscomp$0, props, type2);
      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":
        break;
      case "head":
        if (2 > formatContext.insertionMode) {
          var preamble = preambleState || renderState.preamble;
          if (preamble.headChunks)
            throw Error("The `<head>` tag may only be rendered once.");
          null !== preambleState && target$jscomp$0.push("<!--head-->");
          preamble.headChunks = [];
          var JSCompiler_inline_result$jscomp$9 = pushStartSingletonElement(
            preamble.headChunks,
            props,
            "head"
          );
        } else
          JSCompiler_inline_result$jscomp$9 = pushStartGenericElement(
            target$jscomp$0,
            props,
            "head"
          );
        return JSCompiler_inline_result$jscomp$9;
      case "body":
        if (2 > formatContext.insertionMode) {
          var preamble$jscomp$0 = preambleState || renderState.preamble;
          if (preamble$jscomp$0.bodyChunks)
            throw Error("The `<body>` tag may only be rendered once.");
          null !== preambleState && target$jscomp$0.push("<!--body-->");
          preamble$jscomp$0.bodyChunks = [];
          var JSCompiler_inline_result$jscomp$10 = pushStartSingletonElement(
            preamble$jscomp$0.bodyChunks,
            props,
            "body"
          );
        } else
          JSCompiler_inline_result$jscomp$10 = pushStartGenericElement(
            target$jscomp$0,
            props,
            "body"
          );
        return JSCompiler_inline_result$jscomp$10;
      case "html":
        if (0 === formatContext.insertionMode) {
          var preamble$jscomp$1 = preambleState || renderState.preamble;
          if (preamble$jscomp$1.htmlChunks)
            throw Error("The `<html>` tag may only be rendered once.");
          null !== preambleState && target$jscomp$0.push("<!--html-->");
          preamble$jscomp$1.htmlChunks = [""];
          var JSCompiler_inline_result$jscomp$11 = pushStartSingletonElement(
            preamble$jscomp$1.htmlChunks,
            props,
            "html"
          );
        } else
          JSCompiler_inline_result$jscomp$11 = pushStartGenericElement(
            target$jscomp$0,
            props,
            "html"
          );
        return JSCompiler_inline_result$jscomp$11;
      default:
        if (-1 !== type2.indexOf("-")) {
          target$jscomp$0.push(startChunkForTag(type2));
          var children$jscomp$9 = null, innerHTML$jscomp$8 = null, propKey$jscomp$11;
          for (propKey$jscomp$11 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$11)) {
              var propValue$jscomp$11 = props[propKey$jscomp$11];
              if (null != propValue$jscomp$11) {
                var attributeName = propKey$jscomp$11;
                switch (propKey$jscomp$11) {
                  case "children":
                    children$jscomp$9 = propValue$jscomp$11;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$8 = propValue$jscomp$11;
                    break;
                  case "style":
                    pushStyleAttribute(target$jscomp$0, propValue$jscomp$11);
                    break;
                  case "suppressContentEditableWarning":
                  case "suppressHydrationWarning":
                  case "ref":
                    break;
                  case "className":
                    attributeName = "class";
                  default:
                    if (isAttributeNameSafe(propKey$jscomp$11) && "function" !== typeof propValue$jscomp$11 && "symbol" !== typeof propValue$jscomp$11 && false !== propValue$jscomp$11) {
                      if (true === propValue$jscomp$11) propValue$jscomp$11 = "";
                      else if ("object" === typeof propValue$jscomp$11) continue;
                      target$jscomp$0.push(
                        " ",
                        attributeName,
                        '="',
                        escapeTextForBrowser(propValue$jscomp$11),
                        '"'
                      );
                    }
                }
              }
            }
          target$jscomp$0.push(">");
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$8, children$jscomp$9);
          return children$jscomp$9;
        }
    }
    return pushStartGenericElement(target$jscomp$0, props, type2);
  }
  var endTagCache = /* @__PURE__ */ new Map();
  function endChunkForTag(tag) {
    var chunk2 = endTagCache.get(tag);
    void 0 === chunk2 && (chunk2 = "</" + tag + ">", endTagCache.set(tag, chunk2));
    return chunk2;
  }
  function hoistPreambleState(renderState, preambleState) {
    renderState = renderState.preamble;
    null === renderState.htmlChunks && preambleState.htmlChunks && (renderState.htmlChunks = preambleState.htmlChunks);
    null === renderState.headChunks && preambleState.headChunks && (renderState.headChunks = preambleState.headChunks);
    null === renderState.bodyChunks && preambleState.bodyChunks && (renderState.bodyChunks = preambleState.bodyChunks);
  }
  function writeBootstrap(destination, renderState) {
    renderState = renderState.bootstrapChunks;
    for (var i = 0; i < renderState.length - 1; i++)
      destination.push(renderState[i]);
    return i < renderState.length ? (i = renderState[i], renderState.length = 0, destination.push(i)) : true;
  }
  function writeStartPendingSuspenseBoundary(destination, renderState, id) {
    destination.push('<!--$?--><template id="');
    if (null === id)
      throw Error(
        "An ID must have been assigned before we can complete the boundary."
      );
    destination.push(renderState.boundaryPrefix);
    renderState = id.toString(16);
    destination.push(renderState);
    return destination.push('"></template>');
  }
  function writeStartSegment(destination, renderState, formatContext, id) {
    switch (formatContext.insertionMode) {
      case 0:
      case 1:
      case 3:
      case 2:
        return destination.push('<div hidden id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      case 4:
        return destination.push('<svg aria-hidden="true" style="display:none" id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      case 5:
        return destination.push('<math aria-hidden="true" style="display:none" id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      case 6:
        return destination.push('<table hidden id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      case 7:
        return destination.push('<table hidden><tbody id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      case 8:
        return destination.push('<table hidden><tr id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      case 9:
        return destination.push('<table hidden><colgroup id="'), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push('">');
      default:
        throw Error("Unknown insertion mode. This is a bug in React.");
    }
  }
  function writeEndSegment(destination, formatContext) {
    switch (formatContext.insertionMode) {
      case 0:
      case 1:
      case 3:
      case 2:
        return destination.push("</div>");
      case 4:
        return destination.push("</svg>");
      case 5:
        return destination.push("</math>");
      case 6:
        return destination.push("</table>");
      case 7:
        return destination.push("</tbody></table>");
      case 8:
        return destination.push("</tr></table>");
      case 9:
        return destination.push("</colgroup></table>");
      default:
        throw Error("Unknown insertion mode. This is a bug in React.");
    }
  }
  var regexForJSStringsInInstructionScripts = /[<\u2028\u2029]/g;
  function escapeJSStringsForInstructionScripts(input) {
    return JSON.stringify(input).replace(
      regexForJSStringsInInstructionScripts,
      function(match) {
        switch (match) {
          case "<":
            return "\\u003c";
          case "\u2028":
            return "\\u2028";
          case "\u2029":
            return "\\u2029";
          default:
            throw Error(
              "escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
            );
        }
      }
    );
  }
  var regexForJSStringsInScripts = /[&><\u2028\u2029]/g;
  function escapeJSObjectForInstructionScripts(input) {
    return JSON.stringify(input).replace(
      regexForJSStringsInScripts,
      function(match) {
        switch (match) {
          case "&":
            return "\\u0026";
          case ">":
            return "\\u003e";
          case "<":
            return "\\u003c";
          case "\u2028":
            return "\\u2028";
          case "\u2029":
            return "\\u2029";
          default:
            throw Error(
              "escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
            );
        }
      }
    );
  }
  var currentlyRenderingBoundaryHasStylesToHoist = false, destinationHasCapacity = true;
  function flushStyleTagsLateForBoundary(styleQueue) {
    var rules = styleQueue.rules, hrefs = styleQueue.hrefs, i = 0;
    if (hrefs.length) {
      this.push(currentlyFlushingRenderState.startInlineStyle);
      this.push(' media="not all" data-precedence="');
      this.push(styleQueue.precedence);
      for (this.push('" data-href="'); i < hrefs.length - 1; i++)
        this.push(hrefs[i]), this.push(" ");
      this.push(hrefs[i]);
      this.push('">');
      for (i = 0; i < rules.length; i++) this.push(rules[i]);
      destinationHasCapacity = this.push("</style>");
      currentlyRenderingBoundaryHasStylesToHoist = true;
      rules.length = 0;
      hrefs.length = 0;
    }
  }
  function hasStylesToHoist(stylesheet) {
    return 2 !== stylesheet.state ? currentlyRenderingBoundaryHasStylesToHoist = true : false;
  }
  function writeHoistablesForBoundary(destination, hoistableState, renderState) {
    currentlyRenderingBoundaryHasStylesToHoist = false;
    destinationHasCapacity = true;
    currentlyFlushingRenderState = renderState;
    hoistableState.styles.forEach(flushStyleTagsLateForBoundary, destination);
    currentlyFlushingRenderState = null;
    hoistableState.stylesheets.forEach(hasStylesToHoist);
    currentlyRenderingBoundaryHasStylesToHoist && (renderState.stylesToHoist = true);
    return destinationHasCapacity;
  }
  function flushResource(resource) {
    for (var i = 0; i < resource.length; i++) this.push(resource[i]);
    resource.length = 0;
  }
  var stylesheetFlushingQueue = [];
  function flushStyleInPreamble(stylesheet) {
    pushLinkImpl(stylesheetFlushingQueue, stylesheet.props);
    for (var i = 0; i < stylesheetFlushingQueue.length; i++)
      this.push(stylesheetFlushingQueue[i]);
    stylesheetFlushingQueue.length = 0;
    stylesheet.state = 2;
  }
  function flushStylesInPreamble(styleQueue) {
    var hasStylesheets = 0 < styleQueue.sheets.size;
    styleQueue.sheets.forEach(flushStyleInPreamble, this);
    styleQueue.sheets.clear();
    var rules = styleQueue.rules, hrefs = styleQueue.hrefs;
    if (!hasStylesheets || hrefs.length) {
      this.push(currentlyFlushingRenderState.startInlineStyle);
      this.push(' data-precedence="');
      this.push(styleQueue.precedence);
      styleQueue = 0;
      if (hrefs.length) {
        for (this.push('" data-href="'); styleQueue < hrefs.length - 1; styleQueue++)
          this.push(hrefs[styleQueue]), this.push(" ");
        this.push(hrefs[styleQueue]);
      }
      this.push('">');
      for (styleQueue = 0; styleQueue < rules.length; styleQueue++)
        this.push(rules[styleQueue]);
      this.push("</style>");
      rules.length = 0;
      hrefs.length = 0;
    }
  }
  function preloadLateStyle(stylesheet) {
    if (0 === stylesheet.state) {
      stylesheet.state = 1;
      var props = stylesheet.props;
      pushLinkImpl(stylesheetFlushingQueue, {
        rel: "preload",
        as: "style",
        href: stylesheet.props.href,
        crossOrigin: props.crossOrigin,
        fetchPriority: props.fetchPriority,
        integrity: props.integrity,
        media: props.media,
        hrefLang: props.hrefLang,
        referrerPolicy: props.referrerPolicy
      });
      for (stylesheet = 0; stylesheet < stylesheetFlushingQueue.length; stylesheet++)
        this.push(stylesheetFlushingQueue[stylesheet]);
      stylesheetFlushingQueue.length = 0;
    }
  }
  function preloadLateStyles(styleQueue) {
    styleQueue.sheets.forEach(preloadLateStyle, this);
    styleQueue.sheets.clear();
  }
  function pushCompletedShellIdAttribute(target, resumableState) {
    0 === (resumableState.instructions & 32) && (resumableState.instructions |= 32, target.push(
      ' id="',
      escapeTextForBrowser("_" + resumableState.idPrefix + "R_"),
      '"'
    ));
  }
  function writeStyleResourceDependenciesInJS(destination, hoistableState) {
    destination.push("[");
    var nextArrayOpenBrackChunk = "[";
    hoistableState.stylesheets.forEach(function(resource) {
      if (2 !== resource.state)
        if (3 === resource.state)
          destination.push(nextArrayOpenBrackChunk), resource = escapeJSObjectForInstructionScripts(
            "" + resource.props.href
          ), destination.push(resource), destination.push("]"), nextArrayOpenBrackChunk = ",[";
        else {
          destination.push(nextArrayOpenBrackChunk);
          var precedence = resource.props["data-precedence"], props = resource.props, coercedHref = sanitizeURL("" + resource.props.href);
          coercedHref = escapeJSObjectForInstructionScripts(coercedHref);
          destination.push(coercedHref);
          precedence = "" + precedence;
          destination.push(",");
          precedence = escapeJSObjectForInstructionScripts(precedence);
          destination.push(precedence);
          for (var propKey in props)
            if (hasOwnProperty2.call(props, propKey) && (precedence = props[propKey], null != precedence))
              switch (propKey) {
                case "href":
                case "rel":
                case "precedence":
                case "data-precedence":
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                  );
                default:
                  writeStyleResourceAttributeInJS(
                    destination,
                    propKey,
                    precedence
                  );
              }
          destination.push("]");
          nextArrayOpenBrackChunk = ",[";
          resource.state = 3;
        }
    });
    destination.push("]");
  }
  function writeStyleResourceAttributeInJS(destination, name2, value) {
    var attributeName = name2.toLowerCase();
    switch (typeof value) {
      case "function":
      case "symbol":
        return;
    }
    switch (name2) {
      case "innerHTML":
      case "dangerouslySetInnerHTML":
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "style":
      case "ref":
        return;
      case "className":
        attributeName = "class";
        name2 = "" + value;
        break;
      case "hidden":
        if (false === value) return;
        name2 = "";
        break;
      case "src":
      case "href":
        value = sanitizeURL(value);
        name2 = "" + value;
        break;
      default:
        if (2 < name2.length && ("o" === name2[0] || "O" === name2[0]) && ("n" === name2[1] || "N" === name2[1]) || !isAttributeNameSafe(name2))
          return;
        name2 = "" + value;
    }
    destination.push(",");
    attributeName = escapeJSObjectForInstructionScripts(attributeName);
    destination.push(attributeName);
    destination.push(",");
    attributeName = escapeJSObjectForInstructionScripts(name2);
    destination.push(attributeName);
  }
  function createHoistableState() {
    return { styles: /* @__PURE__ */ new Set(), stylesheets: /* @__PURE__ */ new Set(), suspenseyImages: false };
  }
  function prefetchDNS(href) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if ("string" === typeof href && href) {
        if (!resumableState.dnsResources.hasOwnProperty(href)) {
          resumableState.dnsResources[href] = null;
          resumableState = renderState.headers;
          var header, JSCompiler_temp;
          if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity)
            JSCompiler_temp = (header = "<" + ("" + href).replace(
              regexForHrefInLinkHeaderURLContext,
              escapeHrefForLinkHeaderURLContextReplacer
            ) + ">; rel=dns-prefetch", 0 <= (resumableState.remainingCapacity -= header.length + 2));
          JSCompiler_temp ? (renderState.resets.dns[href] = null, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (header = [], pushLinkImpl(header, { href, rel: "dns-prefetch" }), renderState.preconnects.add(header));
        }
        enqueueFlush(request);
      }
    } else previousDispatcher.D(href);
  }
  function preconnect(href, crossOrigin) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if ("string" === typeof href && href) {
        var bucket = "use-credentials" === crossOrigin ? "credentials" : "string" === typeof crossOrigin ? "anonymous" : "default";
        if (!resumableState.connectResources[bucket].hasOwnProperty(href)) {
          resumableState.connectResources[bucket][href] = null;
          resumableState = renderState.headers;
          var header, JSCompiler_temp;
          if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity) {
            JSCompiler_temp = "<" + ("" + href).replace(
              regexForHrefInLinkHeaderURLContext,
              escapeHrefForLinkHeaderURLContextReplacer
            ) + ">; rel=preconnect";
            if ("string" === typeof crossOrigin) {
              var escapedCrossOrigin = ("" + crossOrigin).replace(
                regexForLinkHeaderQuotedParamValueContext,
                escapeStringForLinkHeaderQuotedParamValueContextReplacer
              );
              JSCompiler_temp += '; crossorigin="' + escapedCrossOrigin + '"';
            }
            JSCompiler_temp = (header = JSCompiler_temp, 0 <= (resumableState.remainingCapacity -= header.length + 2));
          }
          JSCompiler_temp ? (renderState.resets.connect[bucket][href] = null, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (bucket = [], pushLinkImpl(bucket, {
            rel: "preconnect",
            href,
            crossOrigin
          }), renderState.preconnects.add(bucket));
        }
        enqueueFlush(request);
      }
    } else previousDispatcher.C(href, crossOrigin);
  }
  function preload(href, as, options) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (as && href) {
        switch (as) {
          case "image":
            if (options) {
              var imageSrcSet = options.imageSrcSet;
              var imageSizes = options.imageSizes;
              var fetchPriority = options.fetchPriority;
            }
            var key = imageSrcSet ? imageSrcSet + "\n" + (imageSizes || "") : href;
            if (resumableState.imageResources.hasOwnProperty(key)) return;
            resumableState.imageResources[key] = PRELOAD_NO_CREDS;
            resumableState = renderState.headers;
            var header;
            resumableState && 0 < resumableState.remainingCapacity && "string" !== typeof imageSrcSet && "high" === fetchPriority && (header = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key] = PRELOAD_NO_CREDS, resumableState.highImagePreloads && (resumableState.highImagePreloads += ", "), resumableState.highImagePreloads += header) : (resumableState = [], pushLinkImpl(
              resumableState,
              assign(
                { rel: "preload", href: imageSrcSet ? void 0 : href, as },
                options
              )
            ), "high" === fetchPriority ? renderState.highImagePreloads.add(resumableState) : (renderState.bulkPreloads.add(resumableState), renderState.preloads.images.set(key, resumableState)));
            break;
          case "style":
            if (resumableState.styleResources.hasOwnProperty(href)) return;
            imageSrcSet = [];
            pushLinkImpl(
              imageSrcSet,
              assign({ rel: "preload", href, as }, options)
            );
            resumableState.styleResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
            renderState.preloads.stylesheets.set(href, imageSrcSet);
            renderState.bulkPreloads.add(imageSrcSet);
            break;
          case "script":
            if (resumableState.scriptResources.hasOwnProperty(href)) return;
            imageSrcSet = [];
            renderState.preloads.scripts.set(href, imageSrcSet);
            renderState.bulkPreloads.add(imageSrcSet);
            pushLinkImpl(
              imageSrcSet,
              assign({ rel: "preload", href, as }, options)
            );
            resumableState.scriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
            break;
          default:
            if (resumableState.unknownResources.hasOwnProperty(as)) {
              if (imageSrcSet = resumableState.unknownResources[as], imageSrcSet.hasOwnProperty(href))
                return;
            } else
              imageSrcSet = {}, resumableState.unknownResources[as] = imageSrcSet;
            imageSrcSet[href] = PRELOAD_NO_CREDS;
            if ((resumableState = renderState.headers) && 0 < resumableState.remainingCapacity && "font" === as && (key = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= key.length + 2)))
              renderState.resets.font[href] = PRELOAD_NO_CREDS, resumableState.fontPreloads && (resumableState.fontPreloads += ", "), resumableState.fontPreloads += key;
            else
              switch (resumableState = [], href = assign({ rel: "preload", href, as }, options), pushLinkImpl(resumableState, href), as) {
                case "font":
                  renderState.fontPreloads.add(resumableState);
                  break;
                default:
                  renderState.bulkPreloads.add(resumableState);
              }
        }
        enqueueFlush(request);
      }
    } else previousDispatcher.L(href, as, options);
  }
  function preloadModule(href, options) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (href) {
        var as = options && "string" === typeof options.as ? options.as : "script";
        switch (as) {
          case "script":
            if (resumableState.moduleScriptResources.hasOwnProperty(href)) return;
            as = [];
            resumableState.moduleScriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
            renderState.preloads.moduleScripts.set(href, as);
            break;
          default:
            if (resumableState.moduleUnknownResources.hasOwnProperty(as)) {
              var resources = resumableState.unknownResources[as];
              if (resources.hasOwnProperty(href)) return;
            } else
              resources = {}, resumableState.moduleUnknownResources[as] = resources;
            as = [];
            resources[href] = PRELOAD_NO_CREDS;
        }
        pushLinkImpl(as, assign({ rel: "modulepreload", href }, options));
        renderState.bulkPreloads.add(as);
        enqueueFlush(request);
      }
    } else previousDispatcher.m(href, options);
  }
  function preinitStyle(href, precedence, options) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (href) {
        precedence = precedence || "default";
        var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(href) ? resumableState.styleResources[href] : void 0;
        null !== resourceState && (resumableState.styleResources[href] = null, styleQueue || (styleQueue = {
          precedence: escapeTextForBrowser(precedence),
          rules: [],
          hrefs: [],
          sheets: /* @__PURE__ */ new Map()
        }, renderState.styles.set(precedence, styleQueue)), precedence = {
          state: 0,
          props: assign(
            { rel: "stylesheet", href, "data-precedence": precedence },
            options
          )
        }, resourceState && (2 === resourceState.length && adoptPreloadCredentials(precedence.props, resourceState), (renderState = renderState.preloads.stylesheets.get(href)) && 0 < renderState.length ? renderState.length = 0 : precedence.state = 1), styleQueue.sheets.set(href, precedence), enqueueFlush(request));
      }
    } else previousDispatcher.S(href, precedence, options);
  }
  function preinitScript(src2, options) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (src2) {
        var resourceState = resumableState.scriptResources.hasOwnProperty(src2) ? resumableState.scriptResources[src2] : void 0;
        null !== resourceState && (resumableState.scriptResources[src2] = null, options = assign({ src: src2, async: true }, options), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.scripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
      }
    } else previousDispatcher.X(src2, options);
  }
  function preinitModuleScript(src2, options) {
    var request = currentRequest ? currentRequest : null;
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (src2) {
        var resourceState = resumableState.moduleScriptResources.hasOwnProperty(
          src2
        ) ? resumableState.moduleScriptResources[src2] : void 0;
        null !== resourceState && (resumableState.moduleScriptResources[src2] = null, options = assign({ src: src2, type: "module", async: true }, options), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.moduleScripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
      }
    } else previousDispatcher.M(src2, options);
  }
  function adoptPreloadCredentials(target, preloadState) {
    null == target.crossOrigin && (target.crossOrigin = preloadState[0]);
    null == target.integrity && (target.integrity = preloadState[1]);
  }
  function getPreloadAsHeader(href, as, params) {
    href = ("" + href).replace(
      regexForHrefInLinkHeaderURLContext,
      escapeHrefForLinkHeaderURLContextReplacer
    );
    as = ("" + as).replace(
      regexForLinkHeaderQuotedParamValueContext,
      escapeStringForLinkHeaderQuotedParamValueContextReplacer
    );
    as = "<" + href + '>; rel=preload; as="' + as + '"';
    for (var paramName in params)
      hasOwnProperty2.call(params, paramName) && (href = params[paramName], "string" === typeof href && (as += "; " + paramName.toLowerCase() + '="' + ("" + href).replace(
        regexForLinkHeaderQuotedParamValueContext,
        escapeStringForLinkHeaderQuotedParamValueContextReplacer
      ) + '"'));
    return as;
  }
  var regexForHrefInLinkHeaderURLContext = /[<>\r\n]/g;
  function escapeHrefForLinkHeaderURLContextReplacer(match) {
    switch (match) {
      case "<":
        return "%3C";
      case ">":
        return "%3E";
      case "\n":
        return "%0A";
      case "\r":
        return "%0D";
      default:
        throw Error(
          "escapeLinkHrefForHeaderContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
        );
    }
  }
  var regexForLinkHeaderQuotedParamValueContext = /["';,\r\n]/g;
  function escapeStringForLinkHeaderQuotedParamValueContextReplacer(match) {
    switch (match) {
      case '"':
        return "%22";
      case "'":
        return "%27";
      case ";":
        return "%3B";
      case ",":
        return "%2C";
      case "\n":
        return "%0A";
      case "\r":
        return "%0D";
      default:
        throw Error(
          "escapeStringForLinkHeaderQuotedParamValueContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
        );
    }
  }
  function hoistStyleQueueDependency(styleQueue) {
    this.styles.add(styleQueue);
  }
  function hoistStylesheetDependency(stylesheet) {
    this.stylesheets.add(stylesheet);
  }
  function hoistHoistables(parentState, childState) {
    childState.styles.forEach(hoistStyleQueueDependency, parentState);
    childState.stylesheets.forEach(hoistStylesheetDependency, parentState);
    childState.suspenseyImages && (parentState.suspenseyImages = true);
  }
  function createRenderState(resumableState, generateStaticMarkup) {
    var idPrefix = resumableState.idPrefix, bootstrapChunks = [], bootstrapScriptContent = resumableState.bootstrapScriptContent, bootstrapScripts = resumableState.bootstrapScripts, bootstrapModules = resumableState.bootstrapModules;
    void 0 !== bootstrapScriptContent && (bootstrapChunks.push("<script"), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
      ">",
      ("" + bootstrapScriptContent).replace(scriptRegex, scriptReplacer),
      "<\/script>"
    ));
    bootstrapScriptContent = idPrefix + "P:";
    var JSCompiler_object_inline_segmentPrefix_1673 = idPrefix + "S:";
    idPrefix += "B:";
    var JSCompiler_object_inline_preconnects_1687 = /* @__PURE__ */ new Set(), JSCompiler_object_inline_fontPreloads_1688 = /* @__PURE__ */ new Set(), JSCompiler_object_inline_highImagePreloads_1689 = /* @__PURE__ */ new Set(), JSCompiler_object_inline_styles_1690 = /* @__PURE__ */ new Map(), JSCompiler_object_inline_bootstrapScripts_1691 = /* @__PURE__ */ new Set(), JSCompiler_object_inline_scripts_1692 = /* @__PURE__ */ new Set(), JSCompiler_object_inline_bulkPreloads_1693 = /* @__PURE__ */ new Set(), JSCompiler_object_inline_preloads_1694 = {
      images: /* @__PURE__ */ new Map(),
      stylesheets: /* @__PURE__ */ new Map(),
      scripts: /* @__PURE__ */ new Map(),
      moduleScripts: /* @__PURE__ */ new Map()
    };
    if (void 0 !== bootstrapScripts)
      for (var i = 0; i < bootstrapScripts.length; i++) {
        var scriptConfig = bootstrapScripts[i], src2, crossOrigin = void 0, integrity = void 0, props = {
          rel: "preload",
          as: "script",
          fetchPriority: "low",
          nonce: void 0
        };
        "string" === typeof scriptConfig ? props.href = src2 = scriptConfig : (props.href = src2 = scriptConfig.src, props.integrity = integrity = "string" === typeof scriptConfig.integrity ? scriptConfig.integrity : void 0, props.crossOrigin = crossOrigin = "string" === typeof scriptConfig || null == scriptConfig.crossOrigin ? void 0 : "use-credentials" === scriptConfig.crossOrigin ? "use-credentials" : "");
        scriptConfig = resumableState;
        var href = src2;
        scriptConfig.scriptResources[href] = null;
        scriptConfig.moduleScriptResources[href] = null;
        scriptConfig = [];
        pushLinkImpl(scriptConfig, props);
        JSCompiler_object_inline_bootstrapScripts_1691.add(scriptConfig);
        bootstrapChunks.push('<script src="', escapeTextForBrowser(src2), '"');
        "string" === typeof integrity && bootstrapChunks.push(
          ' integrity="',
          escapeTextForBrowser(integrity),
          '"'
        );
        "string" === typeof crossOrigin && bootstrapChunks.push(
          ' crossorigin="',
          escapeTextForBrowser(crossOrigin),
          '"'
        );
        pushCompletedShellIdAttribute(bootstrapChunks, resumableState);
        bootstrapChunks.push(' async=""><\/script>');
      }
    if (void 0 !== bootstrapModules)
      for (bootstrapScripts = 0; bootstrapScripts < bootstrapModules.length; bootstrapScripts++)
        props = bootstrapModules[bootstrapScripts], crossOrigin = src2 = void 0, integrity = {
          rel: "modulepreload",
          fetchPriority: "low",
          nonce: void 0
        }, "string" === typeof props ? integrity.href = i = props : (integrity.href = i = props.src, integrity.integrity = crossOrigin = "string" === typeof props.integrity ? props.integrity : void 0, integrity.crossOrigin = src2 = "string" === typeof props || null == props.crossOrigin ? void 0 : "use-credentials" === props.crossOrigin ? "use-credentials" : ""), props = resumableState, scriptConfig = i, props.scriptResources[scriptConfig] = null, props.moduleScriptResources[scriptConfig] = null, props = [], pushLinkImpl(props, integrity), JSCompiler_object_inline_bootstrapScripts_1691.add(props), bootstrapChunks.push(
          '<script type="module" src="',
          escapeTextForBrowser(i),
          '"'
        ), "string" === typeof crossOrigin && bootstrapChunks.push(
          ' integrity="',
          escapeTextForBrowser(crossOrigin),
          '"'
        ), "string" === typeof src2 && bootstrapChunks.push(
          ' crossorigin="',
          escapeTextForBrowser(src2),
          '"'
        ), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(' async=""><\/script>');
    return {
      placeholderPrefix: bootstrapScriptContent,
      segmentPrefix: JSCompiler_object_inline_segmentPrefix_1673,
      boundaryPrefix: idPrefix,
      startInlineScript: "<script",
      startInlineStyle: "<style",
      preamble: { htmlChunks: null, headChunks: null, bodyChunks: null },
      externalRuntimeScript: null,
      bootstrapChunks,
      importMapChunks: [],
      onHeaders: void 0,
      headers: null,
      resets: {
        font: {},
        dns: {},
        connect: { default: {}, anonymous: {}, credentials: {} },
        image: {},
        style: {}
      },
      charsetChunks: [],
      viewportChunks: [],
      hoistableChunks: [],
      preconnects: JSCompiler_object_inline_preconnects_1687,
      fontPreloads: JSCompiler_object_inline_fontPreloads_1688,
      highImagePreloads: JSCompiler_object_inline_highImagePreloads_1689,
      styles: JSCompiler_object_inline_styles_1690,
      bootstrapScripts: JSCompiler_object_inline_bootstrapScripts_1691,
      scripts: JSCompiler_object_inline_scripts_1692,
      bulkPreloads: JSCompiler_object_inline_bulkPreloads_1693,
      preloads: JSCompiler_object_inline_preloads_1694,
      nonce: { script: void 0, style: void 0 },
      stylesToHoist: false,
      generateStaticMarkup
    };
  }
  function pushTextInstance(target, text2, renderState, textEmbedded) {
    if (renderState.generateStaticMarkup)
      return target.push(escapeTextForBrowser(text2)), false;
    "" === text2 ? target = textEmbedded : (textEmbedded && target.push("<!-- -->"), target.push(escapeTextForBrowser(text2)), target = true);
    return target;
  }
  function pushSegmentFinale(target, renderState, lastPushedText, textEmbedded) {
    renderState.generateStaticMarkup || lastPushedText && textEmbedded && target.push("<!-- -->");
  }
  var bind2 = Function.prototype.bind, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference");
  function getComponentNameFromType(type2) {
    if (null == type2) return null;
    if ("function" === typeof type2)
      return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
    if ("string" === typeof type2) return type2;
    switch (type2) {
      case REACT_FRAGMENT_TYPE:
        return "Fragment";
      case REACT_PROFILER_TYPE:
        return "Profiler";
      case REACT_STRICT_MODE_TYPE:
        return "StrictMode";
      case REACT_SUSPENSE_TYPE:
        return "Suspense";
      case REACT_SUSPENSE_LIST_TYPE:
        return "SuspenseList";
      case REACT_ACTIVITY_TYPE:
        return "Activity";
    }
    if ("object" === typeof type2)
      switch (type2.$$typeof) {
        case REACT_PORTAL_TYPE:
          return "Portal";
        case REACT_CONTEXT_TYPE:
          return type2.displayName || "Context";
        case REACT_CONSUMER_TYPE:
          return (type2._context.displayName || "Context") + ".Consumer";
        case REACT_FORWARD_REF_TYPE:
          var innerType = type2.render;
          type2 = type2.displayName;
          type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
          return type2;
        case REACT_MEMO_TYPE:
          return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
        case REACT_LAZY_TYPE:
          innerType = type2._payload;
          type2 = type2._init;
          try {
            return getComponentNameFromType(type2(innerType));
          } catch (x2) {
          }
      }
    return null;
  }
  var emptyContextObject = {}, currentActiveSnapshot = null;
  function popToNearestCommonAncestor(prev, next) {
    if (prev !== next) {
      prev.context._currentValue2 = prev.parentValue;
      prev = prev.parent;
      var parentNext = next.parent;
      if (null === prev) {
        if (null !== parentNext)
          throw Error(
            "The stacks must reach the root at the same time. This is a bug in React."
          );
      } else {
        if (null === parentNext)
          throw Error(
            "The stacks must reach the root at the same time. This is a bug in React."
          );
        popToNearestCommonAncestor(prev, parentNext);
      }
      next.context._currentValue2 = next.value;
    }
  }
  function popAllPrevious(prev) {
    prev.context._currentValue2 = prev.parentValue;
    prev = prev.parent;
    null !== prev && popAllPrevious(prev);
  }
  function pushAllNext(next) {
    var parentNext = next.parent;
    null !== parentNext && pushAllNext(parentNext);
    next.context._currentValue2 = next.value;
  }
  function popPreviousToCommonLevel(prev, next) {
    prev.context._currentValue2 = prev.parentValue;
    prev = prev.parent;
    if (null === prev)
      throw Error(
        "The depth must equal at least at zero before reaching the root. This is a bug in React."
      );
    prev.depth === next.depth ? popToNearestCommonAncestor(prev, next) : popPreviousToCommonLevel(prev, next);
  }
  function popNextToCommonLevel(prev, next) {
    var parentNext = next.parent;
    if (null === parentNext)
      throw Error(
        "The depth must equal at least at zero before reaching the root. This is a bug in React."
      );
    prev.depth === parentNext.depth ? popToNearestCommonAncestor(prev, parentNext) : popNextToCommonLevel(prev, parentNext);
    next.context._currentValue2 = next.value;
  }
  function switchContext(newSnapshot) {
    var prev = currentActiveSnapshot;
    prev !== newSnapshot && (null === prev ? pushAllNext(newSnapshot) : null === newSnapshot ? popAllPrevious(prev) : prev.depth === newSnapshot.depth ? popToNearestCommonAncestor(prev, newSnapshot) : prev.depth > newSnapshot.depth ? popPreviousToCommonLevel(prev, newSnapshot) : popNextToCommonLevel(prev, newSnapshot), currentActiveSnapshot = newSnapshot);
  }
  var classComponentUpdater = {
    enqueueSetState: function(inst, payload) {
      inst = inst._reactInternals;
      null !== inst.queue && inst.queue.push(payload);
    },
    enqueueReplaceState: function(inst, payload) {
      inst = inst._reactInternals;
      inst.replace = true;
      inst.queue = [payload];
    },
    enqueueForceUpdate: function() {
    }
  }, emptyTreeContext = { id: 1, overflow: "" };
  function pushTreeContext(baseContext, totalChildren, index2) {
    var baseIdWithLeadingBit = baseContext.id;
    baseContext = baseContext.overflow;
    var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
    baseIdWithLeadingBit &= ~(1 << baseLength);
    index2 += 1;
    var length = 32 - clz32(totalChildren) + baseLength;
    if (30 < length) {
      var numberOfOverflowBits = baseLength - baseLength % 5;
      length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
      baseIdWithLeadingBit >>= numberOfOverflowBits;
      baseLength -= numberOfOverflowBits;
      return {
        id: 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit,
        overflow: length + baseContext
      };
    }
    return {
      id: 1 << length | index2 << baseLength | baseIdWithLeadingBit,
      overflow: baseContext
    };
  }
  var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2;
  function clz32Fallback(x2) {
    x2 >>>= 0;
    return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
  }
  function noop2() {
  }
  var SuspenseException = Error(
    "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
  );
  function trackUsedThenable(thenableState2, thenable, index2) {
    index2 = thenableState2[index2];
    void 0 === index2 ? thenableState2.push(thenable) : index2 !== thenable && (thenable.then(noop2, noop2), thenable = index2);
    switch (thenable.status) {
      case "fulfilled":
        return thenable.value;
      case "rejected":
        throw thenable.reason;
      default:
        "string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenableState2 = thenable, thenableState2.status = "pending", thenableState2.then(
          function(fulfilledValue) {
            if ("pending" === thenable.status) {
              var fulfilledThenable = thenable;
              fulfilledThenable.status = "fulfilled";
              fulfilledThenable.value = fulfilledValue;
            }
          },
          function(error) {
            if ("pending" === thenable.status) {
              var rejectedThenable = thenable;
              rejectedThenable.status = "rejected";
              rejectedThenable.reason = error;
            }
          }
        ));
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenable.reason;
        }
        suspendedThenable = thenable;
        throw SuspenseException;
    }
  }
  var suspendedThenable = null;
  function getSuspendedThenable() {
    if (null === suspendedThenable)
      throw Error(
        "Expected a suspended thenable. This is a bug in React. Please file an issue."
      );
    var thenable = suspendedThenable;
    suspendedThenable = null;
    return thenable;
  }
  function is(x2, y2) {
    return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
  }
  var objectIs = "function" === typeof Object.is ? Object.is : is, currentlyRenderingComponent = null, currentlyRenderingTask = null, currentlyRenderingRequest = null, currentlyRenderingKeyPath = null, firstWorkInProgressHook = null, workInProgressHook = null, isReRender = false, didScheduleRenderPhaseUpdate = false, localIdCounter = 0, actionStateCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, thenableState = null, renderPhaseUpdates = null, numberOfReRenders = 0;
  function resolveCurrentlyRenderingComponent() {
    if (null === currentlyRenderingComponent)
      throw Error(
        "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
      );
    return currentlyRenderingComponent;
  }
  function createHook() {
    if (0 < numberOfReRenders)
      throw Error("Rendered more hooks than during the previous render");
    return { memoizedState: null, queue: null, next: null };
  }
  function createWorkInProgressHook() {
    null === workInProgressHook ? null === firstWorkInProgressHook ? (isReRender = false, firstWorkInProgressHook = workInProgressHook = createHook()) : (isReRender = true, workInProgressHook = firstWorkInProgressHook) : null === workInProgressHook.next ? (isReRender = false, workInProgressHook = workInProgressHook.next = createHook()) : (isReRender = true, workInProgressHook = workInProgressHook.next);
    return workInProgressHook;
  }
  function getThenableStateAfterSuspending() {
    var state = thenableState;
    thenableState = null;
    return state;
  }
  function resetHooksState() {
    currentlyRenderingKeyPath = currentlyRenderingRequest = currentlyRenderingTask = currentlyRenderingComponent = null;
    didScheduleRenderPhaseUpdate = false;
    firstWorkInProgressHook = null;
    numberOfReRenders = 0;
    workInProgressHook = renderPhaseUpdates = null;
  }
  function basicStateReducer(state, action) {
    return "function" === typeof action ? action(state) : action;
  }
  function useReducer(reducer2, initialArg, init2) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    if (isReRender) {
      var queue = workInProgressHook.queue;
      initialArg = queue.dispatch;
      if (null !== renderPhaseUpdates && (init2 = renderPhaseUpdates.get(queue), void 0 !== init2)) {
        renderPhaseUpdates.delete(queue);
        queue = workInProgressHook.memoizedState;
        do
          queue = reducer2(queue, init2.action), init2 = init2.next;
        while (null !== init2);
        workInProgressHook.memoizedState = queue;
        return [queue, initialArg];
      }
      return [workInProgressHook.memoizedState, initialArg];
    }
    reducer2 = reducer2 === basicStateReducer ? "function" === typeof initialArg ? initialArg() : initialArg : void 0 !== init2 ? init2(initialArg) : initialArg;
    workInProgressHook.memoizedState = reducer2;
    reducer2 = workInProgressHook.queue = { last: null, dispatch: null };
    reducer2 = reducer2.dispatch = dispatchAction.bind(
      null,
      currentlyRenderingComponent,
      reducer2
    );
    return [workInProgressHook.memoizedState, reducer2];
  }
  function useMemo(nextCreate, deps) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    deps = void 0 === deps ? null : deps;
    if (null !== workInProgressHook) {
      var prevState = workInProgressHook.memoizedState;
      if (null !== prevState && null !== deps) {
        var prevDeps = prevState[1];
        a: if (null === prevDeps) prevDeps = false;
        else {
          for (var i = 0; i < prevDeps.length && i < deps.length; i++)
            if (!objectIs(deps[i], prevDeps[i])) {
              prevDeps = false;
              break a;
            }
          prevDeps = true;
        }
        if (prevDeps) return prevState[0];
      }
    }
    nextCreate = nextCreate();
    workInProgressHook.memoizedState = [nextCreate, deps];
    return nextCreate;
  }
  function dispatchAction(componentIdentity, queue, action) {
    if (25 <= numberOfReRenders)
      throw Error(
        "Too many re-renders. React limits the number of renders to prevent an infinite loop."
      );
    if (componentIdentity === currentlyRenderingComponent)
      if (didScheduleRenderPhaseUpdate = true, componentIdentity = { action, next: null }, null === renderPhaseUpdates && (renderPhaseUpdates = /* @__PURE__ */ new Map()), action = renderPhaseUpdates.get(queue), void 0 === action)
        renderPhaseUpdates.set(queue, componentIdentity);
      else {
        for (queue = action; null !== queue.next; ) queue = queue.next;
        queue.next = componentIdentity;
      }
  }
  function throwOnUseEffectEventCall() {
    throw Error(
      "A function wrapped in useEffectEvent can't be called during rendering."
    );
  }
  function unsupportedStartTransition() {
    throw Error("startTransition cannot be called during server rendering.");
  }
  function unsupportedSetOptimisticState() {
    throw Error("Cannot update optimistic state while rendering.");
  }
  function useActionState(action, initialState2, permalink) {
    resolveCurrentlyRenderingComponent();
    var actionStateHookIndex = actionStateCounter++, request = currentlyRenderingRequest;
    if ("function" === typeof action.$$FORM_ACTION) {
      var nextPostbackStateKey = null, componentKeyPath = currentlyRenderingKeyPath;
      request = request.formState;
      var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL;
      if (null !== request && "function" === typeof isSignatureEqual) {
        var postbackKey = request[1];
        isSignatureEqual.call(action, request[2], request[3]) && (nextPostbackStateKey = void 0 !== permalink ? "p" + permalink : "k" + murmurhash3_32_gc(
          JSON.stringify([componentKeyPath, null, actionStateHookIndex]),
          0
        ), postbackKey === nextPostbackStateKey && (actionStateMatchingIndex = actionStateHookIndex, initialState2 = request[0]));
      }
      var boundAction = action.bind(null, initialState2);
      action = function(payload) {
        boundAction(payload);
      };
      "function" === typeof boundAction.$$FORM_ACTION && (action.$$FORM_ACTION = function(prefix2) {
        prefix2 = boundAction.$$FORM_ACTION(prefix2);
        void 0 !== permalink && (permalink += "", prefix2.action = permalink);
        var formData = prefix2.data;
        formData && (null === nextPostbackStateKey && (nextPostbackStateKey = void 0 !== permalink ? "p" + permalink : "k" + murmurhash3_32_gc(
          JSON.stringify([
            componentKeyPath,
            null,
            actionStateHookIndex
          ]),
          0
        )), formData.append("$ACTION_KEY", nextPostbackStateKey));
        return prefix2;
      });
      return [initialState2, action, false];
    }
    var boundAction$22 = action.bind(null, initialState2);
    return [
      initialState2,
      function(payload) {
        boundAction$22(payload);
      },
      false
    ];
  }
  function unwrapThenable(thenable) {
    var index2 = thenableIndexCounter;
    thenableIndexCounter += 1;
    null === thenableState && (thenableState = []);
    return trackUsedThenable(thenableState, thenable, index2);
  }
  function unsupportedRefresh() {
    throw Error("Cache cannot be refreshed during server rendering.");
  }
  var HooksDispatcher = {
    readContext: function(context) {
      return context._currentValue2;
    },
    use: function(usable) {
      if (null !== usable && "object" === typeof usable) {
        if ("function" === typeof usable.then) return unwrapThenable(usable);
        if (usable.$$typeof === REACT_CONTEXT_TYPE)
          return usable._currentValue2;
      }
      throw Error("An unsupported type was passed to use(): " + String(usable));
    },
    useContext: function(context) {
      resolveCurrentlyRenderingComponent();
      return context._currentValue2;
    },
    useMemo,
    useReducer,
    useRef: function(initialValue) {
      currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
      workInProgressHook = createWorkInProgressHook();
      var previousRef = workInProgressHook.memoizedState;
      return null === previousRef ? (initialValue = { current: initialValue }, workInProgressHook.memoizedState = initialValue) : previousRef;
    },
    useState: function(initialState2) {
      return useReducer(basicStateReducer, initialState2);
    },
    useInsertionEffect: noop2,
    useLayoutEffect: noop2,
    useCallback: function(callback, deps) {
      return useMemo(function() {
        return callback;
      }, deps);
    },
    useImperativeHandle: noop2,
    useEffect: noop2,
    useDebugValue: noop2,
    useDeferredValue: function(value, initialValue) {
      resolveCurrentlyRenderingComponent();
      return void 0 !== initialValue ? initialValue : value;
    },
    useTransition: function() {
      resolveCurrentlyRenderingComponent();
      return [false, unsupportedStartTransition];
    },
    useId: function() {
      var JSCompiler_inline_result = currentlyRenderingTask.treeContext;
      var overflow = JSCompiler_inline_result.overflow;
      JSCompiler_inline_result = JSCompiler_inline_result.id;
      JSCompiler_inline_result = (JSCompiler_inline_result & ~(1 << 32 - clz32(JSCompiler_inline_result) - 1)).toString(32) + overflow;
      var resumableState = currentResumableState;
      if (null === resumableState)
        throw Error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component."
        );
      overflow = localIdCounter++;
      JSCompiler_inline_result = "_" + resumableState.idPrefix + "R_" + JSCompiler_inline_result;
      0 < overflow && (JSCompiler_inline_result += "H" + overflow.toString(32));
      return JSCompiler_inline_result + "_";
    },
    useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
      if (void 0 === getServerSnapshot)
        throw Error(
          "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
        );
      return getServerSnapshot();
    },
    useOptimistic: function(passthrough) {
      resolveCurrentlyRenderingComponent();
      return [passthrough, unsupportedSetOptimisticState];
    },
    useActionState,
    useFormState: useActionState,
    useHostTransitionStatus: function() {
      resolveCurrentlyRenderingComponent();
      return sharedNotPendingObject;
    },
    useMemoCache: function(size) {
      for (var data = Array(size), i = 0; i < size; i++)
        data[i] = REACT_MEMO_CACHE_SENTINEL;
      return data;
    },
    useCacheRefresh: function() {
      return unsupportedRefresh;
    },
    useEffectEvent: function() {
      return throwOnUseEffectEventCall;
    }
  }, currentResumableState = null, DefaultAsyncDispatcher = {
    getCacheForType: function() {
      throw Error("Not implemented.");
    },
    cacheSignal: function() {
      throw Error("Not implemented.");
    }
  }, prefix, suffix;
  function describeBuiltInComponentFrame(name2) {
    if (void 0 === prefix)
      try {
        throw Error();
      } catch (x2) {
        var match = x2.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || "";
        suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
      }
    return "\n" + prefix + name2 + suffix;
  }
  var reentry = false;
  function describeNativeComponentFrame(fn, construct) {
    if (!fn || reentry) return "";
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace;
    Error.prepareStackTrace = void 0;
    try {
      var RunInRootFrame = {
        DetermineComponentFrameRoot: function() {
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if ("object" === typeof Reflect && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  var control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x$24) {
                  control = x$24;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x$25) {
                control = x$25;
              }
              (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
              });
            }
          } catch (sample) {
            if (sample && control && "string" === typeof sample.stack)
              return [sample.stack, control.stack];
          }
          return [null, null];
        }
      };
      RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
      var namePropDescriptor = Object.getOwnPropertyDescriptor(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name"
      );
      namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name",
        { value: "DetermineComponentFrameRoot" }
      );
      var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
      if (sampleStack && controlStack) {
        var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
        for (namePropDescriptor = RunInRootFrame = 0; RunInRootFrame < sampleLines.length && !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); )
          RunInRootFrame++;
        for (; namePropDescriptor < controlLines.length && !controlLines[namePropDescriptor].includes(
          "DetermineComponentFrameRoot"
        ); )
          namePropDescriptor++;
        if (RunInRootFrame === sampleLines.length || namePropDescriptor === controlLines.length)
          for (RunInRootFrame = sampleLines.length - 1, namePropDescriptor = controlLines.length - 1; 1 <= RunInRootFrame && 0 <= namePropDescriptor && sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; )
            namePropDescriptor--;
        for (; 1 <= RunInRootFrame && 0 <= namePropDescriptor; RunInRootFrame--, namePropDescriptor--)
          if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
            if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
              do
                if (RunInRootFrame--, namePropDescriptor--, 0 > namePropDescriptor || sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
                  var frame = "\n" + sampleLines[RunInRootFrame].replace(" at new ", " at ");
                  fn.displayName && frame.includes("<anonymous>") && (frame = frame.replace("<anonymous>", fn.displayName));
                  return frame;
                }
              while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
            }
            break;
          }
      }
    } finally {
      reentry = false, Error.prepareStackTrace = previousPrepareStackTrace;
    }
    return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(previousPrepareStackTrace) : "";
  }
  function describeComponentStackByType(type2) {
    if ("string" === typeof type2) return describeBuiltInComponentFrame(type2);
    if ("function" === typeof type2)
      return type2.prototype && type2.prototype.isReactComponent ? describeNativeComponentFrame(type2, true) : describeNativeComponentFrame(type2, false);
    if ("object" === typeof type2 && null !== type2) {
      switch (type2.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          return describeNativeComponentFrame(type2.render, false);
        case REACT_MEMO_TYPE:
          return describeNativeComponentFrame(type2.type, false);
        case REACT_LAZY_TYPE:
          var lazyComponent = type2, payload = lazyComponent._payload;
          lazyComponent = lazyComponent._init;
          try {
            type2 = lazyComponent(payload);
          } catch (x2) {
            return describeBuiltInComponentFrame("Lazy");
          }
          return describeComponentStackByType(type2);
      }
      if ("string" === typeof type2.name) {
        a: {
          payload = type2.name;
          lazyComponent = type2.env;
          var location = type2.debugLocation;
          if (null != location && (type2 = Error.prepareStackTrace, Error.prepareStackTrace = void 0, location = location.stack, Error.prepareStackTrace = type2, location.startsWith("Error: react-stack-top-frame\n") && (location = location.slice(29)), type2 = location.indexOf("\n"), -1 !== type2 && (location = location.slice(type2 + 1)), type2 = location.indexOf("react_stack_bottom_frame"), -1 !== type2 && (type2 = location.lastIndexOf("\n", type2)), type2 = -1 !== type2 ? location = location.slice(0, type2) : "", location = type2.lastIndexOf("\n"), type2 = -1 === location ? type2 : type2.slice(location + 1), -1 !== type2.indexOf(payload))) {
            payload = "\n" + type2;
            break a;
          }
          payload = describeBuiltInComponentFrame(
            payload + (lazyComponent ? " [" + lazyComponent + "]" : "")
          );
        }
        return payload;
      }
    }
    switch (type2) {
      case REACT_SUSPENSE_LIST_TYPE:
        return describeBuiltInComponentFrame("SuspenseList");
      case REACT_SUSPENSE_TYPE:
        return describeBuiltInComponentFrame("Suspense");
    }
    return "";
  }
  function isEligibleForOutlining(request, boundary) {
    return (500 < boundary.byteSize || false) && null === boundary.contentPreamble;
  }
  function defaultErrorHandler(error) {
    if ("object" === typeof error && null !== error && "string" === typeof error.environmentName) {
      var JSCompiler_inline_result = error.environmentName;
      error = [error].slice(0);
      "string" === typeof error[0] ? error.splice(
        0,
        1,
        "[%s] " + error[0],
        " " + JSCompiler_inline_result + " "
      ) : error.splice(0, 0, "[%s]", " " + JSCompiler_inline_result + " ");
      error.unshift(console);
      JSCompiler_inline_result = bind2.apply(console.error, error);
      JSCompiler_inline_result();
    } else console.error(error);
    return null;
  }
  function RequestInstance(resumableState, renderState, rootFormatContext, progressiveChunkSize, onError2, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
    var abortSet = /* @__PURE__ */ new Set();
    this.destination = null;
    this.flushScheduled = false;
    this.resumableState = resumableState;
    this.renderState = renderState;
    this.rootFormatContext = rootFormatContext;
    this.progressiveChunkSize = void 0 === progressiveChunkSize ? 12800 : progressiveChunkSize;
    this.status = 10;
    this.fatalError = null;
    this.pendingRootTasks = this.allPendingTasks = this.nextSegmentId = 0;
    this.completedPreambleSegments = this.completedRootSegment = null;
    this.byteSize = 0;
    this.abortableTasks = abortSet;
    this.pingedTasks = [];
    this.clientRenderedBoundaries = [];
    this.completedBoundaries = [];
    this.partialBoundaries = [];
    this.trackedPostpones = null;
    this.onError = void 0 === onError2 ? defaultErrorHandler : onError2;
    this.onPostpone = void 0 === onPostpone ? noop2 : onPostpone;
    this.onAllReady = void 0 === onAllReady ? noop2 : onAllReady;
    this.onShellReady = void 0 === onShellReady ? noop2 : onShellReady;
    this.onShellError = void 0 === onShellError ? noop2 : onShellError;
    this.onFatalError = void 0 === onFatalError ? noop2 : onFatalError;
    this.formState = void 0 === formState ? null : formState;
  }
  function createRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError2, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
    resumableState = new RequestInstance(
      resumableState,
      renderState,
      rootFormatContext,
      progressiveChunkSize,
      onError2,
      onAllReady,
      onShellReady,
      onShellError,
      onFatalError,
      onPostpone,
      formState
    );
    renderState = createPendingSegment(
      resumableState,
      0,
      null,
      rootFormatContext,
      false,
      false
    );
    renderState.parentFlushed = true;
    children = createRenderTask(
      resumableState,
      null,
      children,
      -1,
      null,
      renderState,
      null,
      null,
      resumableState.abortableTasks,
      null,
      rootFormatContext,
      null,
      emptyTreeContext,
      null,
      null
    );
    pushComponentStack(children);
    resumableState.pingedTasks.push(children);
    return resumableState;
  }
  var currentRequest = null;
  function pingTask(request, task) {
    request.pingedTasks.push(task);
    1 === request.pingedTasks.length && (request.flushScheduled = null !== request.destination, performWork(request));
  }
  function createSuspenseBoundary(request, row, fallbackAbortableTasks, contentPreamble, fallbackPreamble) {
    fallbackAbortableTasks = {
      status: 0,
      rootSegmentID: -1,
      parentFlushed: false,
      pendingTasks: 0,
      row,
      completedSegments: [],
      byteSize: 0,
      fallbackAbortableTasks,
      errorDigest: null,
      contentState: createHoistableState(),
      fallbackState: createHoistableState(),
      contentPreamble,
      fallbackPreamble,
      trackedContentKeyPath: null,
      trackedFallbackNode: null
    };
    null !== row && (row.pendingTasks++, contentPreamble = row.boundaries, null !== contentPreamble && (request.allPendingTasks++, fallbackAbortableTasks.pendingTasks++, contentPreamble.push(fallbackAbortableTasks)), request = row.inheritedHoistables, null !== request && hoistHoistables(fallbackAbortableTasks.contentState, request));
    return fallbackAbortableTasks;
  }
  function createRenderTask(request, thenableState2, node2, childIndex, blockedBoundary, blockedSegment, blockedPreamble, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack) {
    request.allPendingTasks++;
    null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
    null !== row && row.pendingTasks++;
    var task = {
      replay: null,
      node: node2,
      childIndex,
      ping: function() {
        return pingTask(request, task);
      },
      blockedBoundary,
      blockedSegment,
      blockedPreamble,
      hoistableState,
      abortSet,
      keyPath,
      formatContext,
      context,
      treeContext,
      row,
      componentStack,
      thenableState: thenableState2
    };
    abortSet.add(task);
    return task;
  }
  function createReplayTask(request, thenableState2, replay, node2, childIndex, blockedBoundary, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack) {
    request.allPendingTasks++;
    null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
    null !== row && row.pendingTasks++;
    replay.pendingTasks++;
    var task = {
      replay,
      node: node2,
      childIndex,
      ping: function() {
        return pingTask(request, task);
      },
      blockedBoundary,
      blockedSegment: null,
      blockedPreamble: null,
      hoistableState,
      abortSet,
      keyPath,
      formatContext,
      context,
      treeContext,
      row,
      componentStack,
      thenableState: thenableState2
    };
    abortSet.add(task);
    return task;
  }
  function createPendingSegment(request, index2, boundary, parentFormatContext, lastPushedText, textEmbedded) {
    return {
      status: 0,
      parentFlushed: false,
      id: -1,
      index: index2,
      chunks: [],
      children: [],
      preambleChildren: [],
      parentFormatContext,
      boundary,
      lastPushedText,
      textEmbedded
    };
  }
  function pushComponentStack(task) {
    var node2 = task.node;
    if ("object" === typeof node2 && null !== node2)
      switch (node2.$$typeof) {
        case REACT_ELEMENT_TYPE:
          task.componentStack = { parent: task.componentStack, type: node2.type };
      }
  }
  function replaceSuspenseComponentStackWithSuspenseFallbackStack(componentStack) {
    return null === componentStack ? null : { parent: componentStack.parent, type: "Suspense Fallback" };
  }
  function getThrownInfo(node$jscomp$0) {
    var errorInfo = {};
    node$jscomp$0 && Object.defineProperty(errorInfo, "componentStack", {
      configurable: true,
      enumerable: true,
      get: function() {
        try {
          var info = "", node2 = node$jscomp$0;
          do
            info += describeComponentStackByType(node2.type), node2 = node2.parent;
          while (node2);
          var JSCompiler_inline_result = info;
        } catch (x2) {
          JSCompiler_inline_result = "\nError generating stack: " + x2.message + "\n" + x2.stack;
        }
        Object.defineProperty(errorInfo, "componentStack", {
          value: JSCompiler_inline_result
        });
        return JSCompiler_inline_result;
      }
    });
    return errorInfo;
  }
  function logRecoverableError(request, error, errorInfo) {
    request = request.onError;
    error = request(error, errorInfo);
    if (null == error || "string" === typeof error) return error;
  }
  function fatalError(request, error) {
    var onShellError = request.onShellError, onFatalError = request.onFatalError;
    onShellError(error);
    onFatalError(error);
    null !== request.destination ? (request.status = 14, request.destination.destroy(error)) : (request.status = 13, request.fatalError = error);
  }
  function finishSuspenseListRow(request, row) {
    unblockSuspenseListRow(request, row.next, row.hoistables);
  }
  function unblockSuspenseListRow(request, unblockedRow, inheritedHoistables) {
    for (; null !== unblockedRow; ) {
      null !== inheritedHoistables && (hoistHoistables(unblockedRow.hoistables, inheritedHoistables), unblockedRow.inheritedHoistables = inheritedHoistables);
      var unblockedBoundaries = unblockedRow.boundaries;
      if (null !== unblockedBoundaries) {
        unblockedRow.boundaries = null;
        for (var i = 0; i < unblockedBoundaries.length; i++) {
          var unblockedBoundary = unblockedBoundaries[i];
          null !== inheritedHoistables && hoistHoistables(unblockedBoundary.contentState, inheritedHoistables);
          finishedTask(request, unblockedBoundary, null, null);
        }
      }
      unblockedRow.pendingTasks--;
      if (0 < unblockedRow.pendingTasks) break;
      inheritedHoistables = unblockedRow.hoistables;
      unblockedRow = unblockedRow.next;
    }
  }
  function tryToResolveTogetherRow(request, togetherRow) {
    var boundaries = togetherRow.boundaries;
    if (null !== boundaries && togetherRow.pendingTasks === boundaries.length) {
      for (var allCompleteAndInlinable = true, i = 0; i < boundaries.length; i++) {
        var rowBoundary = boundaries[i];
        if (1 !== rowBoundary.pendingTasks || rowBoundary.parentFlushed || isEligibleForOutlining(request, rowBoundary)) {
          allCompleteAndInlinable = false;
          break;
        }
      }
      allCompleteAndInlinable && unblockSuspenseListRow(request, togetherRow, togetherRow.hoistables);
    }
  }
  function createSuspenseListRow(previousRow) {
    var newRow = {
      pendingTasks: 1,
      boundaries: null,
      hoistables: createHoistableState(),
      inheritedHoistables: null,
      together: false,
      next: null
    };
    null !== previousRow && 0 < previousRow.pendingTasks && (newRow.pendingTasks++, newRow.boundaries = [], previousRow.next = newRow);
    return newRow;
  }
  function renderSuspenseListRows(request, task, keyPath, rows, revealOrder) {
    var prevKeyPath = task.keyPath, prevTreeContext = task.treeContext, prevRow = task.row;
    task.keyPath = keyPath;
    keyPath = rows.length;
    var previousSuspenseListRow = null;
    if (null !== task.replay) {
      var resumeSlots = task.replay.slots;
      if (null !== resumeSlots && "object" === typeof resumeSlots)
        for (var n = 0; n < keyPath; n++) {
          var i = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? n : keyPath - 1 - n, node2 = rows[i];
          task.row = previousSuspenseListRow = createSuspenseListRow(
            previousSuspenseListRow
          );
          task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
          var resumeSegmentID = resumeSlots[i];
          "number" === typeof resumeSegmentID ? (resumeNode(request, task, resumeSegmentID, node2, i), delete resumeSlots[i]) : renderNode(request, task, node2, i);
          0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
        }
      else
        for (resumeSlots = 0; resumeSlots < keyPath; resumeSlots++)
          n = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? resumeSlots : keyPath - 1 - resumeSlots, i = rows[n], task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(prevTreeContext, keyPath, n), renderNode(request, task, i, n), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
    } else if ("backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder)
      for (revealOrder = 0; revealOrder < keyPath; revealOrder++)
        resumeSlots = rows[revealOrder], task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(
          prevTreeContext,
          keyPath,
          revealOrder
        ), renderNode(request, task, resumeSlots, revealOrder), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
    else {
      revealOrder = task.blockedSegment;
      resumeSlots = revealOrder.children.length;
      n = revealOrder.chunks.length;
      for (i = keyPath - 1; 0 <= i; i--) {
        node2 = rows[i];
        task.row = previousSuspenseListRow = createSuspenseListRow(
          previousSuspenseListRow
        );
        task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
        resumeSegmentID = createPendingSegment(
          request,
          n,
          null,
          task.formatContext,
          0 === i ? revealOrder.lastPushedText : true,
          true
        );
        revealOrder.children.splice(resumeSlots, 0, resumeSegmentID);
        task.blockedSegment = resumeSegmentID;
        try {
          renderNode(request, task, node2, i), pushSegmentFinale(
            resumeSegmentID.chunks,
            request.renderState,
            resumeSegmentID.lastPushedText,
            resumeSegmentID.textEmbedded
          ), resumeSegmentID.status = 1, 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
        } catch (thrownValue) {
          throw resumeSegmentID.status = 12 === request.status ? 3 : 4, thrownValue;
        }
      }
      task.blockedSegment = revealOrder;
      revealOrder.lastPushedText = false;
    }
    null !== prevRow && null !== previousSuspenseListRow && 0 < previousSuspenseListRow.pendingTasks && (prevRow.pendingTasks++, previousSuspenseListRow.next = prevRow);
    task.treeContext = prevTreeContext;
    task.row = prevRow;
    task.keyPath = prevKeyPath;
  }
  function renderWithHooks(request, task, keyPath, Component, props, secondArg) {
    var prevThenableState = task.thenableState;
    task.thenableState = null;
    currentlyRenderingComponent = {};
    currentlyRenderingTask = task;
    currentlyRenderingRequest = request;
    currentlyRenderingKeyPath = keyPath;
    actionStateCounter = localIdCounter = 0;
    actionStateMatchingIndex = -1;
    thenableIndexCounter = 0;
    thenableState = prevThenableState;
    for (request = Component(props, secondArg); didScheduleRenderPhaseUpdate; )
      didScheduleRenderPhaseUpdate = false, actionStateCounter = localIdCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, numberOfReRenders += 1, workInProgressHook = null, request = Component(props, secondArg);
    resetHooksState();
    return request;
  }
  function finishFunctionComponent(request, task, keyPath, children, hasId, actionStateCount, actionStateMatchingIndex2) {
    var didEmitActionStateMarkers = false;
    if (0 !== actionStateCount && null !== request.formState) {
      var segment = task.blockedSegment;
      if (null !== segment) {
        didEmitActionStateMarkers = true;
        segment = segment.chunks;
        for (var i = 0; i < actionStateCount; i++)
          i === actionStateMatchingIndex2 ? segment.push("<!--F!-->") : segment.push("<!--F-->");
      }
    }
    actionStateCount = task.keyPath;
    task.keyPath = keyPath;
    hasId ? (keyPath = task.treeContext, task.treeContext = pushTreeContext(keyPath, 1, 0), renderNode(request, task, children, -1), task.treeContext = keyPath) : didEmitActionStateMarkers ? renderNode(request, task, children, -1) : renderNodeDestructive(request, task, children, -1);
    task.keyPath = actionStateCount;
  }
  function renderElement(request, task, keyPath, type2, props, ref2) {
    if ("function" === typeof type2)
      if (type2.prototype && type2.prototype.isReactComponent) {
        var newProps = props;
        if ("ref" in props) {
          newProps = {};
          for (var propName in props)
            "ref" !== propName && (newProps[propName] = props[propName]);
        }
        var defaultProps = type2.defaultProps;
        if (defaultProps) {
          newProps === props && (newProps = assign({}, newProps, props));
          for (var propName$43 in defaultProps)
            void 0 === newProps[propName$43] && (newProps[propName$43] = defaultProps[propName$43]);
        }
        props = newProps;
        newProps = emptyContextObject;
        defaultProps = type2.contextType;
        "object" === typeof defaultProps && null !== defaultProps && (newProps = defaultProps._currentValue2);
        newProps = new type2(props, newProps);
        var initialState2 = void 0 !== newProps.state ? newProps.state : null;
        newProps.updater = classComponentUpdater;
        newProps.props = props;
        newProps.state = initialState2;
        defaultProps = { queue: [], replace: false };
        newProps._reactInternals = defaultProps;
        ref2 = type2.contextType;
        newProps.context = "object" === typeof ref2 && null !== ref2 ? ref2._currentValue2 : emptyContextObject;
        ref2 = type2.getDerivedStateFromProps;
        "function" === typeof ref2 && (ref2 = ref2(props, initialState2), initialState2 = null === ref2 || void 0 === ref2 ? initialState2 : assign({}, initialState2, ref2), newProps.state = initialState2);
        if ("function" !== typeof type2.getDerivedStateFromProps && "function" !== typeof newProps.getSnapshotBeforeUpdate && ("function" === typeof newProps.UNSAFE_componentWillMount || "function" === typeof newProps.componentWillMount))
          if (type2 = newProps.state, "function" === typeof newProps.componentWillMount && newProps.componentWillMount(), "function" === typeof newProps.UNSAFE_componentWillMount && newProps.UNSAFE_componentWillMount(), type2 !== newProps.state && classComponentUpdater.enqueueReplaceState(
            newProps,
            newProps.state,
            null
          ), null !== defaultProps.queue && 0 < defaultProps.queue.length)
            if (type2 = defaultProps.queue, ref2 = defaultProps.replace, defaultProps.queue = null, defaultProps.replace = false, ref2 && 1 === type2.length)
              newProps.state = type2[0];
            else {
              defaultProps = ref2 ? type2[0] : newProps.state;
              initialState2 = true;
              for (ref2 = ref2 ? 1 : 0; ref2 < type2.length; ref2++)
                propName$43 = type2[ref2], propName$43 = "function" === typeof propName$43 ? propName$43.call(newProps, defaultProps, props, void 0) : propName$43, null != propName$43 && (initialState2 ? (initialState2 = false, defaultProps = assign({}, defaultProps, propName$43)) : assign(defaultProps, propName$43));
              newProps.state = defaultProps;
            }
          else defaultProps.queue = null;
        type2 = newProps.render();
        if (12 === request.status) throw null;
        props = task.keyPath;
        task.keyPath = keyPath;
        renderNodeDestructive(request, task, type2, -1);
        task.keyPath = props;
      } else {
        type2 = renderWithHooks(request, task, keyPath, type2, props, void 0);
        if (12 === request.status) throw null;
        finishFunctionComponent(
          request,
          task,
          keyPath,
          type2,
          0 !== localIdCounter,
          actionStateCounter,
          actionStateMatchingIndex
        );
      }
    else if ("string" === typeof type2)
      if (newProps = task.blockedSegment, null === newProps)
        newProps = props.children, defaultProps = task.formatContext, initialState2 = task.keyPath, task.formatContext = getChildFormatContext(defaultProps, type2, props), task.keyPath = keyPath, renderNode(request, task, newProps, -1), task.formatContext = defaultProps, task.keyPath = initialState2;
      else {
        initialState2 = pushStartInstance(
          newProps.chunks,
          type2,
          props,
          request.resumableState,
          request.renderState,
          task.blockedPreamble,
          task.hoistableState,
          task.formatContext,
          newProps.lastPushedText
        );
        newProps.lastPushedText = false;
        defaultProps = task.formatContext;
        ref2 = task.keyPath;
        task.keyPath = keyPath;
        if (3 === (task.formatContext = getChildFormatContext(defaultProps, type2, props)).insertionMode) {
          keyPath = createPendingSegment(
            request,
            0,
            null,
            task.formatContext,
            false,
            false
          );
          newProps.preambleChildren.push(keyPath);
          task.blockedSegment = keyPath;
          try {
            keyPath.status = 6, renderNode(request, task, initialState2, -1), pushSegmentFinale(
              keyPath.chunks,
              request.renderState,
              keyPath.lastPushedText,
              keyPath.textEmbedded
            ), keyPath.status = 1;
          } finally {
            task.blockedSegment = newProps;
          }
        } else renderNode(request, task, initialState2, -1);
        task.formatContext = defaultProps;
        task.keyPath = ref2;
        a: {
          task = newProps.chunks;
          request = request.resumableState;
          switch (type2) {
            case "title":
            case "style":
            case "script":
            case "area":
            case "base":
            case "br":
            case "col":
            case "embed":
            case "hr":
            case "img":
            case "input":
            case "keygen":
            case "link":
            case "meta":
            case "param":
            case "source":
            case "track":
            case "wbr":
              break a;
            case "body":
              if (1 >= defaultProps.insertionMode) {
                request.hasBody = true;
                break a;
              }
              break;
            case "html":
              if (0 === defaultProps.insertionMode) {
                request.hasHtml = true;
                break a;
              }
              break;
            case "head":
              if (1 >= defaultProps.insertionMode) break a;
          }
          task.push(endChunkForTag(type2));
        }
        newProps.lastPushedText = false;
      }
    else {
      switch (type2) {
        case REACT_LEGACY_HIDDEN_TYPE:
        case REACT_STRICT_MODE_TYPE:
        case REACT_PROFILER_TYPE:
        case REACT_FRAGMENT_TYPE:
          type2 = task.keyPath;
          task.keyPath = keyPath;
          renderNodeDestructive(request, task, props.children, -1);
          task.keyPath = type2;
          return;
        case REACT_ACTIVITY_TYPE:
          type2 = task.blockedSegment;
          null === type2 ? "hidden" !== props.mode && (type2 = task.keyPath, task.keyPath = keyPath, renderNode(request, task, props.children, -1), task.keyPath = type2) : "hidden" !== props.mode && (request.renderState.generateStaticMarkup || type2.chunks.push("<!--&-->"), type2.lastPushedText = false, newProps = task.keyPath, task.keyPath = keyPath, renderNode(request, task, props.children, -1), task.keyPath = newProps, request.renderState.generateStaticMarkup || type2.chunks.push("<!--/&-->"), type2.lastPushedText = false);
          return;
        case REACT_SUSPENSE_LIST_TYPE:
          a: {
            type2 = props.children;
            props = props.revealOrder;
            if ("forwards" === props || "backwards" === props || "unstable_legacy-backwards" === props) {
              if (isArrayImpl(type2)) {
                renderSuspenseListRows(request, task, keyPath, type2, props);
                break a;
              }
              if (newProps = getIteratorFn(type2)) {
                if (newProps = newProps.call(type2)) {
                  defaultProps = newProps.next();
                  if (!defaultProps.done) {
                    do
                      defaultProps = newProps.next();
                    while (!defaultProps.done);
                    renderSuspenseListRows(request, task, keyPath, type2, props);
                  }
                  break a;
                }
              }
            }
            "together" === props ? (props = task.keyPath, newProps = task.row, defaultProps = task.row = createSuspenseListRow(null), defaultProps.boundaries = [], defaultProps.together = true, task.keyPath = keyPath, renderNodeDestructive(request, task, type2, -1), 0 === --defaultProps.pendingTasks && finishSuspenseListRow(request, defaultProps), task.keyPath = props, task.row = newProps, null !== newProps && 0 < defaultProps.pendingTasks && (newProps.pendingTasks++, defaultProps.next = newProps)) : (props = task.keyPath, task.keyPath = keyPath, renderNodeDestructive(request, task, type2, -1), task.keyPath = props);
          }
          return;
        case REACT_VIEW_TRANSITION_TYPE:
        case REACT_SCOPE_TYPE:
          throw Error("ReactDOMServer does not yet support scope components.");
        case REACT_SUSPENSE_TYPE:
          a: if (null !== task.replay) {
            type2 = task.keyPath;
            newProps = task.formatContext;
            defaultProps = task.row;
            task.keyPath = keyPath;
            task.formatContext = getSuspenseContentFormatContext(
              request.resumableState,
              newProps
            );
            task.row = null;
            keyPath = props.children;
            try {
              renderNode(request, task, keyPath, -1);
            } finally {
              task.keyPath = type2, task.formatContext = newProps, task.row = defaultProps;
            }
          } else {
            type2 = task.keyPath;
            ref2 = task.formatContext;
            var prevRow = task.row, parentBoundary = task.blockedBoundary;
            propName$43 = task.blockedPreamble;
            var parentHoistableState = task.hoistableState;
            propName = task.blockedSegment;
            var fallback = props.fallback;
            props = props.children;
            var fallbackAbortSet = /* @__PURE__ */ new Set();
            var newBoundary = createSuspenseBoundary(
              request,
              task.row,
              fallbackAbortSet,
              null,
              null
            );
            null !== request.trackedPostpones && (newBoundary.trackedContentKeyPath = keyPath);
            var boundarySegment = createPendingSegment(
              request,
              propName.chunks.length,
              newBoundary,
              task.formatContext,
              false,
              false
            );
            propName.children.push(boundarySegment);
            propName.lastPushedText = false;
            var contentRootSegment = createPendingSegment(
              request,
              0,
              null,
              task.formatContext,
              false,
              false
            );
            contentRootSegment.parentFlushed = true;
            if (null !== request.trackedPostpones) {
              newProps = task.componentStack;
              defaultProps = [keyPath[0], "Suspense Fallback", keyPath[2]];
              initialState2 = [defaultProps[1], defaultProps[2], [], null];
              request.trackedPostpones.workingMap.set(defaultProps, initialState2);
              newBoundary.trackedFallbackNode = initialState2;
              task.blockedSegment = boundarySegment;
              task.blockedPreamble = newBoundary.fallbackPreamble;
              task.keyPath = defaultProps;
              task.formatContext = getSuspenseFallbackFormatContext(
                request.resumableState,
                ref2
              );
              task.componentStack = replaceSuspenseComponentStackWithSuspenseFallbackStack(newProps);
              boundarySegment.status = 6;
              try {
                renderNode(request, task, fallback, -1), pushSegmentFinale(
                  boundarySegment.chunks,
                  request.renderState,
                  boundarySegment.lastPushedText,
                  boundarySegment.textEmbedded
                ), boundarySegment.status = 1;
              } catch (thrownValue) {
                throw boundarySegment.status = 12 === request.status ? 3 : 4, thrownValue;
              } finally {
                task.blockedSegment = propName, task.blockedPreamble = propName$43, task.keyPath = type2, task.formatContext = ref2;
              }
              task = createRenderTask(
                request,
                null,
                props,
                -1,
                newBoundary,
                contentRootSegment,
                newBoundary.contentPreamble,
                newBoundary.contentState,
                task.abortSet,
                keyPath,
                getSuspenseContentFormatContext(
                  request.resumableState,
                  task.formatContext
                ),
                task.context,
                task.treeContext,
                null,
                newProps
              );
              pushComponentStack(task);
              request.pingedTasks.push(task);
            } else {
              task.blockedBoundary = newBoundary;
              task.blockedPreamble = newBoundary.contentPreamble;
              task.hoistableState = newBoundary.contentState;
              task.blockedSegment = contentRootSegment;
              task.keyPath = keyPath;
              task.formatContext = getSuspenseContentFormatContext(
                request.resumableState,
                ref2
              );
              task.row = null;
              contentRootSegment.status = 6;
              try {
                if (renderNode(request, task, props, -1), pushSegmentFinale(
                  contentRootSegment.chunks,
                  request.renderState,
                  contentRootSegment.lastPushedText,
                  contentRootSegment.textEmbedded
                ), contentRootSegment.status = 1, queueCompletedSegment(newBoundary, contentRootSegment), 0 === newBoundary.pendingTasks && 0 === newBoundary.status) {
                  if (newBoundary.status = 1, !isEligibleForOutlining(request, newBoundary)) {
                    null !== prevRow && 0 === --prevRow.pendingTasks && finishSuspenseListRow(request, prevRow);
                    0 === request.pendingRootTasks && task.blockedPreamble && preparePreamble(request);
                    break a;
                  }
                } else
                  null !== prevRow && prevRow.together && tryToResolveTogetherRow(request, prevRow);
              } catch (thrownValue$30) {
                newBoundary.status = 4, 12 === request.status ? (contentRootSegment.status = 3, newProps = request.fatalError) : (contentRootSegment.status = 4, newProps = thrownValue$30), defaultProps = getThrownInfo(task.componentStack), initialState2 = logRecoverableError(
                  request,
                  newProps,
                  defaultProps
                ), newBoundary.errorDigest = initialState2, untrackBoundary(request, newBoundary);
              } finally {
                task.blockedBoundary = parentBoundary, task.blockedPreamble = propName$43, task.hoistableState = parentHoistableState, task.blockedSegment = propName, task.keyPath = type2, task.formatContext = ref2, task.row = prevRow;
              }
              task = createRenderTask(
                request,
                null,
                fallback,
                -1,
                parentBoundary,
                boundarySegment,
                newBoundary.fallbackPreamble,
                newBoundary.fallbackState,
                fallbackAbortSet,
                [keyPath[0], "Suspense Fallback", keyPath[2]],
                getSuspenseFallbackFormatContext(
                  request.resumableState,
                  task.formatContext
                ),
                task.context,
                task.treeContext,
                task.row,
                replaceSuspenseComponentStackWithSuspenseFallbackStack(
                  task.componentStack
                )
              );
              pushComponentStack(task);
              request.pingedTasks.push(task);
            }
          }
          return;
      }
      if ("object" === typeof type2 && null !== type2)
        switch (type2.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            if ("ref" in props)
              for (fallback in newProps = {}, props)
                "ref" !== fallback && (newProps[fallback] = props[fallback]);
            else newProps = props;
            type2 = renderWithHooks(
              request,
              task,
              keyPath,
              type2.render,
              newProps,
              ref2
            );
            finishFunctionComponent(
              request,
              task,
              keyPath,
              type2,
              0 !== localIdCounter,
              actionStateCounter,
              actionStateMatchingIndex
            );
            return;
          case REACT_MEMO_TYPE:
            renderElement(request, task, keyPath, type2.type, props, ref2);
            return;
          case REACT_CONTEXT_TYPE:
            defaultProps = props.children;
            newProps = task.keyPath;
            props = props.value;
            initialState2 = type2._currentValue2;
            type2._currentValue2 = props;
            ref2 = currentActiveSnapshot;
            currentActiveSnapshot = type2 = {
              parent: ref2,
              depth: null === ref2 ? 0 : ref2.depth + 1,
              context: type2,
              parentValue: initialState2,
              value: props
            };
            task.context = type2;
            task.keyPath = keyPath;
            renderNodeDestructive(request, task, defaultProps, -1);
            request = currentActiveSnapshot;
            if (null === request)
              throw Error(
                "Tried to pop a Context at the root of the app. This is a bug in React."
              );
            request.context._currentValue2 = request.parentValue;
            request = currentActiveSnapshot = request.parent;
            task.context = request;
            task.keyPath = newProps;
            return;
          case REACT_CONSUMER_TYPE:
            props = props.children;
            type2 = props(type2._context._currentValue2);
            props = task.keyPath;
            task.keyPath = keyPath;
            renderNodeDestructive(request, task, type2, -1);
            task.keyPath = props;
            return;
          case REACT_LAZY_TYPE:
            newProps = type2._init;
            type2 = newProps(type2._payload);
            if (12 === request.status) throw null;
            renderElement(request, task, keyPath, type2, props, ref2);
            return;
        }
      throw Error(
        "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + ((null == type2 ? type2 : typeof type2) + ".")
      );
    }
  }
  function resumeNode(request, task, segmentId, node2, childIndex) {
    var prevReplay = task.replay, blockedBoundary = task.blockedBoundary, resumedSegment = createPendingSegment(
      request,
      0,
      null,
      task.formatContext,
      false,
      false
    );
    resumedSegment.id = segmentId;
    resumedSegment.parentFlushed = true;
    try {
      task.replay = null, task.blockedSegment = resumedSegment, renderNode(request, task, node2, childIndex), resumedSegment.status = 1, null === blockedBoundary ? request.completedRootSegment = resumedSegment : (queueCompletedSegment(blockedBoundary, resumedSegment), blockedBoundary.parentFlushed && request.partialBoundaries.push(blockedBoundary));
    } finally {
      task.replay = prevReplay, task.blockedSegment = null;
    }
  }
  function renderNodeDestructive(request, task, node2, childIndex) {
    null !== task.replay && "number" === typeof task.replay.slots ? resumeNode(request, task, task.replay.slots, node2, childIndex) : (task.node = node2, task.childIndex = childIndex, node2 = task.componentStack, pushComponentStack(task), retryNode(request, task), task.componentStack = node2);
  }
  function retryNode(request, task) {
    var node2 = task.node, childIndex = task.childIndex;
    if (null !== node2) {
      if ("object" === typeof node2) {
        switch (node2.$$typeof) {
          case REACT_ELEMENT_TYPE:
            var type2 = node2.type, key = node2.key, props = node2.props;
            node2 = props.ref;
            var ref2 = void 0 !== node2 ? node2 : null, name2 = getComponentNameFromType(type2), keyOrIndex = null == key ? -1 === childIndex ? 0 : childIndex : key;
            key = [task.keyPath, name2, keyOrIndex];
            if (null !== task.replay)
              a: {
                var replay = task.replay;
                childIndex = replay.nodes;
                for (node2 = 0; node2 < childIndex.length; node2++) {
                  var node$jscomp$0 = childIndex[node2];
                  if (keyOrIndex === node$jscomp$0[1]) {
                    if (4 === node$jscomp$0.length) {
                      if (null !== name2 && name2 !== node$jscomp$0[0])
                        throw Error(
                          "Expected the resume to render <" + node$jscomp$0[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
                        );
                      var childNodes = node$jscomp$0[2];
                      name2 = node$jscomp$0[3];
                      keyOrIndex = task.node;
                      task.replay = {
                        nodes: childNodes,
                        slots: name2,
                        pendingTasks: 1
                      };
                      try {
                        renderElement(request, task, key, type2, props, ref2);
                        if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                          throw Error(
                            "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                          );
                        task.replay.pendingTasks--;
                      } catch (x2) {
                        if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
                          throw task.node === keyOrIndex ? task.replay = replay : childIndex.splice(node2, 1), x2;
                        task.replay.pendingTasks--;
                        props = getThrownInfo(task.componentStack);
                        key = request;
                        request = task.blockedBoundary;
                        type2 = x2;
                        props = logRecoverableError(key, type2, props);
                        abortRemainingReplayNodes(
                          key,
                          request,
                          childNodes,
                          name2,
                          type2,
                          props
                        );
                      }
                      task.replay = replay;
                    } else {
                      if (type2 !== REACT_SUSPENSE_TYPE)
                        throw Error(
                          "Expected the resume to render <Suspense> in this slot but instead it rendered <" + (getComponentNameFromType(type2) || "Unknown") + ">. The tree doesn't match so React will fallback to client rendering."
                        );
                      b: {
                        replay = void 0;
                        type2 = node$jscomp$0[5];
                        ref2 = node$jscomp$0[2];
                        name2 = node$jscomp$0[3];
                        keyOrIndex = null === node$jscomp$0[4] ? [] : node$jscomp$0[4][2];
                        node$jscomp$0 = null === node$jscomp$0[4] ? null : node$jscomp$0[4][3];
                        var prevKeyPath = task.keyPath, prevContext = task.formatContext, prevRow = task.row, previousReplaySet = task.replay, parentBoundary = task.blockedBoundary, parentHoistableState = task.hoistableState, content2 = props.children, fallback = props.fallback, fallbackAbortSet = /* @__PURE__ */ new Set();
                        props = createSuspenseBoundary(
                          request,
                          task.row,
                          fallbackAbortSet,
                          null,
                          null
                        );
                        props.parentFlushed = true;
                        props.rootSegmentID = type2;
                        task.blockedBoundary = props;
                        task.hoistableState = props.contentState;
                        task.keyPath = key;
                        task.formatContext = getSuspenseContentFormatContext(
                          request.resumableState,
                          prevContext
                        );
                        task.row = null;
                        task.replay = {
                          nodes: ref2,
                          slots: name2,
                          pendingTasks: 1
                        };
                        try {
                          renderNode(request, task, content2, -1);
                          if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                            throw Error(
                              "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                            );
                          task.replay.pendingTasks--;
                          if (0 === props.pendingTasks && 0 === props.status) {
                            props.status = 1;
                            request.completedBoundaries.push(props);
                            break b;
                          }
                        } catch (error) {
                          props.status = 4, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
                            request,
                            error,
                            childNodes
                          ), props.errorDigest = replay, task.replay.pendingTasks--, request.clientRenderedBoundaries.push(props);
                        } finally {
                          task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath, task.formatContext = prevContext, task.row = prevRow;
                        }
                        childNodes = createReplayTask(
                          request,
                          null,
                          {
                            nodes: keyOrIndex,
                            slots: node$jscomp$0,
                            pendingTasks: 0
                          },
                          fallback,
                          -1,
                          parentBoundary,
                          props.fallbackState,
                          fallbackAbortSet,
                          [key[0], "Suspense Fallback", key[2]],
                          getSuspenseFallbackFormatContext(
                            request.resumableState,
                            task.formatContext
                          ),
                          task.context,
                          task.treeContext,
                          task.row,
                          replaceSuspenseComponentStackWithSuspenseFallbackStack(
                            task.componentStack
                          )
                        );
                        pushComponentStack(childNodes);
                        request.pingedTasks.push(childNodes);
                      }
                    }
                    childIndex.splice(node2, 1);
                    break a;
                  }
                }
              }
            else renderElement(request, task, key, type2, props, ref2);
            return;
          case REACT_PORTAL_TYPE:
            throw Error(
              "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render."
            );
          case REACT_LAZY_TYPE:
            childNodes = node2._init;
            node2 = childNodes(node2._payload);
            if (12 === request.status) throw null;
            renderNodeDestructive(request, task, node2, childIndex);
            return;
        }
        if (isArrayImpl(node2)) {
          renderChildrenArray(request, task, node2, childIndex);
          return;
        }
        if (childNodes = getIteratorFn(node2)) {
          if (childNodes = childNodes.call(node2)) {
            node2 = childNodes.next();
            if (!node2.done) {
              props = [];
              do
                props.push(node2.value), node2 = childNodes.next();
              while (!node2.done);
              renderChildrenArray(request, task, props, childIndex);
            }
            return;
          }
        }
        if ("function" === typeof node2.then)
          return task.thenableState = null, renderNodeDestructive(request, task, unwrapThenable(node2), childIndex);
        if (node2.$$typeof === REACT_CONTEXT_TYPE)
          return renderNodeDestructive(
            request,
            task,
            node2._currentValue2,
            childIndex
          );
        childIndex = Object.prototype.toString.call(node2);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === childIndex ? "object with keys {" + Object.keys(node2).join(", ") + "}" : childIndex) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      if ("string" === typeof node2)
        childIndex = task.blockedSegment, null !== childIndex && (childIndex.lastPushedText = pushTextInstance(
          childIndex.chunks,
          node2,
          request.renderState,
          childIndex.lastPushedText
        ));
      else if ("number" === typeof node2 || "bigint" === typeof node2)
        childIndex = task.blockedSegment, null !== childIndex && (childIndex.lastPushedText = pushTextInstance(
          childIndex.chunks,
          "" + node2,
          request.renderState,
          childIndex.lastPushedText
        ));
    }
  }
  function renderChildrenArray(request, task, children, childIndex) {
    var prevKeyPath = task.keyPath;
    if (-1 !== childIndex && (task.keyPath = [task.keyPath, "Fragment", childIndex], null !== task.replay)) {
      for (var replay = task.replay, replayNodes = replay.nodes, j2 = 0; j2 < replayNodes.length; j2++) {
        var node2 = replayNodes[j2];
        if (node2[1] === childIndex) {
          childIndex = node2[2];
          node2 = node2[3];
          task.replay = { nodes: childIndex, slots: node2, pendingTasks: 1 };
          try {
            renderChildrenArray(request, task, children, -1);
            if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
              throw Error(
                "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
              );
            task.replay.pendingTasks--;
          } catch (x2) {
            if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
              throw x2;
            task.replay.pendingTasks--;
            children = getThrownInfo(task.componentStack);
            var boundary = task.blockedBoundary, error = x2;
            children = logRecoverableError(request, error, children);
            abortRemainingReplayNodes(
              request,
              boundary,
              childIndex,
              node2,
              error,
              children
            );
          }
          task.replay = replay;
          replayNodes.splice(j2, 1);
          break;
        }
      }
      task.keyPath = prevKeyPath;
      return;
    }
    replay = task.treeContext;
    replayNodes = children.length;
    if (null !== task.replay && (j2 = task.replay.slots, null !== j2 && "object" === typeof j2)) {
      for (childIndex = 0; childIndex < replayNodes; childIndex++)
        node2 = children[childIndex], task.treeContext = pushTreeContext(replay, replayNodes, childIndex), boundary = j2[childIndex], "number" === typeof boundary ? (resumeNode(request, task, boundary, node2, childIndex), delete j2[childIndex]) : renderNode(request, task, node2, childIndex);
      task.treeContext = replay;
      task.keyPath = prevKeyPath;
      return;
    }
    for (j2 = 0; j2 < replayNodes; j2++)
      childIndex = children[j2], task.treeContext = pushTreeContext(replay, replayNodes, j2), renderNode(request, task, childIndex, j2);
    task.treeContext = replay;
    task.keyPath = prevKeyPath;
  }
  function trackPostponedBoundary(request, trackedPostpones, boundary) {
    boundary.status = 5;
    boundary.rootSegmentID = request.nextSegmentId++;
    request = boundary.trackedContentKeyPath;
    if (null === request)
      throw Error(
        "It should not be possible to postpone at the root. This is a bug in React."
      );
    var fallbackReplayNode = boundary.trackedFallbackNode, children = [], boundaryNode = trackedPostpones.workingMap.get(request);
    if (void 0 === boundaryNode)
      return boundary = [
        request[1],
        request[2],
        children,
        null,
        fallbackReplayNode,
        boundary.rootSegmentID
      ], trackedPostpones.workingMap.set(request, boundary), addToReplayParent(boundary, request[0], trackedPostpones), boundary;
    boundaryNode[4] = fallbackReplayNode;
    boundaryNode[5] = boundary.rootSegmentID;
    return boundaryNode;
  }
  function trackPostpone(request, trackedPostpones, task, segment) {
    segment.status = 5;
    var keyPath = task.keyPath, boundary = task.blockedBoundary;
    if (null === boundary)
      segment.id = request.nextSegmentId++, trackedPostpones.rootSlots = segment.id, null !== request.completedRootSegment && (request.completedRootSegment.status = 5);
    else {
      if (null !== boundary && 0 === boundary.status) {
        var boundaryNode = trackPostponedBoundary(
          request,
          trackedPostpones,
          boundary
        );
        if (boundary.trackedContentKeyPath === keyPath && -1 === task.childIndex) {
          -1 === segment.id && (segment.id = segment.parentFlushed ? boundary.rootSegmentID : request.nextSegmentId++);
          boundaryNode[3] = segment.id;
          return;
        }
      }
      -1 === segment.id && (segment.id = segment.parentFlushed && null !== boundary ? boundary.rootSegmentID : request.nextSegmentId++);
      if (-1 === task.childIndex)
        null === keyPath ? trackedPostpones.rootSlots = segment.id : (task = trackedPostpones.workingMap.get(keyPath), void 0 === task ? (task = [keyPath[1], keyPath[2], [], segment.id], addToReplayParent(task, keyPath[0], trackedPostpones)) : task[3] = segment.id);
      else {
        if (null === keyPath)
          if (request = trackedPostpones.rootSlots, null === request)
            request = trackedPostpones.rootSlots = {};
          else {
            if ("number" === typeof request)
              throw Error(
                "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
              );
          }
        else if (boundary = trackedPostpones.workingMap, boundaryNode = boundary.get(keyPath), void 0 === boundaryNode)
          request = {}, boundaryNode = [keyPath[1], keyPath[2], [], request], boundary.set(keyPath, boundaryNode), addToReplayParent(boundaryNode, keyPath[0], trackedPostpones);
        else if (request = boundaryNode[3], null === request)
          request = boundaryNode[3] = {};
        else if ("number" === typeof request)
          throw Error(
            "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
          );
        request[task.childIndex] = segment.id;
      }
    }
  }
  function untrackBoundary(request, boundary) {
    request = request.trackedPostpones;
    null !== request && (boundary = boundary.trackedContentKeyPath, null !== boundary && (boundary = request.workingMap.get(boundary), void 0 !== boundary && (boundary.length = 4, boundary[2] = [], boundary[3] = null)));
  }
  function spawnNewSuspendedReplayTask(request, task, thenableState2) {
    return createReplayTask(
      request,
      thenableState2,
      task.replay,
      task.node,
      task.childIndex,
      task.blockedBoundary,
      task.hoistableState,
      task.abortSet,
      task.keyPath,
      task.formatContext,
      task.context,
      task.treeContext,
      task.row,
      task.componentStack
    );
  }
  function spawnNewSuspendedRenderTask(request, task, thenableState2) {
    var segment = task.blockedSegment, newSegment = createPendingSegment(
      request,
      segment.chunks.length,
      null,
      task.formatContext,
      segment.lastPushedText,
      true
    );
    segment.children.push(newSegment);
    segment.lastPushedText = false;
    return createRenderTask(
      request,
      thenableState2,
      task.node,
      task.childIndex,
      task.blockedBoundary,
      newSegment,
      task.blockedPreamble,
      task.hoistableState,
      task.abortSet,
      task.keyPath,
      task.formatContext,
      task.context,
      task.treeContext,
      task.row,
      task.componentStack
    );
  }
  function renderNode(request, task, node2, childIndex) {
    var previousFormatContext = task.formatContext, previousContext = task.context, previousKeyPath = task.keyPath, previousTreeContext = task.treeContext, previousComponentStack = task.componentStack, segment = task.blockedSegment;
    if (null === segment) {
      segment = task.replay;
      try {
        return renderNodeDestructive(request, task, node2, childIndex);
      } catch (thrownValue) {
        if (resetHooksState(), node2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue, 12 !== request.status && "object" === typeof node2 && null !== node2) {
          if ("function" === typeof node2.then) {
            childIndex = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
            request = spawnNewSuspendedReplayTask(request, task, childIndex).ping;
            node2.then(request, request);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            task.replay = segment;
            switchContext(previousContext);
            return;
          }
          if ("Maximum call stack size exceeded" === node2.message) {
            node2 = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
            node2 = spawnNewSuspendedReplayTask(request, task, node2);
            request.pingedTasks.push(node2);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            task.replay = segment;
            switchContext(previousContext);
            return;
          }
        }
      }
    } else {
      var childrenLength = segment.children.length, chunkLength = segment.chunks.length;
      try {
        return renderNodeDestructive(request, task, node2, childIndex);
      } catch (thrownValue$62) {
        if (resetHooksState(), segment.children.length = childrenLength, segment.chunks.length = chunkLength, node2 = thrownValue$62 === SuspenseException ? getSuspendedThenable() : thrownValue$62, 12 !== request.status && "object" === typeof node2 && null !== node2) {
          if ("function" === typeof node2.then) {
            segment = node2;
            node2 = thrownValue$62 === SuspenseException ? getThenableStateAfterSuspending() : null;
            request = spawnNewSuspendedRenderTask(request, task, node2).ping;
            segment.then(request, request);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            switchContext(previousContext);
            return;
          }
          if ("Maximum call stack size exceeded" === node2.message) {
            segment = thrownValue$62 === SuspenseException ? getThenableStateAfterSuspending() : null;
            segment = spawnNewSuspendedRenderTask(request, task, segment);
            request.pingedTasks.push(segment);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            switchContext(previousContext);
            return;
          }
        }
      }
    }
    task.formatContext = previousFormatContext;
    task.context = previousContext;
    task.keyPath = previousKeyPath;
    task.treeContext = previousTreeContext;
    switchContext(previousContext);
    throw node2;
  }
  function abortTaskSoft(task) {
    var boundary = task.blockedBoundary, segment = task.blockedSegment;
    null !== segment && (segment.status = 3, finishedTask(this, boundary, task.row, segment));
  }
  function abortRemainingReplayNodes(request$jscomp$0, boundary, nodes, slots, error, errorDigest$jscomp$0) {
    for (var i = 0; i < nodes.length; i++) {
      var node2 = nodes[i];
      if (4 === node2.length)
        abortRemainingReplayNodes(
          request$jscomp$0,
          boundary,
          node2[2],
          node2[3],
          error,
          errorDigest$jscomp$0
        );
      else {
        node2 = node2[5];
        var request = request$jscomp$0, errorDigest = errorDigest$jscomp$0, resumedBoundary = createSuspenseBoundary(
          request,
          null,
          /* @__PURE__ */ new Set(),
          null,
          null
        );
        resumedBoundary.parentFlushed = true;
        resumedBoundary.rootSegmentID = node2;
        resumedBoundary.status = 4;
        resumedBoundary.errorDigest = errorDigest;
        resumedBoundary.parentFlushed && request.clientRenderedBoundaries.push(resumedBoundary);
      }
    }
    nodes.length = 0;
    if (null !== slots) {
      if (null === boundary)
        throw Error(
          "We should not have any resumable nodes in the shell. This is a bug in React."
        );
      4 !== boundary.status && (boundary.status = 4, boundary.errorDigest = errorDigest$jscomp$0, boundary.parentFlushed && request$jscomp$0.clientRenderedBoundaries.push(boundary));
      if ("object" === typeof slots) for (var index2 in slots) delete slots[index2];
    }
  }
  function abortTask(task, request, error) {
    var boundary = task.blockedBoundary, segment = task.blockedSegment;
    if (null !== segment) {
      if (6 === segment.status) return;
      segment.status = 3;
    }
    var errorInfo = getThrownInfo(task.componentStack);
    if (null === boundary) {
      if (13 !== request.status && 14 !== request.status) {
        boundary = task.replay;
        if (null === boundary) {
          null !== request.trackedPostpones && null !== segment ? (boundary = request.trackedPostpones, logRecoverableError(request, error, errorInfo), trackPostpone(request, boundary, task, segment), finishedTask(request, null, task.row, segment)) : (logRecoverableError(request, error, errorInfo), fatalError(request, error));
          return;
        }
        boundary.pendingTasks--;
        0 === boundary.pendingTasks && 0 < boundary.nodes.length && (segment = logRecoverableError(request, error, errorInfo), abortRemainingReplayNodes(
          request,
          null,
          boundary.nodes,
          boundary.slots,
          error,
          segment
        ));
        request.pendingRootTasks--;
        0 === request.pendingRootTasks && completeShell(request);
      }
    } else {
      var trackedPostpones$63 = request.trackedPostpones;
      if (4 !== boundary.status) {
        if (null !== trackedPostpones$63 && null !== segment)
          return logRecoverableError(request, error, errorInfo), trackPostpone(request, trackedPostpones$63, task, segment), boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
            return abortTask(fallbackTask, request, error);
          }), boundary.fallbackAbortableTasks.clear(), finishedTask(request, boundary, task.row, segment);
        boundary.status = 4;
        segment = logRecoverableError(request, error, errorInfo);
        boundary.status = 4;
        boundary.errorDigest = segment;
        untrackBoundary(request, boundary);
        boundary.parentFlushed && request.clientRenderedBoundaries.push(boundary);
      }
      boundary.pendingTasks--;
      segment = boundary.row;
      null !== segment && 0 === --segment.pendingTasks && finishSuspenseListRow(request, segment);
      boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
        return abortTask(fallbackTask, request, error);
      });
      boundary.fallbackAbortableTasks.clear();
    }
    task = task.row;
    null !== task && 0 === --task.pendingTasks && finishSuspenseListRow(request, task);
    request.allPendingTasks--;
    0 === request.allPendingTasks && completeAll(request);
  }
  function safelyEmitEarlyPreloads(request, shellComplete) {
    try {
      var renderState = request.renderState, onHeaders = renderState.onHeaders;
      if (onHeaders) {
        var headers = renderState.headers;
        if (headers) {
          renderState.headers = null;
          var linkHeader = headers.preconnects;
          headers.fontPreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.fontPreloads);
          headers.highImagePreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.highImagePreloads);
          if (!shellComplete) {
            var queueIter = renderState.styles.values(), queueStep = queueIter.next();
            b: for (; 0 < headers.remainingCapacity && !queueStep.done; queueStep = queueIter.next())
              for (var sheetIter = queueStep.value.sheets.values(), sheetStep = sheetIter.next(); 0 < headers.remainingCapacity && !sheetStep.done; sheetStep = sheetIter.next()) {
                var sheet = sheetStep.value, props = sheet.props, key = props.href, props$jscomp$0 = sheet.props, header = getPreloadAsHeader(props$jscomp$0.href, "style", {
                  crossOrigin: props$jscomp$0.crossOrigin,
                  integrity: props$jscomp$0.integrity,
                  nonce: props$jscomp$0.nonce,
                  type: props$jscomp$0.type,
                  fetchPriority: props$jscomp$0.fetchPriority,
                  referrerPolicy: props$jscomp$0.referrerPolicy,
                  media: props$jscomp$0.media
                });
                if (0 <= (headers.remainingCapacity -= header.length + 2))
                  renderState.resets.style[key] = PRELOAD_NO_CREDS, linkHeader && (linkHeader += ", "), linkHeader += header, renderState.resets.style[key] = "string" === typeof props.crossOrigin || "string" === typeof props.integrity ? [props.crossOrigin, props.integrity] : PRELOAD_NO_CREDS;
                else break b;
              }
          }
          linkHeader ? onHeaders({ Link: linkHeader }) : onHeaders({});
        }
      }
    } catch (error) {
      logRecoverableError(request, error, {});
    }
  }
  function completeShell(request) {
    null === request.trackedPostpones && safelyEmitEarlyPreloads(request, true);
    null === request.trackedPostpones && preparePreamble(request);
    request.onShellError = noop2;
    request = request.onShellReady;
    request();
  }
  function completeAll(request) {
    safelyEmitEarlyPreloads(
      request,
      null === request.trackedPostpones ? true : null === request.completedRootSegment || 5 !== request.completedRootSegment.status
    );
    preparePreamble(request);
    request = request.onAllReady;
    request();
  }
  function queueCompletedSegment(boundary, segment) {
    if (0 === segment.chunks.length && 1 === segment.children.length && null === segment.children[0].boundary && -1 === segment.children[0].id) {
      var childSegment = segment.children[0];
      childSegment.id = segment.id;
      childSegment.parentFlushed = true;
      1 !== childSegment.status && 3 !== childSegment.status && 4 !== childSegment.status || queueCompletedSegment(boundary, childSegment);
    } else boundary.completedSegments.push(segment);
  }
  function finishedTask(request, boundary, row, segment) {
    null !== row && (0 === --row.pendingTasks ? finishSuspenseListRow(request, row) : row.together && tryToResolveTogetherRow(request, row));
    request.allPendingTasks--;
    if (null === boundary) {
      if (null !== segment && segment.parentFlushed) {
        if (null !== request.completedRootSegment)
          throw Error(
            "There can only be one root segment. This is a bug in React."
          );
        request.completedRootSegment = segment;
      }
      request.pendingRootTasks--;
      0 === request.pendingRootTasks && completeShell(request);
    } else if (boundary.pendingTasks--, 4 !== boundary.status)
      if (0 === boundary.pendingTasks)
        if (0 === boundary.status && (boundary.status = 1), null !== segment && segment.parentFlushed && (1 === segment.status || 3 === segment.status) && queueCompletedSegment(boundary, segment), boundary.parentFlushed && request.completedBoundaries.push(boundary), 1 === boundary.status)
          row = boundary.row, null !== row && hoistHoistables(row.hoistables, boundary.contentState), isEligibleForOutlining(request, boundary) || (boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request), boundary.fallbackAbortableTasks.clear(), null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row)), 0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary.contentPreamble && preparePreamble(request);
        else {
          if (5 === boundary.status && (boundary = boundary.row, null !== boundary)) {
            if (null !== request.trackedPostpones) {
              row = request.trackedPostpones;
              var postponedRow = boundary.next;
              if (null !== postponedRow && (segment = postponedRow.boundaries, null !== segment))
                for (postponedRow.boundaries = null, postponedRow = 0; postponedRow < segment.length; postponedRow++) {
                  var postponedBoundary = segment[postponedRow];
                  trackPostponedBoundary(request, row, postponedBoundary);
                  finishedTask(request, postponedBoundary, null, null);
                }
            }
            0 === --boundary.pendingTasks && finishSuspenseListRow(request, boundary);
          }
        }
      else
        null === segment || !segment.parentFlushed || 1 !== segment.status && 3 !== segment.status || (queueCompletedSegment(boundary, segment), 1 === boundary.completedSegments.length && boundary.parentFlushed && request.partialBoundaries.push(boundary)), boundary = boundary.row, null !== boundary && boundary.together && tryToResolveTogetherRow(request, boundary);
    0 === request.allPendingTasks && completeAll(request);
  }
  function performWork(request$jscomp$2) {
    if (14 !== request$jscomp$2.status && 13 !== request$jscomp$2.status) {
      var prevContext = currentActiveSnapshot, prevDispatcher = ReactSharedInternals.H;
      ReactSharedInternals.H = HooksDispatcher;
      var prevAsyncDispatcher = ReactSharedInternals.A;
      ReactSharedInternals.A = DefaultAsyncDispatcher;
      var prevRequest = currentRequest;
      currentRequest = request$jscomp$2;
      var prevResumableState = currentResumableState;
      currentResumableState = request$jscomp$2.resumableState;
      try {
        var pingedTasks = request$jscomp$2.pingedTasks, i;
        for (i = 0; i < pingedTasks.length; i++) {
          var task = pingedTasks[i], request = request$jscomp$2, segment = task.blockedSegment;
          if (null === segment) {
            var request$jscomp$0 = request;
            if (0 !== task.replay.pendingTasks) {
              switchContext(task.context);
              try {
                "number" === typeof task.replay.slots ? resumeNode(
                  request$jscomp$0,
                  task,
                  task.replay.slots,
                  task.node,
                  task.childIndex
                ) : retryNode(request$jscomp$0, task);
                if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                  throw Error(
                    "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                  );
                task.replay.pendingTasks--;
                task.abortSet.delete(task);
                finishedTask(
                  request$jscomp$0,
                  task.blockedBoundary,
                  task.row,
                  null
                );
              } catch (thrownValue) {
                resetHooksState();
                var x2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue;
                if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then) {
                  var ping = task.ping;
                  x2.then(ping, ping);
                  task.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                } else {
                  task.replay.pendingTasks--;
                  task.abortSet.delete(task);
                  var errorInfo = getThrownInfo(task.componentStack);
                  request = void 0;
                  var request$jscomp$1 = request$jscomp$0, boundary = task.blockedBoundary, error$jscomp$0 = 12 === request$jscomp$0.status ? request$jscomp$0.fatalError : x2, replayNodes = task.replay.nodes, resumeSlots = task.replay.slots;
                  request = logRecoverableError(
                    request$jscomp$1,
                    error$jscomp$0,
                    errorInfo
                  );
                  abortRemainingReplayNodes(
                    request$jscomp$1,
                    boundary,
                    replayNodes,
                    resumeSlots,
                    error$jscomp$0,
                    request
                  );
                  request$jscomp$0.pendingRootTasks--;
                  0 === request$jscomp$0.pendingRootTasks && completeShell(request$jscomp$0);
                  request$jscomp$0.allPendingTasks--;
                  0 === request$jscomp$0.allPendingTasks && completeAll(request$jscomp$0);
                }
              } finally {
              }
            }
          } else if (request$jscomp$0 = void 0, request$jscomp$1 = segment, 0 === request$jscomp$1.status) {
            request$jscomp$1.status = 6;
            switchContext(task.context);
            var childrenLength = request$jscomp$1.children.length, chunkLength = request$jscomp$1.chunks.length;
            try {
              retryNode(request, task), pushSegmentFinale(
                request$jscomp$1.chunks,
                request.renderState,
                request$jscomp$1.lastPushedText,
                request$jscomp$1.textEmbedded
              ), task.abortSet.delete(task), request$jscomp$1.status = 1, finishedTask(
                request,
                task.blockedBoundary,
                task.row,
                request$jscomp$1
              );
            } catch (thrownValue) {
              resetHooksState();
              request$jscomp$1.children.length = childrenLength;
              request$jscomp$1.chunks.length = chunkLength;
              var x$jscomp$0 = thrownValue === SuspenseException ? getSuspendedThenable() : 12 === request.status ? request.fatalError : thrownValue;
              if (12 === request.status && null !== request.trackedPostpones) {
                var trackedPostpones = request.trackedPostpones, thrownInfo = getThrownInfo(task.componentStack);
                task.abortSet.delete(task);
                logRecoverableError(request, x$jscomp$0, thrownInfo);
                trackPostpone(request, trackedPostpones, task, request$jscomp$1);
                finishedTask(
                  request,
                  task.blockedBoundary,
                  task.row,
                  request$jscomp$1
                );
              } else if ("object" === typeof x$jscomp$0 && null !== x$jscomp$0 && "function" === typeof x$jscomp$0.then) {
                request$jscomp$1.status = 0;
                task.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                var ping$jscomp$0 = task.ping;
                x$jscomp$0.then(ping$jscomp$0, ping$jscomp$0);
              } else {
                var errorInfo$jscomp$0 = getThrownInfo(task.componentStack);
                task.abortSet.delete(task);
                request$jscomp$1.status = 4;
                var boundary$jscomp$0 = task.blockedBoundary, row = task.row;
                null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
                request.allPendingTasks--;
                request$jscomp$0 = logRecoverableError(
                  request,
                  x$jscomp$0,
                  errorInfo$jscomp$0
                );
                if (null === boundary$jscomp$0) fatalError(request, x$jscomp$0);
                else if (boundary$jscomp$0.pendingTasks--, 4 !== boundary$jscomp$0.status) {
                  boundary$jscomp$0.status = 4;
                  boundary$jscomp$0.errorDigest = request$jscomp$0;
                  untrackBoundary(request, boundary$jscomp$0);
                  var boundaryRow = boundary$jscomp$0.row;
                  null !== boundaryRow && 0 === --boundaryRow.pendingTasks && finishSuspenseListRow(request, boundaryRow);
                  boundary$jscomp$0.parentFlushed && request.clientRenderedBoundaries.push(boundary$jscomp$0);
                  0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary$jscomp$0.contentPreamble && preparePreamble(request);
                }
                0 === request.allPendingTasks && completeAll(request);
              }
            } finally {
            }
          }
        }
        pingedTasks.splice(0, i);
        null !== request$jscomp$2.destination && flushCompletedQueues(request$jscomp$2, request$jscomp$2.destination);
      } catch (error) {
        logRecoverableError(request$jscomp$2, error, {}), fatalError(request$jscomp$2, error);
      } finally {
        currentResumableState = prevResumableState, ReactSharedInternals.H = prevDispatcher, ReactSharedInternals.A = prevAsyncDispatcher, prevDispatcher === HooksDispatcher && switchContext(prevContext), currentRequest = prevRequest;
      }
    }
  }
  function preparePreambleFromSubtree(request, segment, collectedPreambleSegments) {
    segment.preambleChildren.length && collectedPreambleSegments.push(segment.preambleChildren);
    for (var pendingPreambles = false, i = 0; i < segment.children.length; i++)
      pendingPreambles = preparePreambleFromSegment(
        request,
        segment.children[i],
        collectedPreambleSegments
      ) || pendingPreambles;
    return pendingPreambles;
  }
  function preparePreambleFromSegment(request, segment, collectedPreambleSegments) {
    var boundary = segment.boundary;
    if (null === boundary)
      return preparePreambleFromSubtree(
        request,
        segment,
        collectedPreambleSegments
      );
    var preamble = boundary.contentPreamble, fallbackPreamble = boundary.fallbackPreamble;
    if (null === preamble || null === fallbackPreamble) return false;
    switch (boundary.status) {
      case 1:
        hoistPreambleState(request.renderState, preamble);
        request.byteSize += boundary.byteSize;
        segment = boundary.completedSegments[0];
        if (!segment)
          throw Error(
            "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
          );
        return preparePreambleFromSubtree(
          request,
          segment,
          collectedPreambleSegments
        );
      case 5:
        if (null !== request.trackedPostpones) return true;
      case 4:
        if (1 === segment.status)
          return hoistPreambleState(request.renderState, fallbackPreamble), preparePreambleFromSubtree(
            request,
            segment,
            collectedPreambleSegments
          );
      default:
        return true;
    }
  }
  function preparePreamble(request) {
    if (request.completedRootSegment && null === request.completedPreambleSegments) {
      var collectedPreambleSegments = [], originalRequestByteSize = request.byteSize, hasPendingPreambles = preparePreambleFromSegment(
        request,
        request.completedRootSegment,
        collectedPreambleSegments
      ), preamble = request.renderState.preamble;
      false === hasPendingPreambles || preamble.headChunks && preamble.bodyChunks ? request.completedPreambleSegments = collectedPreambleSegments : request.byteSize = originalRequestByteSize;
    }
  }
  function flushSubtree(request, destination, segment, hoistableState) {
    segment.parentFlushed = true;
    switch (segment.status) {
      case 0:
        segment.id = request.nextSegmentId++;
      case 5:
        return hoistableState = segment.id, segment.lastPushedText = false, segment.textEmbedded = false, request = request.renderState, destination.push('<template id="'), destination.push(request.placeholderPrefix), request = hoistableState.toString(16), destination.push(request), destination.push('"></template>');
      case 1:
        segment.status = 2;
        var r = true, chunks = segment.chunks, chunkIdx = 0;
        segment = segment.children;
        for (var childIdx = 0; childIdx < segment.length; childIdx++) {
          for (r = segment[childIdx]; chunkIdx < r.index; chunkIdx++)
            destination.push(chunks[chunkIdx]);
          r = flushSegment(request, destination, r, hoistableState);
        }
        for (; chunkIdx < chunks.length - 1; chunkIdx++)
          destination.push(chunks[chunkIdx]);
        chunkIdx < chunks.length && (r = destination.push(chunks[chunkIdx]));
        return r;
      case 3:
        return true;
      default:
        throw Error(
          "Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React."
        );
    }
  }
  var flushedByteSize = 0;
  function flushSegment(request, destination, segment, hoistableState) {
    var boundary = segment.boundary;
    if (null === boundary)
      return flushSubtree(request, destination, segment, hoistableState);
    boundary.parentFlushed = true;
    if (4 === boundary.status) {
      var row = boundary.row;
      null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
      request.renderState.generateStaticMarkup || (boundary = boundary.errorDigest, destination.push("<!--$!-->"), destination.push("<template"), boundary && (destination.push(' data-dgst="'), boundary = escapeTextForBrowser(boundary), destination.push(boundary), destination.push('"')), destination.push("></template>"));
      flushSubtree(request, destination, segment, hoistableState);
      request = request.renderState.generateStaticMarkup ? true : destination.push("<!--/$-->");
      return request;
    }
    if (1 !== boundary.status)
      return 0 === boundary.status && (boundary.rootSegmentID = request.nextSegmentId++), 0 < boundary.completedSegments.length && request.partialBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
        destination,
        request.renderState,
        boundary.rootSegmentID
      ), hoistableState && hoistHoistables(hoistableState, boundary.fallbackState), flushSubtree(request, destination, segment, hoistableState), destination.push("<!--/$-->");
    if (!flushingPartialBoundaries && isEligibleForOutlining(request, boundary) && flushedByteSize + boundary.byteSize > request.progressiveChunkSize)
      return boundary.rootSegmentID = request.nextSegmentId++, request.completedBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
        destination,
        request.renderState,
        boundary.rootSegmentID
      ), flushSubtree(request, destination, segment, hoistableState), destination.push("<!--/$-->");
    flushedByteSize += boundary.byteSize;
    hoistableState && hoistHoistables(hoistableState, boundary.contentState);
    segment = boundary.row;
    null !== segment && isEligibleForOutlining(request, boundary) && 0 === --segment.pendingTasks && finishSuspenseListRow(request, segment);
    request.renderState.generateStaticMarkup || destination.push("<!--$-->");
    segment = boundary.completedSegments;
    if (1 !== segment.length)
      throw Error(
        "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
      );
    flushSegment(request, destination, segment[0], hoistableState);
    request = request.renderState.generateStaticMarkup ? true : destination.push("<!--/$-->");
    return request;
  }
  function flushSegmentContainer(request, destination, segment, hoistableState) {
    writeStartSegment(
      destination,
      request.renderState,
      segment.parentFormatContext,
      segment.id
    );
    flushSegment(request, destination, segment, hoistableState);
    return writeEndSegment(destination, segment.parentFormatContext);
  }
  function flushCompletedBoundary(request, destination, boundary) {
    flushedByteSize = boundary.byteSize;
    for (var completedSegments = boundary.completedSegments, i = 0; i < completedSegments.length; i++)
      flushPartiallyCompletedSegment(
        request,
        destination,
        boundary,
        completedSegments[i]
      );
    completedSegments.length = 0;
    completedSegments = boundary.row;
    null !== completedSegments && isEligibleForOutlining(request, boundary) && 0 === --completedSegments.pendingTasks && finishSuspenseListRow(request, completedSegments);
    writeHoistablesForBoundary(
      destination,
      boundary.contentState,
      request.renderState
    );
    completedSegments = request.resumableState;
    request = request.renderState;
    i = boundary.rootSegmentID;
    boundary = boundary.contentState;
    var requiresStyleInsertion = request.stylesToHoist;
    request.stylesToHoist = false;
    destination.push(request.startInlineScript);
    destination.push(">");
    requiresStyleInsertion ? (0 === (completedSegments.instructions & 4) && (completedSegments.instructions |= 4, destination.push(
      '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};'
    )), 0 === (completedSegments.instructions & 2) && (completedSegments.instructions |= 2, destination.push(
      '$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};\n$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};'
    )), 0 === (completedSegments.instructions & 8) ? (completedSegments.instructions |= 8, destination.push(
      '$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=\n"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=\n"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("'
    )) : destination.push('$RR("')) : (0 === (completedSegments.instructions & 2) && (completedSegments.instructions |= 2, destination.push(
      '$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};\n$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};'
    )), destination.push('$RC("'));
    completedSegments = i.toString(16);
    destination.push(request.boundaryPrefix);
    destination.push(completedSegments);
    destination.push('","');
    destination.push(request.segmentPrefix);
    destination.push(completedSegments);
    requiresStyleInsertion ? (destination.push('",'), writeStyleResourceDependenciesInJS(destination, boundary)) : destination.push('"');
    boundary = destination.push(")<\/script>");
    return writeBootstrap(destination, request) && boundary;
  }
  function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
    if (2 === segment.status) return true;
    var hoistableState = boundary.contentState, segmentID = segment.id;
    if (-1 === segmentID) {
      if (-1 === (segment.id = boundary.rootSegmentID))
        throw Error(
          "A root segment ID must have been assigned by now. This is a bug in React."
        );
      return flushSegmentContainer(request, destination, segment, hoistableState);
    }
    if (segmentID === boundary.rootSegmentID)
      return flushSegmentContainer(request, destination, segment, hoistableState);
    flushSegmentContainer(request, destination, segment, hoistableState);
    boundary = request.resumableState;
    request = request.renderState;
    destination.push(request.startInlineScript);
    destination.push(">");
    0 === (boundary.instructions & 1) ? (boundary.instructions |= 1, destination.push(
      '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'
    )) : destination.push('$RS("');
    destination.push(request.segmentPrefix);
    segmentID = segmentID.toString(16);
    destination.push(segmentID);
    destination.push('","');
    destination.push(request.placeholderPrefix);
    destination.push(segmentID);
    destination = destination.push('")<\/script>');
    return destination;
  }
  var flushingPartialBoundaries = false;
  function flushCompletedQueues(request, destination) {
    try {
      if (!(0 < request.pendingRootTasks)) {
        var i, completedRootSegment = request.completedRootSegment;
        if (null !== completedRootSegment) {
          if (5 === completedRootSegment.status) return;
          var completedPreambleSegments = request.completedPreambleSegments;
          if (null === completedPreambleSegments) return;
          flushedByteSize = request.byteSize;
          var resumableState = request.resumableState, renderState = request.renderState, preamble = renderState.preamble, htmlChunks = preamble.htmlChunks, headChunks = preamble.headChunks, i$jscomp$0;
          if (htmlChunks) {
            for (i$jscomp$0 = 0; i$jscomp$0 < htmlChunks.length; i$jscomp$0++)
              destination.push(htmlChunks[i$jscomp$0]);
            if (headChunks)
              for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
                destination.push(headChunks[i$jscomp$0]);
            else {
              var chunk2 = startChunkForTag("head");
              destination.push(chunk2);
              destination.push(">");
            }
          } else if (headChunks)
            for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
              destination.push(headChunks[i$jscomp$0]);
          var charsetChunks = renderState.charsetChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < charsetChunks.length; i$jscomp$0++)
            destination.push(charsetChunks[i$jscomp$0]);
          charsetChunks.length = 0;
          renderState.preconnects.forEach(flushResource, destination);
          renderState.preconnects.clear();
          var viewportChunks = renderState.viewportChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < viewportChunks.length; i$jscomp$0++)
            destination.push(viewportChunks[i$jscomp$0]);
          viewportChunks.length = 0;
          renderState.fontPreloads.forEach(flushResource, destination);
          renderState.fontPreloads.clear();
          renderState.highImagePreloads.forEach(flushResource, destination);
          renderState.highImagePreloads.clear();
          currentlyFlushingRenderState = renderState;
          renderState.styles.forEach(flushStylesInPreamble, destination);
          currentlyFlushingRenderState = null;
          var importMapChunks = renderState.importMapChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < importMapChunks.length; i$jscomp$0++)
            destination.push(importMapChunks[i$jscomp$0]);
          importMapChunks.length = 0;
          renderState.bootstrapScripts.forEach(flushResource, destination);
          renderState.scripts.forEach(flushResource, destination);
          renderState.scripts.clear();
          renderState.bulkPreloads.forEach(flushResource, destination);
          renderState.bulkPreloads.clear();
          resumableState.instructions |= 32;
          var hoistableChunks = renderState.hoistableChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < hoistableChunks.length; i$jscomp$0++)
            destination.push(hoistableChunks[i$jscomp$0]);
          for (resumableState = hoistableChunks.length = 0; resumableState < completedPreambleSegments.length; resumableState++) {
            var segments = completedPreambleSegments[resumableState];
            for (renderState = 0; renderState < segments.length; renderState++)
              flushSegment(request, destination, segments[renderState], null);
          }
          var preamble$jscomp$0 = request.renderState.preamble, headChunks$jscomp$0 = preamble$jscomp$0.headChunks;
          if (preamble$jscomp$0.htmlChunks || headChunks$jscomp$0) {
            var chunk$jscomp$0 = endChunkForTag("head");
            destination.push(chunk$jscomp$0);
          }
          var bodyChunks = preamble$jscomp$0.bodyChunks;
          if (bodyChunks)
            for (completedPreambleSegments = 0; completedPreambleSegments < bodyChunks.length; completedPreambleSegments++)
              destination.push(bodyChunks[completedPreambleSegments]);
          flushSegment(request, destination, completedRootSegment, null);
          request.completedRootSegment = null;
          var renderState$jscomp$0 = request.renderState;
          if (0 !== request.allPendingTasks || 0 !== request.clientRenderedBoundaries.length || 0 !== request.completedBoundaries.length || null !== request.trackedPostpones && (0 !== request.trackedPostpones.rootNodes.length || null !== request.trackedPostpones.rootSlots)) {
            var resumableState$jscomp$0 = request.resumableState;
            if (0 === (resumableState$jscomp$0.instructions & 64)) {
              resumableState$jscomp$0.instructions |= 64;
              destination.push(renderState$jscomp$0.startInlineScript);
              if (0 === (resumableState$jscomp$0.instructions & 32)) {
                resumableState$jscomp$0.instructions |= 32;
                var shellId = "_" + resumableState$jscomp$0.idPrefix + "R_";
                destination.push(' id="');
                var chunk$jscomp$1 = escapeTextForBrowser(shellId);
                destination.push(chunk$jscomp$1);
                destination.push('"');
              }
              destination.push(">");
              destination.push(
                "requestAnimationFrame(function(){$RT=performance.now()});"
              );
              destination.push("<\/script>");
            }
          }
          writeBootstrap(destination, renderState$jscomp$0);
        }
        var renderState$jscomp$1 = request.renderState;
        completedRootSegment = 0;
        var viewportChunks$jscomp$0 = renderState$jscomp$1.viewportChunks;
        for (completedRootSegment = 0; completedRootSegment < viewportChunks$jscomp$0.length; completedRootSegment++)
          destination.push(viewportChunks$jscomp$0[completedRootSegment]);
        viewportChunks$jscomp$0.length = 0;
        renderState$jscomp$1.preconnects.forEach(flushResource, destination);
        renderState$jscomp$1.preconnects.clear();
        renderState$jscomp$1.fontPreloads.forEach(flushResource, destination);
        renderState$jscomp$1.fontPreloads.clear();
        renderState$jscomp$1.highImagePreloads.forEach(
          flushResource,
          destination
        );
        renderState$jscomp$1.highImagePreloads.clear();
        renderState$jscomp$1.styles.forEach(preloadLateStyles, destination);
        renderState$jscomp$1.scripts.forEach(flushResource, destination);
        renderState$jscomp$1.scripts.clear();
        renderState$jscomp$1.bulkPreloads.forEach(flushResource, destination);
        renderState$jscomp$1.bulkPreloads.clear();
        var hoistableChunks$jscomp$0 = renderState$jscomp$1.hoistableChunks;
        for (completedRootSegment = 0; completedRootSegment < hoistableChunks$jscomp$0.length; completedRootSegment++)
          destination.push(hoistableChunks$jscomp$0[completedRootSegment]);
        hoistableChunks$jscomp$0.length = 0;
        var clientRenderedBoundaries = request.clientRenderedBoundaries;
        for (i = 0; i < clientRenderedBoundaries.length; i++) {
          var boundary = clientRenderedBoundaries[i];
          renderState$jscomp$1 = destination;
          var resumableState$jscomp$1 = request.resumableState, renderState$jscomp$2 = request.renderState, id = boundary.rootSegmentID, errorDigest = boundary.errorDigest;
          renderState$jscomp$1.push(renderState$jscomp$2.startInlineScript);
          renderState$jscomp$1.push(">");
          0 === (resumableState$jscomp$1.instructions & 4) ? (resumableState$jscomp$1.instructions |= 4, renderState$jscomp$1.push(
            '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("'
          )) : renderState$jscomp$1.push('$RX("');
          renderState$jscomp$1.push(renderState$jscomp$2.boundaryPrefix);
          var chunk$jscomp$2 = id.toString(16);
          renderState$jscomp$1.push(chunk$jscomp$2);
          renderState$jscomp$1.push('"');
          if (errorDigest) {
            renderState$jscomp$1.push(",");
            var chunk$jscomp$3 = escapeJSStringsForInstructionScripts(
              errorDigest || ""
            );
            renderState$jscomp$1.push(chunk$jscomp$3);
          }
          var JSCompiler_inline_result = renderState$jscomp$1.push(")<\/script>");
          if (!JSCompiler_inline_result) {
            request.destination = null;
            i++;
            clientRenderedBoundaries.splice(0, i);
            return;
          }
        }
        clientRenderedBoundaries.splice(0, i);
        var completedBoundaries = request.completedBoundaries;
        for (i = 0; i < completedBoundaries.length; i++)
          if (!flushCompletedBoundary(request, destination, completedBoundaries[i])) {
            request.destination = null;
            i++;
            completedBoundaries.splice(0, i);
            return;
          }
        completedBoundaries.splice(0, i);
        flushingPartialBoundaries = true;
        var partialBoundaries = request.partialBoundaries;
        for (i = 0; i < partialBoundaries.length; i++) {
          var boundary$69 = partialBoundaries[i];
          a: {
            clientRenderedBoundaries = request;
            boundary = destination;
            flushedByteSize = boundary$69.byteSize;
            var completedSegments = boundary$69.completedSegments;
            for (JSCompiler_inline_result = 0; JSCompiler_inline_result < completedSegments.length; JSCompiler_inline_result++)
              if (!flushPartiallyCompletedSegment(
                clientRenderedBoundaries,
                boundary,
                boundary$69,
                completedSegments[JSCompiler_inline_result]
              )) {
                JSCompiler_inline_result++;
                completedSegments.splice(0, JSCompiler_inline_result);
                var JSCompiler_inline_result$jscomp$0 = false;
                break a;
              }
            completedSegments.splice(0, JSCompiler_inline_result);
            var row = boundary$69.row;
            null !== row && row.together && 1 === boundary$69.pendingTasks && (1 === row.pendingTasks ? unblockSuspenseListRow(
              clientRenderedBoundaries,
              row,
              row.hoistables
            ) : row.pendingTasks--);
            JSCompiler_inline_result$jscomp$0 = writeHoistablesForBoundary(
              boundary,
              boundary$69.contentState,
              clientRenderedBoundaries.renderState
            );
          }
          if (!JSCompiler_inline_result$jscomp$0) {
            request.destination = null;
            i++;
            partialBoundaries.splice(0, i);
            return;
          }
        }
        partialBoundaries.splice(0, i);
        flushingPartialBoundaries = false;
        var largeBoundaries = request.completedBoundaries;
        for (i = 0; i < largeBoundaries.length; i++)
          if (!flushCompletedBoundary(request, destination, largeBoundaries[i])) {
            request.destination = null;
            i++;
            largeBoundaries.splice(0, i);
            return;
          }
        largeBoundaries.splice(0, i);
      }
    } finally {
      flushingPartialBoundaries = false, 0 === request.allPendingTasks && 0 === request.clientRenderedBoundaries.length && 0 === request.completedBoundaries.length && (request.flushScheduled = false, i = request.resumableState, i.hasBody && (partialBoundaries = endChunkForTag("body"), destination.push(partialBoundaries)), i.hasHtml && (i = endChunkForTag("html"), destination.push(i)), request.status = 14, destination.push(null), request.destination = null);
    }
  }
  function enqueueFlush(request) {
    if (false === request.flushScheduled && 0 === request.pingedTasks.length && null !== request.destination) {
      request.flushScheduled = true;
      var destination = request.destination;
      destination ? flushCompletedQueues(request, destination) : request.flushScheduled = false;
    }
  }
  function startFlowing(request, destination) {
    if (13 === request.status)
      request.status = 14, destination.destroy(request.fatalError);
    else if (14 !== request.status && null === request.destination) {
      request.destination = destination;
      try {
        flushCompletedQueues(request, destination);
      } catch (error) {
        logRecoverableError(request, error, {}), fatalError(request, error);
      }
    }
  }
  function abort(request, reason) {
    if (11 === request.status || 10 === request.status) request.status = 12;
    try {
      var abortableTasks = request.abortableTasks;
      if (0 < abortableTasks.size) {
        var error = void 0 === reason ? Error("The render was aborted by the server without a reason.") : "object" === typeof reason && null !== reason && "function" === typeof reason.then ? Error("The render was aborted by the server with a promise.") : reason;
        request.fatalError = error;
        abortableTasks.forEach(function(task) {
          return abortTask(task, request, error);
        });
        abortableTasks.clear();
      }
      null !== request.destination && flushCompletedQueues(request, request.destination);
    } catch (error$71) {
      logRecoverableError(request, error$71, {}), fatalError(request, error$71);
    }
  }
  function addToReplayParent(node2, parentKeyPath, trackedPostpones) {
    if (null === parentKeyPath) trackedPostpones.rootNodes.push(node2);
    else {
      var workingMap = trackedPostpones.workingMap, parentNode = workingMap.get(parentKeyPath);
      void 0 === parentNode && (parentNode = [parentKeyPath[1], parentKeyPath[2], [], null], workingMap.set(parentKeyPath, parentNode), addToReplayParent(parentNode, parentKeyPath[0], trackedPostpones));
      parentNode[2].push(node2);
    }
  }
  function onError() {
  }
  function renderToStringImpl(children, options, generateStaticMarkup, abortReason) {
    var didFatal = false, fatalError2 = null, result = "", readyToStream = false;
    options = createResumableState(options ? options.identifierPrefix : void 0);
    children = createRequest(
      children,
      options,
      createRenderState(options, generateStaticMarkup),
      createFormatContext(0, null, 0, null),
      Infinity,
      onError,
      void 0,
      function() {
        readyToStream = true;
      },
      void 0,
      void 0,
      void 0
    );
    children.flushScheduled = null !== children.destination;
    performWork(children);
    10 === children.status && (children.status = 11);
    null === children.trackedPostpones && safelyEmitEarlyPreloads(children, 0 === children.pendingRootTasks);
    abort(children, abortReason);
    startFlowing(children, {
      push: function(chunk2) {
        null !== chunk2 && (result += chunk2);
        return true;
      },
      destroy: function(error) {
        didFatal = true;
        fatalError2 = error;
      }
    });
    if (didFatal && fatalError2 !== abortReason) throw fatalError2;
    if (!readyToStream)
      throw Error(
        "A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition."
      );
    return result;
  }
  reactDomServerLegacy_node_production.renderToStaticMarkup = function(children, options) {
    return renderToStringImpl(
      children,
      options,
      true,
      'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server'
    );
  };
  reactDomServerLegacy_node_production.renderToString = function(children, options) {
    return renderToStringImpl(
      children,
      options,
      false,
      'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server'
    );
  };
  reactDomServerLegacy_node_production.version = "19.2.4";
  return reactDomServerLegacy_node_production;
}
var reactDomServer_node_production = {};
var hasRequiredReactDomServer_node_production;
function requireReactDomServer_node_production() {
  if (hasRequiredReactDomServer_node_production) return reactDomServer_node_production;
  hasRequiredReactDomServer_node_production = 1;
  var util = require$$0$1, crypto2 = require$$1$1, async_hooks = require$$2, React2 = requireReact(), ReactDOM = requireReactDom(), stream$1 = stream, REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_SCOPE_TYPE = /* @__PURE__ */ Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = /* @__PURE__ */ Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
  function getIteratorFn(maybeIterable) {
    if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
    maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
    return "function" === typeof maybeIterable ? maybeIterable : null;
  }
  var isArrayImpl = Array.isArray, scheduleMicrotask = queueMicrotask;
  function flushBuffered(destination) {
    "function" === typeof destination.flush && destination.flush();
  }
  var currentView = null, writtenBytes = 0, destinationHasCapacity$1 = true;
  function writeChunk(destination, chunk2) {
    if ("string" === typeof chunk2) {
      if (0 !== chunk2.length)
        if (2048 < 3 * chunk2.length)
          0 < writtenBytes && (writeToDestination(
            destination,
            currentView.subarray(0, writtenBytes)
          ), currentView = new Uint8Array(2048), writtenBytes = 0), writeToDestination(destination, chunk2);
        else {
          var target = currentView;
          0 < writtenBytes && (target = currentView.subarray(writtenBytes));
          target = textEncoder2.encodeInto(chunk2, target);
          var read = target.read;
          writtenBytes += target.written;
          read < chunk2.length && (writeToDestination(
            destination,
            currentView.subarray(0, writtenBytes)
          ), currentView = new Uint8Array(2048), writtenBytes = textEncoder2.encodeInto(
            chunk2.slice(read),
            currentView
          ).written);
          2048 === writtenBytes && (writeToDestination(destination, currentView), currentView = new Uint8Array(2048), writtenBytes = 0);
        }
    } else
      0 !== chunk2.byteLength && (2048 < chunk2.byteLength ? (0 < writtenBytes && (writeToDestination(
        destination,
        currentView.subarray(0, writtenBytes)
      ), currentView = new Uint8Array(2048), writtenBytes = 0), writeToDestination(destination, chunk2)) : (target = currentView.length - writtenBytes, target < chunk2.byteLength && (0 === target ? writeToDestination(destination, currentView) : (currentView.set(chunk2.subarray(0, target), writtenBytes), writtenBytes += target, writeToDestination(destination, currentView), chunk2 = chunk2.subarray(target)), currentView = new Uint8Array(2048), writtenBytes = 0), currentView.set(chunk2, writtenBytes), writtenBytes += chunk2.byteLength, 2048 === writtenBytes && (writeToDestination(destination, currentView), currentView = new Uint8Array(2048), writtenBytes = 0)));
  }
  function writeToDestination(destination, view) {
    destination = destination.write(view);
    destinationHasCapacity$1 = destinationHasCapacity$1 && destination;
  }
  function writeChunkAndReturn(destination, chunk2) {
    writeChunk(destination, chunk2);
    return destinationHasCapacity$1;
  }
  function completeWriting(destination) {
    currentView && 0 < writtenBytes && destination.write(currentView.subarray(0, writtenBytes));
    currentView = null;
    writtenBytes = 0;
    destinationHasCapacity$1 = true;
  }
  var textEncoder2 = new util.TextEncoder();
  function stringToPrecomputedChunk(content2) {
    return textEncoder2.encode(content2);
  }
  function byteLengthOfChunk(chunk2) {
    return "string" === typeof chunk2 ? Buffer.byteLength(chunk2, "utf8") : chunk2.byteLength;
  }
  var assign = Object.assign, hasOwnProperty2 = Object.prototype.hasOwnProperty, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
    "^[: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]*$"
  ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {};
  function isAttributeNameSafe(attributeName) {
    if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
      return true;
    if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName)) return false;
    if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
      return validatedAttributeNameCache[attributeName] = true;
    illegalAttributeNameCache[attributeName] = true;
    return false;
  }
  var unitlessNumbers = new Set(
    "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
      " "
    )
  ), aliases = /* @__PURE__ */ new Map([
    ["acceptCharset", "accept-charset"],
    ["htmlFor", "for"],
    ["httpEquiv", "http-equiv"],
    ["crossOrigin", "crossorigin"],
    ["accentHeight", "accent-height"],
    ["alignmentBaseline", "alignment-baseline"],
    ["arabicForm", "arabic-form"],
    ["baselineShift", "baseline-shift"],
    ["capHeight", "cap-height"],
    ["clipPath", "clip-path"],
    ["clipRule", "clip-rule"],
    ["colorInterpolation", "color-interpolation"],
    ["colorInterpolationFilters", "color-interpolation-filters"],
    ["colorProfile", "color-profile"],
    ["colorRendering", "color-rendering"],
    ["dominantBaseline", "dominant-baseline"],
    ["enableBackground", "enable-background"],
    ["fillOpacity", "fill-opacity"],
    ["fillRule", "fill-rule"],
    ["floodColor", "flood-color"],
    ["floodOpacity", "flood-opacity"],
    ["fontFamily", "font-family"],
    ["fontSize", "font-size"],
    ["fontSizeAdjust", "font-size-adjust"],
    ["fontStretch", "font-stretch"],
    ["fontStyle", "font-style"],
    ["fontVariant", "font-variant"],
    ["fontWeight", "font-weight"],
    ["glyphName", "glyph-name"],
    ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
    ["glyphOrientationVertical", "glyph-orientation-vertical"],
    ["horizAdvX", "horiz-adv-x"],
    ["horizOriginX", "horiz-origin-x"],
    ["imageRendering", "image-rendering"],
    ["letterSpacing", "letter-spacing"],
    ["lightingColor", "lighting-color"],
    ["markerEnd", "marker-end"],
    ["markerMid", "marker-mid"],
    ["markerStart", "marker-start"],
    ["overlinePosition", "overline-position"],
    ["overlineThickness", "overline-thickness"],
    ["paintOrder", "paint-order"],
    ["panose-1", "panose-1"],
    ["pointerEvents", "pointer-events"],
    ["renderingIntent", "rendering-intent"],
    ["shapeRendering", "shape-rendering"],
    ["stopColor", "stop-color"],
    ["stopOpacity", "stop-opacity"],
    ["strikethroughPosition", "strikethrough-position"],
    ["strikethroughThickness", "strikethrough-thickness"],
    ["strokeDasharray", "stroke-dasharray"],
    ["strokeDashoffset", "stroke-dashoffset"],
    ["strokeLinecap", "stroke-linecap"],
    ["strokeLinejoin", "stroke-linejoin"],
    ["strokeMiterlimit", "stroke-miterlimit"],
    ["strokeOpacity", "stroke-opacity"],
    ["strokeWidth", "stroke-width"],
    ["textAnchor", "text-anchor"],
    ["textDecoration", "text-decoration"],
    ["textRendering", "text-rendering"],
    ["transformOrigin", "transform-origin"],
    ["underlinePosition", "underline-position"],
    ["underlineThickness", "underline-thickness"],
    ["unicodeBidi", "unicode-bidi"],
    ["unicodeRange", "unicode-range"],
    ["unitsPerEm", "units-per-em"],
    ["vAlphabetic", "v-alphabetic"],
    ["vHanging", "v-hanging"],
    ["vIdeographic", "v-ideographic"],
    ["vMathematical", "v-mathematical"],
    ["vectorEffect", "vector-effect"],
    ["vertAdvY", "vert-adv-y"],
    ["vertOriginX", "vert-origin-x"],
    ["vertOriginY", "vert-origin-y"],
    ["wordSpacing", "word-spacing"],
    ["writingMode", "writing-mode"],
    ["xmlnsXlink", "xmlns:xlink"],
    ["xHeight", "x-height"]
  ]), matchHtmlRegExp = /["'&<>]/;
  function escapeTextForBrowser(text2) {
    if ("boolean" === typeof text2 || "number" === typeof text2 || "bigint" === typeof text2)
      return "" + text2;
    text2 = "" + text2;
    var match = matchHtmlRegExp.exec(text2);
    if (match) {
      var html2 = "", index2, lastIndex = 0;
      for (index2 = match.index; index2 < text2.length; index2++) {
        switch (text2.charCodeAt(index2)) {
          case 34:
            match = "&quot;";
            break;
          case 38:
            match = "&amp;";
            break;
          case 39:
            match = "&#x27;";
            break;
          case 60:
            match = "&lt;";
            break;
          case 62:
            match = "&gt;";
            break;
          default:
            continue;
        }
        lastIndex !== index2 && (html2 += text2.slice(lastIndex, index2));
        lastIndex = index2 + 1;
        html2 += match;
      }
      text2 = lastIndex !== index2 ? html2 + text2.slice(lastIndex, index2) : html2;
    }
    return text2;
  }
  var uppercasePattern = /([A-Z])/g, msPattern = /^ms-/, isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;
  function sanitizeURL(url) {
    return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
  }
  var ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, sharedNotPendingObject = {
    pending: false,
    data: null,
    method: null,
    action: null
  }, previousDispatcher = ReactDOMSharedInternals.d;
  ReactDOMSharedInternals.d = {
    f: previousDispatcher.f,
    r: previousDispatcher.r,
    D: prefetchDNS,
    C: preconnect,
    L: preload,
    m: preloadModule,
    X: preinitScript,
    S: preinitStyle,
    M: preinitModuleScript
  };
  var PRELOAD_NO_CREDS = [], currentlyFlushingRenderState = null;
  stringToPrecomputedChunk('"></template>');
  var startInlineScript = stringToPrecomputedChunk("<script"), endInlineScript = stringToPrecomputedChunk("<\/script>"), startScriptSrc = stringToPrecomputedChunk('<script src="'), startModuleSrc = stringToPrecomputedChunk('<script type="module" src="'), scriptNonce = stringToPrecomputedChunk(' nonce="'), scriptIntegirty = stringToPrecomputedChunk(' integrity="'), scriptCrossOrigin = stringToPrecomputedChunk(' crossorigin="'), endAsyncScript = stringToPrecomputedChunk(' async=""><\/script>'), startInlineStyle = stringToPrecomputedChunk("<style"), scriptRegex = /(<\/|<)(s)(cript)/gi;
  function scriptReplacer(match, prefix2, s2, suffix2) {
    return "" + prefix2 + ("s" === s2 ? "\\u0073" : "\\u0053") + suffix2;
  }
  var importMapScriptStart = stringToPrecomputedChunk(
    '<script type="importmap">'
  ), importMapScriptEnd = stringToPrecomputedChunk("<\/script>");
  function createRenderState(resumableState, nonce, externalRuntimeConfig, importMap, onHeaders, maxHeadersLength) {
    externalRuntimeConfig = "string" === typeof nonce ? nonce : nonce && nonce.script;
    var inlineScriptWithNonce = void 0 === externalRuntimeConfig ? startInlineScript : stringToPrecomputedChunk(
      '<script nonce="' + escapeTextForBrowser(externalRuntimeConfig) + '"'
    ), nonceStyle = "string" === typeof nonce ? void 0 : nonce && nonce.style, inlineStyleWithNonce = void 0 === nonceStyle ? startInlineStyle : stringToPrecomputedChunk(
      '<style nonce="' + escapeTextForBrowser(nonceStyle) + '"'
    ), idPrefix = resumableState.idPrefix, bootstrapChunks = [], bootstrapScriptContent = resumableState.bootstrapScriptContent, bootstrapScripts = resumableState.bootstrapScripts, bootstrapModules = resumableState.bootstrapModules;
    void 0 !== bootstrapScriptContent && (bootstrapChunks.push(inlineScriptWithNonce), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
      endOfStartTag,
      ("" + bootstrapScriptContent).replace(scriptRegex, scriptReplacer),
      endInlineScript
    ));
    bootstrapScriptContent = [];
    void 0 !== importMap && (bootstrapScriptContent.push(importMapScriptStart), bootstrapScriptContent.push(
      ("" + JSON.stringify(importMap)).replace(scriptRegex, scriptReplacer)
    ), bootstrapScriptContent.push(importMapScriptEnd));
    importMap = onHeaders ? {
      preconnects: "",
      fontPreloads: "",
      highImagePreloads: "",
      remainingCapacity: 2 + ("number" === typeof maxHeadersLength ? maxHeadersLength : 2e3)
    } : null;
    onHeaders = {
      placeholderPrefix: stringToPrecomputedChunk(idPrefix + "P:"),
      segmentPrefix: stringToPrecomputedChunk(idPrefix + "S:"),
      boundaryPrefix: stringToPrecomputedChunk(idPrefix + "B:"),
      startInlineScript: inlineScriptWithNonce,
      startInlineStyle: inlineStyleWithNonce,
      preamble: createPreambleState(),
      externalRuntimeScript: null,
      bootstrapChunks,
      importMapChunks: bootstrapScriptContent,
      onHeaders,
      headers: importMap,
      resets: {
        font: {},
        dns: {},
        connect: { default: {}, anonymous: {}, credentials: {} },
        image: {},
        style: {}
      },
      charsetChunks: [],
      viewportChunks: [],
      hoistableChunks: [],
      preconnects: /* @__PURE__ */ new Set(),
      fontPreloads: /* @__PURE__ */ new Set(),
      highImagePreloads: /* @__PURE__ */ new Set(),
      styles: /* @__PURE__ */ new Map(),
      bootstrapScripts: /* @__PURE__ */ new Set(),
      scripts: /* @__PURE__ */ new Set(),
      bulkPreloads: /* @__PURE__ */ new Set(),
      preloads: {
        images: /* @__PURE__ */ new Map(),
        stylesheets: /* @__PURE__ */ new Map(),
        scripts: /* @__PURE__ */ new Map(),
        moduleScripts: /* @__PURE__ */ new Map()
      },
      nonce: { script: externalRuntimeConfig, style: nonceStyle },
      hoistableState: null,
      stylesToHoist: false
    };
    if (void 0 !== bootstrapScripts)
      for (importMap = 0; importMap < bootstrapScripts.length; importMap++)
        idPrefix = bootstrapScripts[importMap], nonceStyle = inlineScriptWithNonce = void 0, inlineStyleWithNonce = {
          rel: "preload",
          as: "script",
          fetchPriority: "low",
          nonce
        }, "string" === typeof idPrefix ? inlineStyleWithNonce.href = maxHeadersLength = idPrefix : (inlineStyleWithNonce.href = maxHeadersLength = idPrefix.src, inlineStyleWithNonce.integrity = nonceStyle = "string" === typeof idPrefix.integrity ? idPrefix.integrity : void 0, inlineStyleWithNonce.crossOrigin = inlineScriptWithNonce = "string" === typeof idPrefix || null == idPrefix.crossOrigin ? void 0 : "use-credentials" === idPrefix.crossOrigin ? "use-credentials" : ""), idPrefix = resumableState, bootstrapScriptContent = maxHeadersLength, idPrefix.scriptResources[bootstrapScriptContent] = null, idPrefix.moduleScriptResources[bootstrapScriptContent] = null, idPrefix = [], pushLinkImpl(idPrefix, inlineStyleWithNonce), onHeaders.bootstrapScripts.add(idPrefix), bootstrapChunks.push(
          startScriptSrc,
          escapeTextForBrowser(maxHeadersLength),
          attributeEnd
        ), externalRuntimeConfig && bootstrapChunks.push(
          scriptNonce,
          escapeTextForBrowser(externalRuntimeConfig),
          attributeEnd
        ), "string" === typeof nonceStyle && bootstrapChunks.push(
          scriptIntegirty,
          escapeTextForBrowser(nonceStyle),
          attributeEnd
        ), "string" === typeof inlineScriptWithNonce && bootstrapChunks.push(
          scriptCrossOrigin,
          escapeTextForBrowser(inlineScriptWithNonce),
          attributeEnd
        ), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(endAsyncScript);
    if (void 0 !== bootstrapModules)
      for (nonce = 0; nonce < bootstrapModules.length; nonce++)
        nonceStyle = bootstrapModules[nonce], maxHeadersLength = importMap = void 0, inlineScriptWithNonce = {
          rel: "modulepreload",
          fetchPriority: "low",
          nonce: externalRuntimeConfig
        }, "string" === typeof nonceStyle ? inlineScriptWithNonce.href = bootstrapScripts = nonceStyle : (inlineScriptWithNonce.href = bootstrapScripts = nonceStyle.src, inlineScriptWithNonce.integrity = maxHeadersLength = "string" === typeof nonceStyle.integrity ? nonceStyle.integrity : void 0, inlineScriptWithNonce.crossOrigin = importMap = "string" === typeof nonceStyle || null == nonceStyle.crossOrigin ? void 0 : "use-credentials" === nonceStyle.crossOrigin ? "use-credentials" : ""), nonceStyle = resumableState, inlineStyleWithNonce = bootstrapScripts, nonceStyle.scriptResources[inlineStyleWithNonce] = null, nonceStyle.moduleScriptResources[inlineStyleWithNonce] = null, nonceStyle = [], pushLinkImpl(nonceStyle, inlineScriptWithNonce), onHeaders.bootstrapScripts.add(nonceStyle), bootstrapChunks.push(
          startModuleSrc,
          escapeTextForBrowser(bootstrapScripts),
          attributeEnd
        ), externalRuntimeConfig && bootstrapChunks.push(
          scriptNonce,
          escapeTextForBrowser(externalRuntimeConfig),
          attributeEnd
        ), "string" === typeof maxHeadersLength && bootstrapChunks.push(
          scriptIntegirty,
          escapeTextForBrowser(maxHeadersLength),
          attributeEnd
        ), "string" === typeof importMap && bootstrapChunks.push(
          scriptCrossOrigin,
          escapeTextForBrowser(importMap),
          attributeEnd
        ), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(endAsyncScript);
    return onHeaders;
  }
  function createResumableState(identifierPrefix, externalRuntimeConfig, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
    return {
      idPrefix: void 0 === identifierPrefix ? "" : identifierPrefix,
      nextFormID: 0,
      streamingFormat: 0,
      bootstrapScriptContent,
      bootstrapScripts,
      bootstrapModules,
      instructions: 0,
      hasBody: false,
      hasHtml: false,
      unknownResources: {},
      dnsResources: {},
      connectResources: { default: {}, anonymous: {}, credentials: {} },
      imageResources: {},
      styleResources: {},
      scriptResources: {},
      moduleUnknownResources: {},
      moduleScriptResources: {}
    };
  }
  function createPreambleState() {
    return { htmlChunks: null, headChunks: null, bodyChunks: null };
  }
  function createFormatContext(insertionMode, selectedValue, tagScope, viewTransition) {
    return {
      insertionMode,
      selectedValue,
      tagScope,
      viewTransition
    };
  }
  function createRootFormatContext(namespaceURI) {
    return createFormatContext(
      "http://www.w3.org/2000/svg" === namespaceURI ? 4 : "http://www.w3.org/1998/Math/MathML" === namespaceURI ? 5 : 0,
      null,
      0,
      null
    );
  }
  function getChildFormatContext(parentContext, type2, props) {
    var subtreeScope = parentContext.tagScope & -25;
    switch (type2) {
      case "noscript":
        return createFormatContext(2, null, subtreeScope | 1, null);
      case "select":
        return createFormatContext(
          2,
          null != props.value ? props.value : props.defaultValue,
          subtreeScope,
          null
        );
      case "svg":
        return createFormatContext(4, null, subtreeScope, null);
      case "picture":
        return createFormatContext(2, null, subtreeScope | 2, null);
      case "math":
        return createFormatContext(5, null, subtreeScope, null);
      case "foreignObject":
        return createFormatContext(2, null, subtreeScope, null);
      case "table":
        return createFormatContext(6, null, subtreeScope, null);
      case "thead":
      case "tbody":
      case "tfoot":
        return createFormatContext(7, null, subtreeScope, null);
      case "colgroup":
        return createFormatContext(9, null, subtreeScope, null);
      case "tr":
        return createFormatContext(8, null, subtreeScope, null);
      case "head":
        if (2 > parentContext.insertionMode)
          return createFormatContext(3, null, subtreeScope, null);
        break;
      case "html":
        if (0 === parentContext.insertionMode)
          return createFormatContext(1, null, subtreeScope, null);
    }
    return 6 <= parentContext.insertionMode || 2 > parentContext.insertionMode ? createFormatContext(2, null, subtreeScope, null) : parentContext.tagScope !== subtreeScope ? createFormatContext(
      parentContext.insertionMode,
      parentContext.selectedValue,
      subtreeScope,
      null
    ) : parentContext;
  }
  function getSuspenseViewTransition(parentViewTransition) {
    return null === parentViewTransition ? null : {
      update: parentViewTransition.update,
      enter: "none",
      exit: "none",
      share: parentViewTransition.update,
      name: parentViewTransition.autoName,
      autoName: parentViewTransition.autoName,
      nameIdx: 0
    };
  }
  function getSuspenseFallbackFormatContext(resumableState, parentContext) {
    parentContext.tagScope & 32 && (resumableState.instructions |= 128);
    return createFormatContext(
      parentContext.insertionMode,
      parentContext.selectedValue,
      parentContext.tagScope | 12,
      getSuspenseViewTransition(parentContext.viewTransition)
    );
  }
  function getSuspenseContentFormatContext(resumableState, parentContext) {
    resumableState = getSuspenseViewTransition(parentContext.viewTransition);
    var subtreeScope = parentContext.tagScope | 16;
    null !== resumableState && "none" !== resumableState.share && (subtreeScope |= 64);
    return createFormatContext(
      parentContext.insertionMode,
      parentContext.selectedValue,
      subtreeScope,
      resumableState
    );
  }
  var textSeparator = stringToPrecomputedChunk("<!-- -->");
  function pushTextInstance(target, text2, renderState, textEmbedded) {
    if ("" === text2) return textEmbedded;
    textEmbedded && target.push(textSeparator);
    target.push(escapeTextForBrowser(text2));
    return true;
  }
  var styleNameCache = /* @__PURE__ */ new Map(), styleAttributeStart = stringToPrecomputedChunk(' style="'), styleAssign = stringToPrecomputedChunk(":"), styleSeparator = stringToPrecomputedChunk(";");
  function pushStyleAttribute(target, style) {
    if ("object" !== typeof style)
      throw Error(
        "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
      );
    var isFirst = true, styleName;
    for (styleName in style)
      if (hasOwnProperty2.call(style, styleName)) {
        var styleValue = style[styleName];
        if (null != styleValue && "boolean" !== typeof styleValue && "" !== styleValue) {
          if (0 === styleName.indexOf("--")) {
            var nameChunk = escapeTextForBrowser(styleName);
            styleValue = escapeTextForBrowser(("" + styleValue).trim());
          } else
            nameChunk = styleNameCache.get(styleName), void 0 === nameChunk && (nameChunk = stringToPrecomputedChunk(
              escapeTextForBrowser(
                styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-")
              )
            ), styleNameCache.set(styleName, nameChunk)), styleValue = "number" === typeof styleValue ? 0 === styleValue || unitlessNumbers.has(styleName) ? "" + styleValue : styleValue + "px" : escapeTextForBrowser(("" + styleValue).trim());
          isFirst ? (isFirst = false, target.push(
            styleAttributeStart,
            nameChunk,
            styleAssign,
            styleValue
          )) : target.push(styleSeparator, nameChunk, styleAssign, styleValue);
        }
      }
    isFirst || target.push(attributeEnd);
  }
  var attributeSeparator = stringToPrecomputedChunk(" "), attributeAssign = stringToPrecomputedChunk('="'), attributeEnd = stringToPrecomputedChunk('"'), attributeEmptyString = stringToPrecomputedChunk('=""');
  function pushBooleanAttribute(target, name2, value) {
    value && "function" !== typeof value && "symbol" !== typeof value && target.push(attributeSeparator, name2, attributeEmptyString);
  }
  function pushStringAttribute(target, name2, value) {
    "function" !== typeof value && "symbol" !== typeof value && "boolean" !== typeof value && target.push(
      attributeSeparator,
      name2,
      attributeAssign,
      escapeTextForBrowser(value),
      attributeEnd
    );
  }
  var actionJavaScriptURL = stringToPrecomputedChunk(
    escapeTextForBrowser(
      "javascript:throw new Error('React form unexpectedly submitted.')"
    )
  ), startHiddenInputChunk = stringToPrecomputedChunk('<input type="hidden"');
  function pushAdditionalFormField(value, key) {
    this.push(startHiddenInputChunk);
    validateAdditionalFormField(value);
    pushStringAttribute(this, "name", key);
    pushStringAttribute(this, "value", value);
    this.push(endOfStartTagSelfClosing);
  }
  function validateAdditionalFormField(value) {
    if ("string" !== typeof value)
      throw Error(
        "File/Blob fields are not yet supported in progressive forms. Will fallback to client hydration."
      );
  }
  function getCustomFormFields(resumableState, formAction) {
    if ("function" === typeof formAction.$$FORM_ACTION) {
      var id = resumableState.nextFormID++;
      resumableState = resumableState.idPrefix + id;
      try {
        var customFields = formAction.$$FORM_ACTION(resumableState);
        if (customFields) {
          var formData = customFields.data;
          null != formData && formData.forEach(validateAdditionalFormField);
        }
        return customFields;
      } catch (x2) {
        if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then)
          throw x2;
      }
    }
    return null;
  }
  function pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name2) {
    var formData = null;
    if ("function" === typeof formAction) {
      var customFields = getCustomFormFields(resumableState, formAction);
      null !== customFields ? (name2 = customFields.name, formAction = customFields.action || "", formEncType = customFields.encType, formMethod = customFields.method, formTarget = customFields.target, formData = customFields.data) : (target.push(
        attributeSeparator,
        "formAction",
        attributeAssign,
        actionJavaScriptURL,
        attributeEnd
      ), formTarget = formMethod = formEncType = formAction = name2 = null, injectFormReplayingRuntime(resumableState, renderState));
    }
    null != name2 && pushAttribute(target, "name", name2);
    null != formAction && pushAttribute(target, "formAction", formAction);
    null != formEncType && pushAttribute(target, "formEncType", formEncType);
    null != formMethod && pushAttribute(target, "formMethod", formMethod);
    null != formTarget && pushAttribute(target, "formTarget", formTarget);
    return formData;
  }
  function pushAttribute(target, name2, value) {
    switch (name2) {
      case "className":
        pushStringAttribute(target, "class", value);
        break;
      case "tabIndex":
        pushStringAttribute(target, "tabindex", value);
        break;
      case "dir":
      case "role":
      case "viewBox":
      case "width":
      case "height":
        pushStringAttribute(target, name2, value);
        break;
      case "style":
        pushStyleAttribute(target, value);
        break;
      case "src":
      case "href":
        if ("" === value) break;
      case "action":
      case "formAction":
        if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
          break;
        value = sanitizeURL("" + value);
        target.push(
          attributeSeparator,
          name2,
          attributeAssign,
          escapeTextForBrowser(value),
          attributeEnd
        );
        break;
      case "defaultValue":
      case "defaultChecked":
      case "innerHTML":
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "ref":
        break;
      case "autoFocus":
      case "multiple":
      case "muted":
        pushBooleanAttribute(target, name2.toLowerCase(), value);
        break;
      case "xlinkHref":
        if ("function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
          break;
        value = sanitizeURL("" + value);
        target.push(
          attributeSeparator,
          "xlink:href",
          attributeAssign,
          escapeTextForBrowser(value),
          attributeEnd
        );
        break;
      case "contentEditable":
      case "spellCheck":
      case "draggable":
      case "value":
      case "autoReverse":
      case "externalResourcesRequired":
      case "focusable":
      case "preserveAlpha":
        "function" !== typeof value && "symbol" !== typeof value && target.push(
          attributeSeparator,
          name2,
          attributeAssign,
          escapeTextForBrowser(value),
          attributeEnd
        );
        break;
      case "inert":
      case "allowFullScreen":
      case "async":
      case "autoPlay":
      case "controls":
      case "default":
      case "defer":
      case "disabled":
      case "disablePictureInPicture":
      case "disableRemotePlayback":
      case "formNoValidate":
      case "hidden":
      case "loop":
      case "noModule":
      case "noValidate":
      case "open":
      case "playsInline":
      case "readOnly":
      case "required":
      case "reversed":
      case "scoped":
      case "seamless":
      case "itemScope":
        value && "function" !== typeof value && "symbol" !== typeof value && target.push(attributeSeparator, name2, attributeEmptyString);
        break;
      case "capture":
      case "download":
        true === value ? target.push(attributeSeparator, name2, attributeEmptyString) : false !== value && "function" !== typeof value && "symbol" !== typeof value && target.push(
          attributeSeparator,
          name2,
          attributeAssign,
          escapeTextForBrowser(value),
          attributeEnd
        );
        break;
      case "cols":
      case "rows":
      case "size":
      case "span":
        "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value && target.push(
          attributeSeparator,
          name2,
          attributeAssign,
          escapeTextForBrowser(value),
          attributeEnd
        );
        break;
      case "rowSpan":
      case "start":
        "function" === typeof value || "symbol" === typeof value || isNaN(value) || target.push(
          attributeSeparator,
          name2,
          attributeAssign,
          escapeTextForBrowser(value),
          attributeEnd
        );
        break;
      case "xlinkActuate":
        pushStringAttribute(target, "xlink:actuate", value);
        break;
      case "xlinkArcrole":
        pushStringAttribute(target, "xlink:arcrole", value);
        break;
      case "xlinkRole":
        pushStringAttribute(target, "xlink:role", value);
        break;
      case "xlinkShow":
        pushStringAttribute(target, "xlink:show", value);
        break;
      case "xlinkTitle":
        pushStringAttribute(target, "xlink:title", value);
        break;
      case "xlinkType":
        pushStringAttribute(target, "xlink:type", value);
        break;
      case "xmlBase":
        pushStringAttribute(target, "xml:base", value);
        break;
      case "xmlLang":
        pushStringAttribute(target, "xml:lang", value);
        break;
      case "xmlSpace":
        pushStringAttribute(target, "xml:space", value);
        break;
      default:
        if (!(2 < name2.length) || "o" !== name2[0] && "O" !== name2[0] || "n" !== name2[1] && "N" !== name2[1]) {
          if (name2 = aliases.get(name2) || name2, isAttributeNameSafe(name2)) {
            switch (typeof value) {
              case "function":
              case "symbol":
                return;
              case "boolean":
                var prefix$8 = name2.toLowerCase().slice(0, 5);
                if ("data-" !== prefix$8 && "aria-" !== prefix$8) return;
            }
            target.push(
              attributeSeparator,
              name2,
              attributeAssign,
              escapeTextForBrowser(value),
              attributeEnd
            );
          }
        }
    }
  }
  var endOfStartTag = stringToPrecomputedChunk(">"), endOfStartTagSelfClosing = stringToPrecomputedChunk("/>");
  function pushInnerHTML(target, innerHTML, children) {
    if (null != innerHTML) {
      if (null != children)
        throw Error(
          "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
        );
      if ("object" !== typeof innerHTML || !("__html" in innerHTML))
        throw Error(
          "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
        );
      innerHTML = innerHTML.__html;
      null !== innerHTML && void 0 !== innerHTML && target.push("" + innerHTML);
    }
  }
  function flattenOptionChildren(children) {
    var content2 = "";
    React2.Children.forEach(children, function(child) {
      null != child && (content2 += child);
    });
    return content2;
  }
  var selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""'), formReplayingRuntimeScript = stringToPrecomputedChunk(
    `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`
  );
  function injectFormReplayingRuntime(resumableState, renderState) {
    if (0 === (resumableState.instructions & 16)) {
      resumableState.instructions |= 16;
      var preamble = renderState.preamble, bootstrapChunks = renderState.bootstrapChunks;
      (preamble.htmlChunks || preamble.headChunks) && 0 === bootstrapChunks.length ? (bootstrapChunks.push(renderState.startInlineScript), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
        endOfStartTag,
        formReplayingRuntimeScript,
        endInlineScript
      )) : bootstrapChunks.unshift(
        renderState.startInlineScript,
        endOfStartTag,
        formReplayingRuntimeScript,
        endInlineScript
      );
    }
  }
  var formStateMarkerIsMatching = stringToPrecomputedChunk("<!--F!-->"), formStateMarkerIsNotMatching = stringToPrecomputedChunk("<!--F-->");
  function pushLinkImpl(target, props) {
    target.push(startChunkForTag("link"));
    for (var propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
            case "dangerouslySetInnerHTML":
              throw Error(
                "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
              );
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(endOfStartTagSelfClosing);
    return null;
  }
  var styleRegex = /(<\/|<)(s)(tyle)/gi;
  function styleReplacer(match, prefix2, s2, suffix2) {
    return "" + prefix2 + ("s" === s2 ? "\\73 " : "\\53 ") + suffix2;
  }
  function pushSelfClosing(target, props, tag) {
    target.push(startChunkForTag(tag));
    for (var propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
            case "dangerouslySetInnerHTML":
              throw Error(
                tag + " is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
              );
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(endOfStartTagSelfClosing);
    return null;
  }
  function pushTitleImpl(target, props) {
    target.push(startChunkForTag("title"));
    var children = null, innerHTML = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              children = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(endOfStartTag);
    props = Array.isArray(children) ? 2 > children.length ? children[0] : null : children;
    "function" !== typeof props && "symbol" !== typeof props && null !== props && void 0 !== props && target.push(escapeTextForBrowser("" + props));
    pushInnerHTML(target, innerHTML, children);
    target.push(endChunkForTag("title"));
    return null;
  }
  var headPreambleContributionChunk = stringToPrecomputedChunk("<!--head-->"), bodyPreambleContributionChunk = stringToPrecomputedChunk("<!--body-->"), htmlPreambleContributionChunk = stringToPrecomputedChunk("<!--html-->");
  function pushScriptImpl(target, props) {
    target.push(startChunkForTag("script"));
    var children = null, innerHTML = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              children = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, children);
    "string" === typeof children && target.push(("" + children).replace(scriptRegex, scriptReplacer));
    target.push(endChunkForTag("script"));
    return null;
  }
  function pushStartSingletonElement(target, props, tag) {
    target.push(startChunkForTag(tag));
    var innerHTML = tag = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              tag = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, tag);
    return tag;
  }
  function pushStartGenericElement(target, props, tag) {
    target.push(startChunkForTag(tag));
    var innerHTML = tag = null, propKey;
    for (propKey in props)
      if (hasOwnProperty2.call(props, propKey)) {
        var propValue = props[propKey];
        if (null != propValue)
          switch (propKey) {
            case "children":
              tag = propValue;
              break;
            case "dangerouslySetInnerHTML":
              innerHTML = propValue;
              break;
            default:
              pushAttribute(target, propKey, propValue);
          }
      }
    target.push(endOfStartTag);
    pushInnerHTML(target, innerHTML, tag);
    return "string" === typeof tag ? (target.push(escapeTextForBrowser(tag)), null) : tag;
  }
  var leadingNewline = stringToPrecomputedChunk("\n"), VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = /* @__PURE__ */ new Map();
  function startChunkForTag(tag) {
    var tagStartChunk = validatedTagCache.get(tag);
    if (void 0 === tagStartChunk) {
      if (!VALID_TAG_REGEX.test(tag)) throw Error("Invalid tag: " + tag);
      tagStartChunk = stringToPrecomputedChunk("<" + tag);
      validatedTagCache.set(tag, tagStartChunk);
    }
    return tagStartChunk;
  }
  var doctypeChunk = stringToPrecomputedChunk("<!DOCTYPE html>");
  function pushStartInstance(target$jscomp$0, type2, props, resumableState, renderState, preambleState, hoistableState, formatContext, textEmbedded) {
    switch (type2) {
      case "div":
      case "span":
      case "svg":
      case "path":
        break;
      case "a":
        target$jscomp$0.push(startChunkForTag("a"));
        var children = null, innerHTML = null, propKey;
        for (propKey in props)
          if (hasOwnProperty2.call(props, propKey)) {
            var propValue = props[propKey];
            if (null != propValue)
              switch (propKey) {
                case "children":
                  children = propValue;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML = propValue;
                  break;
                case "href":
                  "" === propValue ? pushStringAttribute(target$jscomp$0, "href", "") : pushAttribute(target$jscomp$0, propKey, propValue);
                  break;
                default:
                  pushAttribute(target$jscomp$0, propKey, propValue);
              }
          }
        target$jscomp$0.push(endOfStartTag);
        pushInnerHTML(target$jscomp$0, innerHTML, children);
        if ("string" === typeof children) {
          target$jscomp$0.push(escapeTextForBrowser(children));
          var JSCompiler_inline_result = null;
        } else JSCompiler_inline_result = children;
        return JSCompiler_inline_result;
      case "g":
      case "p":
      case "li":
        break;
      case "select":
        target$jscomp$0.push(startChunkForTag("select"));
        var children$jscomp$0 = null, innerHTML$jscomp$0 = null, propKey$jscomp$0;
        for (propKey$jscomp$0 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$0)) {
            var propValue$jscomp$0 = props[propKey$jscomp$0];
            if (null != propValue$jscomp$0)
              switch (propKey$jscomp$0) {
                case "children":
                  children$jscomp$0 = propValue$jscomp$0;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$0 = propValue$jscomp$0;
                  break;
                case "defaultValue":
                case "value":
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$0,
                    propValue$jscomp$0
                  );
              }
          }
        target$jscomp$0.push(endOfStartTag);
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$0, children$jscomp$0);
        return children$jscomp$0;
      case "option":
        var selectedValue = formatContext.selectedValue;
        target$jscomp$0.push(startChunkForTag("option"));
        var children$jscomp$1 = null, value = null, selected = null, innerHTML$jscomp$1 = null, propKey$jscomp$1;
        for (propKey$jscomp$1 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$1)) {
            var propValue$jscomp$1 = props[propKey$jscomp$1];
            if (null != propValue$jscomp$1)
              switch (propKey$jscomp$1) {
                case "children":
                  children$jscomp$1 = propValue$jscomp$1;
                  break;
                case "selected":
                  selected = propValue$jscomp$1;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$1 = propValue$jscomp$1;
                  break;
                case "value":
                  value = propValue$jscomp$1;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$1,
                    propValue$jscomp$1
                  );
              }
          }
        if (null != selectedValue) {
          var stringValue = null !== value ? "" + value : flattenOptionChildren(children$jscomp$1);
          if (isArrayImpl(selectedValue))
            for (var i = 0; i < selectedValue.length; i++) {
              if ("" + selectedValue[i] === stringValue) {
                target$jscomp$0.push(selectedMarkerAttribute);
                break;
              }
            }
          else
            "" + selectedValue === stringValue && target$jscomp$0.push(selectedMarkerAttribute);
        } else selected && target$jscomp$0.push(selectedMarkerAttribute);
        target$jscomp$0.push(endOfStartTag);
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$1, children$jscomp$1);
        return children$jscomp$1;
      case "textarea":
        target$jscomp$0.push(startChunkForTag("textarea"));
        var value$jscomp$0 = null, defaultValue = null, children$jscomp$2 = null, propKey$jscomp$2;
        for (propKey$jscomp$2 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$2)) {
            var propValue$jscomp$2 = props[propKey$jscomp$2];
            if (null != propValue$jscomp$2)
              switch (propKey$jscomp$2) {
                case "children":
                  children$jscomp$2 = propValue$jscomp$2;
                  break;
                case "value":
                  value$jscomp$0 = propValue$jscomp$2;
                  break;
                case "defaultValue":
                  defaultValue = propValue$jscomp$2;
                  break;
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                  );
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$2,
                    propValue$jscomp$2
                  );
              }
          }
        null === value$jscomp$0 && null !== defaultValue && (value$jscomp$0 = defaultValue);
        target$jscomp$0.push(endOfStartTag);
        if (null != children$jscomp$2) {
          if (null != value$jscomp$0)
            throw Error(
              "If you supply `defaultValue` on a <textarea>, do not pass children."
            );
          if (isArrayImpl(children$jscomp$2)) {
            if (1 < children$jscomp$2.length)
              throw Error("<textarea> can only have at most one child.");
            value$jscomp$0 = "" + children$jscomp$2[0];
          }
          value$jscomp$0 = "" + children$jscomp$2;
        }
        "string" === typeof value$jscomp$0 && "\n" === value$jscomp$0[0] && target$jscomp$0.push(leadingNewline);
        null !== value$jscomp$0 && target$jscomp$0.push(escapeTextForBrowser("" + value$jscomp$0));
        return null;
      case "input":
        target$jscomp$0.push(startChunkForTag("input"));
        var name2 = null, formAction = null, formEncType = null, formMethod = null, formTarget = null, value$jscomp$1 = null, defaultValue$jscomp$0 = null, checked = null, defaultChecked = null, propKey$jscomp$3;
        for (propKey$jscomp$3 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$3)) {
            var propValue$jscomp$3 = props[propKey$jscomp$3];
            if (null != propValue$jscomp$3)
              switch (propKey$jscomp$3) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                  );
                case "name":
                  name2 = propValue$jscomp$3;
                  break;
                case "formAction":
                  formAction = propValue$jscomp$3;
                  break;
                case "formEncType":
                  formEncType = propValue$jscomp$3;
                  break;
                case "formMethod":
                  formMethod = propValue$jscomp$3;
                  break;
                case "formTarget":
                  formTarget = propValue$jscomp$3;
                  break;
                case "defaultChecked":
                  defaultChecked = propValue$jscomp$3;
                  break;
                case "defaultValue":
                  defaultValue$jscomp$0 = propValue$jscomp$3;
                  break;
                case "checked":
                  checked = propValue$jscomp$3;
                  break;
                case "value":
                  value$jscomp$1 = propValue$jscomp$3;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$3,
                    propValue$jscomp$3
                  );
              }
          }
        var formData = pushFormActionAttribute(
          target$jscomp$0,
          resumableState,
          renderState,
          formAction,
          formEncType,
          formMethod,
          formTarget,
          name2
        );
        null !== checked ? pushBooleanAttribute(target$jscomp$0, "checked", checked) : null !== defaultChecked && pushBooleanAttribute(target$jscomp$0, "checked", defaultChecked);
        null !== value$jscomp$1 ? pushAttribute(target$jscomp$0, "value", value$jscomp$1) : null !== defaultValue$jscomp$0 && pushAttribute(target$jscomp$0, "value", defaultValue$jscomp$0);
        target$jscomp$0.push(endOfStartTagSelfClosing);
        null != formData && formData.forEach(pushAdditionalFormField, target$jscomp$0);
        return null;
      case "button":
        target$jscomp$0.push(startChunkForTag("button"));
        var children$jscomp$3 = null, innerHTML$jscomp$2 = null, name$jscomp$0 = null, formAction$jscomp$0 = null, formEncType$jscomp$0 = null, formMethod$jscomp$0 = null, formTarget$jscomp$0 = null, propKey$jscomp$4;
        for (propKey$jscomp$4 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$4)) {
            var propValue$jscomp$4 = props[propKey$jscomp$4];
            if (null != propValue$jscomp$4)
              switch (propKey$jscomp$4) {
                case "children":
                  children$jscomp$3 = propValue$jscomp$4;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$2 = propValue$jscomp$4;
                  break;
                case "name":
                  name$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formAction":
                  formAction$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formEncType":
                  formEncType$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formMethod":
                  formMethod$jscomp$0 = propValue$jscomp$4;
                  break;
                case "formTarget":
                  formTarget$jscomp$0 = propValue$jscomp$4;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$4,
                    propValue$jscomp$4
                  );
              }
          }
        var formData$jscomp$0 = pushFormActionAttribute(
          target$jscomp$0,
          resumableState,
          renderState,
          formAction$jscomp$0,
          formEncType$jscomp$0,
          formMethod$jscomp$0,
          formTarget$jscomp$0,
          name$jscomp$0
        );
        target$jscomp$0.push(endOfStartTag);
        null != formData$jscomp$0 && formData$jscomp$0.forEach(pushAdditionalFormField, target$jscomp$0);
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$2, children$jscomp$3);
        if ("string" === typeof children$jscomp$3) {
          target$jscomp$0.push(escapeTextForBrowser(children$jscomp$3));
          var JSCompiler_inline_result$jscomp$0 = null;
        } else JSCompiler_inline_result$jscomp$0 = children$jscomp$3;
        return JSCompiler_inline_result$jscomp$0;
      case "form":
        target$jscomp$0.push(startChunkForTag("form"));
        var children$jscomp$4 = null, innerHTML$jscomp$3 = null, formAction$jscomp$1 = null, formEncType$jscomp$1 = null, formMethod$jscomp$1 = null, formTarget$jscomp$1 = null, propKey$jscomp$5;
        for (propKey$jscomp$5 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$5)) {
            var propValue$jscomp$5 = props[propKey$jscomp$5];
            if (null != propValue$jscomp$5)
              switch (propKey$jscomp$5) {
                case "children":
                  children$jscomp$4 = propValue$jscomp$5;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$3 = propValue$jscomp$5;
                  break;
                case "action":
                  formAction$jscomp$1 = propValue$jscomp$5;
                  break;
                case "encType":
                  formEncType$jscomp$1 = propValue$jscomp$5;
                  break;
                case "method":
                  formMethod$jscomp$1 = propValue$jscomp$5;
                  break;
                case "target":
                  formTarget$jscomp$1 = propValue$jscomp$5;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$5,
                    propValue$jscomp$5
                  );
              }
          }
        var formData$jscomp$1 = null, formActionName = null;
        if ("function" === typeof formAction$jscomp$1) {
          var customFields = getCustomFormFields(
            resumableState,
            formAction$jscomp$1
          );
          null !== customFields ? (formAction$jscomp$1 = customFields.action || "", formEncType$jscomp$1 = customFields.encType, formMethod$jscomp$1 = customFields.method, formTarget$jscomp$1 = customFields.target, formData$jscomp$1 = customFields.data, formActionName = customFields.name) : (target$jscomp$0.push(
            attributeSeparator,
            "action",
            attributeAssign,
            actionJavaScriptURL,
            attributeEnd
          ), formTarget$jscomp$1 = formMethod$jscomp$1 = formEncType$jscomp$1 = formAction$jscomp$1 = null, injectFormReplayingRuntime(resumableState, renderState));
        }
        null != formAction$jscomp$1 && pushAttribute(target$jscomp$0, "action", formAction$jscomp$1);
        null != formEncType$jscomp$1 && pushAttribute(target$jscomp$0, "encType", formEncType$jscomp$1);
        null != formMethod$jscomp$1 && pushAttribute(target$jscomp$0, "method", formMethod$jscomp$1);
        null != formTarget$jscomp$1 && pushAttribute(target$jscomp$0, "target", formTarget$jscomp$1);
        target$jscomp$0.push(endOfStartTag);
        null !== formActionName && (target$jscomp$0.push(startHiddenInputChunk), pushStringAttribute(target$jscomp$0, "name", formActionName), target$jscomp$0.push(endOfStartTagSelfClosing), null != formData$jscomp$1 && formData$jscomp$1.forEach(pushAdditionalFormField, target$jscomp$0));
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$3, children$jscomp$4);
        if ("string" === typeof children$jscomp$4) {
          target$jscomp$0.push(escapeTextForBrowser(children$jscomp$4));
          var JSCompiler_inline_result$jscomp$1 = null;
        } else JSCompiler_inline_result$jscomp$1 = children$jscomp$4;
        return JSCompiler_inline_result$jscomp$1;
      case "menuitem":
        target$jscomp$0.push(startChunkForTag("menuitem"));
        for (var propKey$jscomp$6 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$6)) {
            var propValue$jscomp$6 = props[propKey$jscomp$6];
            if (null != propValue$jscomp$6)
              switch (propKey$jscomp$6) {
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "menuitems cannot have `children` nor `dangerouslySetInnerHTML`."
                  );
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$6,
                    propValue$jscomp$6
                  );
              }
          }
        target$jscomp$0.push(endOfStartTag);
        return null;
      case "object":
        target$jscomp$0.push(startChunkForTag("object"));
        var children$jscomp$5 = null, innerHTML$jscomp$4 = null, propKey$jscomp$7;
        for (propKey$jscomp$7 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$7)) {
            var propValue$jscomp$7 = props[propKey$jscomp$7];
            if (null != propValue$jscomp$7)
              switch (propKey$jscomp$7) {
                case "children":
                  children$jscomp$5 = propValue$jscomp$7;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$4 = propValue$jscomp$7;
                  break;
                case "data":
                  var sanitizedValue = sanitizeURL("" + propValue$jscomp$7);
                  if ("" === sanitizedValue) break;
                  target$jscomp$0.push(
                    attributeSeparator,
                    "data",
                    attributeAssign,
                    escapeTextForBrowser(sanitizedValue),
                    attributeEnd
                  );
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$7,
                    propValue$jscomp$7
                  );
              }
          }
        target$jscomp$0.push(endOfStartTag);
        pushInnerHTML(target$jscomp$0, innerHTML$jscomp$4, children$jscomp$5);
        if ("string" === typeof children$jscomp$5) {
          target$jscomp$0.push(escapeTextForBrowser(children$jscomp$5));
          var JSCompiler_inline_result$jscomp$2 = null;
        } else JSCompiler_inline_result$jscomp$2 = children$jscomp$5;
        return JSCompiler_inline_result$jscomp$2;
      case "title":
        var noscriptTagInScope = formatContext.tagScope & 1, isFallback = formatContext.tagScope & 4;
        if (4 === formatContext.insertionMode || noscriptTagInScope || null != props.itemProp)
          var JSCompiler_inline_result$jscomp$3 = pushTitleImpl(
            target$jscomp$0,
            props
          );
        else
          isFallback ? JSCompiler_inline_result$jscomp$3 = null : (pushTitleImpl(renderState.hoistableChunks, props), JSCompiler_inline_result$jscomp$3 = void 0);
        return JSCompiler_inline_result$jscomp$3;
      case "link":
        var noscriptTagInScope$jscomp$0 = formatContext.tagScope & 1, isFallback$jscomp$0 = formatContext.tagScope & 4, rel = props.rel, href = props.href, precedence = props.precedence;
        if (4 === formatContext.insertionMode || noscriptTagInScope$jscomp$0 || null != props.itemProp || "string" !== typeof rel || "string" !== typeof href || "" === href) {
          pushLinkImpl(target$jscomp$0, props);
          var JSCompiler_inline_result$jscomp$4 = null;
        } else if ("stylesheet" === props.rel)
          if ("string" !== typeof precedence || null != props.disabled || props.onLoad || props.onError)
            JSCompiler_inline_result$jscomp$4 = pushLinkImpl(
              target$jscomp$0,
              props
            );
          else {
            var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(href) ? resumableState.styleResources[href] : void 0;
            if (null !== resourceState) {
              resumableState.styleResources[href] = null;
              styleQueue || (styleQueue = {
                precedence: escapeTextForBrowser(precedence),
                rules: [],
                hrefs: [],
                sheets: /* @__PURE__ */ new Map()
              }, renderState.styles.set(precedence, styleQueue));
              var resource = {
                state: 0,
                props: assign({}, props, {
                  "data-precedence": props.precedence,
                  precedence: null
                })
              };
              if (resourceState) {
                2 === resourceState.length && adoptPreloadCredentials(resource.props, resourceState);
                var preloadResource = renderState.preloads.stylesheets.get(href);
                preloadResource && 0 < preloadResource.length ? preloadResource.length = 0 : resource.state = 1;
              }
              styleQueue.sheets.set(href, resource);
              hoistableState && hoistableState.stylesheets.add(resource);
            } else if (styleQueue) {
              var resource$9 = styleQueue.sheets.get(href);
              resource$9 && hoistableState && hoistableState.stylesheets.add(resource$9);
            }
            textEmbedded && target$jscomp$0.push(textSeparator);
            JSCompiler_inline_result$jscomp$4 = null;
          }
        else
          props.onLoad || props.onError ? JSCompiler_inline_result$jscomp$4 = pushLinkImpl(
            target$jscomp$0,
            props
          ) : (textEmbedded && target$jscomp$0.push(textSeparator), JSCompiler_inline_result$jscomp$4 = isFallback$jscomp$0 ? null : pushLinkImpl(renderState.hoistableChunks, props));
        return JSCompiler_inline_result$jscomp$4;
      case "script":
        var noscriptTagInScope$jscomp$1 = formatContext.tagScope & 1, asyncProp = props.async;
        if ("string" !== typeof props.src || !props.src || !asyncProp || "function" === typeof asyncProp || "symbol" === typeof asyncProp || props.onLoad || props.onError || 4 === formatContext.insertionMode || noscriptTagInScope$jscomp$1 || null != props.itemProp)
          var JSCompiler_inline_result$jscomp$5 = pushScriptImpl(
            target$jscomp$0,
            props
          );
        else {
          var key = props.src;
          if ("module" === props.type) {
            var resources = resumableState.moduleScriptResources;
            var preloads = renderState.preloads.moduleScripts;
          } else
            resources = resumableState.scriptResources, preloads = renderState.preloads.scripts;
          var resourceState$jscomp$0 = resources.hasOwnProperty(key) ? resources[key] : void 0;
          if (null !== resourceState$jscomp$0) {
            resources[key] = null;
            var scriptProps = props;
            if (resourceState$jscomp$0) {
              2 === resourceState$jscomp$0.length && (scriptProps = assign({}, props), adoptPreloadCredentials(scriptProps, resourceState$jscomp$0));
              var preloadResource$jscomp$0 = preloads.get(key);
              preloadResource$jscomp$0 && (preloadResource$jscomp$0.length = 0);
            }
            var resource$jscomp$0 = [];
            renderState.scripts.add(resource$jscomp$0);
            pushScriptImpl(resource$jscomp$0, scriptProps);
          }
          textEmbedded && target$jscomp$0.push(textSeparator);
          JSCompiler_inline_result$jscomp$5 = null;
        }
        return JSCompiler_inline_result$jscomp$5;
      case "style":
        var noscriptTagInScope$jscomp$2 = formatContext.tagScope & 1, precedence$jscomp$0 = props.precedence, href$jscomp$0 = props.href, nonce = props.nonce;
        if (4 === formatContext.insertionMode || noscriptTagInScope$jscomp$2 || null != props.itemProp || "string" !== typeof precedence$jscomp$0 || "string" !== typeof href$jscomp$0 || "" === href$jscomp$0) {
          target$jscomp$0.push(startChunkForTag("style"));
          var children$jscomp$6 = null, innerHTML$jscomp$5 = null, propKey$jscomp$8;
          for (propKey$jscomp$8 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$8)) {
              var propValue$jscomp$8 = props[propKey$jscomp$8];
              if (null != propValue$jscomp$8)
                switch (propKey$jscomp$8) {
                  case "children":
                    children$jscomp$6 = propValue$jscomp$8;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$5 = propValue$jscomp$8;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$8,
                      propValue$jscomp$8
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          var child = Array.isArray(children$jscomp$6) ? 2 > children$jscomp$6.length ? children$jscomp$6[0] : null : children$jscomp$6;
          "function" !== typeof child && "symbol" !== typeof child && null !== child && void 0 !== child && target$jscomp$0.push(("" + child).replace(styleRegex, styleReplacer));
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$5, children$jscomp$6);
          target$jscomp$0.push(endChunkForTag("style"));
          var JSCompiler_inline_result$jscomp$6 = null;
        } else {
          var styleQueue$jscomp$0 = renderState.styles.get(precedence$jscomp$0);
          if (null !== (resumableState.styleResources.hasOwnProperty(href$jscomp$0) ? resumableState.styleResources[href$jscomp$0] : void 0)) {
            resumableState.styleResources[href$jscomp$0] = null;
            styleQueue$jscomp$0 || (styleQueue$jscomp$0 = {
              precedence: escapeTextForBrowser(precedence$jscomp$0),
              rules: [],
              hrefs: [],
              sheets: /* @__PURE__ */ new Map()
            }, renderState.styles.set(precedence$jscomp$0, styleQueue$jscomp$0));
            var nonceStyle = renderState.nonce.style;
            if (!nonceStyle || nonceStyle === nonce) {
              styleQueue$jscomp$0.hrefs.push(escapeTextForBrowser(href$jscomp$0));
              var target = styleQueue$jscomp$0.rules, children$jscomp$7 = null, innerHTML$jscomp$6 = null, propKey$jscomp$9;
              for (propKey$jscomp$9 in props)
                if (hasOwnProperty2.call(props, propKey$jscomp$9)) {
                  var propValue$jscomp$9 = props[propKey$jscomp$9];
                  if (null != propValue$jscomp$9)
                    switch (propKey$jscomp$9) {
                      case "children":
                        children$jscomp$7 = propValue$jscomp$9;
                        break;
                      case "dangerouslySetInnerHTML":
                        innerHTML$jscomp$6 = propValue$jscomp$9;
                    }
                }
              var child$jscomp$0 = Array.isArray(children$jscomp$7) ? 2 > children$jscomp$7.length ? children$jscomp$7[0] : null : children$jscomp$7;
              "function" !== typeof child$jscomp$0 && "symbol" !== typeof child$jscomp$0 && null !== child$jscomp$0 && void 0 !== child$jscomp$0 && target.push(
                ("" + child$jscomp$0).replace(styleRegex, styleReplacer)
              );
              pushInnerHTML(target, innerHTML$jscomp$6, children$jscomp$7);
            }
          }
          styleQueue$jscomp$0 && hoistableState && hoistableState.styles.add(styleQueue$jscomp$0);
          textEmbedded && target$jscomp$0.push(textSeparator);
          JSCompiler_inline_result$jscomp$6 = void 0;
        }
        return JSCompiler_inline_result$jscomp$6;
      case "meta":
        var noscriptTagInScope$jscomp$3 = formatContext.tagScope & 1, isFallback$jscomp$1 = formatContext.tagScope & 4;
        if (4 === formatContext.insertionMode || noscriptTagInScope$jscomp$3 || null != props.itemProp)
          var JSCompiler_inline_result$jscomp$7 = pushSelfClosing(
            target$jscomp$0,
            props,
            "meta"
          );
        else
          textEmbedded && target$jscomp$0.push(textSeparator), JSCompiler_inline_result$jscomp$7 = isFallback$jscomp$1 ? null : "string" === typeof props.charSet ? pushSelfClosing(renderState.charsetChunks, props, "meta") : "viewport" === props.name ? pushSelfClosing(renderState.viewportChunks, props, "meta") : pushSelfClosing(renderState.hoistableChunks, props, "meta");
        return JSCompiler_inline_result$jscomp$7;
      case "listing":
      case "pre":
        target$jscomp$0.push(startChunkForTag(type2));
        var children$jscomp$8 = null, innerHTML$jscomp$7 = null, propKey$jscomp$10;
        for (propKey$jscomp$10 in props)
          if (hasOwnProperty2.call(props, propKey$jscomp$10)) {
            var propValue$jscomp$10 = props[propKey$jscomp$10];
            if (null != propValue$jscomp$10)
              switch (propKey$jscomp$10) {
                case "children":
                  children$jscomp$8 = propValue$jscomp$10;
                  break;
                case "dangerouslySetInnerHTML":
                  innerHTML$jscomp$7 = propValue$jscomp$10;
                  break;
                default:
                  pushAttribute(
                    target$jscomp$0,
                    propKey$jscomp$10,
                    propValue$jscomp$10
                  );
              }
          }
        target$jscomp$0.push(endOfStartTag);
        if (null != innerHTML$jscomp$7) {
          if (null != children$jscomp$8)
            throw Error(
              "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
            );
          if ("object" !== typeof innerHTML$jscomp$7 || !("__html" in innerHTML$jscomp$7))
            throw Error(
              "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
            );
          var html2 = innerHTML$jscomp$7.__html;
          null !== html2 && void 0 !== html2 && ("string" === typeof html2 && 0 < html2.length && "\n" === html2[0] ? target$jscomp$0.push(leadingNewline, html2) : target$jscomp$0.push("" + html2));
        }
        "string" === typeof children$jscomp$8 && "\n" === children$jscomp$8[0] && target$jscomp$0.push(leadingNewline);
        return children$jscomp$8;
      case "img":
        var pictureOrNoScriptTagInScope = formatContext.tagScope & 3, src2 = props.src, srcSet = props.srcSet;
        if (!("lazy" === props.loading || !src2 && !srcSet || "string" !== typeof src2 && null != src2 || "string" !== typeof srcSet && null != srcSet || "low" === props.fetchPriority || pictureOrNoScriptTagInScope) && ("string" !== typeof src2 || ":" !== src2[4] || "d" !== src2[0] && "D" !== src2[0] || "a" !== src2[1] && "A" !== src2[1] || "t" !== src2[2] && "T" !== src2[2] || "a" !== src2[3] && "A" !== src2[3]) && ("string" !== typeof srcSet || ":" !== srcSet[4] || "d" !== srcSet[0] && "D" !== srcSet[0] || "a" !== srcSet[1] && "A" !== srcSet[1] || "t" !== srcSet[2] && "T" !== srcSet[2] || "a" !== srcSet[3] && "A" !== srcSet[3])) {
          null !== hoistableState && formatContext.tagScope & 64 && (hoistableState.suspenseyImages = true);
          var sizes = "string" === typeof props.sizes ? props.sizes : void 0, key$jscomp$0 = srcSet ? srcSet + "\n" + (sizes || "") : src2, promotablePreloads = renderState.preloads.images, resource$jscomp$1 = promotablePreloads.get(key$jscomp$0);
          if (resource$jscomp$1) {
            if ("high" === props.fetchPriority || 10 > renderState.highImagePreloads.size)
              promotablePreloads.delete(key$jscomp$0), renderState.highImagePreloads.add(resource$jscomp$1);
          } else if (!resumableState.imageResources.hasOwnProperty(key$jscomp$0)) {
            resumableState.imageResources[key$jscomp$0] = PRELOAD_NO_CREDS;
            var input = props.crossOrigin;
            var JSCompiler_inline_result$jscomp$8 = "string" === typeof input ? "use-credentials" === input ? input : "" : void 0;
            var headers = renderState.headers, header;
            headers && 0 < headers.remainingCapacity && "string" !== typeof props.srcSet && ("high" === props.fetchPriority || 500 > headers.highImagePreloads.length) && (header = getPreloadAsHeader(src2, "image", {
              imageSrcSet: props.srcSet,
              imageSizes: props.sizes,
              crossOrigin: JSCompiler_inline_result$jscomp$8,
              integrity: props.integrity,
              nonce: props.nonce,
              type: props.type,
              fetchPriority: props.fetchPriority,
              referrerPolicy: props.refererPolicy
            }), 0 <= (headers.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key$jscomp$0] = PRELOAD_NO_CREDS, headers.highImagePreloads && (headers.highImagePreloads += ", "), headers.highImagePreloads += header) : (resource$jscomp$1 = [], pushLinkImpl(resource$jscomp$1, {
              rel: "preload",
              as: "image",
              href: srcSet ? void 0 : src2,
              imageSrcSet: srcSet,
              imageSizes: sizes,
              crossOrigin: JSCompiler_inline_result$jscomp$8,
              integrity: props.integrity,
              type: props.type,
              fetchPriority: props.fetchPriority,
              referrerPolicy: props.referrerPolicy
            }), "high" === props.fetchPriority || 10 > renderState.highImagePreloads.size ? renderState.highImagePreloads.add(resource$jscomp$1) : (renderState.bulkPreloads.add(resource$jscomp$1), promotablePreloads.set(key$jscomp$0, resource$jscomp$1)));
          }
        }
        return pushSelfClosing(target$jscomp$0, props, "img");
      case "base":
      case "area":
      case "br":
      case "col":
      case "embed":
      case "hr":
      case "keygen":
      case "param":
      case "source":
      case "track":
      case "wbr":
        return pushSelfClosing(target$jscomp$0, props, type2);
      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":
        break;
      case "head":
        if (2 > formatContext.insertionMode) {
          var preamble = preambleState || renderState.preamble;
          if (preamble.headChunks)
            throw Error("The `<head>` tag may only be rendered once.");
          null !== preambleState && target$jscomp$0.push(headPreambleContributionChunk);
          preamble.headChunks = [];
          var JSCompiler_inline_result$jscomp$9 = pushStartSingletonElement(
            preamble.headChunks,
            props,
            "head"
          );
        } else
          JSCompiler_inline_result$jscomp$9 = pushStartGenericElement(
            target$jscomp$0,
            props,
            "head"
          );
        return JSCompiler_inline_result$jscomp$9;
      case "body":
        if (2 > formatContext.insertionMode) {
          var preamble$jscomp$0 = preambleState || renderState.preamble;
          if (preamble$jscomp$0.bodyChunks)
            throw Error("The `<body>` tag may only be rendered once.");
          null !== preambleState && target$jscomp$0.push(bodyPreambleContributionChunk);
          preamble$jscomp$0.bodyChunks = [];
          var JSCompiler_inline_result$jscomp$10 = pushStartSingletonElement(
            preamble$jscomp$0.bodyChunks,
            props,
            "body"
          );
        } else
          JSCompiler_inline_result$jscomp$10 = pushStartGenericElement(
            target$jscomp$0,
            props,
            "body"
          );
        return JSCompiler_inline_result$jscomp$10;
      case "html":
        if (0 === formatContext.insertionMode) {
          var preamble$jscomp$1 = preambleState || renderState.preamble;
          if (preamble$jscomp$1.htmlChunks)
            throw Error("The `<html>` tag may only be rendered once.");
          null !== preambleState && target$jscomp$0.push(htmlPreambleContributionChunk);
          preamble$jscomp$1.htmlChunks = [doctypeChunk];
          var JSCompiler_inline_result$jscomp$11 = pushStartSingletonElement(
            preamble$jscomp$1.htmlChunks,
            props,
            "html"
          );
        } else
          JSCompiler_inline_result$jscomp$11 = pushStartGenericElement(
            target$jscomp$0,
            props,
            "html"
          );
        return JSCompiler_inline_result$jscomp$11;
      default:
        if (-1 !== type2.indexOf("-")) {
          target$jscomp$0.push(startChunkForTag(type2));
          var children$jscomp$9 = null, innerHTML$jscomp$8 = null, propKey$jscomp$11;
          for (propKey$jscomp$11 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$11)) {
              var propValue$jscomp$11 = props[propKey$jscomp$11];
              if (null != propValue$jscomp$11) {
                var attributeName = propKey$jscomp$11;
                switch (propKey$jscomp$11) {
                  case "children":
                    children$jscomp$9 = propValue$jscomp$11;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$8 = propValue$jscomp$11;
                    break;
                  case "style":
                    pushStyleAttribute(target$jscomp$0, propValue$jscomp$11);
                    break;
                  case "suppressContentEditableWarning":
                  case "suppressHydrationWarning":
                  case "ref":
                    break;
                  case "className":
                    attributeName = "class";
                  default:
                    if (isAttributeNameSafe(propKey$jscomp$11) && "function" !== typeof propValue$jscomp$11 && "symbol" !== typeof propValue$jscomp$11 && false !== propValue$jscomp$11) {
                      if (true === propValue$jscomp$11) propValue$jscomp$11 = "";
                      else if ("object" === typeof propValue$jscomp$11) continue;
                      target$jscomp$0.push(
                        attributeSeparator,
                        attributeName,
                        attributeAssign,
                        escapeTextForBrowser(propValue$jscomp$11),
                        attributeEnd
                      );
                    }
                }
              }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$8, children$jscomp$9);
          return children$jscomp$9;
        }
    }
    return pushStartGenericElement(target$jscomp$0, props, type2);
  }
  var endTagCache = /* @__PURE__ */ new Map();
  function endChunkForTag(tag) {
    var chunk2 = endTagCache.get(tag);
    void 0 === chunk2 && (chunk2 = stringToPrecomputedChunk("</" + tag + ">"), endTagCache.set(tag, chunk2));
    return chunk2;
  }
  function hoistPreambleState(renderState, preambleState) {
    renderState = renderState.preamble;
    null === renderState.htmlChunks && preambleState.htmlChunks && (renderState.htmlChunks = preambleState.htmlChunks);
    null === renderState.headChunks && preambleState.headChunks && (renderState.headChunks = preambleState.headChunks);
    null === renderState.bodyChunks && preambleState.bodyChunks && (renderState.bodyChunks = preambleState.bodyChunks);
  }
  function writeBootstrap(destination, renderState) {
    renderState = renderState.bootstrapChunks;
    for (var i = 0; i < renderState.length - 1; i++)
      writeChunk(destination, renderState[i]);
    return i < renderState.length ? (i = renderState[i], renderState.length = 0, writeChunkAndReturn(destination, i)) : true;
  }
  var shellTimeRuntimeScript = stringToPrecomputedChunk(
    "requestAnimationFrame(function(){$RT=performance.now()});"
  ), placeholder1 = stringToPrecomputedChunk('<template id="'), placeholder2 = stringToPrecomputedChunk('"></template>'), startActivityBoundary = stringToPrecomputedChunk("<!--&-->"), endActivityBoundary = stringToPrecomputedChunk("<!--/&-->"), startCompletedSuspenseBoundary = stringToPrecomputedChunk("<!--$-->"), startPendingSuspenseBoundary1 = stringToPrecomputedChunk(
    '<!--$?--><template id="'
  ), startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>'), startClientRenderedSuspenseBoundary = stringToPrecomputedChunk("<!--$!-->"), endSuspenseBoundary = stringToPrecomputedChunk("<!--/$-->"), clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk("<template"), clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"'), clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="');
  stringToPrecomputedChunk(' data-msg="');
  stringToPrecomputedChunk(' data-stck="');
  stringToPrecomputedChunk(' data-cstck="');
  var clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk("></template>");
  function writeStartPendingSuspenseBoundary(destination, renderState, id) {
    writeChunk(destination, startPendingSuspenseBoundary1);
    if (null === id)
      throw Error(
        "An ID must have been assigned before we can complete the boundary."
      );
    writeChunk(destination, renderState.boundaryPrefix);
    writeChunk(destination, id.toString(16));
    return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
  }
  var startSegmentHTML = stringToPrecomputedChunk('<div hidden id="'), startSegmentHTML2 = stringToPrecomputedChunk('">'), endSegmentHTML = stringToPrecomputedChunk("</div>"), startSegmentSVG = stringToPrecomputedChunk(
    '<svg aria-hidden="true" style="display:none" id="'
  ), startSegmentSVG2 = stringToPrecomputedChunk('">'), endSegmentSVG = stringToPrecomputedChunk("</svg>"), startSegmentMathML = stringToPrecomputedChunk(
    '<math aria-hidden="true" style="display:none" id="'
  ), startSegmentMathML2 = stringToPrecomputedChunk('">'), endSegmentMathML = stringToPrecomputedChunk("</math>"), startSegmentTable = stringToPrecomputedChunk('<table hidden id="'), startSegmentTable2 = stringToPrecomputedChunk('">'), endSegmentTable = stringToPrecomputedChunk("</table>"), startSegmentTableBody = stringToPrecomputedChunk('<table hidden><tbody id="'), startSegmentTableBody2 = stringToPrecomputedChunk('">'), endSegmentTableBody = stringToPrecomputedChunk("</tbody></table>"), startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="'), startSegmentTableRow2 = stringToPrecomputedChunk('">'), endSegmentTableRow = stringToPrecomputedChunk("</tr></table>"), startSegmentColGroup = stringToPrecomputedChunk(
    '<table hidden><colgroup id="'
  ), startSegmentColGroup2 = stringToPrecomputedChunk('">'), endSegmentColGroup = stringToPrecomputedChunk("</colgroup></table>");
  function writeStartSegment(destination, renderState, formatContext, id) {
    switch (formatContext.insertionMode) {
      case 0:
      case 1:
      case 3:
      case 2:
        return writeChunk(destination, startSegmentHTML), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentHTML2);
      case 4:
        return writeChunk(destination, startSegmentSVG), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentSVG2);
      case 5:
        return writeChunk(destination, startSegmentMathML), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentMathML2);
      case 6:
        return writeChunk(destination, startSegmentTable), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentTable2);
      case 7:
        return writeChunk(destination, startSegmentTableBody), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentTableBody2);
      case 8:
        return writeChunk(destination, startSegmentTableRow), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentTableRow2);
      case 9:
        return writeChunk(destination, startSegmentColGroup), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentColGroup2);
      default:
        throw Error("Unknown insertion mode. This is a bug in React.");
    }
  }
  function writeEndSegment(destination, formatContext) {
    switch (formatContext.insertionMode) {
      case 0:
      case 1:
      case 3:
      case 2:
        return writeChunkAndReturn(destination, endSegmentHTML);
      case 4:
        return writeChunkAndReturn(destination, endSegmentSVG);
      case 5:
        return writeChunkAndReturn(destination, endSegmentMathML);
      case 6:
        return writeChunkAndReturn(destination, endSegmentTable);
      case 7:
        return writeChunkAndReturn(destination, endSegmentTableBody);
      case 8:
        return writeChunkAndReturn(destination, endSegmentTableRow);
      case 9:
        return writeChunkAndReturn(destination, endSegmentColGroup);
      default:
        throw Error("Unknown insertion mode. This is a bug in React.");
    }
  }
  var completeSegmentScript1Full = stringToPrecomputedChunk(
    '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'
  ), completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("'), completeSegmentScript2 = stringToPrecomputedChunk('","'), completeSegmentScriptEnd = stringToPrecomputedChunk('")<\/script>');
  stringToPrecomputedChunk('<template data-rsi="" data-sid="');
  stringToPrecomputedChunk('" data-pid="');
  var completeBoundaryScriptFunctionOnly = stringToPrecomputedChunk(
    '$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};\n$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};'
  ), completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("'), completeBoundaryWithStylesScript1FullPartial = stringToPrecomputedChunk(
    '$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=\n"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=\n"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("'
  ), completeBoundaryWithStylesScript1Partial = stringToPrecomputedChunk('$RR("'), completeBoundaryScript2 = stringToPrecomputedChunk('","'), completeBoundaryScript3a = stringToPrecomputedChunk('",'), completeBoundaryScript3b = stringToPrecomputedChunk('"'), completeBoundaryScriptEnd = stringToPrecomputedChunk(")<\/script>");
  stringToPrecomputedChunk('<template data-rci="" data-bid="');
  stringToPrecomputedChunk('<template data-rri="" data-bid="');
  stringToPrecomputedChunk('" data-sid="');
  stringToPrecomputedChunk('" data-sty="');
  var clientRenderScriptFunctionOnly = stringToPrecomputedChunk(
    '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};'
  ), clientRenderScript1Full = stringToPrecomputedChunk(
    '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("'
  ), clientRenderScript1Partial = stringToPrecomputedChunk('$RX("'), clientRenderScript1A = stringToPrecomputedChunk('"'), clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(","), clientRenderScriptEnd = stringToPrecomputedChunk(")<\/script>");
  stringToPrecomputedChunk('<template data-rxi="" data-bid="');
  stringToPrecomputedChunk('" data-dgst="');
  stringToPrecomputedChunk('" data-msg="');
  stringToPrecomputedChunk('" data-stck="');
  stringToPrecomputedChunk('" data-cstck="');
  var regexForJSStringsInInstructionScripts = /[<\u2028\u2029]/g;
  function escapeJSStringsForInstructionScripts(input) {
    return JSON.stringify(input).replace(
      regexForJSStringsInInstructionScripts,
      function(match) {
        switch (match) {
          case "<":
            return "\\u003c";
          case "\u2028":
            return "\\u2028";
          case "\u2029":
            return "\\u2029";
          default:
            throw Error(
              "escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
            );
        }
      }
    );
  }
  var regexForJSStringsInScripts = /[&><\u2028\u2029]/g;
  function escapeJSObjectForInstructionScripts(input) {
    return JSON.stringify(input).replace(
      regexForJSStringsInScripts,
      function(match) {
        switch (match) {
          case "&":
            return "\\u0026";
          case ">":
            return "\\u003e";
          case "<":
            return "\\u003c";
          case "\u2028":
            return "\\u2028";
          case "\u2029":
            return "\\u2029";
          default:
            throw Error(
              "escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
            );
        }
      }
    );
  }
  var lateStyleTagResourceOpen1 = stringToPrecomputedChunk(
    ' media="not all" data-precedence="'
  ), lateStyleTagResourceOpen2 = stringToPrecomputedChunk('" data-href="'), lateStyleTagResourceOpen3 = stringToPrecomputedChunk('">'), lateStyleTagTemplateClose = stringToPrecomputedChunk("</style>"), currentlyRenderingBoundaryHasStylesToHoist = false, destinationHasCapacity = true;
  function flushStyleTagsLateForBoundary(styleQueue) {
    var rules = styleQueue.rules, hrefs = styleQueue.hrefs, i = 0;
    if (hrefs.length) {
      writeChunk(this, currentlyFlushingRenderState.startInlineStyle);
      writeChunk(this, lateStyleTagResourceOpen1);
      writeChunk(this, styleQueue.precedence);
      for (writeChunk(this, lateStyleTagResourceOpen2); i < hrefs.length - 1; i++)
        writeChunk(this, hrefs[i]), writeChunk(this, spaceSeparator);
      writeChunk(this, hrefs[i]);
      writeChunk(this, lateStyleTagResourceOpen3);
      for (i = 0; i < rules.length; i++) writeChunk(this, rules[i]);
      destinationHasCapacity = writeChunkAndReturn(
        this,
        lateStyleTagTemplateClose
      );
      currentlyRenderingBoundaryHasStylesToHoist = true;
      rules.length = 0;
      hrefs.length = 0;
    }
  }
  function hasStylesToHoist(stylesheet) {
    return 2 !== stylesheet.state ? currentlyRenderingBoundaryHasStylesToHoist = true : false;
  }
  function writeHoistablesForBoundary(destination, hoistableState, renderState) {
    currentlyRenderingBoundaryHasStylesToHoist = false;
    destinationHasCapacity = true;
    currentlyFlushingRenderState = renderState;
    hoistableState.styles.forEach(flushStyleTagsLateForBoundary, destination);
    currentlyFlushingRenderState = null;
    hoistableState.stylesheets.forEach(hasStylesToHoist);
    currentlyRenderingBoundaryHasStylesToHoist && (renderState.stylesToHoist = true);
    return destinationHasCapacity;
  }
  function flushResource(resource) {
    for (var i = 0; i < resource.length; i++) writeChunk(this, resource[i]);
    resource.length = 0;
  }
  var stylesheetFlushingQueue = [];
  function flushStyleInPreamble(stylesheet) {
    pushLinkImpl(stylesheetFlushingQueue, stylesheet.props);
    for (var i = 0; i < stylesheetFlushingQueue.length; i++)
      writeChunk(this, stylesheetFlushingQueue[i]);
    stylesheetFlushingQueue.length = 0;
    stylesheet.state = 2;
  }
  var styleTagResourceOpen1 = stringToPrecomputedChunk(' data-precedence="'), styleTagResourceOpen2 = stringToPrecomputedChunk('" data-href="'), spaceSeparator = stringToPrecomputedChunk(" "), styleTagResourceOpen3 = stringToPrecomputedChunk('">'), styleTagResourceClose = stringToPrecomputedChunk("</style>");
  function flushStylesInPreamble(styleQueue) {
    var hasStylesheets = 0 < styleQueue.sheets.size;
    styleQueue.sheets.forEach(flushStyleInPreamble, this);
    styleQueue.sheets.clear();
    var rules = styleQueue.rules, hrefs = styleQueue.hrefs;
    if (!hasStylesheets || hrefs.length) {
      writeChunk(this, currentlyFlushingRenderState.startInlineStyle);
      writeChunk(this, styleTagResourceOpen1);
      writeChunk(this, styleQueue.precedence);
      styleQueue = 0;
      if (hrefs.length) {
        for (writeChunk(this, styleTagResourceOpen2); styleQueue < hrefs.length - 1; styleQueue++)
          writeChunk(this, hrefs[styleQueue]), writeChunk(this, spaceSeparator);
        writeChunk(this, hrefs[styleQueue]);
      }
      writeChunk(this, styleTagResourceOpen3);
      for (styleQueue = 0; styleQueue < rules.length; styleQueue++)
        writeChunk(this, rules[styleQueue]);
      writeChunk(this, styleTagResourceClose);
      rules.length = 0;
      hrefs.length = 0;
    }
  }
  function preloadLateStyle(stylesheet) {
    if (0 === stylesheet.state) {
      stylesheet.state = 1;
      var props = stylesheet.props;
      pushLinkImpl(stylesheetFlushingQueue, {
        rel: "preload",
        as: "style",
        href: stylesheet.props.href,
        crossOrigin: props.crossOrigin,
        fetchPriority: props.fetchPriority,
        integrity: props.integrity,
        media: props.media,
        hrefLang: props.hrefLang,
        referrerPolicy: props.referrerPolicy
      });
      for (stylesheet = 0; stylesheet < stylesheetFlushingQueue.length; stylesheet++)
        writeChunk(this, stylesheetFlushingQueue[stylesheet]);
      stylesheetFlushingQueue.length = 0;
    }
  }
  function preloadLateStyles(styleQueue) {
    styleQueue.sheets.forEach(preloadLateStyle, this);
    styleQueue.sheets.clear();
  }
  stringToPrecomputedChunk('<link rel="expect" href="#');
  stringToPrecomputedChunk('" blocking="render"/>');
  var completedShellIdAttributeStart = stringToPrecomputedChunk(' id="');
  function pushCompletedShellIdAttribute(target, resumableState) {
    0 === (resumableState.instructions & 32) && (resumableState.instructions |= 32, target.push(
      completedShellIdAttributeStart,
      escapeTextForBrowser("_" + resumableState.idPrefix + "R_"),
      attributeEnd
    ));
  }
  var arrayFirstOpenBracket = stringToPrecomputedChunk("["), arraySubsequentOpenBracket = stringToPrecomputedChunk(",["), arrayInterstitial = stringToPrecomputedChunk(","), arrayCloseBracket = stringToPrecomputedChunk("]");
  function writeStyleResourceDependenciesInJS(destination, hoistableState) {
    writeChunk(destination, arrayFirstOpenBracket);
    var nextArrayOpenBrackChunk = arrayFirstOpenBracket;
    hoistableState.stylesheets.forEach(function(resource) {
      if (2 !== resource.state)
        if (3 === resource.state)
          writeChunk(destination, nextArrayOpenBrackChunk), writeChunk(
            destination,
            escapeJSObjectForInstructionScripts("" + resource.props.href)
          ), writeChunk(destination, arrayCloseBracket), nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
        else {
          writeChunk(destination, nextArrayOpenBrackChunk);
          var precedence = resource.props["data-precedence"], props = resource.props, coercedHref = sanitizeURL("" + resource.props.href);
          writeChunk(
            destination,
            escapeJSObjectForInstructionScripts(coercedHref)
          );
          precedence = "" + precedence;
          writeChunk(destination, arrayInterstitial);
          writeChunk(
            destination,
            escapeJSObjectForInstructionScripts(precedence)
          );
          for (var propKey in props)
            if (hasOwnProperty2.call(props, propKey) && (precedence = props[propKey], null != precedence))
              switch (propKey) {
                case "href":
                case "rel":
                case "precedence":
                case "data-precedence":
                  break;
                case "children":
                case "dangerouslySetInnerHTML":
                  throw Error(
                    "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                  );
                default:
                  writeStyleResourceAttributeInJS(
                    destination,
                    propKey,
                    precedence
                  );
              }
          writeChunk(destination, arrayCloseBracket);
          nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
          resource.state = 3;
        }
    });
    writeChunk(destination, arrayCloseBracket);
  }
  function writeStyleResourceAttributeInJS(destination, name2, value) {
    var attributeName = name2.toLowerCase();
    switch (typeof value) {
      case "function":
      case "symbol":
        return;
    }
    switch (name2) {
      case "innerHTML":
      case "dangerouslySetInnerHTML":
      case "suppressContentEditableWarning":
      case "suppressHydrationWarning":
      case "style":
      case "ref":
        return;
      case "className":
        attributeName = "class";
        name2 = "" + value;
        break;
      case "hidden":
        if (false === value) return;
        name2 = "";
        break;
      case "src":
      case "href":
        value = sanitizeURL(value);
        name2 = "" + value;
        break;
      default:
        if (2 < name2.length && ("o" === name2[0] || "O" === name2[0]) && ("n" === name2[1] || "N" === name2[1]) || !isAttributeNameSafe(name2))
          return;
        name2 = "" + value;
    }
    writeChunk(destination, arrayInterstitial);
    writeChunk(destination, escapeJSObjectForInstructionScripts(attributeName));
    writeChunk(destination, arrayInterstitial);
    writeChunk(destination, escapeJSObjectForInstructionScripts(name2));
  }
  function createHoistableState() {
    return { styles: /* @__PURE__ */ new Set(), stylesheets: /* @__PURE__ */ new Set(), suspenseyImages: false };
  }
  function prefetchDNS(href) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if ("string" === typeof href && href) {
        if (!resumableState.dnsResources.hasOwnProperty(href)) {
          resumableState.dnsResources[href] = null;
          resumableState = renderState.headers;
          var header, JSCompiler_temp;
          if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity)
            JSCompiler_temp = (header = "<" + ("" + href).replace(
              regexForHrefInLinkHeaderURLContext,
              escapeHrefForLinkHeaderURLContextReplacer
            ) + ">; rel=dns-prefetch", 0 <= (resumableState.remainingCapacity -= header.length + 2));
          JSCompiler_temp ? (renderState.resets.dns[href] = null, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (header = [], pushLinkImpl(header, { href, rel: "dns-prefetch" }), renderState.preconnects.add(header));
        }
        enqueueFlush(request);
      }
    } else previousDispatcher.D(href);
  }
  function preconnect(href, crossOrigin) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if ("string" === typeof href && href) {
        var bucket = "use-credentials" === crossOrigin ? "credentials" : "string" === typeof crossOrigin ? "anonymous" : "default";
        if (!resumableState.connectResources[bucket].hasOwnProperty(href)) {
          resumableState.connectResources[bucket][href] = null;
          resumableState = renderState.headers;
          var header, JSCompiler_temp;
          if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity) {
            JSCompiler_temp = "<" + ("" + href).replace(
              regexForHrefInLinkHeaderURLContext,
              escapeHrefForLinkHeaderURLContextReplacer
            ) + ">; rel=preconnect";
            if ("string" === typeof crossOrigin) {
              var escapedCrossOrigin = ("" + crossOrigin).replace(
                regexForLinkHeaderQuotedParamValueContext,
                escapeStringForLinkHeaderQuotedParamValueContextReplacer
              );
              JSCompiler_temp += '; crossorigin="' + escapedCrossOrigin + '"';
            }
            JSCompiler_temp = (header = JSCompiler_temp, 0 <= (resumableState.remainingCapacity -= header.length + 2));
          }
          JSCompiler_temp ? (renderState.resets.connect[bucket][href] = null, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (bucket = [], pushLinkImpl(bucket, {
            rel: "preconnect",
            href,
            crossOrigin
          }), renderState.preconnects.add(bucket));
        }
        enqueueFlush(request);
      }
    } else previousDispatcher.C(href, crossOrigin);
  }
  function preload(href, as, options) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (as && href) {
        switch (as) {
          case "image":
            if (options) {
              var imageSrcSet = options.imageSrcSet;
              var imageSizes = options.imageSizes;
              var fetchPriority = options.fetchPriority;
            }
            var key = imageSrcSet ? imageSrcSet + "\n" + (imageSizes || "") : href;
            if (resumableState.imageResources.hasOwnProperty(key)) return;
            resumableState.imageResources[key] = PRELOAD_NO_CREDS;
            resumableState = renderState.headers;
            var header;
            resumableState && 0 < resumableState.remainingCapacity && "string" !== typeof imageSrcSet && "high" === fetchPriority && (header = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key] = PRELOAD_NO_CREDS, resumableState.highImagePreloads && (resumableState.highImagePreloads += ", "), resumableState.highImagePreloads += header) : (resumableState = [], pushLinkImpl(
              resumableState,
              assign(
                { rel: "preload", href: imageSrcSet ? void 0 : href, as },
                options
              )
            ), "high" === fetchPriority ? renderState.highImagePreloads.add(resumableState) : (renderState.bulkPreloads.add(resumableState), renderState.preloads.images.set(key, resumableState)));
            break;
          case "style":
            if (resumableState.styleResources.hasOwnProperty(href)) return;
            imageSrcSet = [];
            pushLinkImpl(
              imageSrcSet,
              assign({ rel: "preload", href, as }, options)
            );
            resumableState.styleResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
            renderState.preloads.stylesheets.set(href, imageSrcSet);
            renderState.bulkPreloads.add(imageSrcSet);
            break;
          case "script":
            if (resumableState.scriptResources.hasOwnProperty(href)) return;
            imageSrcSet = [];
            renderState.preloads.scripts.set(href, imageSrcSet);
            renderState.bulkPreloads.add(imageSrcSet);
            pushLinkImpl(
              imageSrcSet,
              assign({ rel: "preload", href, as }, options)
            );
            resumableState.scriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
            break;
          default:
            if (resumableState.unknownResources.hasOwnProperty(as)) {
              if (imageSrcSet = resumableState.unknownResources[as], imageSrcSet.hasOwnProperty(href))
                return;
            } else
              imageSrcSet = {}, resumableState.unknownResources[as] = imageSrcSet;
            imageSrcSet[href] = PRELOAD_NO_CREDS;
            if ((resumableState = renderState.headers) && 0 < resumableState.remainingCapacity && "font" === as && (key = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= key.length + 2)))
              renderState.resets.font[href] = PRELOAD_NO_CREDS, resumableState.fontPreloads && (resumableState.fontPreloads += ", "), resumableState.fontPreloads += key;
            else
              switch (resumableState = [], href = assign({ rel: "preload", href, as }, options), pushLinkImpl(resumableState, href), as) {
                case "font":
                  renderState.fontPreloads.add(resumableState);
                  break;
                default:
                  renderState.bulkPreloads.add(resumableState);
              }
        }
        enqueueFlush(request);
      }
    } else previousDispatcher.L(href, as, options);
  }
  function preloadModule(href, options) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (href) {
        var as = options && "string" === typeof options.as ? options.as : "script";
        switch (as) {
          case "script":
            if (resumableState.moduleScriptResources.hasOwnProperty(href)) return;
            as = [];
            resumableState.moduleScriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
            renderState.preloads.moduleScripts.set(href, as);
            break;
          default:
            if (resumableState.moduleUnknownResources.hasOwnProperty(as)) {
              var resources = resumableState.unknownResources[as];
              if (resources.hasOwnProperty(href)) return;
            } else
              resources = {}, resumableState.moduleUnknownResources[as] = resources;
            as = [];
            resources[href] = PRELOAD_NO_CREDS;
        }
        pushLinkImpl(as, assign({ rel: "modulepreload", href }, options));
        renderState.bulkPreloads.add(as);
        enqueueFlush(request);
      }
    } else previousDispatcher.m(href, options);
  }
  function preinitStyle(href, precedence, options) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (href) {
        precedence = precedence || "default";
        var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(href) ? resumableState.styleResources[href] : void 0;
        null !== resourceState && (resumableState.styleResources[href] = null, styleQueue || (styleQueue = {
          precedence: escapeTextForBrowser(precedence),
          rules: [],
          hrefs: [],
          sheets: /* @__PURE__ */ new Map()
        }, renderState.styles.set(precedence, styleQueue)), precedence = {
          state: 0,
          props: assign(
            { rel: "stylesheet", href, "data-precedence": precedence },
            options
          )
        }, resourceState && (2 === resourceState.length && adoptPreloadCredentials(precedence.props, resourceState), (renderState = renderState.preloads.stylesheets.get(href)) && 0 < renderState.length ? renderState.length = 0 : precedence.state = 1), styleQueue.sheets.set(href, precedence), enqueueFlush(request));
      }
    } else previousDispatcher.S(href, precedence, options);
  }
  function preinitScript(src2, options) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (src2) {
        var resourceState = resumableState.scriptResources.hasOwnProperty(src2) ? resumableState.scriptResources[src2] : void 0;
        null !== resourceState && (resumableState.scriptResources[src2] = null, options = assign({ src: src2, async: true }, options), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.scripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
      }
    } else previousDispatcher.X(src2, options);
  }
  function preinitModuleScript(src2, options) {
    var request = resolveRequest();
    if (request) {
      var resumableState = request.resumableState, renderState = request.renderState;
      if (src2) {
        var resourceState = resumableState.moduleScriptResources.hasOwnProperty(
          src2
        ) ? resumableState.moduleScriptResources[src2] : void 0;
        null !== resourceState && (resumableState.moduleScriptResources[src2] = null, options = assign({ src: src2, type: "module", async: true }, options), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.moduleScripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
      }
    } else previousDispatcher.M(src2, options);
  }
  function adoptPreloadCredentials(target, preloadState) {
    null == target.crossOrigin && (target.crossOrigin = preloadState[0]);
    null == target.integrity && (target.integrity = preloadState[1]);
  }
  function getPreloadAsHeader(href, as, params) {
    href = ("" + href).replace(
      regexForHrefInLinkHeaderURLContext,
      escapeHrefForLinkHeaderURLContextReplacer
    );
    as = ("" + as).replace(
      regexForLinkHeaderQuotedParamValueContext,
      escapeStringForLinkHeaderQuotedParamValueContextReplacer
    );
    as = "<" + href + '>; rel=preload; as="' + as + '"';
    for (var paramName in params)
      hasOwnProperty2.call(params, paramName) && (href = params[paramName], "string" === typeof href && (as += "; " + paramName.toLowerCase() + '="' + ("" + href).replace(
        regexForLinkHeaderQuotedParamValueContext,
        escapeStringForLinkHeaderQuotedParamValueContextReplacer
      ) + '"'));
    return as;
  }
  var regexForHrefInLinkHeaderURLContext = /[<>\r\n]/g;
  function escapeHrefForLinkHeaderURLContextReplacer(match) {
    switch (match) {
      case "<":
        return "%3C";
      case ">":
        return "%3E";
      case "\n":
        return "%0A";
      case "\r":
        return "%0D";
      default:
        throw Error(
          "escapeLinkHrefForHeaderContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
        );
    }
  }
  var regexForLinkHeaderQuotedParamValueContext = /["';,\r\n]/g;
  function escapeStringForLinkHeaderQuotedParamValueContextReplacer(match) {
    switch (match) {
      case '"':
        return "%22";
      case "'":
        return "%27";
      case ";":
        return "%3B";
      case ",":
        return "%2C";
      case "\n":
        return "%0A";
      case "\r":
        return "%0D";
      default:
        throw Error(
          "escapeStringForLinkHeaderQuotedParamValueContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
        );
    }
  }
  function hoistStyleQueueDependency(styleQueue) {
    this.styles.add(styleQueue);
  }
  function hoistStylesheetDependency(stylesheet) {
    this.stylesheets.add(stylesheet);
  }
  function hoistHoistables(parentState, childState) {
    childState.styles.forEach(hoistStyleQueueDependency, parentState);
    childState.stylesheets.forEach(hoistStylesheetDependency, parentState);
    childState.suspenseyImages && (parentState.suspenseyImages = true);
  }
  function hasSuspenseyContent(hoistableState) {
    return 0 < hoistableState.stylesheets.size || hoistableState.suspenseyImages;
  }
  var bind2 = Function.prototype.bind, requestStorage = new async_hooks.AsyncLocalStorage(), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference");
  function getComponentNameFromType(type2) {
    if (null == type2) return null;
    if ("function" === typeof type2)
      return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
    if ("string" === typeof type2) return type2;
    switch (type2) {
      case REACT_FRAGMENT_TYPE:
        return "Fragment";
      case REACT_PROFILER_TYPE:
        return "Profiler";
      case REACT_STRICT_MODE_TYPE:
        return "StrictMode";
      case REACT_SUSPENSE_TYPE:
        return "Suspense";
      case REACT_SUSPENSE_LIST_TYPE:
        return "SuspenseList";
      case REACT_ACTIVITY_TYPE:
        return "Activity";
    }
    if ("object" === typeof type2)
      switch (type2.$$typeof) {
        case REACT_PORTAL_TYPE:
          return "Portal";
        case REACT_CONTEXT_TYPE:
          return type2.displayName || "Context";
        case REACT_CONSUMER_TYPE:
          return (type2._context.displayName || "Context") + ".Consumer";
        case REACT_FORWARD_REF_TYPE:
          var innerType = type2.render;
          type2 = type2.displayName;
          type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
          return type2;
        case REACT_MEMO_TYPE:
          return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
        case REACT_LAZY_TYPE:
          innerType = type2._payload;
          type2 = type2._init;
          try {
            return getComponentNameFromType(type2(innerType));
          } catch (x2) {
          }
      }
    return null;
  }
  var emptyContextObject = {}, currentActiveSnapshot = null;
  function popToNearestCommonAncestor(prev, next) {
    if (prev !== next) {
      prev.context._currentValue = prev.parentValue;
      prev = prev.parent;
      var parentNext = next.parent;
      if (null === prev) {
        if (null !== parentNext)
          throw Error(
            "The stacks must reach the root at the same time. This is a bug in React."
          );
      } else {
        if (null === parentNext)
          throw Error(
            "The stacks must reach the root at the same time. This is a bug in React."
          );
        popToNearestCommonAncestor(prev, parentNext);
      }
      next.context._currentValue = next.value;
    }
  }
  function popAllPrevious(prev) {
    prev.context._currentValue = prev.parentValue;
    prev = prev.parent;
    null !== prev && popAllPrevious(prev);
  }
  function pushAllNext(next) {
    var parentNext = next.parent;
    null !== parentNext && pushAllNext(parentNext);
    next.context._currentValue = next.value;
  }
  function popPreviousToCommonLevel(prev, next) {
    prev.context._currentValue = prev.parentValue;
    prev = prev.parent;
    if (null === prev)
      throw Error(
        "The depth must equal at least at zero before reaching the root. This is a bug in React."
      );
    prev.depth === next.depth ? popToNearestCommonAncestor(prev, next) : popPreviousToCommonLevel(prev, next);
  }
  function popNextToCommonLevel(prev, next) {
    var parentNext = next.parent;
    if (null === parentNext)
      throw Error(
        "The depth must equal at least at zero before reaching the root. This is a bug in React."
      );
    prev.depth === parentNext.depth ? popToNearestCommonAncestor(prev, parentNext) : popNextToCommonLevel(prev, parentNext);
    next.context._currentValue = next.value;
  }
  function switchContext(newSnapshot) {
    var prev = currentActiveSnapshot;
    prev !== newSnapshot && (null === prev ? pushAllNext(newSnapshot) : null === newSnapshot ? popAllPrevious(prev) : prev.depth === newSnapshot.depth ? popToNearestCommonAncestor(prev, newSnapshot) : prev.depth > newSnapshot.depth ? popPreviousToCommonLevel(prev, newSnapshot) : popNextToCommonLevel(prev, newSnapshot), currentActiveSnapshot = newSnapshot);
  }
  var classComponentUpdater = {
    enqueueSetState: function(inst, payload) {
      inst = inst._reactInternals;
      null !== inst.queue && inst.queue.push(payload);
    },
    enqueueReplaceState: function(inst, payload) {
      inst = inst._reactInternals;
      inst.replace = true;
      inst.queue = [payload];
    },
    enqueueForceUpdate: function() {
    }
  }, emptyTreeContext = { id: 1, overflow: "" };
  function pushTreeContext(baseContext, totalChildren, index2) {
    var baseIdWithLeadingBit = baseContext.id;
    baseContext = baseContext.overflow;
    var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
    baseIdWithLeadingBit &= ~(1 << baseLength);
    index2 += 1;
    var length = 32 - clz32(totalChildren) + baseLength;
    if (30 < length) {
      var numberOfOverflowBits = baseLength - baseLength % 5;
      length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
      baseIdWithLeadingBit >>= numberOfOverflowBits;
      baseLength -= numberOfOverflowBits;
      return {
        id: 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit,
        overflow: length + baseContext
      };
    }
    return {
      id: 1 << length | index2 << baseLength | baseIdWithLeadingBit,
      overflow: baseContext
    };
  }
  var clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2;
  function clz32Fallback(x2) {
    x2 >>>= 0;
    return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
  }
  function noop2() {
  }
  var SuspenseException = Error(
    "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
  );
  function trackUsedThenable(thenableState2, thenable, index2) {
    index2 = thenableState2[index2];
    void 0 === index2 ? thenableState2.push(thenable) : index2 !== thenable && (thenable.then(noop2, noop2), thenable = index2);
    switch (thenable.status) {
      case "fulfilled":
        return thenable.value;
      case "rejected":
        throw thenable.reason;
      default:
        "string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenableState2 = thenable, thenableState2.status = "pending", thenableState2.then(
          function(fulfilledValue) {
            if ("pending" === thenable.status) {
              var fulfilledThenable = thenable;
              fulfilledThenable.status = "fulfilled";
              fulfilledThenable.value = fulfilledValue;
            }
          },
          function(error) {
            if ("pending" === thenable.status) {
              var rejectedThenable = thenable;
              rejectedThenable.status = "rejected";
              rejectedThenable.reason = error;
            }
          }
        ));
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenable.reason;
        }
        suspendedThenable = thenable;
        throw SuspenseException;
    }
  }
  var suspendedThenable = null;
  function getSuspendedThenable() {
    if (null === suspendedThenable)
      throw Error(
        "Expected a suspended thenable. This is a bug in React. Please file an issue."
      );
    var thenable = suspendedThenable;
    suspendedThenable = null;
    return thenable;
  }
  function is(x2, y2) {
    return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
  }
  var objectIs = "function" === typeof Object.is ? Object.is : is, currentlyRenderingComponent = null, currentlyRenderingTask = null, currentlyRenderingRequest = null, currentlyRenderingKeyPath = null, firstWorkInProgressHook = null, workInProgressHook = null, isReRender = false, didScheduleRenderPhaseUpdate = false, localIdCounter = 0, actionStateCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, thenableState = null, renderPhaseUpdates = null, numberOfReRenders = 0;
  function resolveCurrentlyRenderingComponent() {
    if (null === currentlyRenderingComponent)
      throw Error(
        "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
      );
    return currentlyRenderingComponent;
  }
  function createHook() {
    if (0 < numberOfReRenders)
      throw Error("Rendered more hooks than during the previous render");
    return { memoizedState: null, queue: null, next: null };
  }
  function createWorkInProgressHook() {
    null === workInProgressHook ? null === firstWorkInProgressHook ? (isReRender = false, firstWorkInProgressHook = workInProgressHook = createHook()) : (isReRender = true, workInProgressHook = firstWorkInProgressHook) : null === workInProgressHook.next ? (isReRender = false, workInProgressHook = workInProgressHook.next = createHook()) : (isReRender = true, workInProgressHook = workInProgressHook.next);
    return workInProgressHook;
  }
  function getThenableStateAfterSuspending() {
    var state = thenableState;
    thenableState = null;
    return state;
  }
  function resetHooksState() {
    currentlyRenderingKeyPath = currentlyRenderingRequest = currentlyRenderingTask = currentlyRenderingComponent = null;
    didScheduleRenderPhaseUpdate = false;
    firstWorkInProgressHook = null;
    numberOfReRenders = 0;
    workInProgressHook = renderPhaseUpdates = null;
  }
  function basicStateReducer(state, action) {
    return "function" === typeof action ? action(state) : action;
  }
  function useReducer(reducer2, initialArg, init2) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    if (isReRender) {
      var queue = workInProgressHook.queue;
      initialArg = queue.dispatch;
      if (null !== renderPhaseUpdates && (init2 = renderPhaseUpdates.get(queue), void 0 !== init2)) {
        renderPhaseUpdates.delete(queue);
        queue = workInProgressHook.memoizedState;
        do
          queue = reducer2(queue, init2.action), init2 = init2.next;
        while (null !== init2);
        workInProgressHook.memoizedState = queue;
        return [queue, initialArg];
      }
      return [workInProgressHook.memoizedState, initialArg];
    }
    reducer2 = reducer2 === basicStateReducer ? "function" === typeof initialArg ? initialArg() : initialArg : void 0 !== init2 ? init2(initialArg) : initialArg;
    workInProgressHook.memoizedState = reducer2;
    reducer2 = workInProgressHook.queue = { last: null, dispatch: null };
    reducer2 = reducer2.dispatch = dispatchAction.bind(
      null,
      currentlyRenderingComponent,
      reducer2
    );
    return [workInProgressHook.memoizedState, reducer2];
  }
  function useMemo(nextCreate, deps) {
    currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
    workInProgressHook = createWorkInProgressHook();
    deps = void 0 === deps ? null : deps;
    if (null !== workInProgressHook) {
      var prevState = workInProgressHook.memoizedState;
      if (null !== prevState && null !== deps) {
        var prevDeps = prevState[1];
        a: if (null === prevDeps) prevDeps = false;
        else {
          for (var i = 0; i < prevDeps.length && i < deps.length; i++)
            if (!objectIs(deps[i], prevDeps[i])) {
              prevDeps = false;
              break a;
            }
          prevDeps = true;
        }
        if (prevDeps) return prevState[0];
      }
    }
    nextCreate = nextCreate();
    workInProgressHook.memoizedState = [nextCreate, deps];
    return nextCreate;
  }
  function dispatchAction(componentIdentity, queue, action) {
    if (25 <= numberOfReRenders)
      throw Error(
        "Too many re-renders. React limits the number of renders to prevent an infinite loop."
      );
    if (componentIdentity === currentlyRenderingComponent)
      if (didScheduleRenderPhaseUpdate = true, componentIdentity = { action, next: null }, null === renderPhaseUpdates && (renderPhaseUpdates = /* @__PURE__ */ new Map()), action = renderPhaseUpdates.get(queue), void 0 === action)
        renderPhaseUpdates.set(queue, componentIdentity);
      else {
        for (queue = action; null !== queue.next; ) queue = queue.next;
        queue.next = componentIdentity;
      }
  }
  function throwOnUseEffectEventCall() {
    throw Error(
      "A function wrapped in useEffectEvent can't be called during rendering."
    );
  }
  function unsupportedStartTransition() {
    throw Error("startTransition cannot be called during server rendering.");
  }
  function unsupportedSetOptimisticState() {
    throw Error("Cannot update optimistic state while rendering.");
  }
  function createPostbackActionStateKey(permalink, componentKeyPath, hookIndex) {
    if (void 0 !== permalink) return "p" + permalink;
    permalink = JSON.stringify([componentKeyPath, null, hookIndex]);
    componentKeyPath = crypto2.createHash("md5");
    componentKeyPath.update(permalink);
    return "k" + componentKeyPath.digest("hex");
  }
  function useActionState(action, initialState2, permalink) {
    resolveCurrentlyRenderingComponent();
    var actionStateHookIndex = actionStateCounter++, request = currentlyRenderingRequest;
    if ("function" === typeof action.$$FORM_ACTION) {
      var nextPostbackStateKey = null, componentKeyPath = currentlyRenderingKeyPath;
      request = request.formState;
      var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL;
      if (null !== request && "function" === typeof isSignatureEqual) {
        var postbackKey = request[1];
        isSignatureEqual.call(action, request[2], request[3]) && (nextPostbackStateKey = createPostbackActionStateKey(
          permalink,
          componentKeyPath,
          actionStateHookIndex
        ), postbackKey === nextPostbackStateKey && (actionStateMatchingIndex = actionStateHookIndex, initialState2 = request[0]));
      }
      var boundAction = action.bind(null, initialState2);
      action = function(payload) {
        boundAction(payload);
      };
      "function" === typeof boundAction.$$FORM_ACTION && (action.$$FORM_ACTION = function(prefix2) {
        prefix2 = boundAction.$$FORM_ACTION(prefix2);
        void 0 !== permalink && (permalink += "", prefix2.action = permalink);
        var formData = prefix2.data;
        formData && (null === nextPostbackStateKey && (nextPostbackStateKey = createPostbackActionStateKey(
          permalink,
          componentKeyPath,
          actionStateHookIndex
        )), formData.append("$ACTION_KEY", nextPostbackStateKey));
        return prefix2;
      });
      return [initialState2, action, false];
    }
    var boundAction$22 = action.bind(null, initialState2);
    return [
      initialState2,
      function(payload) {
        boundAction$22(payload);
      },
      false
    ];
  }
  function unwrapThenable(thenable) {
    var index2 = thenableIndexCounter;
    thenableIndexCounter += 1;
    null === thenableState && (thenableState = []);
    return trackUsedThenable(thenableState, thenable, index2);
  }
  function unsupportedRefresh() {
    throw Error("Cache cannot be refreshed during server rendering.");
  }
  var HooksDispatcher = {
    readContext: function(context) {
      return context._currentValue;
    },
    use: function(usable) {
      if (null !== usable && "object" === typeof usable) {
        if ("function" === typeof usable.then) return unwrapThenable(usable);
        if (usable.$$typeof === REACT_CONTEXT_TYPE) return usable._currentValue;
      }
      throw Error("An unsupported type was passed to use(): " + String(usable));
    },
    useContext: function(context) {
      resolveCurrentlyRenderingComponent();
      return context._currentValue;
    },
    useMemo,
    useReducer,
    useRef: function(initialValue) {
      currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
      workInProgressHook = createWorkInProgressHook();
      var previousRef = workInProgressHook.memoizedState;
      return null === previousRef ? (initialValue = { current: initialValue }, workInProgressHook.memoizedState = initialValue) : previousRef;
    },
    useState: function(initialState2) {
      return useReducer(basicStateReducer, initialState2);
    },
    useInsertionEffect: noop2,
    useLayoutEffect: noop2,
    useCallback: function(callback, deps) {
      return useMemo(function() {
        return callback;
      }, deps);
    },
    useImperativeHandle: noop2,
    useEffect: noop2,
    useDebugValue: noop2,
    useDeferredValue: function(value, initialValue) {
      resolveCurrentlyRenderingComponent();
      return void 0 !== initialValue ? initialValue : value;
    },
    useTransition: function() {
      resolveCurrentlyRenderingComponent();
      return [false, unsupportedStartTransition];
    },
    useId: function() {
      var JSCompiler_inline_result = currentlyRenderingTask.treeContext;
      var overflow = JSCompiler_inline_result.overflow;
      JSCompiler_inline_result = JSCompiler_inline_result.id;
      JSCompiler_inline_result = (JSCompiler_inline_result & ~(1 << 32 - clz32(JSCompiler_inline_result) - 1)).toString(32) + overflow;
      var resumableState = currentResumableState;
      if (null === resumableState)
        throw Error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component."
        );
      overflow = localIdCounter++;
      JSCompiler_inline_result = "_" + resumableState.idPrefix + "R_" + JSCompiler_inline_result;
      0 < overflow && (JSCompiler_inline_result += "H" + overflow.toString(32));
      return JSCompiler_inline_result + "_";
    },
    useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
      if (void 0 === getServerSnapshot)
        throw Error(
          "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
        );
      return getServerSnapshot();
    },
    useOptimistic: function(passthrough) {
      resolveCurrentlyRenderingComponent();
      return [passthrough, unsupportedSetOptimisticState];
    },
    useActionState,
    useFormState: useActionState,
    useHostTransitionStatus: function() {
      resolveCurrentlyRenderingComponent();
      return sharedNotPendingObject;
    },
    useMemoCache: function(size) {
      for (var data = Array(size), i = 0; i < size; i++)
        data[i] = REACT_MEMO_CACHE_SENTINEL;
      return data;
    },
    useCacheRefresh: function() {
      return unsupportedRefresh;
    },
    useEffectEvent: function() {
      return throwOnUseEffectEventCall;
    }
  }, currentResumableState = null, DefaultAsyncDispatcher = {
    getCacheForType: function() {
      throw Error("Not implemented.");
    },
    cacheSignal: function() {
      throw Error("Not implemented.");
    }
  };
  function prepareStackTrace(error, structuredStackTrace) {
    error = (error.name || "Error") + ": " + (error.message || "");
    for (var i = 0; i < structuredStackTrace.length; i++)
      error += "\n    at " + structuredStackTrace[i].toString();
    return error;
  }
  var prefix, suffix;
  function describeBuiltInComponentFrame(name2) {
    if (void 0 === prefix)
      try {
        throw Error();
      } catch (x2) {
        var match = x2.stack.trim().match(/\n( *(at )?)/);
        prefix = match && match[1] || "";
        suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
      }
    return "\n" + prefix + name2 + suffix;
  }
  var reentry = false;
  function describeNativeComponentFrame(fn, construct) {
    if (!fn || reentry) return "";
    reentry = true;
    var previousPrepareStackTrace = Error.prepareStackTrace;
    Error.prepareStackTrace = prepareStackTrace;
    try {
      var RunInRootFrame = {
        DetermineComponentFrameRoot: function() {
          try {
            if (construct) {
              var Fake = function() {
                throw Error();
              };
              Object.defineProperty(Fake.prototype, "props", {
                set: function() {
                  throw Error();
                }
              });
              if ("object" === typeof Reflect && Reflect.construct) {
                try {
                  Reflect.construct(Fake, []);
                } catch (x2) {
                  var control = x2;
                }
                Reflect.construct(fn, [], Fake);
              } else {
                try {
                  Fake.call();
                } catch (x$24) {
                  control = x$24;
                }
                fn.call(Fake.prototype);
              }
            } else {
              try {
                throw Error();
              } catch (x$25) {
                control = x$25;
              }
              (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
              });
            }
          } catch (sample) {
            if (sample && control && "string" === typeof sample.stack)
              return [sample.stack, control.stack];
          }
          return [null, null];
        }
      };
      RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
      var namePropDescriptor = Object.getOwnPropertyDescriptor(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name"
      );
      namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
        RunInRootFrame.DetermineComponentFrameRoot,
        "name",
        { value: "DetermineComponentFrameRoot" }
      );
      var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
      if (sampleStack && controlStack) {
        var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
        for (namePropDescriptor = RunInRootFrame = 0; RunInRootFrame < sampleLines.length && !sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot"); )
          RunInRootFrame++;
        for (; namePropDescriptor < controlLines.length && !controlLines[namePropDescriptor].includes(
          "DetermineComponentFrameRoot"
        ); )
          namePropDescriptor++;
        if (RunInRootFrame === sampleLines.length || namePropDescriptor === controlLines.length)
          for (RunInRootFrame = sampleLines.length - 1, namePropDescriptor = controlLines.length - 1; 1 <= RunInRootFrame && 0 <= namePropDescriptor && sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]; )
            namePropDescriptor--;
        for (; 1 <= RunInRootFrame && 0 <= namePropDescriptor; RunInRootFrame--, namePropDescriptor--)
          if (sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
            if (1 !== RunInRootFrame || 1 !== namePropDescriptor) {
              do
                if (RunInRootFrame--, namePropDescriptor--, 0 > namePropDescriptor || sampleLines[RunInRootFrame] !== controlLines[namePropDescriptor]) {
                  var frame = "\n" + sampleLines[RunInRootFrame].replace(" at new ", " at ");
                  fn.displayName && frame.includes("<anonymous>") && (frame = frame.replace("<anonymous>", fn.displayName));
                  return frame;
                }
              while (1 <= RunInRootFrame && 0 <= namePropDescriptor);
            }
            break;
          }
      }
    } finally {
      reentry = false, Error.prepareStackTrace = previousPrepareStackTrace;
    }
    return (previousPrepareStackTrace = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(previousPrepareStackTrace) : "";
  }
  function describeComponentStackByType(type2) {
    if ("string" === typeof type2) return describeBuiltInComponentFrame(type2);
    if ("function" === typeof type2)
      return type2.prototype && type2.prototype.isReactComponent ? describeNativeComponentFrame(type2, true) : describeNativeComponentFrame(type2, false);
    if ("object" === typeof type2 && null !== type2) {
      switch (type2.$$typeof) {
        case REACT_FORWARD_REF_TYPE:
          return describeNativeComponentFrame(type2.render, false);
        case REACT_MEMO_TYPE:
          return describeNativeComponentFrame(type2.type, false);
        case REACT_LAZY_TYPE:
          var lazyComponent = type2, payload = lazyComponent._payload;
          lazyComponent = lazyComponent._init;
          try {
            type2 = lazyComponent(payload);
          } catch (x2) {
            return describeBuiltInComponentFrame("Lazy");
          }
          return describeComponentStackByType(type2);
      }
      if ("string" === typeof type2.name) {
        a: {
          payload = type2.name;
          lazyComponent = type2.env;
          var location = type2.debugLocation;
          if (null != location && (type2 = Error.prepareStackTrace, Error.prepareStackTrace = prepareStackTrace, location = location.stack, Error.prepareStackTrace = type2, location.startsWith("Error: react-stack-top-frame\n") && (location = location.slice(29)), type2 = location.indexOf("\n"), -1 !== type2 && (location = location.slice(type2 + 1)), type2 = location.indexOf("react_stack_bottom_frame"), -1 !== type2 && (type2 = location.lastIndexOf("\n", type2)), type2 = -1 !== type2 ? location = location.slice(0, type2) : "", location = type2.lastIndexOf("\n"), type2 = -1 === location ? type2 : type2.slice(location + 1), -1 !== type2.indexOf(payload))) {
            payload = "\n" + type2;
            break a;
          }
          payload = describeBuiltInComponentFrame(
            payload + (lazyComponent ? " [" + lazyComponent + "]" : "")
          );
        }
        return payload;
      }
    }
    switch (type2) {
      case REACT_SUSPENSE_LIST_TYPE:
        return describeBuiltInComponentFrame("SuspenseList");
      case REACT_SUSPENSE_TYPE:
        return describeBuiltInComponentFrame("Suspense");
    }
    return "";
  }
  function isEligibleForOutlining(request, boundary) {
    return (500 < boundary.byteSize || hasSuspenseyContent(boundary.contentState)) && null === boundary.contentPreamble;
  }
  function defaultErrorHandler(error) {
    if ("object" === typeof error && null !== error && "string" === typeof error.environmentName) {
      var JSCompiler_inline_result = error.environmentName;
      error = [error].slice(0);
      "string" === typeof error[0] ? error.splice(
        0,
        1,
        "\x1B[0m\x1B[7m%c%s\x1B[0m%c " + error[0],
        "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px",
        " " + JSCompiler_inline_result + " ",
        ""
      ) : error.splice(
        0,
        0,
        "\x1B[0m\x1B[7m%c%s\x1B[0m%c",
        "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px",
        " " + JSCompiler_inline_result + " ",
        ""
      );
      error.unshift(console);
      JSCompiler_inline_result = bind2.apply(console.error, error);
      JSCompiler_inline_result();
    } else console.error(error);
    return null;
  }
  function RequestInstance(resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
    var abortSet = /* @__PURE__ */ new Set();
    this.destination = null;
    this.flushScheduled = false;
    this.resumableState = resumableState;
    this.renderState = renderState;
    this.rootFormatContext = rootFormatContext;
    this.progressiveChunkSize = void 0 === progressiveChunkSize ? 12800 : progressiveChunkSize;
    this.status = 10;
    this.fatalError = null;
    this.pendingRootTasks = this.allPendingTasks = this.nextSegmentId = 0;
    this.completedPreambleSegments = this.completedRootSegment = null;
    this.byteSize = 0;
    this.abortableTasks = abortSet;
    this.pingedTasks = [];
    this.clientRenderedBoundaries = [];
    this.completedBoundaries = [];
    this.partialBoundaries = [];
    this.trackedPostpones = null;
    this.onError = void 0 === onError ? defaultErrorHandler : onError;
    this.onPostpone = void 0 === onPostpone ? noop2 : onPostpone;
    this.onAllReady = void 0 === onAllReady ? noop2 : onAllReady;
    this.onShellReady = void 0 === onShellReady ? noop2 : onShellReady;
    this.onShellError = void 0 === onShellError ? noop2 : onShellError;
    this.onFatalError = void 0 === onFatalError ? noop2 : onFatalError;
    this.formState = void 0 === formState ? null : formState;
  }
  function createRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
    resumableState = new RequestInstance(
      resumableState,
      renderState,
      rootFormatContext,
      progressiveChunkSize,
      onError,
      onAllReady,
      onShellReady,
      onShellError,
      onFatalError,
      onPostpone,
      formState
    );
    renderState = createPendingSegment(
      resumableState,
      0,
      null,
      rootFormatContext,
      false,
      false
    );
    renderState.parentFlushed = true;
    children = createRenderTask(
      resumableState,
      null,
      children,
      -1,
      null,
      renderState,
      null,
      null,
      resumableState.abortableTasks,
      null,
      rootFormatContext,
      null,
      emptyTreeContext,
      null,
      null
    );
    pushComponentStack(children);
    resumableState.pingedTasks.push(children);
    return resumableState;
  }
  function createPrerenderRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone) {
    children = createRequest(
      children,
      resumableState,
      renderState,
      rootFormatContext,
      progressiveChunkSize,
      onError,
      onAllReady,
      onShellReady,
      onShellError,
      onFatalError,
      onPostpone,
      void 0
    );
    children.trackedPostpones = {
      workingMap: /* @__PURE__ */ new Map(),
      rootNodes: [],
      rootSlots: null
    };
    return children;
  }
  function resumeRequest(children, postponedState, renderState, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone) {
    renderState = new RequestInstance(
      postponedState.resumableState,
      renderState,
      postponedState.rootFormatContext,
      postponedState.progressiveChunkSize,
      onError,
      onAllReady,
      onShellReady,
      onShellError,
      onFatalError,
      onPostpone,
      null
    );
    renderState.nextSegmentId = postponedState.nextSegmentId;
    if ("number" === typeof postponedState.replaySlots)
      return onError = createPendingSegment(
        renderState,
        0,
        null,
        postponedState.rootFormatContext,
        false,
        false
      ), onError.parentFlushed = true, children = createRenderTask(
        renderState,
        null,
        children,
        -1,
        null,
        onError,
        null,
        null,
        renderState.abortableTasks,
        null,
        postponedState.rootFormatContext,
        null,
        emptyTreeContext,
        null,
        null
      ), pushComponentStack(children), renderState.pingedTasks.push(children), renderState;
    children = createReplayTask(
      renderState,
      null,
      {
        nodes: postponedState.replayNodes,
        slots: postponedState.replaySlots,
        pendingTasks: 0
      },
      children,
      -1,
      null,
      null,
      renderState.abortableTasks,
      null,
      postponedState.rootFormatContext,
      null,
      emptyTreeContext,
      null,
      null
    );
    pushComponentStack(children);
    renderState.pingedTasks.push(children);
    return renderState;
  }
  function resumeAndPrerenderRequest(children, postponedState, renderState, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone) {
    children = resumeRequest(
      children,
      postponedState,
      renderState,
      onError,
      onAllReady,
      onShellReady,
      onShellError,
      onFatalError,
      onPostpone
    );
    children.trackedPostpones = {
      workingMap: /* @__PURE__ */ new Map(),
      rootNodes: [],
      rootSlots: null
    };
    return children;
  }
  var currentRequest = null;
  function resolveRequest() {
    if (currentRequest) return currentRequest;
    var store = requestStorage.getStore();
    return store ? store : null;
  }
  function pingTask(request, task) {
    request.pingedTasks.push(task);
    1 === request.pingedTasks.length && (request.flushScheduled = null !== request.destination, null !== request.trackedPostpones || 10 === request.status ? scheduleMicrotask(function() {
      return performWork(request);
    }) : setImmediate(function() {
      return performWork(request);
    }));
  }
  function createSuspenseBoundary(request, row, fallbackAbortableTasks, contentPreamble, fallbackPreamble) {
    fallbackAbortableTasks = {
      status: 0,
      rootSegmentID: -1,
      parentFlushed: false,
      pendingTasks: 0,
      row,
      completedSegments: [],
      byteSize: 0,
      fallbackAbortableTasks,
      errorDigest: null,
      contentState: createHoistableState(),
      fallbackState: createHoistableState(),
      contentPreamble,
      fallbackPreamble,
      trackedContentKeyPath: null,
      trackedFallbackNode: null
    };
    null !== row && (row.pendingTasks++, contentPreamble = row.boundaries, null !== contentPreamble && (request.allPendingTasks++, fallbackAbortableTasks.pendingTasks++, contentPreamble.push(fallbackAbortableTasks)), request = row.inheritedHoistables, null !== request && hoistHoistables(fallbackAbortableTasks.contentState, request));
    return fallbackAbortableTasks;
  }
  function createRenderTask(request, thenableState2, node2, childIndex, blockedBoundary, blockedSegment, blockedPreamble, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack) {
    request.allPendingTasks++;
    null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
    null !== row && row.pendingTasks++;
    var task = {
      replay: null,
      node: node2,
      childIndex,
      ping: function() {
        return pingTask(request, task);
      },
      blockedBoundary,
      blockedSegment,
      blockedPreamble,
      hoistableState,
      abortSet,
      keyPath,
      formatContext,
      context,
      treeContext,
      row,
      componentStack,
      thenableState: thenableState2
    };
    abortSet.add(task);
    return task;
  }
  function createReplayTask(request, thenableState2, replay, node2, childIndex, blockedBoundary, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack) {
    request.allPendingTasks++;
    null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
    null !== row && row.pendingTasks++;
    replay.pendingTasks++;
    var task = {
      replay,
      node: node2,
      childIndex,
      ping: function() {
        return pingTask(request, task);
      },
      blockedBoundary,
      blockedSegment: null,
      blockedPreamble: null,
      hoistableState,
      abortSet,
      keyPath,
      formatContext,
      context,
      treeContext,
      row,
      componentStack,
      thenableState: thenableState2
    };
    abortSet.add(task);
    return task;
  }
  function createPendingSegment(request, index2, boundary, parentFormatContext, lastPushedText, textEmbedded) {
    return {
      status: 0,
      parentFlushed: false,
      id: -1,
      index: index2,
      chunks: [],
      children: [],
      preambleChildren: [],
      parentFormatContext,
      boundary,
      lastPushedText,
      textEmbedded
    };
  }
  function pushComponentStack(task) {
    var node2 = task.node;
    if ("object" === typeof node2 && null !== node2)
      switch (node2.$$typeof) {
        case REACT_ELEMENT_TYPE:
          task.componentStack = { parent: task.componentStack, type: node2.type };
      }
  }
  function replaceSuspenseComponentStackWithSuspenseFallbackStack(componentStack) {
    return null === componentStack ? null : { parent: componentStack.parent, type: "Suspense Fallback" };
  }
  function getThrownInfo(node$jscomp$0) {
    var errorInfo = {};
    node$jscomp$0 && Object.defineProperty(errorInfo, "componentStack", {
      configurable: true,
      enumerable: true,
      get: function() {
        try {
          var info = "", node2 = node$jscomp$0;
          do
            info += describeComponentStackByType(node2.type), node2 = node2.parent;
          while (node2);
          var JSCompiler_inline_result = info;
        } catch (x2) {
          JSCompiler_inline_result = "\nError generating stack: " + x2.message + "\n" + x2.stack;
        }
        Object.defineProperty(errorInfo, "componentStack", {
          value: JSCompiler_inline_result
        });
        return JSCompiler_inline_result;
      }
    });
    return errorInfo;
  }
  function logRecoverableError(request, error, errorInfo) {
    request = request.onError;
    error = request(error, errorInfo);
    if (null == error || "string" === typeof error) return error;
  }
  function fatalError(request, error) {
    var onShellError = request.onShellError, onFatalError = request.onFatalError;
    onShellError(error);
    onFatalError(error);
    null !== request.destination ? (request.status = 14, request.destination.destroy(error)) : (request.status = 13, request.fatalError = error);
  }
  function finishSuspenseListRow(request, row) {
    unblockSuspenseListRow(request, row.next, row.hoistables);
  }
  function unblockSuspenseListRow(request, unblockedRow, inheritedHoistables) {
    for (; null !== unblockedRow; ) {
      null !== inheritedHoistables && (hoistHoistables(unblockedRow.hoistables, inheritedHoistables), unblockedRow.inheritedHoistables = inheritedHoistables);
      var unblockedBoundaries = unblockedRow.boundaries;
      if (null !== unblockedBoundaries) {
        unblockedRow.boundaries = null;
        for (var i = 0; i < unblockedBoundaries.length; i++) {
          var unblockedBoundary = unblockedBoundaries[i];
          null !== inheritedHoistables && hoistHoistables(unblockedBoundary.contentState, inheritedHoistables);
          finishedTask(request, unblockedBoundary, null, null);
        }
      }
      unblockedRow.pendingTasks--;
      if (0 < unblockedRow.pendingTasks) break;
      inheritedHoistables = unblockedRow.hoistables;
      unblockedRow = unblockedRow.next;
    }
  }
  function tryToResolveTogetherRow(request, togetherRow) {
    var boundaries = togetherRow.boundaries;
    if (null !== boundaries && togetherRow.pendingTasks === boundaries.length) {
      for (var allCompleteAndInlinable = true, i = 0; i < boundaries.length; i++) {
        var rowBoundary = boundaries[i];
        if (1 !== rowBoundary.pendingTasks || rowBoundary.parentFlushed || isEligibleForOutlining(request, rowBoundary)) {
          allCompleteAndInlinable = false;
          break;
        }
      }
      allCompleteAndInlinable && unblockSuspenseListRow(request, togetherRow, togetherRow.hoistables);
    }
  }
  function createSuspenseListRow(previousRow) {
    var newRow = {
      pendingTasks: 1,
      boundaries: null,
      hoistables: createHoistableState(),
      inheritedHoistables: null,
      together: false,
      next: null
    };
    null !== previousRow && 0 < previousRow.pendingTasks && (newRow.pendingTasks++, newRow.boundaries = [], previousRow.next = newRow);
    return newRow;
  }
  function renderSuspenseListRows(request, task, keyPath, rows, revealOrder) {
    var prevKeyPath = task.keyPath, prevTreeContext = task.treeContext, prevRow = task.row;
    task.keyPath = keyPath;
    keyPath = rows.length;
    var previousSuspenseListRow = null;
    if (null !== task.replay) {
      var resumeSlots = task.replay.slots;
      if (null !== resumeSlots && "object" === typeof resumeSlots)
        for (var n = 0; n < keyPath; n++) {
          var i = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? n : keyPath - 1 - n, node2 = rows[i];
          task.row = previousSuspenseListRow = createSuspenseListRow(
            previousSuspenseListRow
          );
          task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
          var resumeSegmentID = resumeSlots[i];
          "number" === typeof resumeSegmentID ? (resumeNode(request, task, resumeSegmentID, node2, i), delete resumeSlots[i]) : renderNode(request, task, node2, i);
          0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
        }
      else
        for (resumeSlots = 0; resumeSlots < keyPath; resumeSlots++)
          n = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? resumeSlots : keyPath - 1 - resumeSlots, i = rows[n], task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(prevTreeContext, keyPath, n), renderNode(request, task, i, n), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
    } else if ("backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder)
      for (revealOrder = 0; revealOrder < keyPath; revealOrder++)
        resumeSlots = rows[revealOrder], task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(
          prevTreeContext,
          keyPath,
          revealOrder
        ), renderNode(request, task, resumeSlots, revealOrder), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
    else {
      revealOrder = task.blockedSegment;
      resumeSlots = revealOrder.children.length;
      n = revealOrder.chunks.length;
      for (i = keyPath - 1; 0 <= i; i--) {
        node2 = rows[i];
        task.row = previousSuspenseListRow = createSuspenseListRow(
          previousSuspenseListRow
        );
        task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
        resumeSegmentID = createPendingSegment(
          request,
          n,
          null,
          task.formatContext,
          0 === i ? revealOrder.lastPushedText : true,
          true
        );
        revealOrder.children.splice(resumeSlots, 0, resumeSegmentID);
        task.blockedSegment = resumeSegmentID;
        try {
          renderNode(request, task, node2, i), resumeSegmentID.lastPushedText && resumeSegmentID.textEmbedded && resumeSegmentID.chunks.push(textSeparator), resumeSegmentID.status = 1, finishedSegment(request, task.blockedBoundary, resumeSegmentID), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
        } catch (thrownValue) {
          throw resumeSegmentID.status = 12 === request.status ? 3 : 4, thrownValue;
        }
      }
      task.blockedSegment = revealOrder;
      revealOrder.lastPushedText = false;
    }
    null !== prevRow && null !== previousSuspenseListRow && 0 < previousSuspenseListRow.pendingTasks && (prevRow.pendingTasks++, previousSuspenseListRow.next = prevRow);
    task.treeContext = prevTreeContext;
    task.row = prevRow;
    task.keyPath = prevKeyPath;
  }
  function renderWithHooks(request, task, keyPath, Component, props, secondArg) {
    var prevThenableState = task.thenableState;
    task.thenableState = null;
    currentlyRenderingComponent = {};
    currentlyRenderingTask = task;
    currentlyRenderingRequest = request;
    currentlyRenderingKeyPath = keyPath;
    actionStateCounter = localIdCounter = 0;
    actionStateMatchingIndex = -1;
    thenableIndexCounter = 0;
    thenableState = prevThenableState;
    for (request = Component(props, secondArg); didScheduleRenderPhaseUpdate; )
      didScheduleRenderPhaseUpdate = false, actionStateCounter = localIdCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, numberOfReRenders += 1, workInProgressHook = null, request = Component(props, secondArg);
    resetHooksState();
    return request;
  }
  function finishFunctionComponent(request, task, keyPath, children, hasId, actionStateCount, actionStateMatchingIndex2) {
    var didEmitActionStateMarkers = false;
    if (0 !== actionStateCount && null !== request.formState) {
      var segment = task.blockedSegment;
      if (null !== segment) {
        didEmitActionStateMarkers = true;
        segment = segment.chunks;
        for (var i = 0; i < actionStateCount; i++)
          i === actionStateMatchingIndex2 ? segment.push(formStateMarkerIsMatching) : segment.push(formStateMarkerIsNotMatching);
      }
    }
    actionStateCount = task.keyPath;
    task.keyPath = keyPath;
    hasId ? (keyPath = task.treeContext, task.treeContext = pushTreeContext(keyPath, 1, 0), renderNode(request, task, children, -1), task.treeContext = keyPath) : didEmitActionStateMarkers ? renderNode(request, task, children, -1) : renderNodeDestructive(request, task, children, -1);
    task.keyPath = actionStateCount;
  }
  function renderElement(request, task, keyPath, type2, props, ref2) {
    if ("function" === typeof type2)
      if (type2.prototype && type2.prototype.isReactComponent) {
        var newProps = props;
        if ("ref" in props) {
          newProps = {};
          for (var propName in props)
            "ref" !== propName && (newProps[propName] = props[propName]);
        }
        var defaultProps = type2.defaultProps;
        if (defaultProps) {
          newProps === props && (newProps = assign({}, newProps, props));
          for (var propName$44 in defaultProps)
            void 0 === newProps[propName$44] && (newProps[propName$44] = defaultProps[propName$44]);
        }
        props = newProps;
        newProps = emptyContextObject;
        defaultProps = type2.contextType;
        "object" === typeof defaultProps && null !== defaultProps && (newProps = defaultProps._currentValue);
        newProps = new type2(props, newProps);
        var initialState2 = void 0 !== newProps.state ? newProps.state : null;
        newProps.updater = classComponentUpdater;
        newProps.props = props;
        newProps.state = initialState2;
        defaultProps = { queue: [], replace: false };
        newProps._reactInternals = defaultProps;
        ref2 = type2.contextType;
        newProps.context = "object" === typeof ref2 && null !== ref2 ? ref2._currentValue : emptyContextObject;
        ref2 = type2.getDerivedStateFromProps;
        "function" === typeof ref2 && (ref2 = ref2(props, initialState2), initialState2 = null === ref2 || void 0 === ref2 ? initialState2 : assign({}, initialState2, ref2), newProps.state = initialState2);
        if ("function" !== typeof type2.getDerivedStateFromProps && "function" !== typeof newProps.getSnapshotBeforeUpdate && ("function" === typeof newProps.UNSAFE_componentWillMount || "function" === typeof newProps.componentWillMount))
          if (type2 = newProps.state, "function" === typeof newProps.componentWillMount && newProps.componentWillMount(), "function" === typeof newProps.UNSAFE_componentWillMount && newProps.UNSAFE_componentWillMount(), type2 !== newProps.state && classComponentUpdater.enqueueReplaceState(
            newProps,
            newProps.state,
            null
          ), null !== defaultProps.queue && 0 < defaultProps.queue.length)
            if (type2 = defaultProps.queue, ref2 = defaultProps.replace, defaultProps.queue = null, defaultProps.replace = false, ref2 && 1 === type2.length)
              newProps.state = type2[0];
            else {
              defaultProps = ref2 ? type2[0] : newProps.state;
              initialState2 = true;
              for (ref2 = ref2 ? 1 : 0; ref2 < type2.length; ref2++)
                propName$44 = type2[ref2], propName$44 = "function" === typeof propName$44 ? propName$44.call(newProps, defaultProps, props, void 0) : propName$44, null != propName$44 && (initialState2 ? (initialState2 = false, defaultProps = assign({}, defaultProps, propName$44)) : assign(defaultProps, propName$44));
              newProps.state = defaultProps;
            }
          else defaultProps.queue = null;
        type2 = newProps.render();
        if (12 === request.status) throw null;
        props = task.keyPath;
        task.keyPath = keyPath;
        renderNodeDestructive(request, task, type2, -1);
        task.keyPath = props;
      } else {
        type2 = renderWithHooks(request, task, keyPath, type2, props, void 0);
        if (12 === request.status) throw null;
        finishFunctionComponent(
          request,
          task,
          keyPath,
          type2,
          0 !== localIdCounter,
          actionStateCounter,
          actionStateMatchingIndex
        );
      }
    else if ("string" === typeof type2)
      if (newProps = task.blockedSegment, null === newProps)
        newProps = props.children, defaultProps = task.formatContext, initialState2 = task.keyPath, task.formatContext = getChildFormatContext(defaultProps, type2, props), task.keyPath = keyPath, renderNode(request, task, newProps, -1), task.formatContext = defaultProps, task.keyPath = initialState2;
      else {
        initialState2 = pushStartInstance(
          newProps.chunks,
          type2,
          props,
          request.resumableState,
          request.renderState,
          task.blockedPreamble,
          task.hoistableState,
          task.formatContext,
          newProps.lastPushedText
        );
        newProps.lastPushedText = false;
        defaultProps = task.formatContext;
        ref2 = task.keyPath;
        task.keyPath = keyPath;
        if (3 === (task.formatContext = getChildFormatContext(defaultProps, type2, props)).insertionMode) {
          keyPath = createPendingSegment(
            request,
            0,
            null,
            task.formatContext,
            false,
            false
          );
          newProps.preambleChildren.push(keyPath);
          task.blockedSegment = keyPath;
          try {
            keyPath.status = 6, renderNode(request, task, initialState2, -1), keyPath.lastPushedText && keyPath.textEmbedded && keyPath.chunks.push(textSeparator), keyPath.status = 1, finishedSegment(request, task.blockedBoundary, keyPath);
          } finally {
            task.blockedSegment = newProps;
          }
        } else renderNode(request, task, initialState2, -1);
        task.formatContext = defaultProps;
        task.keyPath = ref2;
        a: {
          task = newProps.chunks;
          request = request.resumableState;
          switch (type2) {
            case "title":
            case "style":
            case "script":
            case "area":
            case "base":
            case "br":
            case "col":
            case "embed":
            case "hr":
            case "img":
            case "input":
            case "keygen":
            case "link":
            case "meta":
            case "param":
            case "source":
            case "track":
            case "wbr":
              break a;
            case "body":
              if (1 >= defaultProps.insertionMode) {
                request.hasBody = true;
                break a;
              }
              break;
            case "html":
              if (0 === defaultProps.insertionMode) {
                request.hasHtml = true;
                break a;
              }
              break;
            case "head":
              if (1 >= defaultProps.insertionMode) break a;
          }
          task.push(endChunkForTag(type2));
        }
        newProps.lastPushedText = false;
      }
    else {
      switch (type2) {
        case REACT_LEGACY_HIDDEN_TYPE:
        case REACT_STRICT_MODE_TYPE:
        case REACT_PROFILER_TYPE:
        case REACT_FRAGMENT_TYPE:
          type2 = task.keyPath;
          task.keyPath = keyPath;
          renderNodeDestructive(request, task, props.children, -1);
          task.keyPath = type2;
          return;
        case REACT_ACTIVITY_TYPE:
          type2 = task.blockedSegment;
          null === type2 ? "hidden" !== props.mode && (type2 = task.keyPath, task.keyPath = keyPath, renderNode(request, task, props.children, -1), task.keyPath = type2) : "hidden" !== props.mode && (type2.chunks.push(startActivityBoundary), type2.lastPushedText = false, newProps = task.keyPath, task.keyPath = keyPath, renderNode(request, task, props.children, -1), task.keyPath = newProps, type2.chunks.push(endActivityBoundary), type2.lastPushedText = false);
          return;
        case REACT_SUSPENSE_LIST_TYPE:
          a: {
            type2 = props.children;
            props = props.revealOrder;
            if ("forwards" === props || "backwards" === props || "unstable_legacy-backwards" === props) {
              if (isArrayImpl(type2)) {
                renderSuspenseListRows(request, task, keyPath, type2, props);
                break a;
              }
              if (newProps = getIteratorFn(type2)) {
                if (newProps = newProps.call(type2)) {
                  defaultProps = newProps.next();
                  if (!defaultProps.done) {
                    do
                      defaultProps = newProps.next();
                    while (!defaultProps.done);
                    renderSuspenseListRows(request, task, keyPath, type2, props);
                  }
                  break a;
                }
              }
            }
            "together" === props ? (props = task.keyPath, newProps = task.row, defaultProps = task.row = createSuspenseListRow(null), defaultProps.boundaries = [], defaultProps.together = true, task.keyPath = keyPath, renderNodeDestructive(request, task, type2, -1), 0 === --defaultProps.pendingTasks && finishSuspenseListRow(request, defaultProps), task.keyPath = props, task.row = newProps, null !== newProps && 0 < defaultProps.pendingTasks && (newProps.pendingTasks++, defaultProps.next = newProps)) : (props = task.keyPath, task.keyPath = keyPath, renderNodeDestructive(request, task, type2, -1), task.keyPath = props);
          }
          return;
        case REACT_VIEW_TRANSITION_TYPE:
        case REACT_SCOPE_TYPE:
          throw Error("ReactDOMServer does not yet support scope components.");
        case REACT_SUSPENSE_TYPE:
          a: if (null !== task.replay) {
            type2 = task.keyPath;
            newProps = task.formatContext;
            defaultProps = task.row;
            task.keyPath = keyPath;
            task.formatContext = getSuspenseContentFormatContext(
              request.resumableState,
              newProps
            );
            task.row = null;
            keyPath = props.children;
            try {
              renderNode(request, task, keyPath, -1);
            } finally {
              task.keyPath = type2, task.formatContext = newProps, task.row = defaultProps;
            }
          } else {
            type2 = task.keyPath;
            ref2 = task.formatContext;
            var prevRow = task.row;
            propName$44 = task.blockedBoundary;
            propName = task.blockedPreamble;
            var parentHoistableState = task.hoistableState, parentSegment = task.blockedSegment, fallback = props.fallback;
            props = props.children;
            var fallbackAbortSet = /* @__PURE__ */ new Set();
            var newBoundary = 2 > task.formatContext.insertionMode ? createSuspenseBoundary(
              request,
              task.row,
              fallbackAbortSet,
              createPreambleState(),
              createPreambleState()
            ) : createSuspenseBoundary(
              request,
              task.row,
              fallbackAbortSet,
              null,
              null
            );
            null !== request.trackedPostpones && (newBoundary.trackedContentKeyPath = keyPath);
            var boundarySegment = createPendingSegment(
              request,
              parentSegment.chunks.length,
              newBoundary,
              task.formatContext,
              false,
              false
            );
            parentSegment.children.push(boundarySegment);
            parentSegment.lastPushedText = false;
            var contentRootSegment = createPendingSegment(
              request,
              0,
              null,
              task.formatContext,
              false,
              false
            );
            contentRootSegment.parentFlushed = true;
            if (null !== request.trackedPostpones) {
              newProps = task.componentStack;
              defaultProps = [keyPath[0], "Suspense Fallback", keyPath[2]];
              initialState2 = [defaultProps[1], defaultProps[2], [], null];
              request.trackedPostpones.workingMap.set(defaultProps, initialState2);
              newBoundary.trackedFallbackNode = initialState2;
              task.blockedSegment = boundarySegment;
              task.blockedPreamble = newBoundary.fallbackPreamble;
              task.keyPath = defaultProps;
              task.formatContext = getSuspenseFallbackFormatContext(
                request.resumableState,
                ref2
              );
              task.componentStack = replaceSuspenseComponentStackWithSuspenseFallbackStack(newProps);
              boundarySegment.status = 6;
              try {
                renderNode(request, task, fallback, -1), boundarySegment.lastPushedText && boundarySegment.textEmbedded && boundarySegment.chunks.push(textSeparator), boundarySegment.status = 1, finishedSegment(request, propName$44, boundarySegment);
              } catch (thrownValue) {
                throw boundarySegment.status = 12 === request.status ? 3 : 4, thrownValue;
              } finally {
                task.blockedSegment = parentSegment, task.blockedPreamble = propName, task.keyPath = type2, task.formatContext = ref2;
              }
              task = createRenderTask(
                request,
                null,
                props,
                -1,
                newBoundary,
                contentRootSegment,
                newBoundary.contentPreamble,
                newBoundary.contentState,
                task.abortSet,
                keyPath,
                getSuspenseContentFormatContext(
                  request.resumableState,
                  task.formatContext
                ),
                task.context,
                task.treeContext,
                null,
                newProps
              );
              pushComponentStack(task);
              request.pingedTasks.push(task);
            } else {
              task.blockedBoundary = newBoundary;
              task.blockedPreamble = newBoundary.contentPreamble;
              task.hoistableState = newBoundary.contentState;
              task.blockedSegment = contentRootSegment;
              task.keyPath = keyPath;
              task.formatContext = getSuspenseContentFormatContext(
                request.resumableState,
                ref2
              );
              task.row = null;
              contentRootSegment.status = 6;
              try {
                if (renderNode(request, task, props, -1), contentRootSegment.lastPushedText && contentRootSegment.textEmbedded && contentRootSegment.chunks.push(textSeparator), contentRootSegment.status = 1, finishedSegment(request, newBoundary, contentRootSegment), queueCompletedSegment(newBoundary, contentRootSegment), 0 === newBoundary.pendingTasks && 0 === newBoundary.status) {
                  if (newBoundary.status = 1, !isEligibleForOutlining(request, newBoundary)) {
                    null !== prevRow && 0 === --prevRow.pendingTasks && finishSuspenseListRow(request, prevRow);
                    0 === request.pendingRootTasks && task.blockedPreamble && preparePreamble(request);
                    break a;
                  }
                } else
                  null !== prevRow && prevRow.together && tryToResolveTogetherRow(request, prevRow);
              } catch (thrownValue$31) {
                newBoundary.status = 4, 12 === request.status ? (contentRootSegment.status = 3, newProps = request.fatalError) : (contentRootSegment.status = 4, newProps = thrownValue$31), defaultProps = getThrownInfo(task.componentStack), initialState2 = logRecoverableError(
                  request,
                  newProps,
                  defaultProps
                ), newBoundary.errorDigest = initialState2, untrackBoundary(request, newBoundary);
              } finally {
                task.blockedBoundary = propName$44, task.blockedPreamble = propName, task.hoistableState = parentHoistableState, task.blockedSegment = parentSegment, task.keyPath = type2, task.formatContext = ref2, task.row = prevRow;
              }
              task = createRenderTask(
                request,
                null,
                fallback,
                -1,
                propName$44,
                boundarySegment,
                newBoundary.fallbackPreamble,
                newBoundary.fallbackState,
                fallbackAbortSet,
                [keyPath[0], "Suspense Fallback", keyPath[2]],
                getSuspenseFallbackFormatContext(
                  request.resumableState,
                  task.formatContext
                ),
                task.context,
                task.treeContext,
                task.row,
                replaceSuspenseComponentStackWithSuspenseFallbackStack(
                  task.componentStack
                )
              );
              pushComponentStack(task);
              request.pingedTasks.push(task);
            }
          }
          return;
      }
      if ("object" === typeof type2 && null !== type2)
        switch (type2.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            if ("ref" in props)
              for (parentSegment in newProps = {}, props)
                "ref" !== parentSegment && (newProps[parentSegment] = props[parentSegment]);
            else newProps = props;
            type2 = renderWithHooks(
              request,
              task,
              keyPath,
              type2.render,
              newProps,
              ref2
            );
            finishFunctionComponent(
              request,
              task,
              keyPath,
              type2,
              0 !== localIdCounter,
              actionStateCounter,
              actionStateMatchingIndex
            );
            return;
          case REACT_MEMO_TYPE:
            renderElement(request, task, keyPath, type2.type, props, ref2);
            return;
          case REACT_CONTEXT_TYPE:
            defaultProps = props.children;
            newProps = task.keyPath;
            props = props.value;
            initialState2 = type2._currentValue;
            type2._currentValue = props;
            ref2 = currentActiveSnapshot;
            currentActiveSnapshot = type2 = {
              parent: ref2,
              depth: null === ref2 ? 0 : ref2.depth + 1,
              context: type2,
              parentValue: initialState2,
              value: props
            };
            task.context = type2;
            task.keyPath = keyPath;
            renderNodeDestructive(request, task, defaultProps, -1);
            request = currentActiveSnapshot;
            if (null === request)
              throw Error(
                "Tried to pop a Context at the root of the app. This is a bug in React."
              );
            request.context._currentValue = request.parentValue;
            request = currentActiveSnapshot = request.parent;
            task.context = request;
            task.keyPath = newProps;
            return;
          case REACT_CONSUMER_TYPE:
            props = props.children;
            type2 = props(type2._context._currentValue);
            props = task.keyPath;
            task.keyPath = keyPath;
            renderNodeDestructive(request, task, type2, -1);
            task.keyPath = props;
            return;
          case REACT_LAZY_TYPE:
            newProps = type2._init;
            type2 = newProps(type2._payload);
            if (12 === request.status) throw null;
            renderElement(request, task, keyPath, type2, props, ref2);
            return;
        }
      throw Error(
        "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + ((null == type2 ? type2 : typeof type2) + ".")
      );
    }
  }
  function resumeNode(request, task, segmentId, node2, childIndex) {
    var prevReplay = task.replay, blockedBoundary = task.blockedBoundary, resumedSegment = createPendingSegment(
      request,
      0,
      null,
      task.formatContext,
      false,
      false
    );
    resumedSegment.id = segmentId;
    resumedSegment.parentFlushed = true;
    try {
      task.replay = null, task.blockedSegment = resumedSegment, renderNode(request, task, node2, childIndex), resumedSegment.status = 1, finishedSegment(request, blockedBoundary, resumedSegment), null === blockedBoundary ? request.completedRootSegment = resumedSegment : (queueCompletedSegment(blockedBoundary, resumedSegment), blockedBoundary.parentFlushed && request.partialBoundaries.push(blockedBoundary));
    } finally {
      task.replay = prevReplay, task.blockedSegment = null;
    }
  }
  function renderNodeDestructive(request, task, node2, childIndex) {
    null !== task.replay && "number" === typeof task.replay.slots ? resumeNode(request, task, task.replay.slots, node2, childIndex) : (task.node = node2, task.childIndex = childIndex, node2 = task.componentStack, pushComponentStack(task), retryNode(request, task), task.componentStack = node2);
  }
  function retryNode(request, task) {
    var node2 = task.node, childIndex = task.childIndex;
    if (null !== node2) {
      if ("object" === typeof node2) {
        switch (node2.$$typeof) {
          case REACT_ELEMENT_TYPE:
            var type2 = node2.type, key = node2.key, props = node2.props;
            node2 = props.ref;
            var ref2 = void 0 !== node2 ? node2 : null, name2 = getComponentNameFromType(type2), keyOrIndex = null == key ? -1 === childIndex ? 0 : childIndex : key;
            key = [task.keyPath, name2, keyOrIndex];
            if (null !== task.replay)
              a: {
                var replay = task.replay;
                childIndex = replay.nodes;
                for (node2 = 0; node2 < childIndex.length; node2++) {
                  var node$jscomp$0 = childIndex[node2];
                  if (keyOrIndex === node$jscomp$0[1]) {
                    if (4 === node$jscomp$0.length) {
                      if (null !== name2 && name2 !== node$jscomp$0[0])
                        throw Error(
                          "Expected the resume to render <" + node$jscomp$0[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
                        );
                      var childNodes = node$jscomp$0[2];
                      name2 = node$jscomp$0[3];
                      keyOrIndex = task.node;
                      task.replay = {
                        nodes: childNodes,
                        slots: name2,
                        pendingTasks: 1
                      };
                      try {
                        renderElement(request, task, key, type2, props, ref2);
                        if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                          throw Error(
                            "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                          );
                        task.replay.pendingTasks--;
                      } catch (x2) {
                        if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
                          throw task.node === keyOrIndex ? task.replay = replay : childIndex.splice(node2, 1), x2;
                        task.replay.pendingTasks--;
                        props = getThrownInfo(task.componentStack);
                        key = request;
                        request = task.blockedBoundary;
                        type2 = x2;
                        props = logRecoverableError(key, type2, props);
                        abortRemainingReplayNodes(
                          key,
                          request,
                          childNodes,
                          name2,
                          type2,
                          props
                        );
                      }
                      task.replay = replay;
                    } else {
                      if (type2 !== REACT_SUSPENSE_TYPE)
                        throw Error(
                          "Expected the resume to render <Suspense> in this slot but instead it rendered <" + (getComponentNameFromType(type2) || "Unknown") + ">. The tree doesn't match so React will fallback to client rendering."
                        );
                      b: {
                        replay = void 0;
                        type2 = node$jscomp$0[5];
                        ref2 = node$jscomp$0[2];
                        name2 = node$jscomp$0[3];
                        keyOrIndex = null === node$jscomp$0[4] ? [] : node$jscomp$0[4][2];
                        node$jscomp$0 = null === node$jscomp$0[4] ? null : node$jscomp$0[4][3];
                        var prevKeyPath = task.keyPath, prevContext = task.formatContext, prevRow = task.row, previousReplaySet = task.replay, parentBoundary = task.blockedBoundary, parentHoistableState = task.hoistableState, content2 = props.children, fallback = props.fallback, fallbackAbortSet = /* @__PURE__ */ new Set();
                        props = 2 > task.formatContext.insertionMode ? createSuspenseBoundary(
                          request,
                          task.row,
                          fallbackAbortSet,
                          createPreambleState(),
                          createPreambleState()
                        ) : createSuspenseBoundary(
                          request,
                          task.row,
                          fallbackAbortSet,
                          null,
                          null
                        );
                        props.parentFlushed = true;
                        props.rootSegmentID = type2;
                        task.blockedBoundary = props;
                        task.hoistableState = props.contentState;
                        task.keyPath = key;
                        task.formatContext = getSuspenseContentFormatContext(
                          request.resumableState,
                          prevContext
                        );
                        task.row = null;
                        task.replay = {
                          nodes: ref2,
                          slots: name2,
                          pendingTasks: 1
                        };
                        try {
                          renderNode(request, task, content2, -1);
                          if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                            throw Error(
                              "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                            );
                          task.replay.pendingTasks--;
                          if (0 === props.pendingTasks && 0 === props.status) {
                            props.status = 1;
                            request.completedBoundaries.push(props);
                            break b;
                          }
                        } catch (error) {
                          props.status = 4, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
                            request,
                            error,
                            childNodes
                          ), props.errorDigest = replay, task.replay.pendingTasks--, request.clientRenderedBoundaries.push(props);
                        } finally {
                          task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath, task.formatContext = prevContext, task.row = prevRow;
                        }
                        childNodes = createReplayTask(
                          request,
                          null,
                          {
                            nodes: keyOrIndex,
                            slots: node$jscomp$0,
                            pendingTasks: 0
                          },
                          fallback,
                          -1,
                          parentBoundary,
                          props.fallbackState,
                          fallbackAbortSet,
                          [key[0], "Suspense Fallback", key[2]],
                          getSuspenseFallbackFormatContext(
                            request.resumableState,
                            task.formatContext
                          ),
                          task.context,
                          task.treeContext,
                          task.row,
                          replaceSuspenseComponentStackWithSuspenseFallbackStack(
                            task.componentStack
                          )
                        );
                        pushComponentStack(childNodes);
                        request.pingedTasks.push(childNodes);
                      }
                    }
                    childIndex.splice(node2, 1);
                    break a;
                  }
                }
              }
            else renderElement(request, task, key, type2, props, ref2);
            return;
          case REACT_PORTAL_TYPE:
            throw Error(
              "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render."
            );
          case REACT_LAZY_TYPE:
            childNodes = node2._init;
            node2 = childNodes(node2._payload);
            if (12 === request.status) throw null;
            renderNodeDestructive(request, task, node2, childIndex);
            return;
        }
        if (isArrayImpl(node2)) {
          renderChildrenArray(request, task, node2, childIndex);
          return;
        }
        if (childNodes = getIteratorFn(node2)) {
          if (childNodes = childNodes.call(node2)) {
            node2 = childNodes.next();
            if (!node2.done) {
              props = [];
              do
                props.push(node2.value), node2 = childNodes.next();
              while (!node2.done);
              renderChildrenArray(request, task, props, childIndex);
            }
            return;
          }
        }
        if ("function" === typeof node2.then)
          return task.thenableState = null, renderNodeDestructive(request, task, unwrapThenable(node2), childIndex);
        if (node2.$$typeof === REACT_CONTEXT_TYPE)
          return renderNodeDestructive(
            request,
            task,
            node2._currentValue,
            childIndex
          );
        childIndex = Object.prototype.toString.call(node2);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === childIndex ? "object with keys {" + Object.keys(node2).join(", ") + "}" : childIndex) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      if ("string" === typeof node2)
        childIndex = task.blockedSegment, null !== childIndex && (childIndex.lastPushedText = pushTextInstance(
          childIndex.chunks,
          node2,
          request.renderState,
          childIndex.lastPushedText
        ));
      else if ("number" === typeof node2 || "bigint" === typeof node2)
        childIndex = task.blockedSegment, null !== childIndex && (childIndex.lastPushedText = pushTextInstance(
          childIndex.chunks,
          "" + node2,
          request.renderState,
          childIndex.lastPushedText
        ));
    }
  }
  function renderChildrenArray(request, task, children, childIndex) {
    var prevKeyPath = task.keyPath;
    if (-1 !== childIndex && (task.keyPath = [task.keyPath, "Fragment", childIndex], null !== task.replay)) {
      for (var replay = task.replay, replayNodes = replay.nodes, j2 = 0; j2 < replayNodes.length; j2++) {
        var node2 = replayNodes[j2];
        if (node2[1] === childIndex) {
          childIndex = node2[2];
          node2 = node2[3];
          task.replay = { nodes: childIndex, slots: node2, pendingTasks: 1 };
          try {
            renderChildrenArray(request, task, children, -1);
            if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
              throw Error(
                "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
              );
            task.replay.pendingTasks--;
          } catch (x2) {
            if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
              throw x2;
            task.replay.pendingTasks--;
            children = getThrownInfo(task.componentStack);
            var boundary = task.blockedBoundary, error = x2;
            children = logRecoverableError(request, error, children);
            abortRemainingReplayNodes(
              request,
              boundary,
              childIndex,
              node2,
              error,
              children
            );
          }
          task.replay = replay;
          replayNodes.splice(j2, 1);
          break;
        }
      }
      task.keyPath = prevKeyPath;
      return;
    }
    replay = task.treeContext;
    replayNodes = children.length;
    if (null !== task.replay && (j2 = task.replay.slots, null !== j2 && "object" === typeof j2)) {
      for (childIndex = 0; childIndex < replayNodes; childIndex++)
        node2 = children[childIndex], task.treeContext = pushTreeContext(replay, replayNodes, childIndex), boundary = j2[childIndex], "number" === typeof boundary ? (resumeNode(request, task, boundary, node2, childIndex), delete j2[childIndex]) : renderNode(request, task, node2, childIndex);
      task.treeContext = replay;
      task.keyPath = prevKeyPath;
      return;
    }
    for (j2 = 0; j2 < replayNodes; j2++)
      childIndex = children[j2], task.treeContext = pushTreeContext(replay, replayNodes, j2), renderNode(request, task, childIndex, j2);
    task.treeContext = replay;
    task.keyPath = prevKeyPath;
  }
  function trackPostponedBoundary(request, trackedPostpones, boundary) {
    boundary.status = 5;
    boundary.rootSegmentID = request.nextSegmentId++;
    request = boundary.trackedContentKeyPath;
    if (null === request)
      throw Error(
        "It should not be possible to postpone at the root. This is a bug in React."
      );
    var fallbackReplayNode = boundary.trackedFallbackNode, children = [], boundaryNode = trackedPostpones.workingMap.get(request);
    if (void 0 === boundaryNode)
      return boundary = [
        request[1],
        request[2],
        children,
        null,
        fallbackReplayNode,
        boundary.rootSegmentID
      ], trackedPostpones.workingMap.set(request, boundary), addToReplayParent(boundary, request[0], trackedPostpones), boundary;
    boundaryNode[4] = fallbackReplayNode;
    boundaryNode[5] = boundary.rootSegmentID;
    return boundaryNode;
  }
  function trackPostpone(request, trackedPostpones, task, segment) {
    segment.status = 5;
    var keyPath = task.keyPath, boundary = task.blockedBoundary;
    if (null === boundary)
      segment.id = request.nextSegmentId++, trackedPostpones.rootSlots = segment.id, null !== request.completedRootSegment && (request.completedRootSegment.status = 5);
    else {
      if (null !== boundary && 0 === boundary.status) {
        var boundaryNode = trackPostponedBoundary(
          request,
          trackedPostpones,
          boundary
        );
        if (boundary.trackedContentKeyPath === keyPath && -1 === task.childIndex) {
          -1 === segment.id && (segment.id = segment.parentFlushed ? boundary.rootSegmentID : request.nextSegmentId++);
          boundaryNode[3] = segment.id;
          return;
        }
      }
      -1 === segment.id && (segment.id = segment.parentFlushed && null !== boundary ? boundary.rootSegmentID : request.nextSegmentId++);
      if (-1 === task.childIndex)
        null === keyPath ? trackedPostpones.rootSlots = segment.id : (task = trackedPostpones.workingMap.get(keyPath), void 0 === task ? (task = [keyPath[1], keyPath[2], [], segment.id], addToReplayParent(task, keyPath[0], trackedPostpones)) : task[3] = segment.id);
      else {
        if (null === keyPath)
          if (request = trackedPostpones.rootSlots, null === request)
            request = trackedPostpones.rootSlots = {};
          else {
            if ("number" === typeof request)
              throw Error(
                "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
              );
          }
        else if (boundary = trackedPostpones.workingMap, boundaryNode = boundary.get(keyPath), void 0 === boundaryNode)
          request = {}, boundaryNode = [keyPath[1], keyPath[2], [], request], boundary.set(keyPath, boundaryNode), addToReplayParent(boundaryNode, keyPath[0], trackedPostpones);
        else if (request = boundaryNode[3], null === request)
          request = boundaryNode[3] = {};
        else if ("number" === typeof request)
          throw Error(
            "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
          );
        request[task.childIndex] = segment.id;
      }
    }
  }
  function untrackBoundary(request, boundary) {
    request = request.trackedPostpones;
    null !== request && (boundary = boundary.trackedContentKeyPath, null !== boundary && (boundary = request.workingMap.get(boundary), void 0 !== boundary && (boundary.length = 4, boundary[2] = [], boundary[3] = null)));
  }
  function spawnNewSuspendedReplayTask(request, task, thenableState2) {
    return createReplayTask(
      request,
      thenableState2,
      task.replay,
      task.node,
      task.childIndex,
      task.blockedBoundary,
      task.hoistableState,
      task.abortSet,
      task.keyPath,
      task.formatContext,
      task.context,
      task.treeContext,
      task.row,
      task.componentStack
    );
  }
  function spawnNewSuspendedRenderTask(request, task, thenableState2) {
    var segment = task.blockedSegment, newSegment = createPendingSegment(
      request,
      segment.chunks.length,
      null,
      task.formatContext,
      segment.lastPushedText,
      true
    );
    segment.children.push(newSegment);
    segment.lastPushedText = false;
    return createRenderTask(
      request,
      thenableState2,
      task.node,
      task.childIndex,
      task.blockedBoundary,
      newSegment,
      task.blockedPreamble,
      task.hoistableState,
      task.abortSet,
      task.keyPath,
      task.formatContext,
      task.context,
      task.treeContext,
      task.row,
      task.componentStack
    );
  }
  function renderNode(request, task, node2, childIndex) {
    var previousFormatContext = task.formatContext, previousContext = task.context, previousKeyPath = task.keyPath, previousTreeContext = task.treeContext, previousComponentStack = task.componentStack, segment = task.blockedSegment;
    if (null === segment) {
      segment = task.replay;
      try {
        return renderNodeDestructive(request, task, node2, childIndex);
      } catch (thrownValue) {
        if (resetHooksState(), node2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue, 12 !== request.status && "object" === typeof node2 && null !== node2) {
          if ("function" === typeof node2.then) {
            childIndex = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
            request = spawnNewSuspendedReplayTask(request, task, childIndex).ping;
            node2.then(request, request);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            task.replay = segment;
            switchContext(previousContext);
            return;
          }
          if ("Maximum call stack size exceeded" === node2.message) {
            node2 = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
            node2 = spawnNewSuspendedReplayTask(request, task, node2);
            request.pingedTasks.push(node2);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            task.replay = segment;
            switchContext(previousContext);
            return;
          }
        }
      }
    } else {
      var childrenLength = segment.children.length, chunkLength = segment.chunks.length;
      try {
        return renderNodeDestructive(request, task, node2, childIndex);
      } catch (thrownValue$63) {
        if (resetHooksState(), segment.children.length = childrenLength, segment.chunks.length = chunkLength, node2 = thrownValue$63 === SuspenseException ? getSuspendedThenable() : thrownValue$63, 12 !== request.status && "object" === typeof node2 && null !== node2) {
          if ("function" === typeof node2.then) {
            segment = node2;
            node2 = thrownValue$63 === SuspenseException ? getThenableStateAfterSuspending() : null;
            request = spawnNewSuspendedRenderTask(request, task, node2).ping;
            segment.then(request, request);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            switchContext(previousContext);
            return;
          }
          if ("Maximum call stack size exceeded" === node2.message) {
            segment = thrownValue$63 === SuspenseException ? getThenableStateAfterSuspending() : null;
            segment = spawnNewSuspendedRenderTask(request, task, segment);
            request.pingedTasks.push(segment);
            task.formatContext = previousFormatContext;
            task.context = previousContext;
            task.keyPath = previousKeyPath;
            task.treeContext = previousTreeContext;
            task.componentStack = previousComponentStack;
            switchContext(previousContext);
            return;
          }
        }
      }
    }
    task.formatContext = previousFormatContext;
    task.context = previousContext;
    task.keyPath = previousKeyPath;
    task.treeContext = previousTreeContext;
    switchContext(previousContext);
    throw node2;
  }
  function abortTaskSoft(task) {
    var boundary = task.blockedBoundary, segment = task.blockedSegment;
    null !== segment && (segment.status = 3, finishedTask(this, boundary, task.row, segment));
  }
  function abortRemainingReplayNodes(request$jscomp$0, boundary, nodes, slots, error, errorDigest$jscomp$0) {
    for (var i = 0; i < nodes.length; i++) {
      var node2 = nodes[i];
      if (4 === node2.length)
        abortRemainingReplayNodes(
          request$jscomp$0,
          boundary,
          node2[2],
          node2[3],
          error,
          errorDigest$jscomp$0
        );
      else {
        node2 = node2[5];
        var request = request$jscomp$0, errorDigest = errorDigest$jscomp$0, resumedBoundary = createSuspenseBoundary(
          request,
          null,
          /* @__PURE__ */ new Set(),
          null,
          null
        );
        resumedBoundary.parentFlushed = true;
        resumedBoundary.rootSegmentID = node2;
        resumedBoundary.status = 4;
        resumedBoundary.errorDigest = errorDigest;
        resumedBoundary.parentFlushed && request.clientRenderedBoundaries.push(resumedBoundary);
      }
    }
    nodes.length = 0;
    if (null !== slots) {
      if (null === boundary)
        throw Error(
          "We should not have any resumable nodes in the shell. This is a bug in React."
        );
      4 !== boundary.status && (boundary.status = 4, boundary.errorDigest = errorDigest$jscomp$0, boundary.parentFlushed && request$jscomp$0.clientRenderedBoundaries.push(boundary));
      if ("object" === typeof slots) for (var index2 in slots) delete slots[index2];
    }
  }
  function abortTask(task, request, error) {
    var boundary = task.blockedBoundary, segment = task.blockedSegment;
    if (null !== segment) {
      if (6 === segment.status) return;
      segment.status = 3;
    }
    var errorInfo = getThrownInfo(task.componentStack);
    if (null === boundary) {
      if (13 !== request.status && 14 !== request.status) {
        boundary = task.replay;
        if (null === boundary) {
          null !== request.trackedPostpones && null !== segment ? (boundary = request.trackedPostpones, logRecoverableError(request, error, errorInfo), trackPostpone(request, boundary, task, segment), finishedTask(request, null, task.row, segment)) : (logRecoverableError(request, error, errorInfo), fatalError(request, error));
          return;
        }
        boundary.pendingTasks--;
        0 === boundary.pendingTasks && 0 < boundary.nodes.length && (segment = logRecoverableError(request, error, errorInfo), abortRemainingReplayNodes(
          request,
          null,
          boundary.nodes,
          boundary.slots,
          error,
          segment
        ));
        request.pendingRootTasks--;
        0 === request.pendingRootTasks && completeShell(request);
      }
    } else {
      var trackedPostpones$64 = request.trackedPostpones;
      if (4 !== boundary.status) {
        if (null !== trackedPostpones$64 && null !== segment)
          return logRecoverableError(request, error, errorInfo), trackPostpone(request, trackedPostpones$64, task, segment), boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
            return abortTask(fallbackTask, request, error);
          }), boundary.fallbackAbortableTasks.clear(), finishedTask(request, boundary, task.row, segment);
        boundary.status = 4;
        segment = logRecoverableError(request, error, errorInfo);
        boundary.status = 4;
        boundary.errorDigest = segment;
        untrackBoundary(request, boundary);
        boundary.parentFlushed && request.clientRenderedBoundaries.push(boundary);
      }
      boundary.pendingTasks--;
      segment = boundary.row;
      null !== segment && 0 === --segment.pendingTasks && finishSuspenseListRow(request, segment);
      boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
        return abortTask(fallbackTask, request, error);
      });
      boundary.fallbackAbortableTasks.clear();
    }
    task = task.row;
    null !== task && 0 === --task.pendingTasks && finishSuspenseListRow(request, task);
    request.allPendingTasks--;
    0 === request.allPendingTasks && completeAll(request);
  }
  function safelyEmitEarlyPreloads(request, shellComplete) {
    try {
      var renderState = request.renderState, onHeaders = renderState.onHeaders;
      if (onHeaders) {
        var headers = renderState.headers;
        if (headers) {
          renderState.headers = null;
          var linkHeader = headers.preconnects;
          headers.fontPreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.fontPreloads);
          headers.highImagePreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.highImagePreloads);
          if (!shellComplete) {
            var queueIter = renderState.styles.values(), queueStep = queueIter.next();
            b: for (; 0 < headers.remainingCapacity && !queueStep.done; queueStep = queueIter.next())
              for (var sheetIter = queueStep.value.sheets.values(), sheetStep = sheetIter.next(); 0 < headers.remainingCapacity && !sheetStep.done; sheetStep = sheetIter.next()) {
                var sheet = sheetStep.value, props = sheet.props, key = props.href, props$jscomp$0 = sheet.props, header = getPreloadAsHeader(props$jscomp$0.href, "style", {
                  crossOrigin: props$jscomp$0.crossOrigin,
                  integrity: props$jscomp$0.integrity,
                  nonce: props$jscomp$0.nonce,
                  type: props$jscomp$0.type,
                  fetchPriority: props$jscomp$0.fetchPriority,
                  referrerPolicy: props$jscomp$0.referrerPolicy,
                  media: props$jscomp$0.media
                });
                if (0 <= (headers.remainingCapacity -= header.length + 2))
                  renderState.resets.style[key] = PRELOAD_NO_CREDS, linkHeader && (linkHeader += ", "), linkHeader += header, renderState.resets.style[key] = "string" === typeof props.crossOrigin || "string" === typeof props.integrity ? [props.crossOrigin, props.integrity] : PRELOAD_NO_CREDS;
                else break b;
              }
          }
          linkHeader ? onHeaders({ Link: linkHeader }) : onHeaders({});
        }
      }
    } catch (error) {
      logRecoverableError(request, error, {});
    }
  }
  function completeShell(request) {
    null === request.trackedPostpones && safelyEmitEarlyPreloads(request, true);
    null === request.trackedPostpones && preparePreamble(request);
    request.onShellError = noop2;
    request = request.onShellReady;
    request();
  }
  function completeAll(request) {
    safelyEmitEarlyPreloads(
      request,
      null === request.trackedPostpones ? true : null === request.completedRootSegment || 5 !== request.completedRootSegment.status
    );
    preparePreamble(request);
    request = request.onAllReady;
    request();
  }
  function queueCompletedSegment(boundary, segment) {
    if (0 === segment.chunks.length && 1 === segment.children.length && null === segment.children[0].boundary && -1 === segment.children[0].id) {
      var childSegment = segment.children[0];
      childSegment.id = segment.id;
      childSegment.parentFlushed = true;
      1 !== childSegment.status && 3 !== childSegment.status && 4 !== childSegment.status || queueCompletedSegment(boundary, childSegment);
    } else boundary.completedSegments.push(segment);
  }
  function finishedSegment(request, boundary, segment) {
    if (null !== byteLengthOfChunk) {
      segment = segment.chunks;
      for (var segmentByteSize = 0, i = 0; i < segment.length; i++)
        segmentByteSize += byteLengthOfChunk(segment[i]);
      null === boundary ? request.byteSize += segmentByteSize : boundary.byteSize += segmentByteSize;
    }
  }
  function finishedTask(request, boundary, row, segment) {
    null !== row && (0 === --row.pendingTasks ? finishSuspenseListRow(request, row) : row.together && tryToResolveTogetherRow(request, row));
    request.allPendingTasks--;
    if (null === boundary) {
      if (null !== segment && segment.parentFlushed) {
        if (null !== request.completedRootSegment)
          throw Error(
            "There can only be one root segment. This is a bug in React."
          );
        request.completedRootSegment = segment;
      }
      request.pendingRootTasks--;
      0 === request.pendingRootTasks && completeShell(request);
    } else if (boundary.pendingTasks--, 4 !== boundary.status)
      if (0 === boundary.pendingTasks)
        if (0 === boundary.status && (boundary.status = 1), null !== segment && segment.parentFlushed && (1 === segment.status || 3 === segment.status) && queueCompletedSegment(boundary, segment), boundary.parentFlushed && request.completedBoundaries.push(boundary), 1 === boundary.status)
          row = boundary.row, null !== row && hoistHoistables(row.hoistables, boundary.contentState), isEligibleForOutlining(request, boundary) || (boundary.fallbackAbortableTasks.forEach(abortTaskSoft, request), boundary.fallbackAbortableTasks.clear(), null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row)), 0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary.contentPreamble && preparePreamble(request);
        else {
          if (5 === boundary.status && (boundary = boundary.row, null !== boundary)) {
            if (null !== request.trackedPostpones) {
              row = request.trackedPostpones;
              var postponedRow = boundary.next;
              if (null !== postponedRow && (segment = postponedRow.boundaries, null !== segment))
                for (postponedRow.boundaries = null, postponedRow = 0; postponedRow < segment.length; postponedRow++) {
                  var postponedBoundary = segment[postponedRow];
                  trackPostponedBoundary(request, row, postponedBoundary);
                  finishedTask(request, postponedBoundary, null, null);
                }
            }
            0 === --boundary.pendingTasks && finishSuspenseListRow(request, boundary);
          }
        }
      else
        null === segment || !segment.parentFlushed || 1 !== segment.status && 3 !== segment.status || (queueCompletedSegment(boundary, segment), 1 === boundary.completedSegments.length && boundary.parentFlushed && request.partialBoundaries.push(boundary)), boundary = boundary.row, null !== boundary && boundary.together && tryToResolveTogetherRow(request, boundary);
    0 === request.allPendingTasks && completeAll(request);
  }
  function performWork(request$jscomp$2) {
    if (14 !== request$jscomp$2.status && 13 !== request$jscomp$2.status) {
      var prevContext = currentActiveSnapshot, prevDispatcher = ReactSharedInternals.H;
      ReactSharedInternals.H = HooksDispatcher;
      var prevAsyncDispatcher = ReactSharedInternals.A;
      ReactSharedInternals.A = DefaultAsyncDispatcher;
      var prevRequest = currentRequest;
      currentRequest = request$jscomp$2;
      var prevResumableState = currentResumableState;
      currentResumableState = request$jscomp$2.resumableState;
      try {
        var pingedTasks = request$jscomp$2.pingedTasks, i;
        for (i = 0; i < pingedTasks.length; i++) {
          var task = pingedTasks[i], request = request$jscomp$2, segment = task.blockedSegment;
          if (null === segment) {
            var request$jscomp$0 = request;
            if (0 !== task.replay.pendingTasks) {
              switchContext(task.context);
              try {
                "number" === typeof task.replay.slots ? resumeNode(
                  request$jscomp$0,
                  task,
                  task.replay.slots,
                  task.node,
                  task.childIndex
                ) : retryNode(request$jscomp$0, task);
                if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                  throw Error(
                    "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                  );
                task.replay.pendingTasks--;
                task.abortSet.delete(task);
                finishedTask(
                  request$jscomp$0,
                  task.blockedBoundary,
                  task.row,
                  null
                );
              } catch (thrownValue) {
                resetHooksState();
                var x2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue;
                if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then) {
                  var ping = task.ping;
                  x2.then(ping, ping);
                  task.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                } else {
                  task.replay.pendingTasks--;
                  task.abortSet.delete(task);
                  var errorInfo = getThrownInfo(task.componentStack);
                  request = void 0;
                  var request$jscomp$1 = request$jscomp$0, boundary = task.blockedBoundary, error$jscomp$0 = 12 === request$jscomp$0.status ? request$jscomp$0.fatalError : x2, replayNodes = task.replay.nodes, resumeSlots = task.replay.slots;
                  request = logRecoverableError(
                    request$jscomp$1,
                    error$jscomp$0,
                    errorInfo
                  );
                  abortRemainingReplayNodes(
                    request$jscomp$1,
                    boundary,
                    replayNodes,
                    resumeSlots,
                    error$jscomp$0,
                    request
                  );
                  request$jscomp$0.pendingRootTasks--;
                  0 === request$jscomp$0.pendingRootTasks && completeShell(request$jscomp$0);
                  request$jscomp$0.allPendingTasks--;
                  0 === request$jscomp$0.allPendingTasks && completeAll(request$jscomp$0);
                }
              } finally {
              }
            }
          } else if (request$jscomp$0 = void 0, request$jscomp$1 = segment, 0 === request$jscomp$1.status) {
            request$jscomp$1.status = 6;
            switchContext(task.context);
            var childrenLength = request$jscomp$1.children.length, chunkLength = request$jscomp$1.chunks.length;
            try {
              retryNode(request, task), request$jscomp$1.lastPushedText && request$jscomp$1.textEmbedded && request$jscomp$1.chunks.push(textSeparator), task.abortSet.delete(task), request$jscomp$1.status = 1, finishedSegment(request, task.blockedBoundary, request$jscomp$1), finishedTask(
                request,
                task.blockedBoundary,
                task.row,
                request$jscomp$1
              );
            } catch (thrownValue) {
              resetHooksState();
              request$jscomp$1.children.length = childrenLength;
              request$jscomp$1.chunks.length = chunkLength;
              var x$jscomp$0 = thrownValue === SuspenseException ? getSuspendedThenable() : 12 === request.status ? request.fatalError : thrownValue;
              if (12 === request.status && null !== request.trackedPostpones) {
                var trackedPostpones = request.trackedPostpones, thrownInfo = getThrownInfo(task.componentStack);
                task.abortSet.delete(task);
                logRecoverableError(request, x$jscomp$0, thrownInfo);
                trackPostpone(request, trackedPostpones, task, request$jscomp$1);
                finishedTask(
                  request,
                  task.blockedBoundary,
                  task.row,
                  request$jscomp$1
                );
              } else if ("object" === typeof x$jscomp$0 && null !== x$jscomp$0 && "function" === typeof x$jscomp$0.then) {
                request$jscomp$1.status = 0;
                task.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                var ping$jscomp$0 = task.ping;
                x$jscomp$0.then(ping$jscomp$0, ping$jscomp$0);
              } else {
                var errorInfo$jscomp$0 = getThrownInfo(task.componentStack);
                task.abortSet.delete(task);
                request$jscomp$1.status = 4;
                var boundary$jscomp$0 = task.blockedBoundary, row = task.row;
                null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
                request.allPendingTasks--;
                request$jscomp$0 = logRecoverableError(
                  request,
                  x$jscomp$0,
                  errorInfo$jscomp$0
                );
                if (null === boundary$jscomp$0) fatalError(request, x$jscomp$0);
                else if (boundary$jscomp$0.pendingTasks--, 4 !== boundary$jscomp$0.status) {
                  boundary$jscomp$0.status = 4;
                  boundary$jscomp$0.errorDigest = request$jscomp$0;
                  untrackBoundary(request, boundary$jscomp$0);
                  var boundaryRow = boundary$jscomp$0.row;
                  null !== boundaryRow && 0 === --boundaryRow.pendingTasks && finishSuspenseListRow(request, boundaryRow);
                  boundary$jscomp$0.parentFlushed && request.clientRenderedBoundaries.push(boundary$jscomp$0);
                  0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary$jscomp$0.contentPreamble && preparePreamble(request);
                }
                0 === request.allPendingTasks && completeAll(request);
              }
            } finally {
            }
          }
        }
        pingedTasks.splice(0, i);
        null !== request$jscomp$2.destination && flushCompletedQueues(request$jscomp$2, request$jscomp$2.destination);
      } catch (error) {
        logRecoverableError(request$jscomp$2, error, {}), fatalError(request$jscomp$2, error);
      } finally {
        currentResumableState = prevResumableState, ReactSharedInternals.H = prevDispatcher, ReactSharedInternals.A = prevAsyncDispatcher, prevDispatcher === HooksDispatcher && switchContext(prevContext), currentRequest = prevRequest;
      }
    }
  }
  function preparePreambleFromSubtree(request, segment, collectedPreambleSegments) {
    segment.preambleChildren.length && collectedPreambleSegments.push(segment.preambleChildren);
    for (var pendingPreambles = false, i = 0; i < segment.children.length; i++)
      pendingPreambles = preparePreambleFromSegment(
        request,
        segment.children[i],
        collectedPreambleSegments
      ) || pendingPreambles;
    return pendingPreambles;
  }
  function preparePreambleFromSegment(request, segment, collectedPreambleSegments) {
    var boundary = segment.boundary;
    if (null === boundary)
      return preparePreambleFromSubtree(
        request,
        segment,
        collectedPreambleSegments
      );
    var preamble = boundary.contentPreamble, fallbackPreamble = boundary.fallbackPreamble;
    if (null === preamble || null === fallbackPreamble) return false;
    switch (boundary.status) {
      case 1:
        hoistPreambleState(request.renderState, preamble);
        request.byteSize += boundary.byteSize;
        segment = boundary.completedSegments[0];
        if (!segment)
          throw Error(
            "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
          );
        return preparePreambleFromSubtree(
          request,
          segment,
          collectedPreambleSegments
        );
      case 5:
        if (null !== request.trackedPostpones) return true;
      case 4:
        if (1 === segment.status)
          return hoistPreambleState(request.renderState, fallbackPreamble), preparePreambleFromSubtree(
            request,
            segment,
            collectedPreambleSegments
          );
      default:
        return true;
    }
  }
  function preparePreamble(request) {
    if (request.completedRootSegment && null === request.completedPreambleSegments) {
      var collectedPreambleSegments = [], originalRequestByteSize = request.byteSize, hasPendingPreambles = preparePreambleFromSegment(
        request,
        request.completedRootSegment,
        collectedPreambleSegments
      ), preamble = request.renderState.preamble;
      false === hasPendingPreambles || preamble.headChunks && preamble.bodyChunks ? request.completedPreambleSegments = collectedPreambleSegments : request.byteSize = originalRequestByteSize;
    }
  }
  function flushSubtree(request, destination, segment, hoistableState) {
    segment.parentFlushed = true;
    switch (segment.status) {
      case 0:
        segment.id = request.nextSegmentId++;
      case 5:
        return hoistableState = segment.id, segment.lastPushedText = false, segment.textEmbedded = false, request = request.renderState, writeChunk(destination, placeholder1), writeChunk(destination, request.placeholderPrefix), request = hoistableState.toString(16), writeChunk(destination, request), writeChunkAndReturn(destination, placeholder2);
      case 1:
        segment.status = 2;
        var r = true, chunks = segment.chunks, chunkIdx = 0;
        segment = segment.children;
        for (var childIdx = 0; childIdx < segment.length; childIdx++) {
          for (r = segment[childIdx]; chunkIdx < r.index; chunkIdx++)
            writeChunk(destination, chunks[chunkIdx]);
          r = flushSegment(request, destination, r, hoistableState);
        }
        for (; chunkIdx < chunks.length - 1; chunkIdx++)
          writeChunk(destination, chunks[chunkIdx]);
        chunkIdx < chunks.length && (r = writeChunkAndReturn(destination, chunks[chunkIdx]));
        return r;
      case 3:
        return true;
      default:
        throw Error(
          "Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React."
        );
    }
  }
  var flushedByteSize = 0;
  function flushSegment(request, destination, segment, hoistableState) {
    var boundary = segment.boundary;
    if (null === boundary)
      return flushSubtree(request, destination, segment, hoistableState);
    boundary.parentFlushed = true;
    if (4 === boundary.status) {
      var row = boundary.row;
      null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
      boundary = boundary.errorDigest;
      writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
      writeChunk(destination, clientRenderedSuspenseBoundaryError1);
      boundary && (writeChunk(destination, clientRenderedSuspenseBoundaryError1A), writeChunk(destination, escapeTextForBrowser(boundary)), writeChunk(
        destination,
        clientRenderedSuspenseBoundaryErrorAttrInterstitial
      ));
      writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
      flushSubtree(request, destination, segment, hoistableState);
    } else if (1 !== boundary.status)
      0 === boundary.status && (boundary.rootSegmentID = request.nextSegmentId++), 0 < boundary.completedSegments.length && request.partialBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
        destination,
        request.renderState,
        boundary.rootSegmentID
      ), hoistableState && hoistHoistables(hoistableState, boundary.fallbackState), flushSubtree(request, destination, segment, hoistableState);
    else if (!flushingPartialBoundaries && isEligibleForOutlining(request, boundary) && (flushedByteSize + boundary.byteSize > request.progressiveChunkSize || hasSuspenseyContent(boundary.contentState)))
      boundary.rootSegmentID = request.nextSegmentId++, request.completedBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
        destination,
        request.renderState,
        boundary.rootSegmentID
      ), flushSubtree(request, destination, segment, hoistableState);
    else {
      flushedByteSize += boundary.byteSize;
      hoistableState && hoistHoistables(hoistableState, boundary.contentState);
      segment = boundary.row;
      null !== segment && isEligibleForOutlining(request, boundary) && 0 === --segment.pendingTasks && finishSuspenseListRow(request, segment);
      writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
      segment = boundary.completedSegments;
      if (1 !== segment.length)
        throw Error(
          "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
        );
      flushSegment(request, destination, segment[0], hoistableState);
    }
    return writeChunkAndReturn(destination, endSuspenseBoundary);
  }
  function flushSegmentContainer(request, destination, segment, hoistableState) {
    writeStartSegment(
      destination,
      request.renderState,
      segment.parentFormatContext,
      segment.id
    );
    flushSegment(request, destination, segment, hoistableState);
    return writeEndSegment(destination, segment.parentFormatContext);
  }
  function flushCompletedBoundary(request, destination, boundary) {
    flushedByteSize = boundary.byteSize;
    for (var completedSegments = boundary.completedSegments, i = 0; i < completedSegments.length; i++)
      flushPartiallyCompletedSegment(
        request,
        destination,
        boundary,
        completedSegments[i]
      );
    completedSegments.length = 0;
    completedSegments = boundary.row;
    null !== completedSegments && isEligibleForOutlining(request, boundary) && 0 === --completedSegments.pendingTasks && finishSuspenseListRow(request, completedSegments);
    writeHoistablesForBoundary(
      destination,
      boundary.contentState,
      request.renderState
    );
    completedSegments = request.resumableState;
    request = request.renderState;
    i = boundary.rootSegmentID;
    boundary = boundary.contentState;
    var requiresStyleInsertion = request.stylesToHoist;
    request.stylesToHoist = false;
    writeChunk(destination, request.startInlineScript);
    writeChunk(destination, endOfStartTag);
    requiresStyleInsertion ? (0 === (completedSegments.instructions & 4) && (completedSegments.instructions |= 4, writeChunk(destination, clientRenderScriptFunctionOnly)), 0 === (completedSegments.instructions & 2) && (completedSegments.instructions |= 2, writeChunk(destination, completeBoundaryScriptFunctionOnly)), 0 === (completedSegments.instructions & 8) ? (completedSegments.instructions |= 8, writeChunk(destination, completeBoundaryWithStylesScript1FullPartial)) : writeChunk(destination, completeBoundaryWithStylesScript1Partial)) : (0 === (completedSegments.instructions & 2) && (completedSegments.instructions |= 2, writeChunk(destination, completeBoundaryScriptFunctionOnly)), writeChunk(destination, completeBoundaryScript1Partial));
    completedSegments = i.toString(16);
    writeChunk(destination, request.boundaryPrefix);
    writeChunk(destination, completedSegments);
    writeChunk(destination, completeBoundaryScript2);
    writeChunk(destination, request.segmentPrefix);
    writeChunk(destination, completedSegments);
    requiresStyleInsertion ? (writeChunk(destination, completeBoundaryScript3a), writeStyleResourceDependenciesInJS(destination, boundary)) : writeChunk(destination, completeBoundaryScript3b);
    boundary = writeChunkAndReturn(destination, completeBoundaryScriptEnd);
    return writeBootstrap(destination, request) && boundary;
  }
  function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
    if (2 === segment.status) return true;
    var hoistableState = boundary.contentState, segmentID = segment.id;
    if (-1 === segmentID) {
      if (-1 === (segment.id = boundary.rootSegmentID))
        throw Error(
          "A root segment ID must have been assigned by now. This is a bug in React."
        );
      return flushSegmentContainer(request, destination, segment, hoistableState);
    }
    if (segmentID === boundary.rootSegmentID)
      return flushSegmentContainer(request, destination, segment, hoistableState);
    flushSegmentContainer(request, destination, segment, hoistableState);
    boundary = request.resumableState;
    request = request.renderState;
    writeChunk(destination, request.startInlineScript);
    writeChunk(destination, endOfStartTag);
    0 === (boundary.instructions & 1) ? (boundary.instructions |= 1, writeChunk(destination, completeSegmentScript1Full)) : writeChunk(destination, completeSegmentScript1Partial);
    writeChunk(destination, request.segmentPrefix);
    segmentID = segmentID.toString(16);
    writeChunk(destination, segmentID);
    writeChunk(destination, completeSegmentScript2);
    writeChunk(destination, request.placeholderPrefix);
    writeChunk(destination, segmentID);
    destination = writeChunkAndReturn(destination, completeSegmentScriptEnd);
    return destination;
  }
  var flushingPartialBoundaries = false;
  function flushCompletedQueues(request, destination) {
    currentView = new Uint8Array(2048);
    writtenBytes = 0;
    destinationHasCapacity$1 = true;
    try {
      if (!(0 < request.pendingRootTasks)) {
        var i, completedRootSegment = request.completedRootSegment;
        if (null !== completedRootSegment) {
          if (5 === completedRootSegment.status) return;
          var completedPreambleSegments = request.completedPreambleSegments;
          if (null === completedPreambleSegments) return;
          flushedByteSize = request.byteSize;
          var resumableState = request.resumableState, renderState = request.renderState, preamble = renderState.preamble, htmlChunks = preamble.htmlChunks, headChunks = preamble.headChunks, i$jscomp$0;
          if (htmlChunks) {
            for (i$jscomp$0 = 0; i$jscomp$0 < htmlChunks.length; i$jscomp$0++)
              writeChunk(destination, htmlChunks[i$jscomp$0]);
            if (headChunks)
              for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
                writeChunk(destination, headChunks[i$jscomp$0]);
            else
              writeChunk(destination, startChunkForTag("head")), writeChunk(destination, endOfStartTag);
          } else if (headChunks)
            for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
              writeChunk(destination, headChunks[i$jscomp$0]);
          var charsetChunks = renderState.charsetChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < charsetChunks.length; i$jscomp$0++)
            writeChunk(destination, charsetChunks[i$jscomp$0]);
          charsetChunks.length = 0;
          renderState.preconnects.forEach(flushResource, destination);
          renderState.preconnects.clear();
          var viewportChunks = renderState.viewportChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < viewportChunks.length; i$jscomp$0++)
            writeChunk(destination, viewportChunks[i$jscomp$0]);
          viewportChunks.length = 0;
          renderState.fontPreloads.forEach(flushResource, destination);
          renderState.fontPreloads.clear();
          renderState.highImagePreloads.forEach(flushResource, destination);
          renderState.highImagePreloads.clear();
          currentlyFlushingRenderState = renderState;
          renderState.styles.forEach(flushStylesInPreamble, destination);
          currentlyFlushingRenderState = null;
          var importMapChunks = renderState.importMapChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < importMapChunks.length; i$jscomp$0++)
            writeChunk(destination, importMapChunks[i$jscomp$0]);
          importMapChunks.length = 0;
          renderState.bootstrapScripts.forEach(flushResource, destination);
          renderState.scripts.forEach(flushResource, destination);
          renderState.scripts.clear();
          renderState.bulkPreloads.forEach(flushResource, destination);
          renderState.bulkPreloads.clear();
          htmlChunks || headChunks || (resumableState.instructions |= 32);
          var hoistableChunks = renderState.hoistableChunks;
          for (i$jscomp$0 = 0; i$jscomp$0 < hoistableChunks.length; i$jscomp$0++)
            writeChunk(destination, hoistableChunks[i$jscomp$0]);
          for (resumableState = hoistableChunks.length = 0; resumableState < completedPreambleSegments.length; resumableState++) {
            var segments = completedPreambleSegments[resumableState];
            for (renderState = 0; renderState < segments.length; renderState++)
              flushSegment(request, destination, segments[renderState], null);
          }
          var preamble$jscomp$0 = request.renderState.preamble, headChunks$jscomp$0 = preamble$jscomp$0.headChunks;
          (preamble$jscomp$0.htmlChunks || headChunks$jscomp$0) && writeChunk(destination, endChunkForTag("head"));
          var bodyChunks = preamble$jscomp$0.bodyChunks;
          if (bodyChunks)
            for (completedPreambleSegments = 0; completedPreambleSegments < bodyChunks.length; completedPreambleSegments++)
              writeChunk(destination, bodyChunks[completedPreambleSegments]);
          flushSegment(request, destination, completedRootSegment, null);
          request.completedRootSegment = null;
          var renderState$jscomp$0 = request.renderState;
          if (0 !== request.allPendingTasks || 0 !== request.clientRenderedBoundaries.length || 0 !== request.completedBoundaries.length || null !== request.trackedPostpones && (0 !== request.trackedPostpones.rootNodes.length || null !== request.trackedPostpones.rootSlots)) {
            var resumableState$jscomp$0 = request.resumableState;
            if (0 === (resumableState$jscomp$0.instructions & 64)) {
              resumableState$jscomp$0.instructions |= 64;
              writeChunk(destination, renderState$jscomp$0.startInlineScript);
              if (0 === (resumableState$jscomp$0.instructions & 32)) {
                resumableState$jscomp$0.instructions |= 32;
                var shellId = "_" + resumableState$jscomp$0.idPrefix + "R_";
                writeChunk(destination, completedShellIdAttributeStart);
                writeChunk(destination, escapeTextForBrowser(shellId));
                writeChunk(destination, attributeEnd);
              }
              writeChunk(destination, endOfStartTag);
              writeChunk(destination, shellTimeRuntimeScript);
              writeChunkAndReturn(destination, endInlineScript);
            }
          }
          writeBootstrap(destination, renderState$jscomp$0);
        }
        var renderState$jscomp$1 = request.renderState;
        completedRootSegment = 0;
        var viewportChunks$jscomp$0 = renderState$jscomp$1.viewportChunks;
        for (completedRootSegment = 0; completedRootSegment < viewportChunks$jscomp$0.length; completedRootSegment++)
          writeChunk(destination, viewportChunks$jscomp$0[completedRootSegment]);
        viewportChunks$jscomp$0.length = 0;
        renderState$jscomp$1.preconnects.forEach(flushResource, destination);
        renderState$jscomp$1.preconnects.clear();
        renderState$jscomp$1.fontPreloads.forEach(flushResource, destination);
        renderState$jscomp$1.fontPreloads.clear();
        renderState$jscomp$1.highImagePreloads.forEach(
          flushResource,
          destination
        );
        renderState$jscomp$1.highImagePreloads.clear();
        renderState$jscomp$1.styles.forEach(preloadLateStyles, destination);
        renderState$jscomp$1.scripts.forEach(flushResource, destination);
        renderState$jscomp$1.scripts.clear();
        renderState$jscomp$1.bulkPreloads.forEach(flushResource, destination);
        renderState$jscomp$1.bulkPreloads.clear();
        var hoistableChunks$jscomp$0 = renderState$jscomp$1.hoistableChunks;
        for (completedRootSegment = 0; completedRootSegment < hoistableChunks$jscomp$0.length; completedRootSegment++)
          writeChunk(destination, hoistableChunks$jscomp$0[completedRootSegment]);
        hoistableChunks$jscomp$0.length = 0;
        var clientRenderedBoundaries = request.clientRenderedBoundaries;
        for (i = 0; i < clientRenderedBoundaries.length; i++) {
          var boundary = clientRenderedBoundaries[i];
          renderState$jscomp$1 = destination;
          var resumableState$jscomp$1 = request.resumableState, renderState$jscomp$2 = request.renderState, id = boundary.rootSegmentID, errorDigest = boundary.errorDigest;
          writeChunk(
            renderState$jscomp$1,
            renderState$jscomp$2.startInlineScript
          );
          writeChunk(renderState$jscomp$1, endOfStartTag);
          0 === (resumableState$jscomp$1.instructions & 4) ? (resumableState$jscomp$1.instructions |= 4, writeChunk(renderState$jscomp$1, clientRenderScript1Full)) : writeChunk(renderState$jscomp$1, clientRenderScript1Partial);
          writeChunk(renderState$jscomp$1, renderState$jscomp$2.boundaryPrefix);
          writeChunk(renderState$jscomp$1, id.toString(16));
          writeChunk(renderState$jscomp$1, clientRenderScript1A);
          errorDigest && (writeChunk(
            renderState$jscomp$1,
            clientRenderErrorScriptArgInterstitial
          ), writeChunk(
            renderState$jscomp$1,
            escapeJSStringsForInstructionScripts(errorDigest || "")
          ));
          var JSCompiler_inline_result = writeChunkAndReturn(
            renderState$jscomp$1,
            clientRenderScriptEnd
          );
          if (!JSCompiler_inline_result) {
            request.destination = null;
            i++;
            clientRenderedBoundaries.splice(0, i);
            return;
          }
        }
        clientRenderedBoundaries.splice(0, i);
        var completedBoundaries = request.completedBoundaries;
        for (i = 0; i < completedBoundaries.length; i++)
          if (!flushCompletedBoundary(request, destination, completedBoundaries[i])) {
            request.destination = null;
            i++;
            completedBoundaries.splice(0, i);
            return;
          }
        completedBoundaries.splice(0, i);
        completeWriting(destination);
        currentView = new Uint8Array(2048);
        writtenBytes = 0;
        flushingPartialBoundaries = destinationHasCapacity$1 = true;
        var partialBoundaries = request.partialBoundaries;
        for (i = 0; i < partialBoundaries.length; i++) {
          var boundary$70 = partialBoundaries[i];
          a: {
            clientRenderedBoundaries = request;
            boundary = destination;
            flushedByteSize = boundary$70.byteSize;
            var completedSegments = boundary$70.completedSegments;
            for (JSCompiler_inline_result = 0; JSCompiler_inline_result < completedSegments.length; JSCompiler_inline_result++)
              if (!flushPartiallyCompletedSegment(
                clientRenderedBoundaries,
                boundary,
                boundary$70,
                completedSegments[JSCompiler_inline_result]
              )) {
                JSCompiler_inline_result++;
                completedSegments.splice(0, JSCompiler_inline_result);
                var JSCompiler_inline_result$jscomp$0 = false;
                break a;
              }
            completedSegments.splice(0, JSCompiler_inline_result);
            var row = boundary$70.row;
            null !== row && row.together && 1 === boundary$70.pendingTasks && (1 === row.pendingTasks ? unblockSuspenseListRow(
              clientRenderedBoundaries,
              row,
              row.hoistables
            ) : row.pendingTasks--);
            JSCompiler_inline_result$jscomp$0 = writeHoistablesForBoundary(
              boundary,
              boundary$70.contentState,
              clientRenderedBoundaries.renderState
            );
          }
          if (!JSCompiler_inline_result$jscomp$0) {
            request.destination = null;
            i++;
            partialBoundaries.splice(0, i);
            return;
          }
        }
        partialBoundaries.splice(0, i);
        flushingPartialBoundaries = false;
        var largeBoundaries = request.completedBoundaries;
        for (i = 0; i < largeBoundaries.length; i++)
          if (!flushCompletedBoundary(request, destination, largeBoundaries[i])) {
            request.destination = null;
            i++;
            largeBoundaries.splice(0, i);
            return;
          }
        largeBoundaries.splice(0, i);
      }
    } finally {
      flushingPartialBoundaries = false, 0 === request.allPendingTasks && 0 === request.clientRenderedBoundaries.length && 0 === request.completedBoundaries.length ? (request.flushScheduled = false, i = request.resumableState, i.hasBody && writeChunk(destination, endChunkForTag("body")), i.hasHtml && writeChunk(destination, endChunkForTag("html")), completeWriting(destination), flushBuffered(destination), request.status = 14, destination.end(), request.destination = null) : (completeWriting(destination), flushBuffered(destination));
    }
  }
  function startWork(request) {
    request.flushScheduled = null !== request.destination;
    scheduleMicrotask(function() {
      return requestStorage.run(request, performWork, request);
    });
    setImmediate(function() {
      10 === request.status && (request.status = 11);
      null === request.trackedPostpones && requestStorage.run(
        request,
        enqueueEarlyPreloadsAfterInitialWork,
        request
      );
    });
  }
  function enqueueEarlyPreloadsAfterInitialWork(request) {
    safelyEmitEarlyPreloads(request, 0 === request.pendingRootTasks);
  }
  function enqueueFlush(request) {
    false === request.flushScheduled && 0 === request.pingedTasks.length && null !== request.destination && (request.flushScheduled = true, setImmediate(function() {
      var destination = request.destination;
      destination ? flushCompletedQueues(request, destination) : request.flushScheduled = false;
    }));
  }
  function startFlowing(request, destination) {
    if (13 === request.status)
      request.status = 14, destination.destroy(request.fatalError);
    else if (14 !== request.status && null === request.destination) {
      request.destination = destination;
      try {
        flushCompletedQueues(request, destination);
      } catch (error) {
        logRecoverableError(request, error, {}), fatalError(request, error);
      }
    }
  }
  function abort(request, reason) {
    if (11 === request.status || 10 === request.status) request.status = 12;
    try {
      var abortableTasks = request.abortableTasks;
      if (0 < abortableTasks.size) {
        var error = void 0 === reason ? Error("The render was aborted by the server without a reason.") : "object" === typeof reason && null !== reason && "function" === typeof reason.then ? Error("The render was aborted by the server with a promise.") : reason;
        request.fatalError = error;
        abortableTasks.forEach(function(task) {
          return abortTask(task, request, error);
        });
        abortableTasks.clear();
      }
      null !== request.destination && flushCompletedQueues(request, request.destination);
    } catch (error$72) {
      logRecoverableError(request, error$72, {}), fatalError(request, error$72);
    }
  }
  function addToReplayParent(node2, parentKeyPath, trackedPostpones) {
    if (null === parentKeyPath) trackedPostpones.rootNodes.push(node2);
    else {
      var workingMap = trackedPostpones.workingMap, parentNode = workingMap.get(parentKeyPath);
      void 0 === parentNode && (parentNode = [parentKeyPath[1], parentKeyPath[2], [], null], workingMap.set(parentKeyPath, parentNode), addToReplayParent(parentNode, parentKeyPath[0], trackedPostpones));
      parentNode[2].push(node2);
    }
  }
  function getPostponedState(request) {
    var trackedPostpones = request.trackedPostpones;
    if (null === trackedPostpones || 0 === trackedPostpones.rootNodes.length && null === trackedPostpones.rootSlots)
      return request.trackedPostpones = null;
    if (null === request.completedRootSegment || 5 !== request.completedRootSegment.status && null !== request.completedPreambleSegments) {
      var nextSegmentId = request.nextSegmentId;
      var replaySlots = trackedPostpones.rootSlots;
      var resumableState = request.resumableState;
      resumableState.bootstrapScriptContent = void 0;
      resumableState.bootstrapScripts = void 0;
      resumableState.bootstrapModules = void 0;
    } else {
      nextSegmentId = 0;
      replaySlots = -1;
      resumableState = request.resumableState;
      var renderState = request.renderState;
      resumableState.nextFormID = 0;
      resumableState.hasBody = false;
      resumableState.hasHtml = false;
      resumableState.unknownResources = { font: renderState.resets.font };
      resumableState.dnsResources = renderState.resets.dns;
      resumableState.connectResources = renderState.resets.connect;
      resumableState.imageResources = renderState.resets.image;
      resumableState.styleResources = renderState.resets.style;
      resumableState.scriptResources = {};
      resumableState.moduleUnknownResources = {};
      resumableState.moduleScriptResources = {};
      resumableState.instructions = 0;
    }
    return {
      nextSegmentId,
      rootFormatContext: request.rootFormatContext,
      progressiveChunkSize: request.progressiveChunkSize,
      resumableState: request.resumableState,
      replayNodes: trackedPostpones.rootNodes,
      replaySlots
    };
  }
  function ensureCorrectIsomorphicReactVersion() {
    var isomorphicReactPackageVersion = React2.version;
    if ("19.2.4" !== isomorphicReactPackageVersion)
      throw Error(
        'Incompatible React versions: The "react" and "react-dom" packages must have the exact same version. Instead got:\n  - react:      ' + (isomorphicReactPackageVersion + "\n  - react-dom:  19.2.4\nLearn more: https://react.dev/warnings/version-mismatch")
      );
  }
  ensureCorrectIsomorphicReactVersion();
  function createDrainHandler(destination, request) {
    return function() {
      return startFlowing(request, destination);
    };
  }
  function createCancelHandler(request, reason) {
    return function() {
      request.destination = null;
      abort(request, Error(reason));
    };
  }
  function createRequestImpl(children, options) {
    var resumableState = createResumableState(
      options ? options.identifierPrefix : void 0,
      options ? options.unstable_externalRuntimeSrc : void 0,
      options ? options.bootstrapScriptContent : void 0,
      options ? options.bootstrapScripts : void 0,
      options ? options.bootstrapModules : void 0
    );
    return createRequest(
      children,
      resumableState,
      createRenderState(
        resumableState,
        options ? options.nonce : void 0,
        options ? options.unstable_externalRuntimeSrc : void 0,
        options ? options.importMap : void 0,
        options ? options.onHeaders : void 0,
        options ? options.maxHeadersLength : void 0
      ),
      createRootFormatContext(options ? options.namespaceURI : void 0),
      options ? options.progressiveChunkSize : void 0,
      options ? options.onError : void 0,
      options ? options.onAllReady : void 0,
      options ? options.onShellReady : void 0,
      options ? options.onShellError : void 0,
      void 0,
      options ? options.onPostpone : void 0,
      options ? options.formState : void 0
    );
  }
  function createFakeWritableFromReadableStreamController$1(controller) {
    return {
      write: function(chunk2) {
        "string" === typeof chunk2 && (chunk2 = textEncoder2.encode(chunk2));
        controller.enqueue(chunk2);
        return true;
      },
      end: function() {
        controller.close();
      },
      destroy: function(error) {
        "function" === typeof controller.error ? controller.error(error) : controller.close();
      }
    };
  }
  function resumeRequestImpl(children, postponedState, options) {
    return resumeRequest(
      children,
      postponedState,
      createRenderState(
        postponedState.resumableState,
        options ? options.nonce : void 0,
        void 0,
        void 0,
        void 0,
        void 0
      ),
      options ? options.onError : void 0,
      options ? options.onAllReady : void 0,
      options ? options.onShellReady : void 0,
      options ? options.onShellError : void 0,
      void 0,
      options ? options.onPostpone : void 0
    );
  }
  ensureCorrectIsomorphicReactVersion();
  function createFakeWritableFromReadableStreamController(controller) {
    return {
      write: function(chunk2) {
        "string" === typeof chunk2 && (chunk2 = textEncoder2.encode(chunk2));
        controller.enqueue(chunk2);
        return true;
      },
      end: function() {
        controller.close();
      },
      destroy: function(error) {
        "function" === typeof controller.error ? controller.error(error) : controller.close();
      }
    };
  }
  function createFakeWritableFromReadable(readable) {
    return {
      write: function(chunk2) {
        return readable.push(chunk2);
      },
      end: function() {
        readable.push(null);
      },
      destroy: function(error) {
        readable.destroy(error);
      }
    };
  }
  reactDomServer_node_production.prerender = function(children, options) {
    return new Promise(function(resolve, reject) {
      var onHeaders = options ? options.onHeaders : void 0, onHeadersImpl;
      onHeaders && (onHeadersImpl = function(headersDescriptor) {
        onHeaders(new Headers(headersDescriptor));
      });
      var resources = createResumableState(
        options ? options.identifierPrefix : void 0,
        options ? options.unstable_externalRuntimeSrc : void 0,
        options ? options.bootstrapScriptContent : void 0,
        options ? options.bootstrapScripts : void 0,
        options ? options.bootstrapModules : void 0
      ), request = createPrerenderRequest(
        children,
        resources,
        createRenderState(
          resources,
          void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.importMap : void 0,
          onHeadersImpl,
          options ? options.maxHeadersLength : void 0
        ),
        createRootFormatContext(options ? options.namespaceURI : void 0),
        options ? options.progressiveChunkSize : void 0,
        options ? options.onError : void 0,
        function() {
          var writable, stream2 = new ReadableStream(
            {
              type: "bytes",
              start: function(controller) {
                writable = createFakeWritableFromReadableStreamController(controller);
              },
              pull: function() {
                startFlowing(request, writable);
              },
              cancel: function(reason) {
                request.destination = null;
                abort(request, reason);
              }
            },
            { highWaterMark: 0 }
          );
          stream2 = { postponed: getPostponedState(request), prelude: stream2 };
          resolve(stream2);
        },
        void 0,
        void 0,
        reject,
        options ? options.onPostpone : void 0
      );
      if (options && options.signal) {
        var signal = options.signal;
        if (signal.aborted) abort(request, signal.reason);
        else {
          var listener = function() {
            abort(request, signal.reason);
            signal.removeEventListener("abort", listener);
          };
          signal.addEventListener("abort", listener);
        }
      }
      startWork(request);
    });
  };
  reactDomServer_node_production.prerenderToNodeStream = function(children, options) {
    return new Promise(function(resolve, reject) {
      var resumableState = createResumableState(
        options ? options.identifierPrefix : void 0,
        options ? options.unstable_externalRuntimeSrc : void 0,
        options ? options.bootstrapScriptContent : void 0,
        options ? options.bootstrapScripts : void 0,
        options ? options.bootstrapModules : void 0
      ), request = createPrerenderRequest(
        children,
        resumableState,
        createRenderState(
          resumableState,
          void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.importMap : void 0,
          options ? options.onHeaders : void 0,
          options ? options.maxHeadersLength : void 0
        ),
        createRootFormatContext(options ? options.namespaceURI : void 0),
        options ? options.progressiveChunkSize : void 0,
        options ? options.onError : void 0,
        function() {
          var readable = new stream$1.Readable({
            read: function() {
              startFlowing(request, writable);
            }
          }), writable = createFakeWritableFromReadable(readable);
          readable = {
            postponed: getPostponedState(request),
            prelude: readable
          };
          resolve(readable);
        },
        void 0,
        void 0,
        reject,
        options ? options.onPostpone : void 0
      );
      if (options && options.signal) {
        var signal = options.signal;
        if (signal.aborted) abort(request, signal.reason);
        else {
          var listener = function() {
            abort(request, signal.reason);
            signal.removeEventListener("abort", listener);
          };
          signal.addEventListener("abort", listener);
        }
      }
      startWork(request);
    });
  };
  reactDomServer_node_production.renderToPipeableStream = function(children, options) {
    var request = createRequestImpl(children, options), hasStartedFlowing = false;
    startWork(request);
    return {
      pipe: function(destination) {
        if (hasStartedFlowing)
          throw Error(
            "React currently only supports piping to one writable stream."
          );
        hasStartedFlowing = true;
        safelyEmitEarlyPreloads(
          request,
          null === request.trackedPostpones ? 0 === request.pendingRootTasks : null === request.completedRootSegment ? 0 === request.pendingRootTasks : 5 !== request.completedRootSegment.status
        );
        startFlowing(request, destination);
        destination.on("drain", createDrainHandler(destination, request));
        destination.on(
          "error",
          createCancelHandler(
            request,
            "The destination stream errored while writing data."
          )
        );
        destination.on(
          "close",
          createCancelHandler(request, "The destination stream closed early.")
        );
        return destination;
      },
      abort: function(reason) {
        abort(request, reason);
      }
    };
  };
  reactDomServer_node_production.renderToReadableStream = function(children, options) {
    return new Promise(function(resolve, reject) {
      var onFatalError, onAllReady, allReady = new Promise(function(res, rej) {
        onAllReady = res;
        onFatalError = rej;
      }), onHeaders = options ? options.onHeaders : void 0, onHeadersImpl;
      onHeaders && (onHeadersImpl = function(headersDescriptor) {
        onHeaders(new Headers(headersDescriptor));
      });
      var resumableState = createResumableState(
        options ? options.identifierPrefix : void 0,
        options ? options.unstable_externalRuntimeSrc : void 0,
        options ? options.bootstrapScriptContent : void 0,
        options ? options.bootstrapScripts : void 0,
        options ? options.bootstrapModules : void 0
      ), request = createRequest(
        children,
        resumableState,
        createRenderState(
          resumableState,
          options ? options.nonce : void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.importMap : void 0,
          onHeadersImpl,
          options ? options.maxHeadersLength : void 0
        ),
        createRootFormatContext(options ? options.namespaceURI : void 0),
        options ? options.progressiveChunkSize : void 0,
        options ? options.onError : void 0,
        onAllReady,
        function() {
          var writable, stream2 = new ReadableStream(
            {
              type: "bytes",
              start: function(controller) {
                writable = createFakeWritableFromReadableStreamController$1(
                  controller
                );
              },
              pull: function() {
                startFlowing(request, writable);
              },
              cancel: function(reason) {
                request.destination = null;
                abort(request, reason);
              }
            },
            { highWaterMark: 0 }
          );
          stream2.allReady = allReady;
          resolve(stream2);
        },
        function(error) {
          allReady.catch(function() {
          });
          reject(error);
        },
        onFatalError,
        options ? options.onPostpone : void 0,
        options ? options.formState : void 0
      );
      if (options && options.signal) {
        var signal = options.signal;
        if (signal.aborted) abort(request, signal.reason);
        else {
          var listener = function() {
            abort(request, signal.reason);
            signal.removeEventListener("abort", listener);
          };
          signal.addEventListener("abort", listener);
        }
      }
      startWork(request);
    });
  };
  reactDomServer_node_production.resume = function(children, postponedState, options) {
    return new Promise(function(resolve, reject) {
      var onFatalError, onAllReady, allReady = new Promise(function(res, rej) {
        onAllReady = res;
        onFatalError = rej;
      }), request = resumeRequest(
        children,
        postponedState,
        createRenderState(
          postponedState.resumableState,
          options ? options.nonce : void 0,
          void 0,
          void 0,
          void 0,
          void 0
        ),
        options ? options.onError : void 0,
        onAllReady,
        function() {
          var writable, stream2 = new ReadableStream(
            {
              type: "bytes",
              start: function(controller) {
                writable = createFakeWritableFromReadableStreamController$1(
                  controller
                );
              },
              pull: function() {
                startFlowing(request, writable);
              },
              cancel: function(reason) {
                request.destination = null;
                abort(request, reason);
              }
            },
            { highWaterMark: 0 }
          );
          stream2.allReady = allReady;
          resolve(stream2);
        },
        function(error) {
          allReady.catch(function() {
          });
          reject(error);
        },
        onFatalError,
        options ? options.onPostpone : void 0
      );
      if (options && options.signal) {
        var signal = options.signal;
        if (signal.aborted) abort(request, signal.reason);
        else {
          var listener = function() {
            abort(request, signal.reason);
            signal.removeEventListener("abort", listener);
          };
          signal.addEventListener("abort", listener);
        }
      }
      startWork(request);
    });
  };
  reactDomServer_node_production.resumeAndPrerender = function(children, postponedState, options) {
    return new Promise(function(resolve, reject) {
      var request = resumeAndPrerenderRequest(
        children,
        postponedState,
        createRenderState(
          postponedState.resumableState,
          void 0,
          void 0,
          void 0,
          void 0,
          void 0
        ),
        options ? options.onError : void 0,
        function() {
          var writable, stream2 = new ReadableStream(
            {
              type: "bytes",
              start: function(controller) {
                writable = createFakeWritableFromReadableStreamController(controller);
              },
              pull: function() {
                startFlowing(request, writable);
              },
              cancel: function(reason) {
                request.destination = null;
                abort(request, reason);
              }
            },
            { highWaterMark: 0 }
          );
          stream2 = { postponed: getPostponedState(request), prelude: stream2 };
          resolve(stream2);
        },
        void 0,
        void 0,
        reject,
        options ? options.onPostpone : void 0
      );
      if (options && options.signal) {
        var signal = options.signal;
        if (signal.aborted) abort(request, signal.reason);
        else {
          var listener = function() {
            abort(request, signal.reason);
            signal.removeEventListener("abort", listener);
          };
          signal.addEventListener("abort", listener);
        }
      }
      startWork(request);
    });
  };
  reactDomServer_node_production.resumeAndPrerenderToNodeStream = function(children, postponedState, options) {
    return new Promise(function(resolve, reject) {
      var request = resumeAndPrerenderRequest(
        children,
        postponedState,
        createRenderState(
          postponedState.resumableState,
          void 0,
          void 0,
          void 0,
          void 0,
          void 0
        ),
        options ? options.onError : void 0,
        function() {
          var readable = new stream$1.Readable({
            read: function() {
              startFlowing(request, writable);
            }
          }), writable = createFakeWritableFromReadable(readable);
          readable = { postponed: getPostponedState(request), prelude: readable };
          resolve(readable);
        },
        void 0,
        void 0,
        reject,
        options ? options.onPostpone : void 0
      );
      if (options && options.signal) {
        var signal = options.signal;
        if (signal.aborted) abort(request, signal.reason);
        else {
          var listener = function() {
            abort(request, signal.reason);
            signal.removeEventListener("abort", listener);
          };
          signal.addEventListener("abort", listener);
        }
      }
      startWork(request);
    });
  };
  reactDomServer_node_production.resumeToPipeableStream = function(children, postponedState, options) {
    var request = resumeRequestImpl(children, postponedState, options), hasStartedFlowing = false;
    startWork(request);
    return {
      pipe: function(destination) {
        if (hasStartedFlowing)
          throw Error(
            "React currently only supports piping to one writable stream."
          );
        hasStartedFlowing = true;
        startFlowing(request, destination);
        destination.on("drain", createDrainHandler(destination, request));
        destination.on(
          "error",
          createCancelHandler(
            request,
            "The destination stream errored while writing data."
          )
        );
        destination.on(
          "close",
          createCancelHandler(request, "The destination stream closed early.")
        );
        return destination;
      },
      abort: function(reason) {
        abort(request, reason);
      }
    };
  };
  reactDomServer_node_production.version = "19.2.4";
  return reactDomServer_node_production;
}
var reactDomServerLegacy_node_development = {};
var hasRequiredReactDomServerLegacy_node_development;
function requireReactDomServerLegacy_node_development() {
  if (hasRequiredReactDomServerLegacy_node_development) return reactDomServerLegacy_node_development;
  hasRequiredReactDomServerLegacy_node_development = 1;
  "production" !== process.env.NODE_ENV && (function() {
    function styleReplacer(match, prefix2, s2, suffix2) {
      return "" + prefix2 + ("s" === s2 ? "\\73 " : "\\53 ") + suffix2;
    }
    function scriptReplacer(match, prefix2, s2, suffix2) {
      return "" + prefix2 + ("s" === s2 ? "\\u0073" : "\\u0053") + suffix2;
    }
    function getIteratorFn(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable)
        return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    function objectName(object) {
      object = Object.prototype.toString.call(object);
      return object.slice(8, object.length - 1);
    }
    function describeKeyForErrorMessage(key) {
      var encodedKey = JSON.stringify(key);
      return '"' + key + '"' === encodedKey ? key : encodedKey;
    }
    function describeValueForErrorMessage(value) {
      switch (typeof value) {
        case "string":
          return JSON.stringify(
            10 >= value.length ? value : value.slice(0, 10) + "..."
          );
        case "object":
          if (isArrayImpl(value)) return "[...]";
          if (null !== value && value.$$typeof === CLIENT_REFERENCE_TAG)
            return "client";
          value = objectName(value);
          return "Object" === value ? "{...}" : value;
        case "function":
          return value.$$typeof === CLIENT_REFERENCE_TAG ? "client" : (value = value.displayName || value.name) ? "function " + value : "function";
        default:
          return String(value);
      }
    }
    function describeElementType(type2) {
      if ("string" === typeof type2) return type2;
      switch (type2) {
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
      }
      if ("object" === typeof type2)
        switch (type2.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            return describeElementType(type2.render);
          case REACT_MEMO_TYPE:
            return describeElementType(type2.type);
          case REACT_LAZY_TYPE:
            var payload = type2._payload;
            type2 = type2._init;
            try {
              return describeElementType(type2(payload));
            } catch (x2) {
            }
        }
      return "";
    }
    function describeObjectForErrorMessage(objectOrArray, expandedName) {
      var objKind = objectName(objectOrArray);
      if ("Object" !== objKind && "Array" !== objKind) return objKind;
      var start = -1, length = 0;
      if (isArrayImpl(objectOrArray))
        if (jsxChildrenParents.has(objectOrArray)) {
          var type2 = jsxChildrenParents.get(objectOrArray);
          objKind = "<" + describeElementType(type2) + ">";
          for (var i = 0; i < objectOrArray.length; i++) {
            var value = objectOrArray[i];
            value = "string" === typeof value ? value : "object" === typeof value && null !== value ? "{" + describeObjectForErrorMessage(value) + "}" : "{" + describeValueForErrorMessage(value) + "}";
            "" + i === expandedName ? (start = objKind.length, length = value.length, objKind += value) : objKind = 15 > value.length && 40 > objKind.length + value.length ? objKind + value : objKind + "{...}";
          }
          objKind += "</" + describeElementType(type2) + ">";
        } else {
          objKind = "[";
          for (type2 = 0; type2 < objectOrArray.length; type2++)
            0 < type2 && (objKind += ", "), i = objectOrArray[type2], i = "object" === typeof i && null !== i ? describeObjectForErrorMessage(i) : describeValueForErrorMessage(i), "" + type2 === expandedName ? (start = objKind.length, length = i.length, objKind += i) : objKind = 10 > i.length && 40 > objKind.length + i.length ? objKind + i : objKind + "...";
          objKind += "]";
        }
      else if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE)
        objKind = "<" + describeElementType(objectOrArray.type) + "/>";
      else {
        if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) return "client";
        if (jsxPropsParents.has(objectOrArray)) {
          objKind = jsxPropsParents.get(objectOrArray);
          objKind = "<" + (describeElementType(objKind) || "...");
          type2 = Object.keys(objectOrArray);
          for (i = 0; i < type2.length; i++) {
            objKind += " ";
            value = type2[i];
            objKind += describeKeyForErrorMessage(value) + "=";
            var _value2 = objectOrArray[value];
            var _substr2 = value === expandedName && "object" === typeof _value2 && null !== _value2 ? describeObjectForErrorMessage(_value2) : describeValueForErrorMessage(_value2);
            "string" !== typeof _value2 && (_substr2 = "{" + _substr2 + "}");
            value === expandedName ? (start = objKind.length, length = _substr2.length, objKind += _substr2) : objKind = 10 > _substr2.length && 40 > objKind.length + _substr2.length ? objKind + _substr2 : objKind + "...";
          }
          objKind += ">";
        } else {
          objKind = "{";
          type2 = Object.keys(objectOrArray);
          for (i = 0; i < type2.length; i++)
            0 < i && (objKind += ", "), value = type2[i], objKind += describeKeyForErrorMessage(value) + ": ", _value2 = objectOrArray[value], _value2 = "object" === typeof _value2 && null !== _value2 ? describeObjectForErrorMessage(_value2) : describeValueForErrorMessage(_value2), value === expandedName ? (start = objKind.length, length = _value2.length, objKind += _value2) : objKind = 10 > _value2.length && 40 > objKind.length + _value2.length ? objKind + _value2 : objKind + "...";
          objKind += "}";
        }
      }
      return void 0 === expandedName ? objKind : -1 < start && 0 < length ? (objectOrArray = " ".repeat(start) + "^".repeat(length), "\n  " + objKind + "\n  " + objectOrArray) : "\n  " + objKind;
    }
    function murmurhash3_32_gc(key, seed) {
      var remainder = key.length & 3;
      var bytes = key.length - remainder;
      var h1 = seed;
      for (seed = 0; seed < bytes; ) {
        var k1 = key.charCodeAt(seed) & 255 | (key.charCodeAt(++seed) & 255) << 8 | (key.charCodeAt(++seed) & 255) << 16 | (key.charCodeAt(++seed) & 255) << 24;
        ++seed;
        k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295;
        k1 = k1 << 15 | k1 >>> 17;
        k1 = 461845907 * (k1 & 65535) + ((461845907 * (k1 >>> 16) & 65535) << 16) & 4294967295;
        h1 ^= k1;
        h1 = h1 << 13 | h1 >>> 19;
        h1 = 5 * (h1 & 65535) + ((5 * (h1 >>> 16) & 65535) << 16) & 4294967295;
        h1 = (h1 & 65535) + 27492 + (((h1 >>> 16) + 58964 & 65535) << 16);
      }
      k1 = 0;
      switch (remainder) {
        case 3:
          k1 ^= (key.charCodeAt(seed + 2) & 255) << 16;
        case 2:
          k1 ^= (key.charCodeAt(seed + 1) & 255) << 8;
        case 1:
          k1 ^= key.charCodeAt(seed) & 255, k1 = 3432918353 * (k1 & 65535) + ((3432918353 * (k1 >>> 16) & 65535) << 16) & 4294967295, k1 = k1 << 15 | k1 >>> 17, h1 ^= 461845907 * (k1 & 65535) + ((461845907 * (k1 >>> 16) & 65535) << 16) & 4294967295;
      }
      h1 ^= key.length;
      h1 ^= h1 >>> 16;
      h1 = 2246822507 * (h1 & 65535) + ((2246822507 * (h1 >>> 16) & 65535) << 16) & 4294967295;
      h1 ^= h1 >>> 13;
      h1 = 3266489909 * (h1 & 65535) + ((3266489909 * (h1 >>> 16) & 65535) << 16) & 4294967295;
      return (h1 ^ h1 >>> 16) >>> 0;
    }
    function typeName(value) {
      return "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
    }
    function willCoercionThrow(value) {
      try {
        return testStringCoercion(value), false;
      } catch (e) {
        return true;
      }
    }
    function testStringCoercion(value) {
      return "" + value;
    }
    function checkAttributeStringCoercion(value, attributeName) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before using it here.",
          attributeName,
          typeName(value)
        ), testStringCoercion(value);
    }
    function checkCSSPropertyStringCoercion(value, propName) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before using it here.",
          propName,
          typeName(value)
        ), testStringCoercion(value);
    }
    function checkHtmlStringCoercion(value) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before using it here.",
          typeName(value)
        ), testStringCoercion(value);
    }
    function isAttributeNameSafe(attributeName) {
      if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
        return true;
      if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName))
        return false;
      if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
        return validatedAttributeNameCache[attributeName] = true;
      illegalAttributeNameCache[attributeName] = true;
      console.error("Invalid attribute name: `%s`", attributeName);
      return false;
    }
    function checkControlledValueProps(tagName, props) {
      hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || null == props.value || ("select" === tagName ? console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set `onChange`."
      ) : console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."
      ));
      props.onChange || props.readOnly || props.disabled || null == props.checked || console.error(
        "You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."
      );
    }
    function validateProperty$1(tagName, name2) {
      if (hasOwnProperty2.call(warnedProperties$1, name2) && warnedProperties$1[name2])
        return true;
      if (rARIACamel$1.test(name2)) {
        tagName = "aria-" + name2.slice(4).toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.",
            name2
          ), warnedProperties$1[name2] = true;
        if (name2 !== tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. Did you mean `%s`?",
            name2,
            tagName
          ), warnedProperties$1[name2] = true;
      }
      if (rARIA$1.test(name2)) {
        tagName = name2.toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName) return warnedProperties$1[name2] = true, false;
        name2 !== tagName && (console.error(
          "Unknown ARIA attribute `%s`. Did you mean `%s`?",
          name2,
          tagName
        ), warnedProperties$1[name2] = true);
      }
      return true;
    }
    function validateProperties$2(type2, props) {
      var invalidProps = [], key;
      for (key in props)
        validateProperty$1(type2, key) || invalidProps.push(key);
      props = invalidProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === invalidProps.length ? console.error(
        "Invalid aria prop %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type2
      ) : 1 < invalidProps.length && console.error(
        "Invalid aria props %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type2
      );
    }
    function validateProperty(tagName, name2, value, eventRegistry) {
      if (hasOwnProperty2.call(warnedProperties, name2) && warnedProperties[name2])
        return true;
      var lowerCasedName = name2.toLowerCase();
      if ("onfocusin" === lowerCasedName || "onfocusout" === lowerCasedName)
        return console.error(
          "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."
        ), warnedProperties[name2] = true;
      if ("function" === typeof value && ("form" === tagName && "action" === name2 || "input" === tagName && "formAction" === name2 || "button" === tagName && "formAction" === name2))
        return true;
      if (EVENT_NAME_REGEX.test(name2))
        return INVALID_EVENT_NAME_REGEX.test(name2) && console.error(
          "Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.",
          name2
        ), warnedProperties[name2] = true;
      if (rARIA.test(name2) || rARIACamel.test(name2)) return true;
      if ("innerhtml" === lowerCasedName)
        return console.error(
          "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."
        ), warnedProperties[name2] = true;
      if ("aria" === lowerCasedName)
        return console.error(
          "The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."
        ), warnedProperties[name2] = true;
      if ("is" === lowerCasedName && null !== value && void 0 !== value && "string" !== typeof value)
        return console.error(
          "Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.",
          typeof value
        ), warnedProperties[name2] = true;
      if ("number" === typeof value && isNaN(value))
        return console.error(
          "Received NaN for the `%s` attribute. If this is expected, cast the value to a string.",
          name2
        ), warnedProperties[name2] = true;
      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        if (lowerCasedName = possibleStandardNames[lowerCasedName], lowerCasedName !== name2)
          return console.error(
            "Invalid DOM property `%s`. Did you mean `%s`?",
            name2,
            lowerCasedName
          ), warnedProperties[name2] = true;
      } else if (name2 !== lowerCasedName)
        return console.error(
          "React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.",
          name2,
          lowerCasedName
        ), warnedProperties[name2] = true;
      switch (name2) {
        case "dangerouslySetInnerHTML":
        case "children":
        case "style":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          return true;
        case "innerText":
        case "textContent":
          return true;
      }
      switch (typeof value) {
        case "boolean":
          switch (name2) {
            case "autoFocus":
            case "checked":
            case "multiple":
            case "muted":
            case "selected":
            case "contentEditable":
            case "spellCheck":
            case "draggable":
            case "value":
            case "autoReverse":
            case "externalResourcesRequired":
            case "focusable":
            case "preserveAlpha":
            case "allowFullScreen":
            case "async":
            case "autoPlay":
            case "controls":
            case "default":
            case "defer":
            case "disabled":
            case "disablePictureInPicture":
            case "disableRemotePlayback":
            case "formNoValidate":
            case "hidden":
            case "loop":
            case "noModule":
            case "noValidate":
            case "open":
            case "playsInline":
            case "readOnly":
            case "required":
            case "reversed":
            case "scoped":
            case "seamless":
            case "itemScope":
            case "capture":
            case "download":
            case "inert":
              return true;
            default:
              lowerCasedName = name2.toLowerCase().slice(0, 5);
              if ("data-" === lowerCasedName || "aria-" === lowerCasedName)
                return true;
              value ? console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.',
                value,
                name2,
                name2,
                value,
                name2
              ) : console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.',
                value,
                name2,
                name2,
                value,
                name2,
                name2,
                name2
              );
              return warnedProperties[name2] = true;
          }
        case "function":
        case "symbol":
          return warnedProperties[name2] = true, false;
        case "string":
          if ("false" === value || "true" === value) {
            switch (name2) {
              case "checked":
              case "selected":
              case "multiple":
              case "muted":
              case "allowFullScreen":
              case "async":
              case "autoPlay":
              case "controls":
              case "default":
              case "defer":
              case "disabled":
              case "disablePictureInPicture":
              case "disableRemotePlayback":
              case "formNoValidate":
              case "hidden":
              case "loop":
              case "noModule":
              case "noValidate":
              case "open":
              case "playsInline":
              case "readOnly":
              case "required":
              case "reversed":
              case "scoped":
              case "seamless":
              case "itemScope":
              case "inert":
                break;
              default:
                return true;
            }
            console.error(
              "Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?",
              value,
              name2,
              "false" === value ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".',
              name2,
              value
            );
            warnedProperties[name2] = true;
          }
      }
      return true;
    }
    function warnUnknownProperties(type2, props, eventRegistry) {
      var unknownProps = [], key;
      for (key in props)
        validateProperty(type2, key, props[key]) || unknownProps.push(key);
      props = unknownProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === unknownProps.length ? console.error(
        "Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type2
      ) : 1 < unknownProps.length && console.error(
        "Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type2
      );
    }
    function camelize(string2) {
      return string2.replace(hyphenPattern, function(_2, character) {
        return character.toUpperCase();
      });
    }
    function escapeTextForBrowser(text2) {
      if ("boolean" === typeof text2 || "number" === typeof text2 || "bigint" === typeof text2)
        return "" + text2;
      checkHtmlStringCoercion(text2);
      text2 = "" + text2;
      var match = matchHtmlRegExp.exec(text2);
      if (match) {
        var html2 = "", index2, lastIndex = 0;
        for (index2 = match.index; index2 < text2.length; index2++) {
          switch (text2.charCodeAt(index2)) {
            case 34:
              match = "&quot;";
              break;
            case 38:
              match = "&amp;";
              break;
            case 39:
              match = "&#x27;";
              break;
            case 60:
              match = "&lt;";
              break;
            case 62:
              match = "&gt;";
              break;
            default:
              continue;
          }
          lastIndex !== index2 && (html2 += text2.slice(lastIndex, index2));
          lastIndex = index2 + 1;
          html2 += match;
        }
        text2 = lastIndex !== index2 ? html2 + text2.slice(lastIndex, index2) : html2;
      }
      return text2;
    }
    function sanitizeURL(url) {
      return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
    }
    function escapeEntireInlineScriptContent(scriptText) {
      checkHtmlStringCoercion(scriptText);
      return ("" + scriptText).replace(scriptRegex, scriptReplacer);
    }
    function createResumableState(identifierPrefix, externalRuntimeConfig, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
      return {
        idPrefix: void 0 === identifierPrefix ? "" : identifierPrefix,
        nextFormID: 0,
        streamingFormat: 0,
        bootstrapScriptContent,
        bootstrapScripts,
        bootstrapModules,
        instructions: NothingSent,
        hasBody: false,
        hasHtml: false,
        unknownResources: {},
        dnsResources: {},
        connectResources: { default: {}, anonymous: {}, credentials: {} },
        imageResources: {},
        styleResources: {},
        scriptResources: {},
        moduleUnknownResources: {},
        moduleScriptResources: {}
      };
    }
    function createFormatContext(insertionMode, selectedValue, tagScope, viewTransition) {
      return {
        insertionMode,
        selectedValue,
        tagScope,
        viewTransition
      };
    }
    function getChildFormatContext(parentContext, type2, props) {
      var subtreeScope = parentContext.tagScope & -25;
      switch (type2) {
        case "noscript":
          return createFormatContext(HTML_MODE, null, subtreeScope | 1, null);
        case "select":
          return createFormatContext(
            HTML_MODE,
            null != props.value ? props.value : props.defaultValue,
            subtreeScope,
            null
          );
        case "svg":
          return createFormatContext(SVG_MODE, null, subtreeScope, null);
        case "picture":
          return createFormatContext(HTML_MODE, null, subtreeScope | 2, null);
        case "math":
          return createFormatContext(MATHML_MODE, null, subtreeScope, null);
        case "foreignObject":
          return createFormatContext(HTML_MODE, null, subtreeScope, null);
        case "table":
          return createFormatContext(HTML_TABLE_MODE, null, subtreeScope, null);
        case "thead":
        case "tbody":
        case "tfoot":
          return createFormatContext(
            HTML_TABLE_BODY_MODE,
            null,
            subtreeScope,
            null
          );
        case "colgroup":
          return createFormatContext(
            HTML_COLGROUP_MODE,
            null,
            subtreeScope,
            null
          );
        case "tr":
          return createFormatContext(
            HTML_TABLE_ROW_MODE,
            null,
            subtreeScope,
            null
          );
        case "head":
          if (parentContext.insertionMode < HTML_MODE)
            return createFormatContext(
              HTML_HEAD_MODE,
              null,
              subtreeScope,
              null
            );
          break;
        case "html":
          if (parentContext.insertionMode === ROOT_HTML_MODE)
            return createFormatContext(
              HTML_HTML_MODE,
              null,
              subtreeScope,
              null
            );
      }
      return parentContext.insertionMode >= HTML_TABLE_MODE || parentContext.insertionMode < HTML_MODE ? createFormatContext(HTML_MODE, null, subtreeScope, null) : parentContext.tagScope !== subtreeScope ? createFormatContext(
        parentContext.insertionMode,
        parentContext.selectedValue,
        subtreeScope,
        null
      ) : parentContext;
    }
    function getSuspenseViewTransition(parentViewTransition) {
      return null === parentViewTransition ? null : {
        update: parentViewTransition.update,
        enter: "none",
        exit: "none",
        share: parentViewTransition.update,
        name: parentViewTransition.autoName,
        autoName: parentViewTransition.autoName,
        nameIdx: 0
      };
    }
    function getSuspenseFallbackFormatContext(resumableState, parentContext) {
      parentContext.tagScope & 32 && (resumableState.instructions |= 128);
      return createFormatContext(
        parentContext.insertionMode,
        parentContext.selectedValue,
        parentContext.tagScope | 12,
        getSuspenseViewTransition(parentContext.viewTransition)
      );
    }
    function getSuspenseContentFormatContext(resumableState, parentContext) {
      resumableState = getSuspenseViewTransition(parentContext.viewTransition);
      var subtreeScope = parentContext.tagScope | 16;
      null !== resumableState && "none" !== resumableState.share && (subtreeScope |= 64);
      return createFormatContext(
        parentContext.insertionMode,
        parentContext.selectedValue,
        subtreeScope,
        resumableState
      );
    }
    function pushStyleAttribute(target, style) {
      if ("object" !== typeof style)
        throw Error(
          "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
        );
      var isFirst = true, styleName;
      for (styleName in style)
        if (hasOwnProperty2.call(style, styleName)) {
          var styleValue = style[styleName];
          if (null != styleValue && "boolean" !== typeof styleValue && "" !== styleValue) {
            if (0 === styleName.indexOf("--")) {
              var nameChunk = escapeTextForBrowser(styleName);
              checkCSSPropertyStringCoercion(styleValue, styleName);
              styleValue = escapeTextForBrowser(("" + styleValue).trim());
            } else {
              nameChunk = styleName;
              var value = styleValue;
              if (-1 < nameChunk.indexOf("-")) {
                var name2 = nameChunk;
                warnedStyleNames.hasOwnProperty(name2) && warnedStyleNames[name2] || (warnedStyleNames[name2] = true, console.error(
                  "Unsupported style property %s. Did you mean %s?",
                  name2,
                  camelize(name2.replace(msPattern$1, "ms-"))
                ));
              } else if (badVendoredStyleNamePattern.test(nameChunk))
                name2 = nameChunk, warnedStyleNames.hasOwnProperty(name2) && warnedStyleNames[name2] || (warnedStyleNames[name2] = true, console.error(
                  "Unsupported vendor-prefixed style property %s. Did you mean %s?",
                  name2,
                  name2.charAt(0).toUpperCase() + name2.slice(1)
                ));
              else if (badStyleValueWithSemicolonPattern.test(value)) {
                name2 = nameChunk;
                var value$jscomp$0 = value;
                warnedStyleValues.hasOwnProperty(value$jscomp$0) && warnedStyleValues[value$jscomp$0] || (warnedStyleValues[value$jscomp$0] = true, console.error(
                  `Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`,
                  name2,
                  value$jscomp$0.replace(
                    badStyleValueWithSemicolonPattern,
                    ""
                  )
                ));
              }
              "number" === typeof value && (isNaN(value) ? warnedForNaNValue || (warnedForNaNValue = true, console.error(
                "`NaN` is an invalid value for the `%s` css style property.",
                nameChunk
              )) : isFinite(value) || warnedForInfinityValue || (warnedForInfinityValue = true, console.error(
                "`Infinity` is an invalid value for the `%s` css style property.",
                nameChunk
              )));
              nameChunk = styleName;
              value = styleNameCache.get(nameChunk);
              void 0 !== value ? nameChunk = value : (value = escapeTextForBrowser(
                nameChunk.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-")
              ), styleNameCache.set(nameChunk, value), nameChunk = value);
              "number" === typeof styleValue ? styleValue = 0 === styleValue || unitlessNumbers.has(styleName) ? "" + styleValue : styleValue + "px" : (checkCSSPropertyStringCoercion(styleValue, styleName), styleValue = escapeTextForBrowser(
                ("" + styleValue).trim()
              ));
            }
            isFirst ? (isFirst = false, target.push(
              styleAttributeStart,
              nameChunk,
              styleAssign,
              styleValue
            )) : target.push(styleSeparator, nameChunk, styleAssign, styleValue);
          }
        }
      isFirst || target.push(attributeEnd);
    }
    function pushBooleanAttribute(target, name2, value) {
      value && "function" !== typeof value && "symbol" !== typeof value && target.push(attributeSeparator, name2, attributeEmptyString);
    }
    function pushStringAttribute(target, name2, value) {
      "function" !== typeof value && "symbol" !== typeof value && "boolean" !== typeof value && target.push(
        attributeSeparator,
        name2,
        attributeAssign,
        escapeTextForBrowser(value),
        attributeEnd
      );
    }
    function pushAdditionalFormField(value, key) {
      this.push('<input type="hidden"');
      validateAdditionalFormField(value);
      pushStringAttribute(this, "name", key);
      pushStringAttribute(this, "value", value);
      this.push(endOfStartTagSelfClosing);
    }
    function validateAdditionalFormField(value) {
      if ("string" !== typeof value)
        throw Error(
          "File/Blob fields are not yet supported in progressive forms. Will fallback to client hydration."
        );
    }
    function getCustomFormFields(resumableState, formAction) {
      if ("function" === typeof formAction.$$FORM_ACTION) {
        var id = resumableState.nextFormID++;
        resumableState = resumableState.idPrefix + id;
        try {
          var customFields = formAction.$$FORM_ACTION(resumableState);
          if (customFields) {
            var formData = customFields.data;
            null != formData && formData.forEach(validateAdditionalFormField);
          }
          return customFields;
        } catch (x2) {
          if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then)
            throw x2;
          console.error(
            "Failed to serialize an action for progressive enhancement:\n%s",
            x2
          );
        }
      }
      return null;
    }
    function pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name2) {
      var formData = null;
      if ("function" === typeof formAction) {
        null === name2 || didWarnFormActionName || (didWarnFormActionName = true, console.error(
          'Cannot specify a "name" prop for a button that specifies a function as a formAction. React needs it to encode which action should be invoked. It will get overridden.'
        ));
        null === formEncType && null === formMethod || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
          "Cannot specify a formEncType or formMethod for a button that specifies a function as a formAction. React provides those automatically. They will get overridden."
        ));
        null === formTarget || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
          "Cannot specify a formTarget for a button that specifies a function as a formAction. The function will always be executed in the same window."
        ));
        var customFields = getCustomFormFields(resumableState, formAction);
        null !== customFields ? (name2 = customFields.name, formAction = customFields.action || "", formEncType = customFields.encType, formMethod = customFields.method, formTarget = customFields.target, formData = customFields.data) : (target.push(
          attributeSeparator,
          "formAction",
          attributeAssign,
          actionJavaScriptURL,
          attributeEnd
        ), formTarget = formMethod = formEncType = formAction = name2 = null, injectFormReplayingRuntime(resumableState, renderState));
      }
      null != name2 && pushAttribute(target, "name", name2);
      null != formAction && pushAttribute(target, "formAction", formAction);
      null != formEncType && pushAttribute(target, "formEncType", formEncType);
      null != formMethod && pushAttribute(target, "formMethod", formMethod);
      null != formTarget && pushAttribute(target, "formTarget", formTarget);
      return formData;
    }
    function pushAttribute(target, name2, value) {
      switch (name2) {
        case "className":
          pushStringAttribute(target, "class", value);
          break;
        case "tabIndex":
          pushStringAttribute(target, "tabindex", value);
          break;
        case "dir":
        case "role":
        case "viewBox":
        case "width":
        case "height":
          pushStringAttribute(target, name2, value);
          break;
        case "style":
          pushStyleAttribute(target, value);
          break;
        case "src":
        case "href":
          if ("" === value) {
            "src" === name2 ? console.error(
              'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              name2,
              name2
            ) : console.error(
              'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              name2,
              name2
            );
            break;
          }
        case "action":
        case "formAction":
          if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
            break;
          checkAttributeStringCoercion(value, name2);
          value = sanitizeURL("" + value);
          target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "ref":
          break;
        case "autoFocus":
        case "multiple":
        case "muted":
          pushBooleanAttribute(target, name2.toLowerCase(), value);
          break;
        case "xlinkHref":
          if ("function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
            break;
          checkAttributeStringCoercion(value, name2);
          value = sanitizeURL("" + value);
          target.push(
            attributeSeparator,
            "xlink:href",
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "contentEditable":
        case "spellCheck":
        case "draggable":
        case "value":
        case "autoReverse":
        case "externalResourcesRequired":
        case "focusable":
        case "preserveAlpha":
          "function" !== typeof value && "symbol" !== typeof value && target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "inert":
          "" !== value || didWarnForNewBooleanPropsWithEmptyValue[name2] || (didWarnForNewBooleanPropsWithEmptyValue[name2] = true, console.error(
            "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
            name2
          ));
        case "allowFullScreen":
        case "async":
        case "autoPlay":
        case "controls":
        case "default":
        case "defer":
        case "disabled":
        case "disablePictureInPicture":
        case "disableRemotePlayback":
        case "formNoValidate":
        case "hidden":
        case "loop":
        case "noModule":
        case "noValidate":
        case "open":
        case "playsInline":
        case "readOnly":
        case "required":
        case "reversed":
        case "scoped":
        case "seamless":
        case "itemScope":
          value && "function" !== typeof value && "symbol" !== typeof value && target.push(attributeSeparator, name2, attributeEmptyString);
          break;
        case "capture":
        case "download":
          true === value ? target.push(attributeSeparator, name2, attributeEmptyString) : false !== value && "function" !== typeof value && "symbol" !== typeof value && target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "cols":
        case "rows":
        case "size":
        case "span":
          "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value && target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "rowSpan":
        case "start":
          "function" === typeof value || "symbol" === typeof value || isNaN(value) || target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "xlinkActuate":
          pushStringAttribute(target, "xlink:actuate", value);
          break;
        case "xlinkArcrole":
          pushStringAttribute(target, "xlink:arcrole", value);
          break;
        case "xlinkRole":
          pushStringAttribute(target, "xlink:role", value);
          break;
        case "xlinkShow":
          pushStringAttribute(target, "xlink:show", value);
          break;
        case "xlinkTitle":
          pushStringAttribute(target, "xlink:title", value);
          break;
        case "xlinkType":
          pushStringAttribute(target, "xlink:type", value);
          break;
        case "xmlBase":
          pushStringAttribute(target, "xml:base", value);
          break;
        case "xmlLang":
          pushStringAttribute(target, "xml:lang", value);
          break;
        case "xmlSpace":
          pushStringAttribute(target, "xml:space", value);
          break;
        default:
          if (!(2 < name2.length) || "o" !== name2[0] && "O" !== name2[0] || "n" !== name2[1] && "N" !== name2[1]) {
            if (name2 = aliases.get(name2) || name2, isAttributeNameSafe(name2)) {
              switch (typeof value) {
                case "function":
                case "symbol":
                  return;
                case "boolean":
                  var prefix2 = name2.toLowerCase().slice(0, 5);
                  if ("data-" !== prefix2 && "aria-" !== prefix2) return;
              }
              target.push(
                attributeSeparator,
                name2,
                attributeAssign,
                escapeTextForBrowser(value),
                attributeEnd
              );
            }
          }
      }
    }
    function pushInnerHTML(target, innerHTML, children) {
      if (null != innerHTML) {
        if (null != children)
          throw Error(
            "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
          );
        if ("object" !== typeof innerHTML || !("__html" in innerHTML))
          throw Error(
            "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
          );
        innerHTML = innerHTML.__html;
        null !== innerHTML && void 0 !== innerHTML && (checkHtmlStringCoercion(innerHTML), target.push("" + innerHTML));
      }
    }
    function checkSelectProp(props, propName) {
      var value = props[propName];
      null != value && (value = isArrayImpl(value), props.multiple && !value ? console.error(
        "The `%s` prop supplied to <select> must be an array if `multiple` is true.",
        propName
      ) : !props.multiple && value && console.error(
        "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.",
        propName
      ));
    }
    function flattenOptionChildren(children) {
      var content2 = "";
      React2.Children.forEach(children, function(child) {
        null != child && (content2 += child, didWarnInvalidOptionChildren || "string" === typeof child || "number" === typeof child || "bigint" === typeof child || (didWarnInvalidOptionChildren = true, console.error(
          "Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>."
        )));
      });
      return content2;
    }
    function injectFormReplayingRuntime(resumableState, renderState) {
      if ((resumableState.instructions & 16) === NothingSent) {
        resumableState.instructions |= 16;
        var preamble = renderState.preamble, bootstrapChunks = renderState.bootstrapChunks;
        (preamble.htmlChunks || preamble.headChunks) && 0 === bootstrapChunks.length ? (bootstrapChunks.push(renderState.startInlineScript), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
          endOfStartTag,
          formReplayingRuntimeScript,
          endInlineScript
        )) : bootstrapChunks.unshift(
          renderState.startInlineScript,
          endOfStartTag,
          formReplayingRuntimeScript,
          endInlineScript
        );
      }
    }
    function pushLinkImpl(target, props) {
      target.push(startChunkForTag("link"));
      for (var propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(
                  "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                );
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTagSelfClosing);
      return null;
    }
    function escapeStyleTextContent(styleText) {
      checkHtmlStringCoercion(styleText);
      return ("" + styleText).replace(styleRegex, styleReplacer);
    }
    function pushSelfClosing(target, props, tag) {
      target.push(startChunkForTag(tag));
      for (var propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(
                  tag + " is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                );
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTagSelfClosing);
      return null;
    }
    function pushTitleImpl(target, props) {
      target.push(startChunkForTag("title"));
      var children = null, innerHTML = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                children = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      props = Array.isArray(children) ? 2 > children.length ? children[0] : null : children;
      "function" !== typeof props && "symbol" !== typeof props && null !== props && void 0 !== props && target.push(escapeTextForBrowser("" + props));
      pushInnerHTML(target, innerHTML, children);
      target.push(endChunkForTag("title"));
      return null;
    }
    function pushScriptImpl(target, props) {
      target.push(startChunkForTag("script"));
      var children = null, innerHTML = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                children = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      null != children && "string" !== typeof children && (props = "number" === typeof children ? "a number for children" : Array.isArray(children) ? "an array for children" : "something unexpected for children", console.error(
        "A script element was rendered with %s. If script element has children it must be a single string. Consider using dangerouslySetInnerHTML or passing a plain string as children.",
        props
      ));
      pushInnerHTML(target, innerHTML, children);
      "string" === typeof children && target.push(escapeEntireInlineScriptContent(children));
      target.push(endChunkForTag("script"));
      return null;
    }
    function pushStartSingletonElement(target, props, tag) {
      target.push(startChunkForTag(tag));
      var innerHTML = tag = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                tag = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      pushInnerHTML(target, innerHTML, tag);
      return tag;
    }
    function pushStartGenericElement(target, props, tag) {
      target.push(startChunkForTag(tag));
      var innerHTML = tag = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                tag = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      pushInnerHTML(target, innerHTML, tag);
      return "string" === typeof tag ? (target.push(escapeTextForBrowser(tag)), null) : tag;
    }
    function startChunkForTag(tag) {
      var tagStartChunk = validatedTagCache.get(tag);
      if (void 0 === tagStartChunk) {
        if (!VALID_TAG_REGEX.test(tag)) throw Error("Invalid tag: " + tag);
        tagStartChunk = "<" + tag;
        validatedTagCache.set(tag, tagStartChunk);
      }
      return tagStartChunk;
    }
    function pushStartInstance(target$jscomp$0, type2, props, resumableState, renderState, preambleState, hoistableState, formatContext, textEmbedded) {
      validateProperties$2(type2, props);
      "input" !== type2 && "textarea" !== type2 && "select" !== type2 || null == props || null !== props.value || didWarnValueNull || (didWarnValueNull = true, "select" === type2 && props.multiple ? console.error(
        "`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.",
        type2
      ) : console.error(
        "`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.",
        type2
      ));
      b: if (-1 === type2.indexOf("-")) var JSCompiler_inline_result = false;
      else
        switch (type2) {
          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":
            JSCompiler_inline_result = false;
            break b;
          default:
            JSCompiler_inline_result = true;
        }
      JSCompiler_inline_result || "string" === typeof props.is || warnUnknownProperties(type2, props);
      !props.suppressContentEditableWarning && props.contentEditable && null != props.children && console.error(
        "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."
      );
      formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE && -1 === type2.indexOf("-") && type2.toLowerCase() !== type2 && console.error(
        "<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",
        type2
      );
      switch (type2) {
        case "div":
        case "span":
        case "svg":
        case "path":
          break;
        case "a":
          target$jscomp$0.push(startChunkForTag("a"));
          var children = null, innerHTML = null, propKey;
          for (propKey in props)
            if (hasOwnProperty2.call(props, propKey)) {
              var propValue = props[propKey];
              if (null != propValue)
                switch (propKey) {
                  case "children":
                    children = propValue;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML = propValue;
                    break;
                  case "href":
                    "" === propValue ? pushStringAttribute(target$jscomp$0, "href", "") : pushAttribute(target$jscomp$0, propKey, propValue);
                    break;
                  default:
                    pushAttribute(target$jscomp$0, propKey, propValue);
                }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML, children);
          if ("string" === typeof children) {
            target$jscomp$0.push(escapeTextForBrowser(children));
            var JSCompiler_inline_result$jscomp$0 = null;
          } else JSCompiler_inline_result$jscomp$0 = children;
          return JSCompiler_inline_result$jscomp$0;
        case "g":
        case "p":
        case "li":
          break;
        case "select":
          checkControlledValueProps("select", props);
          checkSelectProp(props, "value");
          checkSelectProp(props, "defaultValue");
          void 0 === props.value || void 0 === props.defaultValue || didWarnDefaultSelectValue || (console.error(
            "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://react.dev/link/controlled-components"
          ), didWarnDefaultSelectValue = true);
          target$jscomp$0.push(startChunkForTag("select"));
          var children$jscomp$0 = null, innerHTML$jscomp$0 = null, propKey$jscomp$0;
          for (propKey$jscomp$0 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$0)) {
              var propValue$jscomp$0 = props[propKey$jscomp$0];
              if (null != propValue$jscomp$0)
                switch (propKey$jscomp$0) {
                  case "children":
                    children$jscomp$0 = propValue$jscomp$0;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$0 = propValue$jscomp$0;
                    break;
                  case "defaultValue":
                  case "value":
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$0,
                      propValue$jscomp$0
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$0, children$jscomp$0);
          return children$jscomp$0;
        case "option":
          var selectedValue = formatContext.selectedValue;
          target$jscomp$0.push(startChunkForTag("option"));
          var children$jscomp$1 = null, value = null, selected = null, innerHTML$jscomp$1 = null, propKey$jscomp$1;
          for (propKey$jscomp$1 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$1)) {
              var propValue$jscomp$1 = props[propKey$jscomp$1];
              if (null != propValue$jscomp$1)
                switch (propKey$jscomp$1) {
                  case "children":
                    children$jscomp$1 = propValue$jscomp$1;
                    break;
                  case "selected":
                    selected = propValue$jscomp$1;
                    didWarnSelectedSetOnOption || (console.error(
                      "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."
                    ), didWarnSelectedSetOnOption = true);
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$1 = propValue$jscomp$1;
                    break;
                  case "value":
                    value = propValue$jscomp$1;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$1,
                      propValue$jscomp$1
                    );
                }
            }
          if (null != selectedValue) {
            if (null !== value) {
              checkAttributeStringCoercion(value, "value");
              var stringValue = "" + value;
            } else
              null === innerHTML$jscomp$1 || didWarnInvalidOptionInnerHTML || (didWarnInvalidOptionInnerHTML = true, console.error(
                "Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."
              )), stringValue = flattenOptionChildren(children$jscomp$1);
            if (isArrayImpl(selectedValue))
              for (var i = 0; i < selectedValue.length; i++) {
                if (checkAttributeStringCoercion(selectedValue[i], "value"), "" + selectedValue[i] === stringValue) {
                  target$jscomp$0.push(' selected=""');
                  break;
                }
              }
            else
              checkAttributeStringCoercion(selectedValue, "select.value"), "" + selectedValue === stringValue && target$jscomp$0.push(' selected=""');
          } else selected && target$jscomp$0.push(' selected=""');
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$1, children$jscomp$1);
          return children$jscomp$1;
        case "textarea":
          checkControlledValueProps("textarea", props);
          void 0 === props.value || void 0 === props.defaultValue || didWarnDefaultTextareaValue || (console.error(
            "Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://react.dev/link/controlled-components"
          ), didWarnDefaultTextareaValue = true);
          target$jscomp$0.push(startChunkForTag("textarea"));
          var value$jscomp$0 = null, defaultValue = null, children$jscomp$2 = null, propKey$jscomp$2;
          for (propKey$jscomp$2 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$2)) {
              var propValue$jscomp$2 = props[propKey$jscomp$2];
              if (null != propValue$jscomp$2)
                switch (propKey$jscomp$2) {
                  case "children":
                    children$jscomp$2 = propValue$jscomp$2;
                    break;
                  case "value":
                    value$jscomp$0 = propValue$jscomp$2;
                    break;
                  case "defaultValue":
                    defaultValue = propValue$jscomp$2;
                    break;
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                    );
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$2,
                      propValue$jscomp$2
                    );
                }
            }
          null === value$jscomp$0 && null !== defaultValue && (value$jscomp$0 = defaultValue);
          target$jscomp$0.push(endOfStartTag);
          if (null != children$jscomp$2) {
            console.error(
              "Use the `defaultValue` or `value` props instead of setting children on <textarea>."
            );
            if (null != value$jscomp$0)
              throw Error(
                "If you supply `defaultValue` on a <textarea>, do not pass children."
              );
            if (isArrayImpl(children$jscomp$2)) {
              if (1 < children$jscomp$2.length)
                throw Error("<textarea> can only have at most one child.");
              checkHtmlStringCoercion(children$jscomp$2[0]);
              value$jscomp$0 = "" + children$jscomp$2[0];
            }
            checkHtmlStringCoercion(children$jscomp$2);
            value$jscomp$0 = "" + children$jscomp$2;
          }
          "string" === typeof value$jscomp$0 && "\n" === value$jscomp$0[0] && target$jscomp$0.push(leadingNewline);
          null !== value$jscomp$0 && (checkAttributeStringCoercion(value$jscomp$0, "value"), target$jscomp$0.push(escapeTextForBrowser("" + value$jscomp$0)));
          return null;
        case "input":
          checkControlledValueProps("input", props);
          target$jscomp$0.push(startChunkForTag("input"));
          var name2 = null, formAction = null, formEncType = null, formMethod = null, formTarget = null, value$jscomp$1 = null, defaultValue$jscomp$0 = null, checked = null, defaultChecked = null, propKey$jscomp$3;
          for (propKey$jscomp$3 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$3)) {
              var propValue$jscomp$3 = props[propKey$jscomp$3];
              if (null != propValue$jscomp$3)
                switch (propKey$jscomp$3) {
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  case "name":
                    name2 = propValue$jscomp$3;
                    break;
                  case "formAction":
                    formAction = propValue$jscomp$3;
                    break;
                  case "formEncType":
                    formEncType = propValue$jscomp$3;
                    break;
                  case "formMethod":
                    formMethod = propValue$jscomp$3;
                    break;
                  case "formTarget":
                    formTarget = propValue$jscomp$3;
                    break;
                  case "defaultChecked":
                    defaultChecked = propValue$jscomp$3;
                    break;
                  case "defaultValue":
                    defaultValue$jscomp$0 = propValue$jscomp$3;
                    break;
                  case "checked":
                    checked = propValue$jscomp$3;
                    break;
                  case "value":
                    value$jscomp$1 = propValue$jscomp$3;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$3,
                      propValue$jscomp$3
                    );
                }
            }
          null === formAction || "image" === props.type || "submit" === props.type || didWarnFormActionType || (didWarnFormActionType = true, console.error(
            'An input can only specify a formAction along with type="submit" or type="image".'
          ));
          var formData = pushFormActionAttribute(
            target$jscomp$0,
            resumableState,
            renderState,
            formAction,
            formEncType,
            formMethod,
            formTarget,
            name2
          );
          null === checked || null === defaultChecked || didWarnDefaultChecked || (console.error(
            "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
            "A component",
            props.type
          ), didWarnDefaultChecked = true);
          null === value$jscomp$1 || null === defaultValue$jscomp$0 || didWarnDefaultInputValue || (console.error(
            "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
            "A component",
            props.type
          ), didWarnDefaultInputValue = true);
          null !== checked ? pushBooleanAttribute(target$jscomp$0, "checked", checked) : null !== defaultChecked && pushBooleanAttribute(target$jscomp$0, "checked", defaultChecked);
          null !== value$jscomp$1 ? pushAttribute(target$jscomp$0, "value", value$jscomp$1) : null !== defaultValue$jscomp$0 && pushAttribute(target$jscomp$0, "value", defaultValue$jscomp$0);
          target$jscomp$0.push(endOfStartTagSelfClosing);
          null != formData && formData.forEach(pushAdditionalFormField, target$jscomp$0);
          return null;
        case "button":
          target$jscomp$0.push(startChunkForTag("button"));
          var children$jscomp$3 = null, innerHTML$jscomp$2 = null, name$jscomp$0 = null, formAction$jscomp$0 = null, formEncType$jscomp$0 = null, formMethod$jscomp$0 = null, formTarget$jscomp$0 = null, propKey$jscomp$4;
          for (propKey$jscomp$4 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$4)) {
              var propValue$jscomp$4 = props[propKey$jscomp$4];
              if (null != propValue$jscomp$4)
                switch (propKey$jscomp$4) {
                  case "children":
                    children$jscomp$3 = propValue$jscomp$4;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$2 = propValue$jscomp$4;
                    break;
                  case "name":
                    name$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formAction":
                    formAction$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formEncType":
                    formEncType$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formMethod":
                    formMethod$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formTarget":
                    formTarget$jscomp$0 = propValue$jscomp$4;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$4,
                      propValue$jscomp$4
                    );
                }
            }
          null === formAction$jscomp$0 || null == props.type || "submit" === props.type || didWarnFormActionType || (didWarnFormActionType = true, console.error(
            'A button can only specify a formAction along with type="submit" or no type.'
          ));
          var formData$jscomp$0 = pushFormActionAttribute(
            target$jscomp$0,
            resumableState,
            renderState,
            formAction$jscomp$0,
            formEncType$jscomp$0,
            formMethod$jscomp$0,
            formTarget$jscomp$0,
            name$jscomp$0
          );
          target$jscomp$0.push(endOfStartTag);
          null != formData$jscomp$0 && formData$jscomp$0.forEach(pushAdditionalFormField, target$jscomp$0);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$2, children$jscomp$3);
          if ("string" === typeof children$jscomp$3) {
            target$jscomp$0.push(escapeTextForBrowser(children$jscomp$3));
            var JSCompiler_inline_result$jscomp$1 = null;
          } else JSCompiler_inline_result$jscomp$1 = children$jscomp$3;
          return JSCompiler_inline_result$jscomp$1;
        case "form":
          target$jscomp$0.push(startChunkForTag("form"));
          var children$jscomp$4 = null, innerHTML$jscomp$3 = null, formAction$jscomp$1 = null, formEncType$jscomp$1 = null, formMethod$jscomp$1 = null, formTarget$jscomp$1 = null, propKey$jscomp$5;
          for (propKey$jscomp$5 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$5)) {
              var propValue$jscomp$5 = props[propKey$jscomp$5];
              if (null != propValue$jscomp$5)
                switch (propKey$jscomp$5) {
                  case "children":
                    children$jscomp$4 = propValue$jscomp$5;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$3 = propValue$jscomp$5;
                    break;
                  case "action":
                    formAction$jscomp$1 = propValue$jscomp$5;
                    break;
                  case "encType":
                    formEncType$jscomp$1 = propValue$jscomp$5;
                    break;
                  case "method":
                    formMethod$jscomp$1 = propValue$jscomp$5;
                    break;
                  case "target":
                    formTarget$jscomp$1 = propValue$jscomp$5;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$5,
                      propValue$jscomp$5
                    );
                }
            }
          var formData$jscomp$1 = null, formActionName = null;
          if ("function" === typeof formAction$jscomp$1) {
            null === formEncType$jscomp$1 && null === formMethod$jscomp$1 || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
              "Cannot specify a encType or method for a form that specifies a function as the action. React provides those automatically. They will get overridden."
            ));
            null === formTarget$jscomp$1 || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
              "Cannot specify a target for a form that specifies a function as the action. The function will always be executed in the same window."
            ));
            var customFields = getCustomFormFields(
              resumableState,
              formAction$jscomp$1
            );
            null !== customFields ? (formAction$jscomp$1 = customFields.action || "", formEncType$jscomp$1 = customFields.encType, formMethod$jscomp$1 = customFields.method, formTarget$jscomp$1 = customFields.target, formData$jscomp$1 = customFields.data, formActionName = customFields.name) : (target$jscomp$0.push(
              attributeSeparator,
              "action",
              attributeAssign,
              actionJavaScriptURL,
              attributeEnd
            ), formTarget$jscomp$1 = formMethod$jscomp$1 = formEncType$jscomp$1 = formAction$jscomp$1 = null, injectFormReplayingRuntime(resumableState, renderState));
          }
          null != formAction$jscomp$1 && pushAttribute(target$jscomp$0, "action", formAction$jscomp$1);
          null != formEncType$jscomp$1 && pushAttribute(target$jscomp$0, "encType", formEncType$jscomp$1);
          null != formMethod$jscomp$1 && pushAttribute(target$jscomp$0, "method", formMethod$jscomp$1);
          null != formTarget$jscomp$1 && pushAttribute(target$jscomp$0, "target", formTarget$jscomp$1);
          target$jscomp$0.push(endOfStartTag);
          null !== formActionName && (target$jscomp$0.push('<input type="hidden"'), pushStringAttribute(target$jscomp$0, "name", formActionName), target$jscomp$0.push(endOfStartTagSelfClosing), null != formData$jscomp$1 && formData$jscomp$1.forEach(
            pushAdditionalFormField,
            target$jscomp$0
          ));
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$3, children$jscomp$4);
          if ("string" === typeof children$jscomp$4) {
            target$jscomp$0.push(escapeTextForBrowser(children$jscomp$4));
            var JSCompiler_inline_result$jscomp$2 = null;
          } else JSCompiler_inline_result$jscomp$2 = children$jscomp$4;
          return JSCompiler_inline_result$jscomp$2;
        case "menuitem":
          target$jscomp$0.push(startChunkForTag("menuitem"));
          for (var propKey$jscomp$6 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$6)) {
              var propValue$jscomp$6 = props[propKey$jscomp$6];
              if (null != propValue$jscomp$6)
                switch (propKey$jscomp$6) {
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "menuitems cannot have `children` nor `dangerouslySetInnerHTML`."
                    );
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$6,
                      propValue$jscomp$6
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          return null;
        case "object":
          target$jscomp$0.push(startChunkForTag("object"));
          var children$jscomp$5 = null, innerHTML$jscomp$4 = null, propKey$jscomp$7;
          for (propKey$jscomp$7 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$7)) {
              var propValue$jscomp$7 = props[propKey$jscomp$7];
              if (null != propValue$jscomp$7)
                switch (propKey$jscomp$7) {
                  case "children":
                    children$jscomp$5 = propValue$jscomp$7;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$4 = propValue$jscomp$7;
                    break;
                  case "data":
                    checkAttributeStringCoercion(propValue$jscomp$7, "data");
                    var sanitizedValue = sanitizeURL("" + propValue$jscomp$7);
                    if ("" === sanitizedValue) {
                      console.error(
                        'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                        propKey$jscomp$7,
                        propKey$jscomp$7
                      );
                      break;
                    }
                    target$jscomp$0.push(
                      attributeSeparator,
                      "data",
                      attributeAssign,
                      escapeTextForBrowser(sanitizedValue),
                      attributeEnd
                    );
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$7,
                      propValue$jscomp$7
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$4, children$jscomp$5);
          if ("string" === typeof children$jscomp$5) {
            target$jscomp$0.push(escapeTextForBrowser(children$jscomp$5));
            var JSCompiler_inline_result$jscomp$3 = null;
          } else JSCompiler_inline_result$jscomp$3 = children$jscomp$5;
          return JSCompiler_inline_result$jscomp$3;
        case "title":
          var noscriptTagInScope = formatContext.tagScope & 1, isFallback = formatContext.tagScope & 4;
          if (hasOwnProperty2.call(props, "children")) {
            var children$jscomp$6 = props.children, child = Array.isArray(children$jscomp$6) ? 2 > children$jscomp$6.length ? children$jscomp$6[0] : null : children$jscomp$6;
            Array.isArray(children$jscomp$6) && 1 < children$jscomp$6.length ? console.error(
              "React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an Array with length %s instead. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert `children` of <title> tags to a single string value which is why Arrays of length greater than 1 are not supported. When using JSX it can be common to combine text nodes and value nodes. For example: <title>hello {nameOfUser}</title>. While not immediately apparent, `children` in this case is an Array with length 2. If your `children` prop is using this form try rewriting it using a template string: <title>{`hello ${nameOfUser}`}</title>.",
              children$jscomp$6.length
            ) : "function" === typeof child || "symbol" === typeof child ? console.error(
              "React expect children of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found %s instead. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value.",
              "function" === typeof child ? "a Function" : "a Sybmol"
            ) : child && child.toString === {}.toString && (null != child.$$typeof ? console.error(
              "React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an object that appears to be a React element which never implements a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value which is why rendering React elements is not supported. If the `children` of <title> is a React Component try moving the <title> tag into that component. If the `children` of <title> is some HTML markup change it to be Text only to be valid HTML."
            ) : console.error(
              "React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an object that does not implement a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value. Using the default `toString` method available on every object is almost certainly an error. Consider whether the `children` of this <title> is an object in error and change it to a string or number value if so. Otherwise implement a `toString` method that React can use to produce a valid <title>."
            ));
          }
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope || null != props.itemProp)
            var JSCompiler_inline_result$jscomp$4 = pushTitleImpl(
              target$jscomp$0,
              props
            );
          else
            isFallback ? JSCompiler_inline_result$jscomp$4 = null : (pushTitleImpl(renderState.hoistableChunks, props), JSCompiler_inline_result$jscomp$4 = void 0);
          return JSCompiler_inline_result$jscomp$4;
        case "link":
          var noscriptTagInScope$jscomp$0 = formatContext.tagScope & 1, isFallback$jscomp$0 = formatContext.tagScope & 4, rel = props.rel, href = props.href, precedence = props.precedence;
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$0 || null != props.itemProp || "string" !== typeof rel || "string" !== typeof href || "" === href) {
            "stylesheet" === rel && "string" === typeof props.precedence && ("string" === typeof href && href || console.error(
              'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and expected the `href` prop to be a non-empty string but ecountered %s instead. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop ensure there is a non-empty string `href` prop as well, otherwise remove the `precedence` prop.',
              null === href ? "`null`" : void 0 === href ? "`undefined`" : "" === href ? "an empty string" : 'something with type "' + typeof href + '"'
            ));
            pushLinkImpl(target$jscomp$0, props);
            var JSCompiler_inline_result$jscomp$5 = null;
          } else if ("stylesheet" === props.rel)
            if ("string" !== typeof precedence || null != props.disabled || props.onLoad || props.onError) {
              if ("string" === typeof precedence) {
                if (null != props.disabled)
                  console.error(
                    'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and a `disabled` prop. The presence of the `disabled` prop indicates an intent to manage the stylesheet active state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `disabled` prop, otherwise remove the `precedence` prop.'
                  );
                else if (props.onLoad || props.onError) {
                  var propDescription = props.onLoad && props.onError ? "`onLoad` and `onError` props" : props.onLoad ? "`onLoad` prop" : "`onError` prop";
                  console.error(
                    'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and %s. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.',
                    propDescription,
                    propDescription
                  );
                }
              }
              JSCompiler_inline_result$jscomp$5 = pushLinkImpl(
                target$jscomp$0,
                props
              );
            } else {
              var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(
                href
              ) ? resumableState.styleResources[href] : void 0;
              if (resourceState !== EXISTS) {
                resumableState.styleResources[href] = EXISTS;
                styleQueue || (styleQueue = {
                  precedence: escapeTextForBrowser(precedence),
                  rules: [],
                  hrefs: [],
                  sheets: /* @__PURE__ */ new Map()
                }, renderState.styles.set(precedence, styleQueue));
                var resource = {
                  state: PENDING$1,
                  props: assign({}, props, {
                    "data-precedence": props.precedence,
                    precedence: null
                  })
                };
                if (resourceState) {
                  2 === resourceState.length && adoptPreloadCredentials(resource.props, resourceState);
                  var preloadResource = renderState.preloads.stylesheets.get(href);
                  preloadResource && 0 < preloadResource.length ? preloadResource.length = 0 : resource.state = PRELOADED;
                }
                styleQueue.sheets.set(href, resource);
                hoistableState && hoistableState.stylesheets.add(resource);
              } else if (styleQueue) {
                var _resource = styleQueue.sheets.get(href);
                _resource && hoistableState && hoistableState.stylesheets.add(_resource);
              }
              textEmbedded && target$jscomp$0.push("<!-- -->");
              JSCompiler_inline_result$jscomp$5 = null;
            }
          else
            props.onLoad || props.onError ? JSCompiler_inline_result$jscomp$5 = pushLinkImpl(
              target$jscomp$0,
              props
            ) : (textEmbedded && target$jscomp$0.push("<!-- -->"), JSCompiler_inline_result$jscomp$5 = isFallback$jscomp$0 ? null : pushLinkImpl(renderState.hoistableChunks, props));
          return JSCompiler_inline_result$jscomp$5;
        case "script":
          var noscriptTagInScope$jscomp$1 = formatContext.tagScope & 1, asyncProp = props.async;
          if ("string" !== typeof props.src || !props.src || !asyncProp || "function" === typeof asyncProp || "symbol" === typeof asyncProp || props.onLoad || props.onError || formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$1 || null != props.itemProp)
            var JSCompiler_inline_result$jscomp$6 = pushScriptImpl(
              target$jscomp$0,
              props
            );
          else {
            var key = props.src;
            if ("module" === props.type) {
              var resources = resumableState.moduleScriptResources;
              var preloads = renderState.preloads.moduleScripts;
            } else
              resources = resumableState.scriptResources, preloads = renderState.preloads.scripts;
            var resourceState$jscomp$0 = resources.hasOwnProperty(key) ? resources[key] : void 0;
            if (resourceState$jscomp$0 !== EXISTS) {
              resources[key] = EXISTS;
              var scriptProps = props;
              if (resourceState$jscomp$0) {
                2 === resourceState$jscomp$0.length && (scriptProps = assign({}, props), adoptPreloadCredentials(scriptProps, resourceState$jscomp$0));
                var preloadResource$jscomp$0 = preloads.get(key);
                preloadResource$jscomp$0 && (preloadResource$jscomp$0.length = 0);
              }
              var resource$jscomp$0 = [];
              renderState.scripts.add(resource$jscomp$0);
              pushScriptImpl(resource$jscomp$0, scriptProps);
            }
            textEmbedded && target$jscomp$0.push("<!-- -->");
            JSCompiler_inline_result$jscomp$6 = null;
          }
          return JSCompiler_inline_result$jscomp$6;
        case "style":
          var noscriptTagInScope$jscomp$2 = formatContext.tagScope & 1;
          if (hasOwnProperty2.call(props, "children")) {
            var children$jscomp$7 = props.children, child$jscomp$0 = Array.isArray(children$jscomp$7) ? 2 > children$jscomp$7.length ? children$jscomp$7[0] : null : children$jscomp$7;
            ("function" === typeof child$jscomp$0 || "symbol" === typeof child$jscomp$0 || Array.isArray(child$jscomp$0)) && console.error(
              "React expect children of <style> tags to be a string, number, or object with a `toString` method but found %s instead. In browsers style Elements can only have `Text` Nodes as children.",
              "function" === typeof child$jscomp$0 ? "a Function" : "symbol" === typeof child$jscomp$0 ? "a Sybmol" : "an Array"
            );
          }
          var precedence$jscomp$0 = props.precedence, href$jscomp$0 = props.href, nonce = props.nonce;
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$2 || null != props.itemProp || "string" !== typeof precedence$jscomp$0 || "string" !== typeof href$jscomp$0 || "" === href$jscomp$0) {
            target$jscomp$0.push(startChunkForTag("style"));
            var children$jscomp$8 = null, innerHTML$jscomp$5 = null, propKey$jscomp$8;
            for (propKey$jscomp$8 in props)
              if (hasOwnProperty2.call(props, propKey$jscomp$8)) {
                var propValue$jscomp$8 = props[propKey$jscomp$8];
                if (null != propValue$jscomp$8)
                  switch (propKey$jscomp$8) {
                    case "children":
                      children$jscomp$8 = propValue$jscomp$8;
                      break;
                    case "dangerouslySetInnerHTML":
                      innerHTML$jscomp$5 = propValue$jscomp$8;
                      break;
                    default:
                      pushAttribute(
                        target$jscomp$0,
                        propKey$jscomp$8,
                        propValue$jscomp$8
                      );
                  }
              }
            target$jscomp$0.push(endOfStartTag);
            var child$jscomp$1 = Array.isArray(children$jscomp$8) ? 2 > children$jscomp$8.length ? children$jscomp$8[0] : null : children$jscomp$8;
            "function" !== typeof child$jscomp$1 && "symbol" !== typeof child$jscomp$1 && null !== child$jscomp$1 && void 0 !== child$jscomp$1 && target$jscomp$0.push(escapeStyleTextContent(child$jscomp$1));
            pushInnerHTML(
              target$jscomp$0,
              innerHTML$jscomp$5,
              children$jscomp$8
            );
            target$jscomp$0.push(endChunkForTag("style"));
            var JSCompiler_inline_result$jscomp$7 = null;
          } else {
            href$jscomp$0.includes(" ") && console.error(
              'React expected the `href` prop for a <style> tag opting into hoisting semantics using the `precedence` prop to not have any spaces but ecountered spaces instead. using spaces in this prop will cause hydration of this style to fail on the client. The href for the <style> where this ocurred is "%s".',
              href$jscomp$0
            );
            var styleQueue$jscomp$0 = renderState.styles.get(precedence$jscomp$0), resourceState$jscomp$1 = resumableState.styleResources.hasOwnProperty(href$jscomp$0) ? resumableState.styleResources[href$jscomp$0] : void 0;
            if (resourceState$jscomp$1 !== EXISTS) {
              resumableState.styleResources[href$jscomp$0] = EXISTS;
              resourceState$jscomp$1 && console.error(
                'React encountered a hoistable style tag for the same href as a preload: "%s". When using a style tag to inline styles you should not also preload it as a stylsheet.',
                href$jscomp$0
              );
              styleQueue$jscomp$0 || (styleQueue$jscomp$0 = {
                precedence: escapeTextForBrowser(precedence$jscomp$0),
                rules: [],
                hrefs: [],
                sheets: /* @__PURE__ */ new Map()
              }, renderState.styles.set(
                precedence$jscomp$0,
                styleQueue$jscomp$0
              ));
              var nonceStyle = renderState.nonce.style;
              if (nonceStyle && nonceStyle !== nonce)
                console.error(
                  'React encountered a style tag with `precedence` "%s" and `nonce` "%s". When React manages style rules using `precedence` it will only include rules if the nonce matches the style nonce "%s" that was included with this render.',
                  precedence$jscomp$0,
                  nonce,
                  nonceStyle
                );
              else {
                !nonceStyle && nonce && console.error(
                  'React encountered a style tag with `precedence` "%s" and `nonce` "%s". When React manages style rules using `precedence` it will only include a nonce attributes if you also provide the same style nonce value as a render option.',
                  precedence$jscomp$0,
                  nonce
                );
                styleQueue$jscomp$0.hrefs.push(
                  escapeTextForBrowser(href$jscomp$0)
                );
                var target = styleQueue$jscomp$0.rules, children$jscomp$9 = null, innerHTML$jscomp$6 = null, propKey$jscomp$9;
                for (propKey$jscomp$9 in props)
                  if (hasOwnProperty2.call(props, propKey$jscomp$9)) {
                    var propValue$jscomp$9 = props[propKey$jscomp$9];
                    if (null != propValue$jscomp$9)
                      switch (propKey$jscomp$9) {
                        case "children":
                          children$jscomp$9 = propValue$jscomp$9;
                          break;
                        case "dangerouslySetInnerHTML":
                          innerHTML$jscomp$6 = propValue$jscomp$9;
                      }
                  }
                var child$jscomp$2 = Array.isArray(children$jscomp$9) ? 2 > children$jscomp$9.length ? children$jscomp$9[0] : null : children$jscomp$9;
                "function" !== typeof child$jscomp$2 && "symbol" !== typeof child$jscomp$2 && null !== child$jscomp$2 && void 0 !== child$jscomp$2 && target.push(escapeStyleTextContent(child$jscomp$2));
                pushInnerHTML(target, innerHTML$jscomp$6, children$jscomp$9);
              }
            }
            styleQueue$jscomp$0 && hoistableState && hoistableState.styles.add(styleQueue$jscomp$0);
            textEmbedded && target$jscomp$0.push("<!-- -->");
            JSCompiler_inline_result$jscomp$7 = void 0;
          }
          return JSCompiler_inline_result$jscomp$7;
        case "meta":
          var noscriptTagInScope$jscomp$3 = formatContext.tagScope & 1, isFallback$jscomp$1 = formatContext.tagScope & 4;
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$3 || null != props.itemProp)
            var JSCompiler_inline_result$jscomp$8 = pushSelfClosing(
              target$jscomp$0,
              props,
              "meta"
            );
          else
            textEmbedded && target$jscomp$0.push("<!-- -->"), JSCompiler_inline_result$jscomp$8 = isFallback$jscomp$1 ? null : "string" === typeof props.charSet ? pushSelfClosing(renderState.charsetChunks, props, "meta") : "viewport" === props.name ? pushSelfClosing(renderState.viewportChunks, props, "meta") : pushSelfClosing(
              renderState.hoistableChunks,
              props,
              "meta"
            );
          return JSCompiler_inline_result$jscomp$8;
        case "listing":
        case "pre":
          target$jscomp$0.push(startChunkForTag(type2));
          var children$jscomp$10 = null, innerHTML$jscomp$7 = null, propKey$jscomp$10;
          for (propKey$jscomp$10 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$10)) {
              var propValue$jscomp$10 = props[propKey$jscomp$10];
              if (null != propValue$jscomp$10)
                switch (propKey$jscomp$10) {
                  case "children":
                    children$jscomp$10 = propValue$jscomp$10;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$7 = propValue$jscomp$10;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$10,
                      propValue$jscomp$10
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          if (null != innerHTML$jscomp$7) {
            if (null != children$jscomp$10)
              throw Error(
                "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
              );
            if ("object" !== typeof innerHTML$jscomp$7 || !("__html" in innerHTML$jscomp$7))
              throw Error(
                "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
              );
            var html2 = innerHTML$jscomp$7.__html;
            null !== html2 && void 0 !== html2 && ("string" === typeof html2 && 0 < html2.length && "\n" === html2[0] ? target$jscomp$0.push(leadingNewline, html2) : (checkHtmlStringCoercion(html2), target$jscomp$0.push("" + html2)));
          }
          "string" === typeof children$jscomp$10 && "\n" === children$jscomp$10[0] && target$jscomp$0.push(leadingNewline);
          return children$jscomp$10;
        case "img":
          var pictureOrNoScriptTagInScope = formatContext.tagScope & 3, src2 = props.src, srcSet = props.srcSet;
          if (!("lazy" === props.loading || !src2 && !srcSet || "string" !== typeof src2 && null != src2 || "string" !== typeof srcSet && null != srcSet || "low" === props.fetchPriority || pictureOrNoScriptTagInScope) && ("string" !== typeof src2 || ":" !== src2[4] || "d" !== src2[0] && "D" !== src2[0] || "a" !== src2[1] && "A" !== src2[1] || "t" !== src2[2] && "T" !== src2[2] || "a" !== src2[3] && "A" !== src2[3]) && ("string" !== typeof srcSet || ":" !== srcSet[4] || "d" !== srcSet[0] && "D" !== srcSet[0] || "a" !== srcSet[1] && "A" !== srcSet[1] || "t" !== srcSet[2] && "T" !== srcSet[2] || "a" !== srcSet[3] && "A" !== srcSet[3])) {
            null !== hoistableState && formatContext.tagScope & 64 && (hoistableState.suspenseyImages = true);
            var sizes = "string" === typeof props.sizes ? props.sizes : void 0, key$jscomp$0 = srcSet ? srcSet + "\n" + (sizes || "") : src2, promotablePreloads = renderState.preloads.images, resource$jscomp$1 = promotablePreloads.get(key$jscomp$0);
            if (resource$jscomp$1) {
              if ("high" === props.fetchPriority || 10 > renderState.highImagePreloads.size)
                promotablePreloads.delete(key$jscomp$0), renderState.highImagePreloads.add(resource$jscomp$1);
            } else if (!resumableState.imageResources.hasOwnProperty(key$jscomp$0)) {
              resumableState.imageResources[key$jscomp$0] = PRELOAD_NO_CREDS;
              var input = props.crossOrigin;
              var crossOrigin = "string" === typeof input ? "use-credentials" === input ? input : "" : void 0;
              var headers = renderState.headers, header;
              headers && 0 < headers.remainingCapacity && "string" !== typeof props.srcSet && ("high" === props.fetchPriority || 500 > headers.highImagePreloads.length) && (header = getPreloadAsHeader(src2, "image", {
                imageSrcSet: props.srcSet,
                imageSizes: props.sizes,
                crossOrigin,
                integrity: props.integrity,
                nonce: props.nonce,
                type: props.type,
                fetchPriority: props.fetchPriority,
                referrerPolicy: props.refererPolicy
              }), 0 <= (headers.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key$jscomp$0] = PRELOAD_NO_CREDS, headers.highImagePreloads && (headers.highImagePreloads += ", "), headers.highImagePreloads += header) : (resource$jscomp$1 = [], pushLinkImpl(resource$jscomp$1, {
                rel: "preload",
                as: "image",
                href: srcSet ? void 0 : src2,
                imageSrcSet: srcSet,
                imageSizes: sizes,
                crossOrigin,
                integrity: props.integrity,
                type: props.type,
                fetchPriority: props.fetchPriority,
                referrerPolicy: props.referrerPolicy
              }), "high" === props.fetchPriority || 10 > renderState.highImagePreloads.size ? renderState.highImagePreloads.add(resource$jscomp$1) : (renderState.bulkPreloads.add(resource$jscomp$1), promotablePreloads.set(key$jscomp$0, resource$jscomp$1)));
            }
          }
          return pushSelfClosing(target$jscomp$0, props, "img");
        case "base":
        case "area":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "keygen":
        case "param":
        case "source":
        case "track":
        case "wbr":
          return pushSelfClosing(target$jscomp$0, props, type2);
        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":
          break;
        case "head":
          if (formatContext.insertionMode < HTML_MODE) {
            var preamble = preambleState || renderState.preamble;
            if (preamble.headChunks)
              throw Error("The `<head>` tag may only be rendered once.");
            null !== preambleState && target$jscomp$0.push("<!--head-->");
            preamble.headChunks = [];
            var JSCompiler_inline_result$jscomp$9 = pushStartSingletonElement(
              preamble.headChunks,
              props,
              "head"
            );
          } else
            JSCompiler_inline_result$jscomp$9 = pushStartGenericElement(
              target$jscomp$0,
              props,
              "head"
            );
          return JSCompiler_inline_result$jscomp$9;
        case "body":
          if (formatContext.insertionMode < HTML_MODE) {
            var preamble$jscomp$0 = preambleState || renderState.preamble;
            if (preamble$jscomp$0.bodyChunks)
              throw Error("The `<body>` tag may only be rendered once.");
            null !== preambleState && target$jscomp$0.push("<!--body-->");
            preamble$jscomp$0.bodyChunks = [];
            var JSCompiler_inline_result$jscomp$10 = pushStartSingletonElement(
              preamble$jscomp$0.bodyChunks,
              props,
              "body"
            );
          } else
            JSCompiler_inline_result$jscomp$10 = pushStartGenericElement(
              target$jscomp$0,
              props,
              "body"
            );
          return JSCompiler_inline_result$jscomp$10;
        case "html":
          if (formatContext.insertionMode === ROOT_HTML_MODE) {
            var preamble$jscomp$1 = preambleState || renderState.preamble;
            if (preamble$jscomp$1.htmlChunks)
              throw Error("The `<html>` tag may only be rendered once.");
            null !== preambleState && target$jscomp$0.push("<!--html-->");
            preamble$jscomp$1.htmlChunks = [doctypeChunk];
            var JSCompiler_inline_result$jscomp$11 = pushStartSingletonElement(
              preamble$jscomp$1.htmlChunks,
              props,
              "html"
            );
          } else
            JSCompiler_inline_result$jscomp$11 = pushStartGenericElement(
              target$jscomp$0,
              props,
              "html"
            );
          return JSCompiler_inline_result$jscomp$11;
        default:
          if (-1 !== type2.indexOf("-")) {
            target$jscomp$0.push(startChunkForTag(type2));
            var children$jscomp$11 = null, innerHTML$jscomp$8 = null, propKey$jscomp$11;
            for (propKey$jscomp$11 in props)
              if (hasOwnProperty2.call(props, propKey$jscomp$11)) {
                var propValue$jscomp$11 = props[propKey$jscomp$11];
                if (null != propValue$jscomp$11) {
                  var attributeName = propKey$jscomp$11;
                  switch (propKey$jscomp$11) {
                    case "children":
                      children$jscomp$11 = propValue$jscomp$11;
                      break;
                    case "dangerouslySetInnerHTML":
                      innerHTML$jscomp$8 = propValue$jscomp$11;
                      break;
                    case "style":
                      pushStyleAttribute(target$jscomp$0, propValue$jscomp$11);
                      break;
                    case "suppressContentEditableWarning":
                    case "suppressHydrationWarning":
                    case "ref":
                      break;
                    case "className":
                      attributeName = "class";
                    default:
                      if (isAttributeNameSafe(propKey$jscomp$11) && "function" !== typeof propValue$jscomp$11 && "symbol" !== typeof propValue$jscomp$11 && false !== propValue$jscomp$11) {
                        if (true === propValue$jscomp$11)
                          propValue$jscomp$11 = "";
                        else if ("object" === typeof propValue$jscomp$11)
                          continue;
                        target$jscomp$0.push(
                          attributeSeparator,
                          attributeName,
                          attributeAssign,
                          escapeTextForBrowser(propValue$jscomp$11),
                          attributeEnd
                        );
                      }
                  }
                }
              }
            target$jscomp$0.push(endOfStartTag);
            pushInnerHTML(
              target$jscomp$0,
              innerHTML$jscomp$8,
              children$jscomp$11
            );
            return children$jscomp$11;
          }
      }
      return pushStartGenericElement(target$jscomp$0, props, type2);
    }
    function endChunkForTag(tag) {
      var chunk2 = endTagCache.get(tag);
      void 0 === chunk2 && (chunk2 = "</" + tag + ">", endTagCache.set(tag, chunk2));
      return chunk2;
    }
    function hoistPreambleState(renderState, preambleState) {
      renderState = renderState.preamble;
      null === renderState.htmlChunks && preambleState.htmlChunks && (renderState.htmlChunks = preambleState.htmlChunks);
      null === renderState.headChunks && preambleState.headChunks && (renderState.headChunks = preambleState.headChunks);
      null === renderState.bodyChunks && preambleState.bodyChunks && (renderState.bodyChunks = preambleState.bodyChunks);
    }
    function writeBootstrap(destination, renderState) {
      renderState = renderState.bootstrapChunks;
      for (var i = 0; i < renderState.length - 1; i++)
        destination.push(renderState[i]);
      return i < renderState.length ? (i = renderState[i], renderState.length = 0, destination.push(i)) : true;
    }
    function writeStartPendingSuspenseBoundary(destination, renderState, id) {
      destination.push(startPendingSuspenseBoundary1);
      if (null === id)
        throw Error(
          "An ID must have been assigned before we can complete the boundary."
        );
      destination.push(renderState.boundaryPrefix);
      renderState = id.toString(16);
      destination.push(renderState);
      return destination.push(startPendingSuspenseBoundary2);
    }
    function writeStartSegment(destination, renderState, formatContext, id) {
      switch (formatContext.insertionMode) {
        case ROOT_HTML_MODE:
        case HTML_HTML_MODE:
        case HTML_HEAD_MODE:
        case HTML_MODE:
          return destination.push(startSegmentHTML), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentHTML2);
        case SVG_MODE:
          return destination.push(startSegmentSVG), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentSVG2);
        case MATHML_MODE:
          return destination.push(startSegmentMathML), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentMathML2);
        case HTML_TABLE_MODE:
          return destination.push(startSegmentTable), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentTable2);
        case HTML_TABLE_BODY_MODE:
          return destination.push(startSegmentTableBody), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentTableBody2);
        case HTML_TABLE_ROW_MODE:
          return destination.push(startSegmentTableRow), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentTableRow2);
        case HTML_COLGROUP_MODE:
          return destination.push(startSegmentColGroup), destination.push(renderState.segmentPrefix), renderState = id.toString(16), destination.push(renderState), destination.push(startSegmentColGroup2);
        default:
          throw Error("Unknown insertion mode. This is a bug in React.");
      }
    }
    function writeEndSegment(destination, formatContext) {
      switch (formatContext.insertionMode) {
        case ROOT_HTML_MODE:
        case HTML_HTML_MODE:
        case HTML_HEAD_MODE:
        case HTML_MODE:
          return destination.push(endSegmentHTML);
        case SVG_MODE:
          return destination.push(endSegmentSVG);
        case MATHML_MODE:
          return destination.push(endSegmentMathML);
        case HTML_TABLE_MODE:
          return destination.push(endSegmentTable);
        case HTML_TABLE_BODY_MODE:
          return destination.push(endSegmentTableBody);
        case HTML_TABLE_ROW_MODE:
          return destination.push(endSegmentTableRow);
        case HTML_COLGROUP_MODE:
          return destination.push(endSegmentColGroup);
        default:
          throw Error("Unknown insertion mode. This is a bug in React.");
      }
    }
    function escapeJSStringsForInstructionScripts(input) {
      return JSON.stringify(input).replace(
        regexForJSStringsInInstructionScripts,
        function(match) {
          switch (match) {
            case "<":
              return "\\u003c";
            case "\u2028":
              return "\\u2028";
            case "\u2029":
              return "\\u2029";
            default:
              throw Error(
                "escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
              );
          }
        }
      );
    }
    function escapeJSObjectForInstructionScripts(input) {
      return JSON.stringify(input).replace(
        regexForJSStringsInScripts,
        function(match) {
          switch (match) {
            case "&":
              return "\\u0026";
            case ">":
              return "\\u003e";
            case "<":
              return "\\u003c";
            case "\u2028":
              return "\\u2028";
            case "\u2029":
              return "\\u2029";
            default:
              throw Error(
                "escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
              );
          }
        }
      );
    }
    function flushStyleTagsLateForBoundary(styleQueue) {
      var rules = styleQueue.rules, hrefs = styleQueue.hrefs;
      0 < rules.length && 0 === hrefs.length && console.error(
        "React expected to have at least one href for an a hoistable style but found none. This is a bug in React."
      );
      var i = 0;
      if (hrefs.length) {
        this.push(currentlyFlushingRenderState.startInlineStyle);
        this.push(lateStyleTagResourceOpen1);
        this.push(styleQueue.precedence);
        for (this.push(lateStyleTagResourceOpen2); i < hrefs.length - 1; i++)
          this.push(hrefs[i]), this.push(spaceSeparator);
        this.push(hrefs[i]);
        this.push(lateStyleTagResourceOpen3);
        for (i = 0; i < rules.length; i++) this.push(rules[i]);
        destinationHasCapacity = this.push(lateStyleTagTemplateClose);
        currentlyRenderingBoundaryHasStylesToHoist = true;
        rules.length = 0;
        hrefs.length = 0;
      }
    }
    function hasStylesToHoist(stylesheet) {
      return stylesheet.state !== PREAMBLE ? currentlyRenderingBoundaryHasStylesToHoist = true : false;
    }
    function writeHoistablesForBoundary(destination, hoistableState, renderState) {
      currentlyRenderingBoundaryHasStylesToHoist = false;
      destinationHasCapacity = true;
      currentlyFlushingRenderState = renderState;
      hoistableState.styles.forEach(flushStyleTagsLateForBoundary, destination);
      currentlyFlushingRenderState = null;
      hoistableState.stylesheets.forEach(hasStylesToHoist);
      currentlyRenderingBoundaryHasStylesToHoist && (renderState.stylesToHoist = true);
      return destinationHasCapacity;
    }
    function flushResource(resource) {
      for (var i = 0; i < resource.length; i++) this.push(resource[i]);
      resource.length = 0;
    }
    function flushStyleInPreamble(stylesheet) {
      pushLinkImpl(stylesheetFlushingQueue, stylesheet.props);
      for (var i = 0; i < stylesheetFlushingQueue.length; i++)
        this.push(stylesheetFlushingQueue[i]);
      stylesheetFlushingQueue.length = 0;
      stylesheet.state = PREAMBLE;
    }
    function flushStylesInPreamble(styleQueue) {
      var hasStylesheets = 0 < styleQueue.sheets.size;
      styleQueue.sheets.forEach(flushStyleInPreamble, this);
      styleQueue.sheets.clear();
      var rules = styleQueue.rules, hrefs = styleQueue.hrefs;
      if (!hasStylesheets || hrefs.length) {
        this.push(currentlyFlushingRenderState.startInlineStyle);
        this.push(styleTagResourceOpen1);
        this.push(styleQueue.precedence);
        styleQueue = 0;
        if (hrefs.length) {
          for (this.push(styleTagResourceOpen2); styleQueue < hrefs.length - 1; styleQueue++)
            this.push(hrefs[styleQueue]), this.push(spaceSeparator);
          this.push(hrefs[styleQueue]);
        }
        this.push(styleTagResourceOpen3);
        for (styleQueue = 0; styleQueue < rules.length; styleQueue++)
          this.push(rules[styleQueue]);
        this.push(styleTagResourceClose);
        rules.length = 0;
        hrefs.length = 0;
      }
    }
    function preloadLateStyle(stylesheet) {
      if (stylesheet.state === PENDING$1) {
        stylesheet.state = PRELOADED;
        var props = stylesheet.props;
        pushLinkImpl(stylesheetFlushingQueue, {
          rel: "preload",
          as: "style",
          href: stylesheet.props.href,
          crossOrigin: props.crossOrigin,
          fetchPriority: props.fetchPriority,
          integrity: props.integrity,
          media: props.media,
          hrefLang: props.hrefLang,
          referrerPolicy: props.referrerPolicy
        });
        for (stylesheet = 0; stylesheet < stylesheetFlushingQueue.length; stylesheet++)
          this.push(stylesheetFlushingQueue[stylesheet]);
        stylesheetFlushingQueue.length = 0;
      }
    }
    function preloadLateStyles(styleQueue) {
      styleQueue.sheets.forEach(preloadLateStyle, this);
      styleQueue.sheets.clear();
    }
    function pushCompletedShellIdAttribute(target, resumableState) {
      (resumableState.instructions & SentCompletedShellId) === NothingSent && (resumableState.instructions |= SentCompletedShellId, target.push(
        completedShellIdAttributeStart,
        escapeTextForBrowser("_" + resumableState.idPrefix + "R_"),
        attributeEnd
      ));
    }
    function writeStyleResourceDependenciesInJS(destination, hoistableState) {
      destination.push(arrayFirstOpenBracket);
      var nextArrayOpenBrackChunk = arrayFirstOpenBracket;
      hoistableState.stylesheets.forEach(function(resource) {
        if (resource.state !== PREAMBLE)
          if (resource.state === LATE)
            destination.push(nextArrayOpenBrackChunk), resource = resource.props.href, checkAttributeStringCoercion(resource, "href"), resource = escapeJSObjectForInstructionScripts("" + resource), destination.push(resource), destination.push(arrayCloseBracket), nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
          else {
            destination.push(nextArrayOpenBrackChunk);
            var precedence = resource.props["data-precedence"], props = resource.props, coercedHref = sanitizeURL("" + resource.props.href);
            coercedHref = escapeJSObjectForInstructionScripts(coercedHref);
            destination.push(coercedHref);
            checkAttributeStringCoercion(precedence, "precedence");
            precedence = "" + precedence;
            destination.push(arrayInterstitial);
            precedence = escapeJSObjectForInstructionScripts(precedence);
            destination.push(precedence);
            for (var propKey in props)
              if (hasOwnProperty2.call(props, propKey) && (precedence = props[propKey], null != precedence))
                switch (propKey) {
                  case "href":
                  case "rel":
                  case "precedence":
                  case "data-precedence":
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  default:
                    writeStyleResourceAttributeInJS(
                      destination,
                      propKey,
                      precedence
                    );
                }
            destination.push(arrayCloseBracket);
            nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
            resource.state = LATE;
          }
      });
      destination.push(arrayCloseBracket);
    }
    function writeStyleResourceAttributeInJS(destination, name2, value) {
      var attributeName = name2.toLowerCase();
      switch (typeof value) {
        case "function":
        case "symbol":
          return;
      }
      switch (name2) {
        case "innerHTML":
        case "dangerouslySetInnerHTML":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "style":
        case "ref":
          return;
        case "className":
          attributeName = "class";
          checkAttributeStringCoercion(value, attributeName);
          name2 = "" + value;
          break;
        case "hidden":
          if (false === value) return;
          name2 = "";
          break;
        case "src":
        case "href":
          value = sanitizeURL(value);
          checkAttributeStringCoercion(value, attributeName);
          name2 = "" + value;
          break;
        default:
          if (2 < name2.length && ("o" === name2[0] || "O" === name2[0]) && ("n" === name2[1] || "N" === name2[1]) || !isAttributeNameSafe(name2))
            return;
          checkAttributeStringCoercion(value, attributeName);
          name2 = "" + value;
      }
      destination.push(arrayInterstitial);
      attributeName = escapeJSObjectForInstructionScripts(attributeName);
      destination.push(attributeName);
      destination.push(arrayInterstitial);
      attributeName = escapeJSObjectForInstructionScripts(name2);
      destination.push(attributeName);
    }
    function createHoistableState() {
      return { styles: /* @__PURE__ */ new Set(), stylesheets: /* @__PURE__ */ new Set(), suspenseyImages: false };
    }
    function preloadBootstrapScriptOrModule(resumableState, renderState, href, props) {
      (resumableState.scriptResources.hasOwnProperty(href) || resumableState.moduleScriptResources.hasOwnProperty(href)) && console.error(
        'Internal React Error: React expected bootstrap script or module with src "%s" to not have been preloaded already. please file an issue',
        href
      );
      resumableState.scriptResources[href] = EXISTS;
      resumableState.moduleScriptResources[href] = EXISTS;
      resumableState = [];
      pushLinkImpl(resumableState, props);
      renderState.bootstrapScripts.add(resumableState);
    }
    function adoptPreloadCredentials(target, preloadState) {
      null == target.crossOrigin && (target.crossOrigin = preloadState[0]);
      null == target.integrity && (target.integrity = preloadState[1]);
    }
    function getPreloadAsHeader(href, as, params) {
      href = escapeHrefForLinkHeaderURLContext(href);
      as = escapeStringForLinkHeaderQuotedParamValueContext(as, "as");
      as = "<" + href + '>; rel=preload; as="' + as + '"';
      for (var paramName in params)
        hasOwnProperty2.call(params, paramName) && (href = params[paramName], "string" === typeof href && (as += "; " + paramName.toLowerCase() + '="' + escapeStringForLinkHeaderQuotedParamValueContext(
          href,
          paramName
        ) + '"'));
      return as;
    }
    function escapeHrefForLinkHeaderURLContext(hrefInput) {
      checkAttributeStringCoercion(hrefInput, "href");
      return ("" + hrefInput).replace(
        regexForHrefInLinkHeaderURLContext,
        escapeHrefForLinkHeaderURLContextReplacer
      );
    }
    function escapeHrefForLinkHeaderURLContextReplacer(match) {
      switch (match) {
        case "<":
          return "%3C";
        case ">":
          return "%3E";
        case "\n":
          return "%0A";
        case "\r":
          return "%0D";
        default:
          throw Error(
            "escapeLinkHrefForHeaderContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
          );
      }
    }
    function escapeStringForLinkHeaderQuotedParamValueContext(value, name2) {
      willCoercionThrow(value) && (console.error(
        "The provided `%s` option is an unsupported type %s. This value must be coerced to a string before using it here.",
        name2,
        typeName(value)
      ), testStringCoercion(value));
      return ("" + value).replace(
        regexForLinkHeaderQuotedParamValueContext,
        escapeStringForLinkHeaderQuotedParamValueContextReplacer
      );
    }
    function escapeStringForLinkHeaderQuotedParamValueContextReplacer(match) {
      switch (match) {
        case '"':
          return "%22";
        case "'":
          return "%27";
        case ";":
          return "%3B";
        case ",":
          return "%2C";
        case "\n":
          return "%0A";
        case "\r":
          return "%0D";
        default:
          throw Error(
            "escapeStringForLinkHeaderQuotedParamValueContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
          );
      }
    }
    function hoistStyleQueueDependency(styleQueue) {
      this.styles.add(styleQueue);
    }
    function hoistStylesheetDependency(stylesheet) {
      this.stylesheets.add(stylesheet);
    }
    function hoistHoistables(parentState, childState) {
      childState.styles.forEach(hoistStyleQueueDependency, parentState);
      childState.stylesheets.forEach(hoistStylesheetDependency, parentState);
      childState.suspenseyImages && (parentState.suspenseyImages = true);
    }
    function createRenderState(resumableState, generateStaticMarkup) {
      var idPrefix = resumableState.idPrefix, bootstrapChunks = [], bootstrapScriptContent = resumableState.bootstrapScriptContent, bootstrapScripts = resumableState.bootstrapScripts, bootstrapModules = resumableState.bootstrapModules;
      void 0 !== bootstrapScriptContent && (bootstrapChunks.push("<script"), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
        endOfStartTag,
        escapeEntireInlineScriptContent(bootstrapScriptContent),
        endInlineScript
      ));
      idPrefix = {
        placeholderPrefix: idPrefix + "P:",
        segmentPrefix: idPrefix + "S:",
        boundaryPrefix: idPrefix + "B:",
        startInlineScript: "<script",
        startInlineStyle: "<style",
        preamble: { htmlChunks: null, headChunks: null, bodyChunks: null },
        externalRuntimeScript: null,
        bootstrapChunks,
        importMapChunks: [],
        onHeaders: void 0,
        headers: null,
        resets: {
          font: {},
          dns: {},
          connect: { default: {}, anonymous: {}, credentials: {} },
          image: {},
          style: {}
        },
        charsetChunks: [],
        viewportChunks: [],
        hoistableChunks: [],
        preconnects: /* @__PURE__ */ new Set(),
        fontPreloads: /* @__PURE__ */ new Set(),
        highImagePreloads: /* @__PURE__ */ new Set(),
        styles: /* @__PURE__ */ new Map(),
        bootstrapScripts: /* @__PURE__ */ new Set(),
        scripts: /* @__PURE__ */ new Set(),
        bulkPreloads: /* @__PURE__ */ new Set(),
        preloads: {
          images: /* @__PURE__ */ new Map(),
          stylesheets: /* @__PURE__ */ new Map(),
          scripts: /* @__PURE__ */ new Map(),
          moduleScripts: /* @__PURE__ */ new Map()
        },
        nonce: { script: void 0, style: void 0 },
        hoistableState: null,
        stylesToHoist: false
      };
      if (void 0 !== bootstrapScripts)
        for (bootstrapScriptContent = 0; bootstrapScriptContent < bootstrapScripts.length; bootstrapScriptContent++) {
          var scriptConfig = bootstrapScripts[bootstrapScriptContent], src2, crossOrigin = void 0, integrity = void 0, props = {
            rel: "preload",
            as: "script",
            fetchPriority: "low",
            nonce: void 0
          };
          "string" === typeof scriptConfig ? props.href = src2 = scriptConfig : (props.href = src2 = scriptConfig.src, props.integrity = integrity = "string" === typeof scriptConfig.integrity ? scriptConfig.integrity : void 0, props.crossOrigin = crossOrigin = "string" === typeof scriptConfig || null == scriptConfig.crossOrigin ? void 0 : "use-credentials" === scriptConfig.crossOrigin ? "use-credentials" : "");
          preloadBootstrapScriptOrModule(resumableState, idPrefix, src2, props);
          bootstrapChunks.push(
            '<script src="',
            escapeTextForBrowser(src2),
            attributeEnd
          );
          "string" === typeof integrity && bootstrapChunks.push(
            ' integrity="',
            escapeTextForBrowser(integrity),
            attributeEnd
          );
          "string" === typeof crossOrigin && bootstrapChunks.push(
            ' crossorigin="',
            escapeTextForBrowser(crossOrigin),
            attributeEnd
          );
          pushCompletedShellIdAttribute(bootstrapChunks, resumableState);
          bootstrapChunks.push(' async=""><\/script>');
        }
      if (void 0 !== bootstrapModules)
        for (bootstrapScripts = 0; bootstrapScripts < bootstrapModules.length; bootstrapScripts++)
          bootstrapScriptContent = bootstrapModules[bootstrapScripts], crossOrigin = src2 = void 0, integrity = {
            rel: "modulepreload",
            fetchPriority: "low",
            nonce: void 0
          }, "string" === typeof bootstrapScriptContent ? integrity.href = scriptConfig = bootstrapScriptContent : (integrity.href = scriptConfig = bootstrapScriptContent.src, integrity.integrity = crossOrigin = "string" === typeof bootstrapScriptContent.integrity ? bootstrapScriptContent.integrity : void 0, integrity.crossOrigin = src2 = "string" === typeof bootstrapScriptContent || null == bootstrapScriptContent.crossOrigin ? void 0 : "use-credentials" === bootstrapScriptContent.crossOrigin ? "use-credentials" : ""), preloadBootstrapScriptOrModule(
            resumableState,
            idPrefix,
            scriptConfig,
            integrity
          ), bootstrapChunks.push(
            '<script type="module" src="',
            escapeTextForBrowser(scriptConfig),
            attributeEnd
          ), "string" === typeof crossOrigin && bootstrapChunks.push(
            ' integrity="',
            escapeTextForBrowser(crossOrigin),
            attributeEnd
          ), "string" === typeof src2 && bootstrapChunks.push(
            ' crossorigin="',
            escapeTextForBrowser(src2),
            attributeEnd
          ), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(' async=""><\/script>');
      return {
        placeholderPrefix: idPrefix.placeholderPrefix,
        segmentPrefix: idPrefix.segmentPrefix,
        boundaryPrefix: idPrefix.boundaryPrefix,
        startInlineScript: idPrefix.startInlineScript,
        startInlineStyle: idPrefix.startInlineStyle,
        preamble: idPrefix.preamble,
        externalRuntimeScript: idPrefix.externalRuntimeScript,
        bootstrapChunks: idPrefix.bootstrapChunks,
        importMapChunks: idPrefix.importMapChunks,
        onHeaders: idPrefix.onHeaders,
        headers: idPrefix.headers,
        resets: idPrefix.resets,
        charsetChunks: idPrefix.charsetChunks,
        viewportChunks: idPrefix.viewportChunks,
        hoistableChunks: idPrefix.hoistableChunks,
        preconnects: idPrefix.preconnects,
        fontPreloads: idPrefix.fontPreloads,
        highImagePreloads: idPrefix.highImagePreloads,
        styles: idPrefix.styles,
        bootstrapScripts: idPrefix.bootstrapScripts,
        scripts: idPrefix.scripts,
        bulkPreloads: idPrefix.bulkPreloads,
        preloads: idPrefix.preloads,
        nonce: idPrefix.nonce,
        stylesToHoist: idPrefix.stylesToHoist,
        generateStaticMarkup
      };
    }
    function pushTextInstance(target, text2, renderState, textEmbedded) {
      if (renderState.generateStaticMarkup)
        return target.push(escapeTextForBrowser(text2)), false;
      "" === text2 ? target = textEmbedded : (textEmbedded && target.push("<!-- -->"), target.push(escapeTextForBrowser(text2)), target = true);
      return target;
    }
    function pushSegmentFinale(target, renderState, lastPushedText, textEmbedded) {
      renderState.generateStaticMarkup || lastPushedText && textEmbedded && target.push("<!-- -->");
    }
    function getComponentNameFromType(type2) {
      if (null == type2) return null;
      if ("function" === typeof type2)
        return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
      if ("string" === typeof type2) return type2;
      switch (type2) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
        case REACT_ACTIVITY_TYPE:
          return "Activity";
      }
      if ("object" === typeof type2)
        switch ("number" === typeof type2.tag && console.error(
          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
        ), type2.$$typeof) {
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_CONTEXT_TYPE:
            return type2.displayName || "Context";
          case REACT_CONSUMER_TYPE:
            return (type2._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type2.render;
            type2 = type2.displayName;
            type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
            return type2;
          case REACT_MEMO_TYPE:
            return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type2._payload;
            type2 = type2._init;
            try {
              return getComponentNameFromType(type2(innerType));
            } catch (x2) {
            }
        }
      return null;
    }
    function popToNearestCommonAncestor(prev, next) {
      if (prev !== next) {
        prev.context._currentValue2 = prev.parentValue;
        prev = prev.parent;
        var parentNext = next.parent;
        if (null === prev) {
          if (null !== parentNext)
            throw Error(
              "The stacks must reach the root at the same time. This is a bug in React."
            );
        } else {
          if (null === parentNext)
            throw Error(
              "The stacks must reach the root at the same time. This is a bug in React."
            );
          popToNearestCommonAncestor(prev, parentNext);
        }
        next.context._currentValue2 = next.value;
      }
    }
    function popAllPrevious(prev) {
      prev.context._currentValue2 = prev.parentValue;
      prev = prev.parent;
      null !== prev && popAllPrevious(prev);
    }
    function pushAllNext(next) {
      var parentNext = next.parent;
      null !== parentNext && pushAllNext(parentNext);
      next.context._currentValue2 = next.value;
    }
    function popPreviousToCommonLevel(prev, next) {
      prev.context._currentValue2 = prev.parentValue;
      prev = prev.parent;
      if (null === prev)
        throw Error(
          "The depth must equal at least at zero before reaching the root. This is a bug in React."
        );
      prev.depth === next.depth ? popToNearestCommonAncestor(prev, next) : popPreviousToCommonLevel(prev, next);
    }
    function popNextToCommonLevel(prev, next) {
      var parentNext = next.parent;
      if (null === parentNext)
        throw Error(
          "The depth must equal at least at zero before reaching the root. This is a bug in React."
        );
      prev.depth === parentNext.depth ? popToNearestCommonAncestor(prev, parentNext) : popNextToCommonLevel(prev, parentNext);
      next.context._currentValue2 = next.value;
    }
    function switchContext(newSnapshot) {
      var prev = currentActiveSnapshot;
      prev !== newSnapshot && (null === prev ? pushAllNext(newSnapshot) : null === newSnapshot ? popAllPrevious(prev) : prev.depth === newSnapshot.depth ? popToNearestCommonAncestor(prev, newSnapshot) : prev.depth > newSnapshot.depth ? popPreviousToCommonLevel(prev, newSnapshot) : popNextToCommonLevel(prev, newSnapshot), currentActiveSnapshot = newSnapshot);
    }
    function warnOnInvalidCallback(callback) {
      if (null !== callback && "function" !== typeof callback) {
        var key = String(callback);
        didWarnOnInvalidCallback.has(key) || (didWarnOnInvalidCallback.add(key), console.error(
          "Expected the last optional `callback` argument to be a function. Instead received: %s.",
          callback
        ));
      }
    }
    function warnNoop(publicInstance, callerName) {
      publicInstance = (publicInstance = publicInstance.constructor) && getComponentNameFromType(publicInstance) || "ReactClass";
      var warningKey = publicInstance + "." + callerName;
      didWarnAboutNoopUpdateForComponent[warningKey] || (console.error(
        "Can only update a mounting component. This usually means you called %s() outside componentWillMount() on the server. This is a no-op.\n\nPlease check the code for the %s component.",
        callerName,
        publicInstance
      ), didWarnAboutNoopUpdateForComponent[warningKey] = true);
    }
    function pushTreeContext(baseContext, totalChildren, index2) {
      var baseIdWithLeadingBit = baseContext.id;
      baseContext = baseContext.overflow;
      var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
      baseIdWithLeadingBit &= ~(1 << baseLength);
      index2 += 1;
      var length = 32 - clz32(totalChildren) + baseLength;
      if (30 < length) {
        var numberOfOverflowBits = baseLength - baseLength % 5;
        length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
        baseIdWithLeadingBit >>= numberOfOverflowBits;
        baseLength -= numberOfOverflowBits;
        return {
          id: 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit,
          overflow: length + baseContext
        };
      }
      return {
        id: 1 << length | index2 << baseLength | baseIdWithLeadingBit,
        overflow: baseContext
      };
    }
    function clz32Fallback(x2) {
      x2 >>>= 0;
      return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
    }
    function noop2() {
    }
    function trackUsedThenable(thenableState2, thenable, index2) {
      index2 = thenableState2[index2];
      void 0 === index2 ? thenableState2.push(thenable) : index2 !== thenable && (thenable.then(noop2, noop2), thenable = index2);
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenable.reason;
        default:
          "string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenableState2 = thenable, thenableState2.status = "pending", thenableState2.then(
            function(fulfilledValue) {
              if ("pending" === thenable.status) {
                var fulfilledThenable = thenable;
                fulfilledThenable.status = "fulfilled";
                fulfilledThenable.value = fulfilledValue;
              }
            },
            function(error) {
              if ("pending" === thenable.status) {
                var rejectedThenable = thenable;
                rejectedThenable.status = "rejected";
                rejectedThenable.reason = error;
              }
            }
          ));
          switch (thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenable.reason;
          }
          suspendedThenable = thenable;
          throw SuspenseException;
      }
    }
    function getSuspendedThenable() {
      if (null === suspendedThenable)
        throw Error(
          "Expected a suspended thenable. This is a bug in React. Please file an issue."
        );
      var thenable = suspendedThenable;
      suspendedThenable = null;
      return thenable;
    }
    function is(x2, y2) {
      return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
    }
    function resolveCurrentlyRenderingComponent() {
      if (null === currentlyRenderingComponent)
        throw Error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
      isInHookUserCodeInDev && console.error(
        "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks"
      );
      return currentlyRenderingComponent;
    }
    function createHook() {
      if (0 < numberOfReRenders)
        throw Error("Rendered more hooks than during the previous render");
      return { memoizedState: null, queue: null, next: null };
    }
    function createWorkInProgressHook() {
      null === workInProgressHook ? null === firstWorkInProgressHook ? (isReRender = false, firstWorkInProgressHook = workInProgressHook = createHook()) : (isReRender = true, workInProgressHook = firstWorkInProgressHook) : null === workInProgressHook.next ? (isReRender = false, workInProgressHook = workInProgressHook.next = createHook()) : (isReRender = true, workInProgressHook = workInProgressHook.next);
      return workInProgressHook;
    }
    function getThenableStateAfterSuspending() {
      var state = thenableState;
      thenableState = null;
      return state;
    }
    function resetHooksState() {
      isInHookUserCodeInDev = false;
      currentlyRenderingKeyPath = currentlyRenderingRequest = currentlyRenderingTask = currentlyRenderingComponent = null;
      didScheduleRenderPhaseUpdate = false;
      firstWorkInProgressHook = null;
      numberOfReRenders = 0;
      workInProgressHook = renderPhaseUpdates = null;
    }
    function readContext(context) {
      isInHookUserCodeInDev && console.error(
        "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
      );
      return context._currentValue2;
    }
    function basicStateReducer(state, action) {
      return "function" === typeof action ? action(state) : action;
    }
    function useReducer(reducer2, initialArg, init2) {
      reducer2 !== basicStateReducer && (currentHookNameInDev = "useReducer");
      currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
      workInProgressHook = createWorkInProgressHook();
      if (isReRender) {
        init2 = workInProgressHook.queue;
        initialArg = init2.dispatch;
        if (null !== renderPhaseUpdates) {
          var firstRenderPhaseUpdate = renderPhaseUpdates.get(init2);
          if (void 0 !== firstRenderPhaseUpdate) {
            renderPhaseUpdates.delete(init2);
            init2 = workInProgressHook.memoizedState;
            do {
              var action = firstRenderPhaseUpdate.action;
              isInHookUserCodeInDev = true;
              init2 = reducer2(init2, action);
              isInHookUserCodeInDev = false;
              firstRenderPhaseUpdate = firstRenderPhaseUpdate.next;
            } while (null !== firstRenderPhaseUpdate);
            workInProgressHook.memoizedState = init2;
            return [init2, initialArg];
          }
        }
        return [workInProgressHook.memoizedState, initialArg];
      }
      isInHookUserCodeInDev = true;
      reducer2 = reducer2 === basicStateReducer ? "function" === typeof initialArg ? initialArg() : initialArg : void 0 !== init2 ? init2(initialArg) : initialArg;
      isInHookUserCodeInDev = false;
      workInProgressHook.memoizedState = reducer2;
      reducer2 = workInProgressHook.queue = { last: null, dispatch: null };
      reducer2 = reducer2.dispatch = dispatchAction.bind(
        null,
        currentlyRenderingComponent,
        reducer2
      );
      return [workInProgressHook.memoizedState, reducer2];
    }
    function useMemo(nextCreate, deps) {
      currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
      workInProgressHook = createWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      if (null !== workInProgressHook) {
        var prevState = workInProgressHook.memoizedState;
        if (null !== prevState && null !== deps) {
          a: {
            var JSCompiler_inline_result = prevState[1];
            if (null === JSCompiler_inline_result)
              console.error(
                "%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",
                currentHookNameInDev
              ), JSCompiler_inline_result = false;
            else {
              deps.length !== JSCompiler_inline_result.length && console.error(
                "The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",
                currentHookNameInDev,
                "[" + deps.join(", ") + "]",
                "[" + JSCompiler_inline_result.join(", ") + "]"
              );
              for (var i = 0; i < JSCompiler_inline_result.length && i < deps.length; i++)
                if (!objectIs(deps[i], JSCompiler_inline_result[i])) {
                  JSCompiler_inline_result = false;
                  break a;
                }
              JSCompiler_inline_result = true;
            }
          }
          if (JSCompiler_inline_result) return prevState[0];
        }
      }
      isInHookUserCodeInDev = true;
      nextCreate = nextCreate();
      isInHookUserCodeInDev = false;
      workInProgressHook.memoizedState = [nextCreate, deps];
      return nextCreate;
    }
    function dispatchAction(componentIdentity, queue, action) {
      if (25 <= numberOfReRenders)
        throw Error(
          "Too many re-renders. React limits the number of renders to prevent an infinite loop."
        );
      if (componentIdentity === currentlyRenderingComponent)
        if (didScheduleRenderPhaseUpdate = true, componentIdentity = { action, next: null }, null === renderPhaseUpdates && (renderPhaseUpdates = /* @__PURE__ */ new Map()), action = renderPhaseUpdates.get(queue), void 0 === action)
          renderPhaseUpdates.set(queue, componentIdentity);
        else {
          for (queue = action; null !== queue.next; ) queue = queue.next;
          queue.next = componentIdentity;
        }
    }
    function throwOnUseEffectEventCall() {
      throw Error(
        "A function wrapped in useEffectEvent can't be called during rendering."
      );
    }
    function unsupportedStartTransition() {
      throw Error("startTransition cannot be called during server rendering.");
    }
    function unsupportedSetOptimisticState() {
      throw Error("Cannot update optimistic state while rendering.");
    }
    function useActionState(action, initialState2, permalink) {
      resolveCurrentlyRenderingComponent();
      var actionStateHookIndex = actionStateCounter++, request = currentlyRenderingRequest;
      if ("function" === typeof action.$$FORM_ACTION) {
        var nextPostbackStateKey = null, componentKeyPath = currentlyRenderingKeyPath;
        request = request.formState;
        var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL;
        if (null !== request && "function" === typeof isSignatureEqual) {
          var postbackKey = request[1];
          isSignatureEqual.call(action, request[2], request[3]) && (nextPostbackStateKey = void 0 !== permalink ? "p" + permalink : "k" + murmurhash3_32_gc(
            JSON.stringify([
              componentKeyPath,
              null,
              actionStateHookIndex
            ]),
            0
          ), postbackKey === nextPostbackStateKey && (actionStateMatchingIndex = actionStateHookIndex, initialState2 = request[0]));
        }
        var boundAction = action.bind(null, initialState2);
        action = function(payload) {
          boundAction(payload);
        };
        "function" === typeof boundAction.$$FORM_ACTION && (action.$$FORM_ACTION = function(prefix2) {
          prefix2 = boundAction.$$FORM_ACTION(prefix2);
          void 0 !== permalink && (checkAttributeStringCoercion(permalink, "target"), permalink += "", prefix2.action = permalink);
          var formData = prefix2.data;
          formData && (null === nextPostbackStateKey && (nextPostbackStateKey = void 0 !== permalink ? "p" + permalink : "k" + murmurhash3_32_gc(
            JSON.stringify([
              componentKeyPath,
              null,
              actionStateHookIndex
            ]),
            0
          )), formData.append("$ACTION_KEY", nextPostbackStateKey));
          return prefix2;
        });
        return [initialState2, action, false];
      }
      var _boundAction = action.bind(null, initialState2);
      return [
        initialState2,
        function(payload) {
          _boundAction(payload);
        },
        false
      ];
    }
    function unwrapThenable(thenable) {
      var index2 = thenableIndexCounter;
      thenableIndexCounter += 1;
      null === thenableState && (thenableState = []);
      return trackUsedThenable(thenableState, thenable, index2);
    }
    function unsupportedRefresh() {
      throw Error("Cache cannot be refreshed during server rendering.");
    }
    function disabledLog() {
    }
    function disableLogs() {
      if (0 === disabledDepth) {
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd;
        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        };
        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
      }
      disabledDepth++;
    }
    function reenableLogs() {
      disabledDepth--;
      if (0 === disabledDepth) {
        var props = { configurable: true, enumerable: true, writable: true };
        Object.defineProperties(console, {
          log: assign({}, props, { value: prevLog }),
          info: assign({}, props, { value: prevInfo }),
          warn: assign({}, props, { value: prevWarn }),
          error: assign({}, props, { value: prevError }),
          group: assign({}, props, { value: prevGroup }),
          groupCollapsed: assign({}, props, { value: prevGroupCollapsed }),
          groupEnd: assign({}, props, { value: prevGroupEnd })
        });
      }
      0 > disabledDepth && console.error(
        "disabledDepth fell below zero. This is a bug in React. Please file an issue."
      );
    }
    function formatOwnerStack(error) {
      var prevPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      error = error.stack;
      Error.prepareStackTrace = prevPrepareStackTrace;
      error.startsWith("Error: react-stack-top-frame\n") && (error = error.slice(29));
      prevPrepareStackTrace = error.indexOf("\n");
      -1 !== prevPrepareStackTrace && (error = error.slice(prevPrepareStackTrace + 1));
      prevPrepareStackTrace = error.indexOf("react_stack_bottom_frame");
      -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error.lastIndexOf(
        "\n",
        prevPrepareStackTrace
      ));
      if (-1 !== prevPrepareStackTrace)
        error = error.slice(0, prevPrepareStackTrace);
      else return "";
      return error;
    }
    function describeBuiltInComponentFrame(name2) {
      if (void 0 === prefix)
        try {
          throw Error();
        } catch (x2) {
          var match = x2.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || "";
          suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
        }
      return "\n" + prefix + name2 + suffix;
    }
    function describeNativeComponentFrame(fn, construct) {
      if (!fn || reentry) return "";
      var frame = componentFrameCache.get(fn);
      if (void 0 !== frame) return frame;
      reentry = true;
      frame = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      var previousDispatcher2 = null;
      previousDispatcher2 = ReactSharedInternals.H;
      ReactSharedInternals.H = null;
      disableLogs();
      try {
        var RunInRootFrame = {
          DetermineComponentFrameRoot: function() {
            try {
              if (construct) {
                var Fake = function() {
                  throw Error();
                };
                Object.defineProperty(Fake.prototype, "props", {
                  set: function() {
                    throw Error();
                  }
                });
                if ("object" === typeof Reflect && Reflect.construct) {
                  try {
                    Reflect.construct(Fake, []);
                  } catch (x2) {
                    var control = x2;
                  }
                  Reflect.construct(fn, [], Fake);
                } else {
                  try {
                    Fake.call();
                  } catch (x$0) {
                    control = x$0;
                  }
                  fn.call(Fake.prototype);
                }
              } else {
                try {
                  throw Error();
                } catch (x$1) {
                  control = x$1;
                }
                (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
                });
              }
            } catch (sample) {
              if (sample && control && "string" === typeof sample.stack)
                return [sample.stack, control.stack];
            }
            return [null, null];
          }
        };
        RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
        var namePropDescriptor = Object.getOwnPropertyDescriptor(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name"
        );
        namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name",
          { value: "DetermineComponentFrameRoot" }
        );
        var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
        if (sampleStack && controlStack) {
          var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
          for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes(
            "DetermineComponentFrameRoot"
          ); )
            namePropDescriptor++;
          for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes(
            "DetermineComponentFrameRoot"
          ); )
            _RunInRootFrame$Deter++;
          if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
            for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
              _RunInRootFrame$Deter--;
          for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
            if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
              if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) {
                do
                  if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                    var _frame = "\n" + sampleLines[namePropDescriptor].replace(
                      " at new ",
                      " at "
                    );
                    fn.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn.displayName));
                    "function" === typeof fn && componentFrameCache.set(fn, _frame);
                    return _frame;
                  }
                while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
              }
              break;
            }
        }
      } finally {
        reentry = false, ReactSharedInternals.H = previousDispatcher2, reenableLogs(), Error.prepareStackTrace = frame;
      }
      sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
      "function" === typeof fn && componentFrameCache.set(fn, sampleLines);
      return sampleLines;
    }
    function describeComponentStackByType(type2) {
      if ("string" === typeof type2) return describeBuiltInComponentFrame(type2);
      if ("function" === typeof type2)
        return type2.prototype && type2.prototype.isReactComponent ? describeNativeComponentFrame(type2, true) : describeNativeComponentFrame(type2, false);
      if ("object" === typeof type2 && null !== type2) {
        switch (type2.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            return describeNativeComponentFrame(type2.render, false);
          case REACT_MEMO_TYPE:
            return describeNativeComponentFrame(type2.type, false);
          case REACT_LAZY_TYPE:
            var lazyComponent = type2, payload = lazyComponent._payload;
            lazyComponent = lazyComponent._init;
            try {
              type2 = lazyComponent(payload);
            } catch (x2) {
              return describeBuiltInComponentFrame("Lazy");
            }
            return describeComponentStackByType(type2);
        }
        if ("string" === typeof type2.name) {
          a: {
            payload = type2.name;
            lazyComponent = type2.env;
            type2 = type2.debugLocation;
            if (null != type2) {
              type2 = formatOwnerStack(type2);
              var idx = type2.lastIndexOf("\n");
              type2 = -1 === idx ? type2 : type2.slice(idx + 1);
              if (-1 !== type2.indexOf(payload)) {
                payload = "\n" + type2;
                break a;
              }
            }
            payload = describeBuiltInComponentFrame(
              payload + (lazyComponent ? " [" + lazyComponent + "]" : "")
            );
          }
          return payload;
        }
      }
      switch (type2) {
        case REACT_SUSPENSE_LIST_TYPE:
          return describeBuiltInComponentFrame("SuspenseList");
        case REACT_SUSPENSE_TYPE:
          return describeBuiltInComponentFrame("Suspense");
      }
      return "";
    }
    function isEligibleForOutlining(request, boundary) {
      return (500 < boundary.byteSize || false) && null === boundary.contentPreamble;
    }
    function defaultErrorHandler(error) {
      if ("object" === typeof error && null !== error && "string" === typeof error.environmentName) {
        var JSCompiler_inline_result = error.environmentName;
        error = [error].slice(0);
        "string" === typeof error[0] ? error.splice(
          0,
          1,
          "[%s] " + error[0],
          " " + JSCompiler_inline_result + " "
        ) : error.splice(0, 0, "[%s]", " " + JSCompiler_inline_result + " ");
        error.unshift(console);
        JSCompiler_inline_result = bind2.apply(console.error, error);
        JSCompiler_inline_result();
      } else console.error(error);
      return null;
    }
    function RequestInstance(resumableState, renderState, rootFormatContext, progressiveChunkSize, onError2, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
      var abortSet = /* @__PURE__ */ new Set();
      this.destination = null;
      this.flushScheduled = false;
      this.resumableState = resumableState;
      this.renderState = renderState;
      this.rootFormatContext = rootFormatContext;
      this.progressiveChunkSize = void 0 === progressiveChunkSize ? 12800 : progressiveChunkSize;
      this.status = 10;
      this.fatalError = null;
      this.pendingRootTasks = this.allPendingTasks = this.nextSegmentId = 0;
      this.completedPreambleSegments = this.completedRootSegment = null;
      this.byteSize = 0;
      this.abortableTasks = abortSet;
      this.pingedTasks = [];
      this.clientRenderedBoundaries = [];
      this.completedBoundaries = [];
      this.partialBoundaries = [];
      this.trackedPostpones = null;
      this.onError = void 0 === onError2 ? defaultErrorHandler : onError2;
      this.onPostpone = void 0 === onPostpone ? noop2 : onPostpone;
      this.onAllReady = void 0 === onAllReady ? noop2 : onAllReady;
      this.onShellReady = void 0 === onShellReady ? noop2 : onShellReady;
      this.onShellError = void 0 === onShellError ? noop2 : onShellError;
      this.onFatalError = void 0 === onFatalError ? noop2 : onFatalError;
      this.formState = void 0 === formState ? null : formState;
      this.didWarnForKey = null;
    }
    function createRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError2, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
      var now = getCurrentTime();
      1e3 < now - lastResetTime && (ReactSharedInternals.recentlyCreatedOwnerStacks = 0, lastResetTime = now);
      resumableState = new RequestInstance(
        resumableState,
        renderState,
        rootFormatContext,
        progressiveChunkSize,
        onError2,
        onAllReady,
        onShellReady,
        onShellError,
        onFatalError,
        onPostpone,
        formState
      );
      renderState = createPendingSegment(
        resumableState,
        0,
        null,
        rootFormatContext,
        false,
        false
      );
      renderState.parentFlushed = true;
      children = createRenderTask(
        resumableState,
        null,
        children,
        -1,
        null,
        renderState,
        null,
        null,
        resumableState.abortableTasks,
        null,
        rootFormatContext,
        null,
        emptyTreeContext,
        null,
        null,
        emptyContextObject,
        null
      );
      pushComponentStack(children);
      resumableState.pingedTasks.push(children);
      return resumableState;
    }
    function pingTask(request, task) {
      request.pingedTasks.push(task);
      1 === request.pingedTasks.length && (request.flushScheduled = null !== request.destination, performWork(request));
    }
    function createSuspenseBoundary(request, row, fallbackAbortableTasks, contentPreamble, fallbackPreamble) {
      fallbackAbortableTasks = {
        status: PENDING,
        rootSegmentID: -1,
        parentFlushed: false,
        pendingTasks: 0,
        row,
        completedSegments: [],
        byteSize: 0,
        fallbackAbortableTasks,
        errorDigest: null,
        contentState: createHoistableState(),
        fallbackState: createHoistableState(),
        contentPreamble,
        fallbackPreamble,
        trackedContentKeyPath: null,
        trackedFallbackNode: null,
        errorMessage: null,
        errorStack: null,
        errorComponentStack: null
      };
      null !== row && (row.pendingTasks++, contentPreamble = row.boundaries, null !== contentPreamble && (request.allPendingTasks++, fallbackAbortableTasks.pendingTasks++, contentPreamble.push(fallbackAbortableTasks)), request = row.inheritedHoistables, null !== request && hoistHoistables(fallbackAbortableTasks.contentState, request));
      return fallbackAbortableTasks;
    }
    function createRenderTask(request, thenableState2, node2, childIndex, blockedBoundary, blockedSegment, blockedPreamble, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack, legacyContext, debugTask) {
      request.allPendingTasks++;
      null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
      null !== row && row.pendingTasks++;
      var task = {
        replay: null,
        node: node2,
        childIndex,
        ping: function() {
          return pingTask(request, task);
        },
        blockedBoundary,
        blockedSegment,
        blockedPreamble,
        hoistableState,
        abortSet,
        keyPath,
        formatContext,
        context,
        treeContext,
        row,
        componentStack,
        thenableState: thenableState2
      };
      task.debugTask = debugTask;
      abortSet.add(task);
      return task;
    }
    function createReplayTask(request, thenableState2, replay, node2, childIndex, blockedBoundary, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack, legacyContext, debugTask) {
      request.allPendingTasks++;
      null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
      null !== row && row.pendingTasks++;
      replay.pendingTasks++;
      var task = {
        replay,
        node: node2,
        childIndex,
        ping: function() {
          return pingTask(request, task);
        },
        blockedBoundary,
        blockedSegment: null,
        blockedPreamble: null,
        hoistableState,
        abortSet,
        keyPath,
        formatContext,
        context,
        treeContext,
        row,
        componentStack,
        thenableState: thenableState2
      };
      task.debugTask = debugTask;
      abortSet.add(task);
      return task;
    }
    function createPendingSegment(request, index2, boundary, parentFormatContext, lastPushedText, textEmbedded) {
      return {
        status: PENDING,
        parentFlushed: false,
        id: -1,
        index: index2,
        chunks: [],
        children: [],
        preambleChildren: [],
        parentFormatContext,
        boundary,
        lastPushedText,
        textEmbedded
      };
    }
    function getCurrentStackInDEV() {
      if (null === currentTaskInDEV || null === currentTaskInDEV.componentStack)
        return "";
      var componentStack = currentTaskInDEV.componentStack;
      try {
        var info = "";
        if ("string" === typeof componentStack.type)
          info += describeBuiltInComponentFrame(componentStack.type);
        else if ("function" === typeof componentStack.type) {
          if (!componentStack.owner) {
            var JSCompiler_temp_const = info, fn = componentStack.type, name2 = fn ? fn.displayName || fn.name : "";
            var JSCompiler_inline_result = name2 ? describeBuiltInComponentFrame(name2) : "";
            info = JSCompiler_temp_const + JSCompiler_inline_result;
          }
        } else
          componentStack.owner || (info += describeComponentStackByType(componentStack.type));
        for (; componentStack; )
          JSCompiler_temp_const = null, null != componentStack.debugStack ? JSCompiler_temp_const = formatOwnerStack(
            componentStack.debugStack
          ) : (JSCompiler_inline_result = componentStack, null != JSCompiler_inline_result.stack && (JSCompiler_temp_const = "string" !== typeof JSCompiler_inline_result.stack ? JSCompiler_inline_result.stack = formatOwnerStack(
            JSCompiler_inline_result.stack
          ) : JSCompiler_inline_result.stack)), (componentStack = componentStack.owner) && JSCompiler_temp_const && (info += "\n" + JSCompiler_temp_const);
        var JSCompiler_inline_result$jscomp$0 = info;
      } catch (x2) {
        JSCompiler_inline_result$jscomp$0 = "\nError generating stack: " + x2.message + "\n" + x2.stack;
      }
      return JSCompiler_inline_result$jscomp$0;
    }
    function pushHaltedAwaitOnComponentStack(task, debugInfo) {
      if (null != debugInfo)
        for (var i = debugInfo.length - 1; 0 <= i; i--) {
          var info = debugInfo[i];
          if ("string" === typeof info.name) break;
          if ("number" === typeof info.time) break;
          if (null != info.awaited) {
            var bestStack = null == info.debugStack ? info.awaited : info;
            if (void 0 !== bestStack.debugStack) {
              task.componentStack = {
                parent: task.componentStack,
                type: info,
                owner: bestStack.owner,
                stack: bestStack.debugStack
              };
              task.debugTask = bestStack.debugTask;
              break;
            }
          }
        }
    }
    function pushServerComponentStack(task, debugInfo) {
      if (null != debugInfo)
        for (var i = 0; i < debugInfo.length; i++) {
          var componentInfo = debugInfo[i];
          "string" === typeof componentInfo.name && void 0 !== componentInfo.debugStack && (task.componentStack = {
            parent: task.componentStack,
            type: componentInfo,
            owner: componentInfo.owner,
            stack: componentInfo.debugStack
          }, task.debugTask = componentInfo.debugTask);
        }
    }
    function pushComponentStack(task) {
      var node2 = task.node;
      if ("object" === typeof node2 && null !== node2)
        switch (node2.$$typeof) {
          case REACT_ELEMENT_TYPE:
            var type2 = node2.type, owner = node2._owner, stack = node2._debugStack;
            pushServerComponentStack(task, node2._debugInfo);
            task.debugTask = node2._debugTask;
            task.componentStack = {
              parent: task.componentStack,
              type: type2,
              owner,
              stack
            };
            break;
          case REACT_LAZY_TYPE:
            pushServerComponentStack(task, node2._debugInfo);
            break;
          default:
            "function" === typeof node2.then && pushServerComponentStack(task, node2._debugInfo);
        }
    }
    function replaceSuspenseComponentStackWithSuspenseFallbackStack(componentStack) {
      return null === componentStack ? null : {
        parent: componentStack.parent,
        type: "Suspense Fallback",
        owner: componentStack.owner,
        stack: componentStack.stack
      };
    }
    function getThrownInfo(node$jscomp$0) {
      var errorInfo = {};
      node$jscomp$0 && Object.defineProperty(errorInfo, "componentStack", {
        configurable: true,
        enumerable: true,
        get: function() {
          try {
            var info = "", node2 = node$jscomp$0;
            do
              info += describeComponentStackByType(node2.type), node2 = node2.parent;
            while (node2);
            var stack = info;
          } catch (x2) {
            stack = "\nError generating stack: " + x2.message + "\n" + x2.stack;
          }
          Object.defineProperty(errorInfo, "componentStack", {
            value: stack
          });
          return stack;
        }
      });
      return errorInfo;
    }
    function encodeErrorForBoundary(boundary, digest, error, thrownInfo, wasAborted) {
      boundary.errorDigest = digest;
      error instanceof Error ? (digest = String(error.message), error = String(error.stack)) : (digest = "object" === typeof error && null !== error ? describeObjectForErrorMessage(error) : String(error), error = null);
      wasAborted = wasAborted ? "Switched to client rendering because the server rendering aborted due to:\n\n" : "Switched to client rendering because the server rendering errored:\n\n";
      boundary.errorMessage = wasAborted + digest;
      boundary.errorStack = null !== error ? wasAborted + error : null;
      boundary.errorComponentStack = thrownInfo.componentStack;
    }
    function logRecoverableError(request, error, errorInfo, debugTask) {
      request = request.onError;
      error = debugTask ? debugTask.run(request.bind(null, error, errorInfo)) : request(error, errorInfo);
      if (null != error && "string" !== typeof error)
        console.error(
          'onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "%s" instead',
          typeof error
        );
      else return error;
    }
    function fatalError(request, error, errorInfo, debugTask) {
      errorInfo = request.onShellError;
      var onFatalError = request.onFatalError;
      debugTask ? (debugTask.run(errorInfo.bind(null, error)), debugTask.run(onFatalError.bind(null, error))) : (errorInfo(error), onFatalError(error));
      null !== request.destination ? (request.status = CLOSED, request.destination.destroy(error)) : (request.status = 13, request.fatalError = error);
    }
    function finishSuspenseListRow(request, row) {
      unblockSuspenseListRow(request, row.next, row.hoistables);
    }
    function unblockSuspenseListRow(request, unblockedRow, inheritedHoistables) {
      for (; null !== unblockedRow; ) {
        null !== inheritedHoistables && (hoistHoistables(unblockedRow.hoistables, inheritedHoistables), unblockedRow.inheritedHoistables = inheritedHoistables);
        var unblockedBoundaries = unblockedRow.boundaries;
        if (null !== unblockedBoundaries) {
          unblockedRow.boundaries = null;
          for (var i = 0; i < unblockedBoundaries.length; i++) {
            var unblockedBoundary = unblockedBoundaries[i];
            null !== inheritedHoistables && hoistHoistables(
              unblockedBoundary.contentState,
              inheritedHoistables
            );
            finishedTask(request, unblockedBoundary, null, null);
          }
        }
        unblockedRow.pendingTasks--;
        if (0 < unblockedRow.pendingTasks) break;
        inheritedHoistables = unblockedRow.hoistables;
        unblockedRow = unblockedRow.next;
      }
    }
    function tryToResolveTogetherRow(request, togetherRow) {
      var boundaries = togetherRow.boundaries;
      if (null !== boundaries && togetherRow.pendingTasks === boundaries.length) {
        for (var allCompleteAndInlinable = true, i = 0; i < boundaries.length; i++) {
          var rowBoundary = boundaries[i];
          if (1 !== rowBoundary.pendingTasks || rowBoundary.parentFlushed || isEligibleForOutlining(request, rowBoundary)) {
            allCompleteAndInlinable = false;
            break;
          }
        }
        allCompleteAndInlinable && unblockSuspenseListRow(request, togetherRow, togetherRow.hoistables);
      }
    }
    function createSuspenseListRow(previousRow) {
      var newRow = {
        pendingTasks: 1,
        boundaries: null,
        hoistables: createHoistableState(),
        inheritedHoistables: null,
        together: false,
        next: null
      };
      null !== previousRow && 0 < previousRow.pendingTasks && (newRow.pendingTasks++, newRow.boundaries = [], previousRow.next = newRow);
      return newRow;
    }
    function renderSuspenseListRows(request, task, keyPath, rows, revealOrder) {
      var prevKeyPath = task.keyPath, prevTreeContext = task.treeContext, prevRow = task.row, previousComponentStack = task.componentStack;
      var previousDebugTask = task.debugTask;
      pushServerComponentStack(task, task.node.props.children._debugInfo);
      task.keyPath = keyPath;
      keyPath = rows.length;
      var previousSuspenseListRow = null;
      if (null !== task.replay) {
        var resumeSlots = task.replay.slots;
        if (null !== resumeSlots && "object" === typeof resumeSlots)
          for (var n = 0; n < keyPath; n++) {
            var i = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? n : keyPath - 1 - n, node2 = rows[i];
            task.row = previousSuspenseListRow = createSuspenseListRow(
              previousSuspenseListRow
            );
            task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
            var resumeSegmentID = resumeSlots[i];
            "number" === typeof resumeSegmentID ? (resumeNode(request, task, resumeSegmentID, node2, i), delete resumeSlots[i]) : renderNode(request, task, node2, i);
            0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
          }
        else
          for (resumeSlots = 0; resumeSlots < keyPath; resumeSlots++)
            n = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? resumeSlots : keyPath - 1 - resumeSlots, i = rows[n], warnForMissingKey(request, task, i), task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(prevTreeContext, keyPath, n), renderNode(request, task, i, n), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
      } else if ("backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder)
        for (revealOrder = 0; revealOrder < keyPath; revealOrder++)
          resumeSlots = rows[revealOrder], warnForMissingKey(request, task, resumeSlots), task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(
            prevTreeContext,
            keyPath,
            revealOrder
          ), renderNode(request, task, resumeSlots, revealOrder), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
      else {
        revealOrder = task.blockedSegment;
        resumeSlots = revealOrder.children.length;
        n = revealOrder.chunks.length;
        for (i = keyPath - 1; 0 <= i; i--) {
          node2 = rows[i];
          task.row = previousSuspenseListRow = createSuspenseListRow(
            previousSuspenseListRow
          );
          task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
          resumeSegmentID = createPendingSegment(
            request,
            n,
            null,
            task.formatContext,
            0 === i ? revealOrder.lastPushedText : true,
            true
          );
          revealOrder.children.splice(resumeSlots, 0, resumeSegmentID);
          task.blockedSegment = resumeSegmentID;
          warnForMissingKey(request, task, node2);
          try {
            renderNode(request, task, node2, i), pushSegmentFinale(
              resumeSegmentID.chunks,
              request.renderState,
              resumeSegmentID.lastPushedText,
              resumeSegmentID.textEmbedded
            ), resumeSegmentID.status = COMPLETED, 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
          } catch (thrownValue) {
            throw resumeSegmentID.status = 12 === request.status ? ABORTED : ERRORED, thrownValue;
          }
        }
        task.blockedSegment = revealOrder;
        revealOrder.lastPushedText = false;
      }
      null !== prevRow && null !== previousSuspenseListRow && 0 < previousSuspenseListRow.pendingTasks && (prevRow.pendingTasks++, previousSuspenseListRow.next = prevRow);
      task.treeContext = prevTreeContext;
      task.row = prevRow;
      task.keyPath = prevKeyPath;
      task.componentStack = previousComponentStack;
      task.debugTask = previousDebugTask;
    }
    function renderWithHooks(request, task, keyPath, Component, props, secondArg) {
      var prevThenableState = task.thenableState;
      task.thenableState = null;
      currentlyRenderingComponent = {};
      currentlyRenderingTask = task;
      currentlyRenderingRequest = request;
      currentlyRenderingKeyPath = keyPath;
      isInHookUserCodeInDev = false;
      actionStateCounter = localIdCounter = 0;
      actionStateMatchingIndex = -1;
      thenableIndexCounter = 0;
      thenableState = prevThenableState;
      for (request = callComponentInDEV(Component, props, secondArg); didScheduleRenderPhaseUpdate; )
        didScheduleRenderPhaseUpdate = false, actionStateCounter = localIdCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, numberOfReRenders += 1, workInProgressHook = null, request = Component(props, secondArg);
      resetHooksState();
      return request;
    }
    function finishFunctionComponent(request, task, keyPath, children, hasId, actionStateCount, actionStateMatchingIndex2) {
      var didEmitActionStateMarkers = false;
      if (0 !== actionStateCount && null !== request.formState) {
        var segment = task.blockedSegment;
        if (null !== segment) {
          didEmitActionStateMarkers = true;
          segment = segment.chunks;
          for (var i = 0; i < actionStateCount; i++)
            i === actionStateMatchingIndex2 ? segment.push("<!--F!-->") : segment.push("<!--F-->");
        }
      }
      actionStateCount = task.keyPath;
      task.keyPath = keyPath;
      hasId ? (keyPath = task.treeContext, task.treeContext = pushTreeContext(keyPath, 1, 0), renderNode(request, task, children, -1), task.treeContext = keyPath) : didEmitActionStateMarkers ? renderNode(request, task, children, -1) : renderNodeDestructive(request, task, children, -1);
      task.keyPath = actionStateCount;
    }
    function renderElement(request, task, keyPath, type2, props, ref2) {
      if ("function" === typeof type2)
        if (type2.prototype && type2.prototype.isReactComponent) {
          var newProps = props;
          if ("ref" in props) {
            newProps = {};
            for (var propName in props)
              "ref" !== propName && (newProps[propName] = props[propName]);
          }
          var defaultProps = type2.defaultProps;
          if (defaultProps) {
            newProps === props && (newProps = assign({}, newProps, props));
            for (var _propName in defaultProps)
              void 0 === newProps[_propName] && (newProps[_propName] = defaultProps[_propName]);
          }
          var resolvedProps = newProps;
          var context = emptyContextObject, contextType = type2.contextType;
          if ("contextType" in type2 && null !== contextType && (void 0 === contextType || contextType.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(type2)) {
            didWarnAboutInvalidateContextType.add(type2);
            var addendum = void 0 === contextType ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : "object" !== typeof contextType ? " However, it is set to a " + typeof contextType + "." : contextType.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}.";
            console.error(
              "%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",
              getComponentNameFromType(type2) || "Component",
              addendum
            );
          }
          "object" === typeof contextType && null !== contextType && (context = contextType._currentValue2);
          var instance = new type2(resolvedProps, context);
          if ("function" === typeof type2.getDerivedStateFromProps && (null === instance.state || void 0 === instance.state)) {
            var componentName = getComponentNameFromType(type2) || "Component";
            didWarnAboutUninitializedState.has(componentName) || (didWarnAboutUninitializedState.add(componentName), console.error(
              "`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",
              componentName,
              null === instance.state ? "null" : "undefined",
              componentName
            ));
          }
          if ("function" === typeof type2.getDerivedStateFromProps || "function" === typeof instance.getSnapshotBeforeUpdate) {
            var foundWillMountName = null, foundWillReceivePropsName = null, foundWillUpdateName = null;
            "function" === typeof instance.componentWillMount && true !== instance.componentWillMount.__suppressDeprecationWarning ? foundWillMountName = "componentWillMount" : "function" === typeof instance.UNSAFE_componentWillMount && (foundWillMountName = "UNSAFE_componentWillMount");
            "function" === typeof instance.componentWillReceiveProps && true !== instance.componentWillReceiveProps.__suppressDeprecationWarning ? foundWillReceivePropsName = "componentWillReceiveProps" : "function" === typeof instance.UNSAFE_componentWillReceiveProps && (foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps");
            "function" === typeof instance.componentWillUpdate && true !== instance.componentWillUpdate.__suppressDeprecationWarning ? foundWillUpdateName = "componentWillUpdate" : "function" === typeof instance.UNSAFE_componentWillUpdate && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
            if (null !== foundWillMountName || null !== foundWillReceivePropsName || null !== foundWillUpdateName) {
              var _componentName = getComponentNameFromType(type2) || "Component", newApiName = "function" === typeof type2.getDerivedStateFromProps ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
              didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(
                _componentName
              ), console.error(
                "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://react.dev/link/unsafe-component-lifecycles",
                _componentName,
                newApiName,
                null !== foundWillMountName ? "\n  " + foundWillMountName : "",
                null !== foundWillReceivePropsName ? "\n  " + foundWillReceivePropsName : "",
                null !== foundWillUpdateName ? "\n  " + foundWillUpdateName : ""
              ));
            }
          }
          var name2 = getComponentNameFromType(type2) || "Component";
          instance.render || (type2.prototype && "function" === typeof type2.prototype.render ? console.error(
            "No `render` method found on the %s instance: did you accidentally return an object from the constructor?",
            name2
          ) : console.error(
            "No `render` method found on the %s instance: you may have forgotten to define `render`.",
            name2
          ));
          !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state || console.error(
            "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",
            name2
          );
          instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved && console.error(
            "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",
            name2
          );
          instance.contextType && console.error(
            "contextType was defined as an instance property on %s. Use a static property to define contextType instead.",
            name2
          );
          type2.childContextTypes && !didWarnAboutChildContextTypes.has(type2) && (didWarnAboutChildContextTypes.add(type2), console.error(
            "%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)",
            name2
          ));
          type2.contextTypes && !didWarnAboutContextTypes$1.has(type2) && (didWarnAboutContextTypes$1.add(type2), console.error(
            "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)",
            name2
          ));
          "function" === typeof instance.componentShouldUpdate && console.error(
            "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",
            name2
          );
          type2.prototype && type2.prototype.isPureReactComponent && "undefined" !== typeof instance.shouldComponentUpdate && console.error(
            "%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",
            getComponentNameFromType(type2) || "A pure component"
          );
          "function" === typeof instance.componentDidUnmount && console.error(
            "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",
            name2
          );
          "function" === typeof instance.componentDidReceiveProps && console.error(
            "%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",
            name2
          );
          "function" === typeof instance.componentWillRecieveProps && console.error(
            "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",
            name2
          );
          "function" === typeof instance.UNSAFE_componentWillRecieveProps && console.error(
            "%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",
            name2
          );
          var hasMutatedProps = instance.props !== resolvedProps;
          void 0 !== instance.props && hasMutatedProps && console.error(
            "When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",
            name2
          );
          instance.defaultProps && console.error(
            "Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",
            name2,
            name2
          );
          "function" !== typeof instance.getSnapshotBeforeUpdate || "function" === typeof instance.componentDidUpdate || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(type2) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(type2), console.error(
            "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",
            getComponentNameFromType(type2)
          ));
          "function" === typeof instance.getDerivedStateFromProps && console.error(
            "%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            name2
          );
          "function" === typeof instance.getDerivedStateFromError && console.error(
            "%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            name2
          );
          "function" === typeof type2.getSnapshotBeforeUpdate && console.error(
            "%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",
            name2
          );
          var state = instance.state;
          state && ("object" !== typeof state || isArrayImpl(state)) && console.error("%s.state: must be set to an object or null", name2);
          "function" === typeof instance.getChildContext && "object" !== typeof type2.childContextTypes && console.error(
            "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",
            name2
          );
          var initialState2 = void 0 !== instance.state ? instance.state : null;
          instance.updater = classComponentUpdater;
          instance.props = resolvedProps;
          instance.state = initialState2;
          var internalInstance = { queue: [], replace: false };
          instance._reactInternals = internalInstance;
          var contextType$jscomp$0 = type2.contextType;
          instance.context = "object" === typeof contextType$jscomp$0 && null !== contextType$jscomp$0 ? contextType$jscomp$0._currentValue2 : emptyContextObject;
          if (instance.state === resolvedProps) {
            var componentName$jscomp$0 = getComponentNameFromType(type2) || "Component";
            didWarnAboutDirectlyAssigningPropsToState.has(
              componentName$jscomp$0
            ) || (didWarnAboutDirectlyAssigningPropsToState.add(
              componentName$jscomp$0
            ), console.error(
              "%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",
              componentName$jscomp$0
            ));
          }
          var getDerivedStateFromProps = type2.getDerivedStateFromProps;
          if ("function" === typeof getDerivedStateFromProps) {
            var partialState = getDerivedStateFromProps(
              resolvedProps,
              initialState2
            );
            if (void 0 === partialState) {
              var componentName$jscomp$1 = getComponentNameFromType(type2) || "Component";
              didWarnAboutUndefinedDerivedState.has(componentName$jscomp$1) || (didWarnAboutUndefinedDerivedState.add(componentName$jscomp$1), console.error(
                "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",
                componentName$jscomp$1
              ));
            }
            var JSCompiler_inline_result = null === partialState || void 0 === partialState ? initialState2 : assign({}, initialState2, partialState);
            instance.state = JSCompiler_inline_result;
          }
          if ("function" !== typeof type2.getDerivedStateFromProps && "function" !== typeof instance.getSnapshotBeforeUpdate && ("function" === typeof instance.UNSAFE_componentWillMount || "function" === typeof instance.componentWillMount)) {
            var oldState = instance.state;
            if ("function" === typeof instance.componentWillMount) {
              if (true !== instance.componentWillMount.__suppressDeprecationWarning) {
                var componentName$jscomp$2 = getComponentNameFromType(type2) || "Unknown";
                didWarnAboutDeprecatedWillMount[componentName$jscomp$2] || (console.warn(
                  "componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code from componentWillMount to componentDidMount (preferred in most cases) or the constructor.\n\nPlease update the following components: %s",
                  componentName$jscomp$2
                ), didWarnAboutDeprecatedWillMount[componentName$jscomp$2] = true);
              }
              instance.componentWillMount();
            }
            "function" === typeof instance.UNSAFE_componentWillMount && instance.UNSAFE_componentWillMount();
            oldState !== instance.state && (console.error(
              "%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
              getComponentNameFromType(type2) || "Component"
            ), classComponentUpdater.enqueueReplaceState(
              instance,
              instance.state,
              null
            ));
            if (null !== internalInstance.queue && 0 < internalInstance.queue.length) {
              var oldQueue = internalInstance.queue, oldReplace = internalInstance.replace;
              internalInstance.queue = null;
              internalInstance.replace = false;
              if (oldReplace && 1 === oldQueue.length)
                instance.state = oldQueue[0];
              else {
                for (var nextState = oldReplace ? oldQueue[0] : instance.state, dontMutate = true, i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
                  var partial = oldQueue[i], partialState$jscomp$0 = "function" === typeof partial ? partial.call(
                    instance,
                    nextState,
                    resolvedProps,
                    void 0
                  ) : partial;
                  null != partialState$jscomp$0 && (dontMutate ? (dontMutate = false, nextState = assign(
                    {},
                    nextState,
                    partialState$jscomp$0
                  )) : assign(nextState, partialState$jscomp$0));
                }
                instance.state = nextState;
              }
            } else internalInstance.queue = null;
          }
          var nextChildren = callRenderInDEV(instance);
          if (12 === request.status) throw null;
          instance.props !== resolvedProps && (didWarnAboutReassigningProps || console.error(
            "It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",
            getComponentNameFromType(type2) || "a component"
          ), didWarnAboutReassigningProps = true);
          var prevKeyPath = task.keyPath;
          task.keyPath = keyPath;
          renderNodeDestructive(request, task, nextChildren, -1);
          task.keyPath = prevKeyPath;
        } else {
          if (type2.prototype && "function" === typeof type2.prototype.render) {
            var componentName$jscomp$3 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutBadClass[componentName$jscomp$3] || (console.error(
              "The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",
              componentName$jscomp$3,
              componentName$jscomp$3
            ), didWarnAboutBadClass[componentName$jscomp$3] = true);
          }
          var value = renderWithHooks(
            request,
            task,
            keyPath,
            type2,
            props,
            void 0
          );
          if (12 === request.status) throw null;
          var hasId = 0 !== localIdCounter, actionStateCount = actionStateCounter, actionStateMatchingIndex$jscomp$0 = actionStateMatchingIndex;
          if (type2.contextTypes) {
            var _componentName$jscomp$0 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutContextTypes[_componentName$jscomp$0] || (didWarnAboutContextTypes[_componentName$jscomp$0] = true, console.error(
              "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)",
              _componentName$jscomp$0
            ));
          }
          type2 && type2.childContextTypes && console.error(
            "childContextTypes cannot be defined on a function component.\n  %s.childContextTypes = ...",
            type2.displayName || type2.name || "Component"
          );
          if ("function" === typeof type2.getDerivedStateFromProps) {
            var componentName$jscomp$4 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutGetDerivedStateOnFunctionComponent[componentName$jscomp$4] || (console.error(
              "%s: Function components do not support getDerivedStateFromProps.",
              componentName$jscomp$4
            ), didWarnAboutGetDerivedStateOnFunctionComponent[componentName$jscomp$4] = true);
          }
          if ("object" === typeof type2.contextType && null !== type2.contextType) {
            var _componentName2 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutContextTypeOnFunctionComponent[_componentName2] || (console.error(
              "%s: Function components do not support contextType.",
              _componentName2
            ), didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true);
          }
          finishFunctionComponent(
            request,
            task,
            keyPath,
            value,
            hasId,
            actionStateCount,
            actionStateMatchingIndex$jscomp$0
          );
        }
      else if ("string" === typeof type2) {
        var segment = task.blockedSegment;
        if (null === segment) {
          var children = props.children, prevContext = task.formatContext, prevKeyPath$jscomp$0 = task.keyPath;
          task.formatContext = getChildFormatContext(prevContext, type2, props);
          task.keyPath = keyPath;
          renderNode(request, task, children, -1);
          task.formatContext = prevContext;
          task.keyPath = prevKeyPath$jscomp$0;
        } else {
          var _children = pushStartInstance(
            segment.chunks,
            type2,
            props,
            request.resumableState,
            request.renderState,
            task.blockedPreamble,
            task.hoistableState,
            task.formatContext,
            segment.lastPushedText
          );
          segment.lastPushedText = false;
          var _prevContext2 = task.formatContext, _prevKeyPath3 = task.keyPath;
          task.keyPath = keyPath;
          if ((task.formatContext = getChildFormatContext(
            _prevContext2,
            type2,
            props
          )).insertionMode === HTML_HEAD_MODE) {
            var preambleSegment = createPendingSegment(
              request,
              0,
              null,
              task.formatContext,
              false,
              false
            );
            segment.preambleChildren.push(preambleSegment);
            task.blockedSegment = preambleSegment;
            try {
              preambleSegment.status = 6, renderNode(request, task, _children, -1), pushSegmentFinale(
                preambleSegment.chunks,
                request.renderState,
                preambleSegment.lastPushedText,
                preambleSegment.textEmbedded
              ), preambleSegment.status = COMPLETED;
            } finally {
              task.blockedSegment = segment;
            }
          } else renderNode(request, task, _children, -1);
          task.formatContext = _prevContext2;
          task.keyPath = _prevKeyPath3;
          a: {
            var target = segment.chunks, resumableState = request.resumableState;
            switch (type2) {
              case "title":
              case "style":
              case "script":
              case "area":
              case "base":
              case "br":
              case "col":
              case "embed":
              case "hr":
              case "img":
              case "input":
              case "keygen":
              case "link":
              case "meta":
              case "param":
              case "source":
              case "track":
              case "wbr":
                break a;
              case "body":
                if (_prevContext2.insertionMode <= HTML_HTML_MODE) {
                  resumableState.hasBody = true;
                  break a;
                }
                break;
              case "html":
                if (_prevContext2.insertionMode === ROOT_HTML_MODE) {
                  resumableState.hasHtml = true;
                  break a;
                }
                break;
              case "head":
                if (_prevContext2.insertionMode <= HTML_HTML_MODE) break a;
            }
            target.push(endChunkForTag(type2));
          }
          segment.lastPushedText = false;
        }
      } else {
        switch (type2) {
          case REACT_LEGACY_HIDDEN_TYPE:
          case REACT_STRICT_MODE_TYPE:
          case REACT_PROFILER_TYPE:
          case REACT_FRAGMENT_TYPE:
            var prevKeyPath$jscomp$1 = task.keyPath;
            task.keyPath = keyPath;
            renderNodeDestructive(request, task, props.children, -1);
            task.keyPath = prevKeyPath$jscomp$1;
            return;
          case REACT_ACTIVITY_TYPE:
            var segment$jscomp$0 = task.blockedSegment;
            if (null === segment$jscomp$0) {
              if ("hidden" !== props.mode) {
                var prevKeyPath$jscomp$2 = task.keyPath;
                task.keyPath = keyPath;
                renderNode(request, task, props.children, -1);
                task.keyPath = prevKeyPath$jscomp$2;
              }
            } else if ("hidden" !== props.mode) {
              request.renderState.generateStaticMarkup || segment$jscomp$0.chunks.push("<!--&-->");
              segment$jscomp$0.lastPushedText = false;
              var _prevKeyPath4 = task.keyPath;
              task.keyPath = keyPath;
              renderNode(request, task, props.children, -1);
              task.keyPath = _prevKeyPath4;
              request.renderState.generateStaticMarkup || segment$jscomp$0.chunks.push("<!--/&-->");
              segment$jscomp$0.lastPushedText = false;
            }
            return;
          case REACT_SUSPENSE_LIST_TYPE:
            a: {
              var children$jscomp$0 = props.children, revealOrder = props.revealOrder;
              if ("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder) {
                if (isArrayImpl(children$jscomp$0)) {
                  renderSuspenseListRows(
                    request,
                    task,
                    keyPath,
                    children$jscomp$0,
                    revealOrder
                  );
                  break a;
                }
                var iteratorFn = getIteratorFn(children$jscomp$0);
                if (iteratorFn) {
                  var iterator2 = iteratorFn.call(children$jscomp$0);
                  if (iterator2) {
                    validateIterable(
                      task,
                      children$jscomp$0,
                      -1,
                      iterator2,
                      iteratorFn
                    );
                    var step = iterator2.next();
                    if (!step.done) {
                      var rows = [];
                      do
                        rows.push(step.value), step = iterator2.next();
                      while (!step.done);
                      renderSuspenseListRows(
                        request,
                        task,
                        keyPath,
                        children$jscomp$0,
                        revealOrder
                      );
                    }
                    break a;
                  }
                }
              }
              if ("together" === revealOrder) {
                var _prevKeyPath2 = task.keyPath, prevRow = task.row, newRow = task.row = createSuspenseListRow(null);
                newRow.boundaries = [];
                newRow.together = true;
                task.keyPath = keyPath;
                renderNodeDestructive(request, task, children$jscomp$0, -1);
                0 === --newRow.pendingTasks && finishSuspenseListRow(request, newRow);
                task.keyPath = _prevKeyPath2;
                task.row = prevRow;
                null !== prevRow && 0 < newRow.pendingTasks && (prevRow.pendingTasks++, newRow.next = prevRow);
              } else {
                var prevKeyPath$jscomp$3 = task.keyPath;
                task.keyPath = keyPath;
                renderNodeDestructive(request, task, children$jscomp$0, -1);
                task.keyPath = prevKeyPath$jscomp$3;
              }
            }
            return;
          case REACT_VIEW_TRANSITION_TYPE:
          case REACT_SCOPE_TYPE:
            throw Error(
              "ReactDOMServer does not yet support scope components."
            );
          case REACT_SUSPENSE_TYPE:
            a: if (null !== task.replay) {
              var _prevKeyPath = task.keyPath, _prevContext = task.formatContext, _prevRow = task.row;
              task.keyPath = keyPath;
              task.formatContext = getSuspenseContentFormatContext(
                request.resumableState,
                _prevContext
              );
              task.row = null;
              var _content = props.children;
              try {
                renderNode(request, task, _content, -1);
              } finally {
                task.keyPath = _prevKeyPath, task.formatContext = _prevContext, task.row = _prevRow;
              }
            } else {
              var prevKeyPath$jscomp$4 = task.keyPath, prevContext$jscomp$0 = task.formatContext, prevRow$jscomp$0 = task.row, parentBoundary = task.blockedBoundary, parentPreamble = task.blockedPreamble, parentHoistableState = task.hoistableState, parentSegment = task.blockedSegment, fallback = props.fallback, content2 = props.children, fallbackAbortSet = /* @__PURE__ */ new Set();
              var newBoundary = createSuspenseBoundary(
                request,
                task.row,
                fallbackAbortSet,
                null,
                null
              );
              null !== request.trackedPostpones && (newBoundary.trackedContentKeyPath = keyPath);
              var boundarySegment = createPendingSegment(
                request,
                parentSegment.chunks.length,
                newBoundary,
                task.formatContext,
                false,
                false
              );
              parentSegment.children.push(boundarySegment);
              parentSegment.lastPushedText = false;
              var contentRootSegment = createPendingSegment(
                request,
                0,
                null,
                task.formatContext,
                false,
                false
              );
              contentRootSegment.parentFlushed = true;
              if (null !== request.trackedPostpones) {
                var suspenseComponentStack = task.componentStack, fallbackKeyPath = [
                  keyPath[0],
                  "Suspense Fallback",
                  keyPath[2]
                ], fallbackReplayNode = [
                  fallbackKeyPath[1],
                  fallbackKeyPath[2],
                  [],
                  null
                ];
                request.trackedPostpones.workingMap.set(
                  fallbackKeyPath,
                  fallbackReplayNode
                );
                newBoundary.trackedFallbackNode = fallbackReplayNode;
                task.blockedSegment = boundarySegment;
                task.blockedPreamble = newBoundary.fallbackPreamble;
                task.keyPath = fallbackKeyPath;
                task.formatContext = getSuspenseFallbackFormatContext(
                  request.resumableState,
                  prevContext$jscomp$0
                );
                task.componentStack = replaceSuspenseComponentStackWithSuspenseFallbackStack(
                  suspenseComponentStack
                );
                boundarySegment.status = 6;
                try {
                  renderNode(request, task, fallback, -1), pushSegmentFinale(
                    boundarySegment.chunks,
                    request.renderState,
                    boundarySegment.lastPushedText,
                    boundarySegment.textEmbedded
                  ), boundarySegment.status = COMPLETED;
                } catch (thrownValue) {
                  throw boundarySegment.status = 12 === request.status ? ABORTED : ERRORED, thrownValue;
                } finally {
                  task.blockedSegment = parentSegment, task.blockedPreamble = parentPreamble, task.keyPath = prevKeyPath$jscomp$4, task.formatContext = prevContext$jscomp$0;
                }
                var suspendedPrimaryTask = createRenderTask(
                  request,
                  null,
                  content2,
                  -1,
                  newBoundary,
                  contentRootSegment,
                  newBoundary.contentPreamble,
                  newBoundary.contentState,
                  task.abortSet,
                  keyPath,
                  getSuspenseContentFormatContext(
                    request.resumableState,
                    task.formatContext
                  ),
                  task.context,
                  task.treeContext,
                  null,
                  suspenseComponentStack,
                  emptyContextObject,
                  task.debugTask
                );
                pushComponentStack(suspendedPrimaryTask);
                request.pingedTasks.push(suspendedPrimaryTask);
              } else {
                task.blockedBoundary = newBoundary;
                task.blockedPreamble = newBoundary.contentPreamble;
                task.hoistableState = newBoundary.contentState;
                task.blockedSegment = contentRootSegment;
                task.keyPath = keyPath;
                task.formatContext = getSuspenseContentFormatContext(
                  request.resumableState,
                  prevContext$jscomp$0
                );
                task.row = null;
                contentRootSegment.status = 6;
                try {
                  if (renderNode(request, task, content2, -1), pushSegmentFinale(
                    contentRootSegment.chunks,
                    request.renderState,
                    contentRootSegment.lastPushedText,
                    contentRootSegment.textEmbedded
                  ), contentRootSegment.status = COMPLETED, queueCompletedSegment(newBoundary, contentRootSegment), 0 === newBoundary.pendingTasks && newBoundary.status === PENDING) {
                    if (newBoundary.status = COMPLETED, !isEligibleForOutlining(request, newBoundary)) {
                      null !== prevRow$jscomp$0 && 0 === --prevRow$jscomp$0.pendingTasks && finishSuspenseListRow(request, prevRow$jscomp$0);
                      0 === request.pendingRootTasks && task.blockedPreamble && preparePreamble(request);
                      break a;
                    }
                  } else
                    null !== prevRow$jscomp$0 && prevRow$jscomp$0.together && tryToResolveTogetherRow(request, prevRow$jscomp$0);
                } catch (thrownValue$2) {
                  newBoundary.status = CLIENT_RENDERED;
                  if (12 === request.status) {
                    contentRootSegment.status = ABORTED;
                    var error = request.fatalError;
                  } else
                    contentRootSegment.status = ERRORED, error = thrownValue$2;
                  var thrownInfo = getThrownInfo(task.componentStack);
                  var errorDigest = logRecoverableError(
                    request,
                    error,
                    thrownInfo,
                    task.debugTask
                  );
                  encodeErrorForBoundary(
                    newBoundary,
                    errorDigest,
                    error,
                    thrownInfo,
                    false
                  );
                  untrackBoundary(request, newBoundary);
                } finally {
                  task.blockedBoundary = parentBoundary, task.blockedPreamble = parentPreamble, task.hoistableState = parentHoistableState, task.blockedSegment = parentSegment, task.keyPath = prevKeyPath$jscomp$4, task.formatContext = prevContext$jscomp$0, task.row = prevRow$jscomp$0;
                }
                var suspendedFallbackTask = createRenderTask(
                  request,
                  null,
                  fallback,
                  -1,
                  parentBoundary,
                  boundarySegment,
                  newBoundary.fallbackPreamble,
                  newBoundary.fallbackState,
                  fallbackAbortSet,
                  [keyPath[0], "Suspense Fallback", keyPath[2]],
                  getSuspenseFallbackFormatContext(
                    request.resumableState,
                    task.formatContext
                  ),
                  task.context,
                  task.treeContext,
                  task.row,
                  replaceSuspenseComponentStackWithSuspenseFallbackStack(
                    task.componentStack
                  ),
                  emptyContextObject,
                  task.debugTask
                );
                pushComponentStack(suspendedFallbackTask);
                request.pingedTasks.push(suspendedFallbackTask);
              }
            }
            return;
        }
        if ("object" === typeof type2 && null !== type2)
          switch (type2.$$typeof) {
            case REACT_FORWARD_REF_TYPE:
              if ("ref" in props) {
                var propsWithoutRef = {};
                for (var key in props)
                  "ref" !== key && (propsWithoutRef[key] = props[key]);
              } else propsWithoutRef = props;
              var children$jscomp$1 = renderWithHooks(
                request,
                task,
                keyPath,
                type2.render,
                propsWithoutRef,
                ref2
              );
              finishFunctionComponent(
                request,
                task,
                keyPath,
                children$jscomp$1,
                0 !== localIdCounter,
                actionStateCounter,
                actionStateMatchingIndex
              );
              return;
            case REACT_MEMO_TYPE:
              renderElement(request, task, keyPath, type2.type, props, ref2);
              return;
            case REACT_CONTEXT_TYPE:
              var value$jscomp$0 = props.value, children$jscomp$2 = props.children;
              var prevSnapshot = task.context;
              var prevKeyPath$jscomp$5 = task.keyPath;
              var prevValue = type2._currentValue2;
              type2._currentValue2 = value$jscomp$0;
              void 0 !== type2._currentRenderer2 && null !== type2._currentRenderer2 && type2._currentRenderer2 !== rendererSigil && console.error(
                "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
              );
              type2._currentRenderer2 = rendererSigil;
              var prevNode = currentActiveSnapshot, newNode = {
                parent: prevNode,
                depth: null === prevNode ? 0 : prevNode.depth + 1,
                context: type2,
                parentValue: prevValue,
                value: value$jscomp$0
              };
              currentActiveSnapshot = newNode;
              task.context = newNode;
              task.keyPath = keyPath;
              renderNodeDestructive(request, task, children$jscomp$2, -1);
              var prevSnapshot$jscomp$0 = currentActiveSnapshot;
              if (null === prevSnapshot$jscomp$0)
                throw Error(
                  "Tried to pop a Context at the root of the app. This is a bug in React."
                );
              prevSnapshot$jscomp$0.context !== type2 && console.error(
                "The parent context is not the expected context. This is probably a bug in React."
              );
              prevSnapshot$jscomp$0.context._currentValue2 = prevSnapshot$jscomp$0.parentValue;
              void 0 !== type2._currentRenderer2 && null !== type2._currentRenderer2 && type2._currentRenderer2 !== rendererSigil && console.error(
                "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
              );
              type2._currentRenderer2 = rendererSigil;
              var JSCompiler_inline_result$jscomp$0 = currentActiveSnapshot = prevSnapshot$jscomp$0.parent;
              task.context = JSCompiler_inline_result$jscomp$0;
              task.keyPath = prevKeyPath$jscomp$5;
              prevSnapshot !== task.context && console.error(
                "Popping the context provider did not return back to the original snapshot. This is a bug in React."
              );
              return;
            case REACT_CONSUMER_TYPE:
              var context$jscomp$0 = type2._context, render = props.children;
              "function" !== typeof render && console.error(
                "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."
              );
              var newChildren = render(context$jscomp$0._currentValue2), prevKeyPath$jscomp$6 = task.keyPath;
              task.keyPath = keyPath;
              renderNodeDestructive(request, task, newChildren, -1);
              task.keyPath = prevKeyPath$jscomp$6;
              return;
            case REACT_LAZY_TYPE:
              var Component = callLazyInitInDEV(type2);
              if (12 === request.status) throw null;
              renderElement(request, task, keyPath, Component, props, ref2);
              return;
          }
        var info = "";
        if (void 0 === type2 || "object" === typeof type2 && null !== type2 && 0 === Object.keys(type2).length)
          info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
        throw Error(
          "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + ((null == type2 ? type2 : typeof type2) + "." + info)
        );
      }
    }
    function resumeNode(request, task, segmentId, node2, childIndex) {
      var prevReplay = task.replay, blockedBoundary = task.blockedBoundary, resumedSegment = createPendingSegment(
        request,
        0,
        null,
        task.formatContext,
        false,
        false
      );
      resumedSegment.id = segmentId;
      resumedSegment.parentFlushed = true;
      try {
        task.replay = null, task.blockedSegment = resumedSegment, renderNode(request, task, node2, childIndex), resumedSegment.status = COMPLETED, null === blockedBoundary ? request.completedRootSegment = resumedSegment : (queueCompletedSegment(blockedBoundary, resumedSegment), blockedBoundary.parentFlushed && request.partialBoundaries.push(blockedBoundary));
      } finally {
        task.replay = prevReplay, task.blockedSegment = null;
      }
    }
    function replayElement(request, task, keyPath, name2, keyOrIndex, childIndex, type2, props, ref2, replay) {
      childIndex = replay.nodes;
      for (var i = 0; i < childIndex.length; i++) {
        var node2 = childIndex[i];
        if (keyOrIndex === node2[1]) {
          if (4 === node2.length) {
            if (null !== name2 && name2 !== node2[0])
              throw Error(
                "Expected the resume to render <" + node2[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
              );
            var childNodes = node2[2];
            name2 = node2[3];
            keyOrIndex = task.node;
            task.replay = { nodes: childNodes, slots: name2, pendingTasks: 1 };
            try {
              renderElement(request, task, keyPath, type2, props, ref2);
              if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                throw Error(
                  "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                );
              task.replay.pendingTasks--;
            } catch (x2) {
              if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
                throw task.node === keyOrIndex ? task.replay = replay : childIndex.splice(i, 1), x2;
              task.replay.pendingTasks--;
              type2 = getThrownInfo(task.componentStack);
              props = request;
              request = task.blockedBoundary;
              keyPath = x2;
              ref2 = name2;
              name2 = logRecoverableError(props, keyPath, type2, task.debugTask);
              abortRemainingReplayNodes(
                props,
                request,
                childNodes,
                ref2,
                keyPath,
                name2,
                type2,
                false
              );
            }
            task.replay = replay;
          } else {
            if (type2 !== REACT_SUSPENSE_TYPE)
              throw Error(
                "Expected the resume to render <Suspense> in this slot but instead it rendered <" + (getComponentNameFromType(type2) || "Unknown") + ">. The tree doesn't match so React will fallback to client rendering."
              );
            a: {
              replay = void 0;
              name2 = node2[5];
              type2 = node2[2];
              ref2 = node2[3];
              keyOrIndex = null === node2[4] ? [] : node2[4][2];
              node2 = null === node2[4] ? null : node2[4][3];
              var prevKeyPath = task.keyPath, prevContext = task.formatContext, prevRow = task.row, previousReplaySet = task.replay, parentBoundary = task.blockedBoundary, parentHoistableState = task.hoistableState, content2 = props.children, fallback = props.fallback, fallbackAbortSet = /* @__PURE__ */ new Set();
              props = createSuspenseBoundary(
                request,
                task.row,
                fallbackAbortSet,
                null,
                null
              );
              props.parentFlushed = true;
              props.rootSegmentID = name2;
              task.blockedBoundary = props;
              task.hoistableState = props.contentState;
              task.keyPath = keyPath;
              task.formatContext = getSuspenseContentFormatContext(
                request.resumableState,
                prevContext
              );
              task.row = null;
              task.replay = { nodes: type2, slots: ref2, pendingTasks: 1 };
              try {
                renderNode(request, task, content2, -1);
                if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                  throw Error(
                    "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                  );
                task.replay.pendingTasks--;
                if (0 === props.pendingTasks && props.status === PENDING) {
                  props.status = COMPLETED;
                  request.completedBoundaries.push(props);
                  break a;
                }
              } catch (error) {
                props.status = CLIENT_RENDERED, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
                  request,
                  error,
                  childNodes,
                  task.debugTask
                ), encodeErrorForBoundary(props, replay, error, childNodes, false), task.replay.pendingTasks--, request.clientRenderedBoundaries.push(props);
              } finally {
                task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath, task.formatContext = prevContext, task.row = prevRow;
              }
              props = createReplayTask(
                request,
                null,
                { nodes: keyOrIndex, slots: node2, pendingTasks: 0 },
                fallback,
                -1,
                parentBoundary,
                props.fallbackState,
                fallbackAbortSet,
                [keyPath[0], "Suspense Fallback", keyPath[2]],
                getSuspenseFallbackFormatContext(
                  request.resumableState,
                  task.formatContext
                ),
                task.context,
                task.treeContext,
                task.row,
                replaceSuspenseComponentStackWithSuspenseFallbackStack(
                  task.componentStack
                ),
                emptyContextObject,
                task.debugTask
              );
              pushComponentStack(props);
              request.pingedTasks.push(props);
            }
          }
          childIndex.splice(i, 1);
          break;
        }
      }
    }
    function validateIterable(task, iterable, childIndex, iterator2, iteratorFn) {
      if (iterator2 === iterable) {
        if (-1 !== childIndex || null === task.componentStack || "function" !== typeof task.componentStack.type || "[object GeneratorFunction]" !== Object.prototype.toString.call(task.componentStack.type) || "[object Generator]" !== Object.prototype.toString.call(iterator2))
          didWarnAboutGenerators || console.error(
            "Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."
          ), didWarnAboutGenerators = true;
      } else
        iterable.entries !== iteratorFn || didWarnAboutMaps || (console.error(
          "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
        ), didWarnAboutMaps = true);
    }
    function renderNodeDestructive(request, task, node2, childIndex) {
      null !== task.replay && "number" === typeof task.replay.slots ? resumeNode(request, task, task.replay.slots, node2, childIndex) : (task.node = node2, task.childIndex = childIndex, node2 = task.componentStack, childIndex = task.debugTask, pushComponentStack(task), retryNode(request, task), task.componentStack = node2, task.debugTask = childIndex);
    }
    function retryNode(request, task) {
      var node2 = task.node, childIndex = task.childIndex;
      if (null !== node2) {
        if ("object" === typeof node2) {
          switch (node2.$$typeof) {
            case REACT_ELEMENT_TYPE:
              var type2 = node2.type, key = node2.key;
              node2 = node2.props;
              var refProp = node2.ref;
              refProp = void 0 !== refProp ? refProp : null;
              var debugTask = task.debugTask, name2 = getComponentNameFromType(type2);
              key = null == key ? -1 === childIndex ? 0 : childIndex : key;
              var keyPath = [task.keyPath, name2, key];
              null !== task.replay ? debugTask ? debugTask.run(
                replayElement.bind(
                  null,
                  request,
                  task,
                  keyPath,
                  name2,
                  key,
                  childIndex,
                  type2,
                  node2,
                  refProp,
                  task.replay
                )
              ) : replayElement(
                request,
                task,
                keyPath,
                name2,
                key,
                childIndex,
                type2,
                node2,
                refProp,
                task.replay
              ) : debugTask ? debugTask.run(
                renderElement.bind(
                  null,
                  request,
                  task,
                  keyPath,
                  type2,
                  node2,
                  refProp
                )
              ) : renderElement(request, task, keyPath, type2, node2, refProp);
              return;
            case REACT_PORTAL_TYPE:
              throw Error(
                "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render."
              );
            case REACT_LAZY_TYPE:
              type2 = callLazyInitInDEV(node2);
              if (12 === request.status) throw null;
              renderNodeDestructive(request, task, type2, childIndex);
              return;
          }
          if (isArrayImpl(node2)) {
            renderChildrenArray(request, task, node2, childIndex);
            return;
          }
          if (key = getIteratorFn(node2)) {
            if (type2 = key.call(node2)) {
              validateIterable(task, node2, childIndex, type2, key);
              node2 = type2.next();
              if (!node2.done) {
                key = [];
                do
                  key.push(node2.value), node2 = type2.next();
                while (!node2.done);
                renderChildrenArray(request, task, key, childIndex);
              }
              return;
            }
          }
          if ("function" === typeof node2.then)
            return task.thenableState = null, renderNodeDestructive(
              request,
              task,
              unwrapThenable(node2),
              childIndex
            );
          if (node2.$$typeof === REACT_CONTEXT_TYPE)
            return renderNodeDestructive(
              request,
              task,
              node2._currentValue2,
              childIndex
            );
          request = Object.prototype.toString.call(node2);
          throw Error(
            "Objects are not valid as a React child (found: " + ("[object Object]" === request ? "object with keys {" + Object.keys(node2).join(", ") + "}" : request) + "). If you meant to render a collection of children, use an array instead."
          );
        }
        "string" === typeof node2 ? (task = task.blockedSegment, null !== task && (task.lastPushedText = pushTextInstance(
          task.chunks,
          node2,
          request.renderState,
          task.lastPushedText
        ))) : "number" === typeof node2 || "bigint" === typeof node2 ? (task = task.blockedSegment, null !== task && (task.lastPushedText = pushTextInstance(
          task.chunks,
          "" + node2,
          request.renderState,
          task.lastPushedText
        ))) : ("function" === typeof node2 && (request = node2.displayName || node2.name || "Component", console.error(
          "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.",
          request,
          request
        )), "symbol" === typeof node2 && console.error(
          "Symbols are not valid as a React child.\n  %s",
          String(node2)
        ));
      }
    }
    function warnForMissingKey(request, task, child) {
      if (null !== child && "object" === typeof child && (child.$$typeof === REACT_ELEMENT_TYPE || child.$$typeof === REACT_PORTAL_TYPE) && child._store && (!child._store.validated && null == child.key || 2 === child._store.validated)) {
        if ("object" !== typeof child._store)
          throw Error(
            "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."
          );
        child._store.validated = 1;
        var didWarnForKey = request.didWarnForKey;
        null == didWarnForKey && (didWarnForKey = request.didWarnForKey = /* @__PURE__ */ new WeakSet());
        request = task.componentStack;
        if (null !== request && !didWarnForKey.has(request)) {
          didWarnForKey.add(request);
          var componentName = getComponentNameFromType(child.type);
          didWarnForKey = child._owner;
          var parentOwner = request.owner;
          request = "";
          if (parentOwner && "undefined" !== typeof parentOwner.type) {
            var name2 = getComponentNameFromType(parentOwner.type);
            name2 && (request = "\n\nCheck the render method of `" + name2 + "`.");
          }
          request || componentName && (request = "\n\nCheck the top-level render call using <" + componentName + ">.");
          componentName = "";
          null != didWarnForKey && parentOwner !== didWarnForKey && (parentOwner = null, "undefined" !== typeof didWarnForKey.type ? parentOwner = getComponentNameFromType(didWarnForKey.type) : "string" === typeof didWarnForKey.name && (parentOwner = didWarnForKey.name), parentOwner && (componentName = " It was passed a child from " + parentOwner + "."));
          didWarnForKey = task.componentStack;
          task.componentStack = {
            parent: task.componentStack,
            type: child.type,
            owner: child._owner,
            stack: child._debugStack
          };
          console.error(
            'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
            request,
            componentName
          );
          task.componentStack = didWarnForKey;
        }
      }
    }
    function renderChildrenArray(request, task, children, childIndex) {
      var prevKeyPath = task.keyPath, previousComponentStack = task.componentStack;
      var previousDebugTask = task.debugTask;
      pushServerComponentStack(task, task.node._debugInfo);
      if (-1 !== childIndex && (task.keyPath = [task.keyPath, "Fragment", childIndex], null !== task.replay)) {
        for (var replay = task.replay, replayNodes = replay.nodes, j2 = 0; j2 < replayNodes.length; j2++) {
          var node2 = replayNodes[j2];
          if (node2[1] === childIndex) {
            childIndex = node2[2];
            node2 = node2[3];
            task.replay = { nodes: childIndex, slots: node2, pendingTasks: 1 };
            try {
              renderChildrenArray(request, task, children, -1);
              if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                throw Error(
                  "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                );
              task.replay.pendingTasks--;
            } catch (x2) {
              if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
                throw x2;
              task.replay.pendingTasks--;
              var thrownInfo = getThrownInfo(task.componentStack);
              children = task.blockedBoundary;
              var error = x2, resumeSlots = node2;
              node2 = logRecoverableError(
                request,
                error,
                thrownInfo,
                task.debugTask
              );
              abortRemainingReplayNodes(
                request,
                children,
                childIndex,
                resumeSlots,
                error,
                node2,
                thrownInfo,
                false
              );
            }
            task.replay = replay;
            replayNodes.splice(j2, 1);
            break;
          }
        }
        task.keyPath = prevKeyPath;
        task.componentStack = previousComponentStack;
        task.debugTask = previousDebugTask;
        return;
      }
      replay = task.treeContext;
      replayNodes = children.length;
      if (null !== task.replay && (j2 = task.replay.slots, null !== j2 && "object" === typeof j2)) {
        for (childIndex = 0; childIndex < replayNodes; childIndex++)
          node2 = children[childIndex], task.treeContext = pushTreeContext(
            replay,
            replayNodes,
            childIndex
          ), error = j2[childIndex], "number" === typeof error ? (resumeNode(request, task, error, node2, childIndex), delete j2[childIndex]) : renderNode(request, task, node2, childIndex);
        task.treeContext = replay;
        task.keyPath = prevKeyPath;
        task.componentStack = previousComponentStack;
        task.debugTask = previousDebugTask;
        return;
      }
      for (j2 = 0; j2 < replayNodes; j2++)
        childIndex = children[j2], warnForMissingKey(request, task, childIndex), task.treeContext = pushTreeContext(replay, replayNodes, j2), renderNode(request, task, childIndex, j2);
      task.treeContext = replay;
      task.keyPath = prevKeyPath;
      task.componentStack = previousComponentStack;
      task.debugTask = previousDebugTask;
    }
    function trackPostponedBoundary(request, trackedPostpones, boundary) {
      boundary.status = POSTPONED;
      boundary.rootSegmentID = request.nextSegmentId++;
      request = boundary.trackedContentKeyPath;
      if (null === request)
        throw Error(
          "It should not be possible to postpone at the root. This is a bug in React."
        );
      var fallbackReplayNode = boundary.trackedFallbackNode, children = [], boundaryNode = trackedPostpones.workingMap.get(request);
      if (void 0 === boundaryNode)
        return boundary = [
          request[1],
          request[2],
          children,
          null,
          fallbackReplayNode,
          boundary.rootSegmentID
        ], trackedPostpones.workingMap.set(request, boundary), addToReplayParent(boundary, request[0], trackedPostpones), boundary;
      boundaryNode[4] = fallbackReplayNode;
      boundaryNode[5] = boundary.rootSegmentID;
      return boundaryNode;
    }
    function trackPostpone(request, trackedPostpones, task, segment) {
      segment.status = POSTPONED;
      var keyPath = task.keyPath, boundary = task.blockedBoundary;
      if (null === boundary)
        segment.id = request.nextSegmentId++, trackedPostpones.rootSlots = segment.id, null !== request.completedRootSegment && (request.completedRootSegment.status = POSTPONED);
      else {
        if (null !== boundary && boundary.status === PENDING) {
          var boundaryNode = trackPostponedBoundary(
            request,
            trackedPostpones,
            boundary
          );
          if (boundary.trackedContentKeyPath === keyPath && -1 === task.childIndex) {
            -1 === segment.id && (segment.id = segment.parentFlushed ? boundary.rootSegmentID : request.nextSegmentId++);
            boundaryNode[3] = segment.id;
            return;
          }
        }
        -1 === segment.id && (segment.id = segment.parentFlushed && null !== boundary ? boundary.rootSegmentID : request.nextSegmentId++);
        if (-1 === task.childIndex)
          null === keyPath ? trackedPostpones.rootSlots = segment.id : (task = trackedPostpones.workingMap.get(keyPath), void 0 === task ? (task = [keyPath[1], keyPath[2], [], segment.id], addToReplayParent(task, keyPath[0], trackedPostpones)) : task[3] = segment.id);
        else {
          if (null === keyPath)
            if (request = trackedPostpones.rootSlots, null === request)
              request = trackedPostpones.rootSlots = {};
            else {
              if ("number" === typeof request)
                throw Error(
                  "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
                );
            }
          else if (boundary = trackedPostpones.workingMap, boundaryNode = boundary.get(keyPath), void 0 === boundaryNode)
            request = {}, boundaryNode = [keyPath[1], keyPath[2], [], request], boundary.set(keyPath, boundaryNode), addToReplayParent(boundaryNode, keyPath[0], trackedPostpones);
          else if (request = boundaryNode[3], null === request)
            request = boundaryNode[3] = {};
          else if ("number" === typeof request)
            throw Error(
              "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
            );
          request[task.childIndex] = segment.id;
        }
      }
    }
    function untrackBoundary(request, boundary) {
      request = request.trackedPostpones;
      null !== request && (boundary = boundary.trackedContentKeyPath, null !== boundary && (boundary = request.workingMap.get(boundary), void 0 !== boundary && (boundary.length = 4, boundary[2] = [], boundary[3] = null)));
    }
    function spawnNewSuspendedReplayTask(request, task, thenableState2) {
      return createReplayTask(
        request,
        thenableState2,
        task.replay,
        task.node,
        task.childIndex,
        task.blockedBoundary,
        task.hoistableState,
        task.abortSet,
        task.keyPath,
        task.formatContext,
        task.context,
        task.treeContext,
        task.row,
        task.componentStack,
        emptyContextObject,
        task.debugTask
      );
    }
    function spawnNewSuspendedRenderTask(request, task, thenableState2) {
      var segment = task.blockedSegment, newSegment = createPendingSegment(
        request,
        segment.chunks.length,
        null,
        task.formatContext,
        segment.lastPushedText,
        true
      );
      segment.children.push(newSegment);
      segment.lastPushedText = false;
      return createRenderTask(
        request,
        thenableState2,
        task.node,
        task.childIndex,
        task.blockedBoundary,
        newSegment,
        task.blockedPreamble,
        task.hoistableState,
        task.abortSet,
        task.keyPath,
        task.formatContext,
        task.context,
        task.treeContext,
        task.row,
        task.componentStack,
        emptyContextObject,
        task.debugTask
      );
    }
    function renderNode(request, task, node2, childIndex) {
      var previousFormatContext = task.formatContext, previousContext = task.context, previousKeyPath = task.keyPath, previousTreeContext = task.treeContext, previousComponentStack = task.componentStack, previousDebugTask = task.debugTask, segment = task.blockedSegment;
      if (null === segment) {
        segment = task.replay;
        try {
          return renderNodeDestructive(request, task, node2, childIndex);
        } catch (thrownValue) {
          if (resetHooksState(), node2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue, 12 !== request.status && "object" === typeof node2 && null !== node2) {
            if ("function" === typeof node2.then) {
              childIndex = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
              request = spawnNewSuspendedReplayTask(
                request,
                task,
                childIndex
              ).ping;
              node2.then(request, request);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.replay = segment;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
            if ("Maximum call stack size exceeded" === node2.message) {
              node2 = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
              node2 = spawnNewSuspendedReplayTask(request, task, node2);
              request.pingedTasks.push(node2);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.replay = segment;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
          }
        }
      } else {
        var childrenLength = segment.children.length, chunkLength = segment.chunks.length;
        try {
          return renderNodeDestructive(request, task, node2, childIndex);
        } catch (thrownValue$3) {
          if (resetHooksState(), segment.children.length = childrenLength, segment.chunks.length = chunkLength, node2 = thrownValue$3 === SuspenseException ? getSuspendedThenable() : thrownValue$3, 12 !== request.status && "object" === typeof node2 && null !== node2) {
            if ("function" === typeof node2.then) {
              segment = node2;
              node2 = thrownValue$3 === SuspenseException ? getThenableStateAfterSuspending() : null;
              request = spawnNewSuspendedRenderTask(request, task, node2).ping;
              segment.then(request, request);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
            if ("Maximum call stack size exceeded" === node2.message) {
              segment = thrownValue$3 === SuspenseException ? getThenableStateAfterSuspending() : null;
              segment = spawnNewSuspendedRenderTask(request, task, segment);
              request.pingedTasks.push(segment);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
          }
        }
      }
      task.formatContext = previousFormatContext;
      task.context = previousContext;
      task.keyPath = previousKeyPath;
      task.treeContext = previousTreeContext;
      switchContext(previousContext);
      throw node2;
    }
    function abortTaskSoft(task) {
      var boundary = task.blockedBoundary, segment = task.blockedSegment;
      null !== segment && (segment.status = ABORTED, finishedTask(this, boundary, task.row, segment));
    }
    function abortRemainingReplayNodes(request$jscomp$0, boundary, nodes, slots, error$jscomp$0, errorDigest$jscomp$0, errorInfo$jscomp$0, aborted) {
      for (var i = 0; i < nodes.length; i++) {
        var node2 = nodes[i];
        if (4 === node2.length)
          abortRemainingReplayNodes(
            request$jscomp$0,
            boundary,
            node2[2],
            node2[3],
            error$jscomp$0,
            errorDigest$jscomp$0,
            errorInfo$jscomp$0,
            aborted
          );
        else {
          var request = request$jscomp$0;
          node2 = node2[5];
          var error = error$jscomp$0, errorDigest = errorDigest$jscomp$0, errorInfo = errorInfo$jscomp$0, wasAborted = aborted, resumedBoundary = createSuspenseBoundary(
            request,
            null,
            /* @__PURE__ */ new Set(),
            null,
            null
          );
          resumedBoundary.parentFlushed = true;
          resumedBoundary.rootSegmentID = node2;
          resumedBoundary.status = CLIENT_RENDERED;
          encodeErrorForBoundary(
            resumedBoundary,
            errorDigest,
            error,
            errorInfo,
            wasAborted
          );
          resumedBoundary.parentFlushed && request.clientRenderedBoundaries.push(resumedBoundary);
        }
      }
      nodes.length = 0;
      if (null !== slots) {
        if (null === boundary)
          throw Error(
            "We should not have any resumable nodes in the shell. This is a bug in React."
          );
        boundary.status !== CLIENT_RENDERED && (boundary.status = CLIENT_RENDERED, encodeErrorForBoundary(
          boundary,
          errorDigest$jscomp$0,
          error$jscomp$0,
          errorInfo$jscomp$0,
          aborted
        ), boundary.parentFlushed && request$jscomp$0.clientRenderedBoundaries.push(boundary));
        if ("object" === typeof slots)
          for (var index2 in slots) delete slots[index2];
      }
    }
    function abortTask(task, request, error) {
      var boundary = task.blockedBoundary, segment = task.blockedSegment;
      if (null !== segment) {
        if (6 === segment.status) return;
        segment.status = ABORTED;
      }
      var errorInfo = getThrownInfo(task.componentStack), node2 = task.node;
      null !== node2 && "object" === typeof node2 && pushHaltedAwaitOnComponentStack(task, node2._debugInfo);
      if (null === boundary) {
        if (13 !== request.status && request.status !== CLOSED) {
          boundary = task.replay;
          if (null === boundary) {
            null !== request.trackedPostpones && null !== segment ? (boundary = request.trackedPostpones, logRecoverableError(request, error, errorInfo, task.debugTask), trackPostpone(request, boundary, task, segment), finishedTask(request, null, task.row, segment)) : (logRecoverableError(request, error, errorInfo, task.debugTask), fatalError(request, error, errorInfo, task.debugTask));
            return;
          }
          boundary.pendingTasks--;
          0 === boundary.pendingTasks && 0 < boundary.nodes.length && (segment = logRecoverableError(request, error, errorInfo, null), abortRemainingReplayNodes(
            request,
            null,
            boundary.nodes,
            boundary.slots,
            error,
            segment,
            errorInfo,
            true
          ));
          request.pendingRootTasks--;
          0 === request.pendingRootTasks && completeShell(request);
        }
      } else {
        node2 = request.trackedPostpones;
        if (boundary.status !== CLIENT_RENDERED) {
          if (null !== node2 && null !== segment)
            return logRecoverableError(request, error, errorInfo, task.debugTask), trackPostpone(request, node2, task, segment), boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
              return abortTask(fallbackTask, request, error);
            }), boundary.fallbackAbortableTasks.clear(), finishedTask(request, boundary, task.row, segment);
          boundary.status = CLIENT_RENDERED;
          segment = logRecoverableError(
            request,
            error,
            errorInfo,
            task.debugTask
          );
          boundary.status = CLIENT_RENDERED;
          encodeErrorForBoundary(boundary, segment, error, errorInfo, true);
          untrackBoundary(request, boundary);
          boundary.parentFlushed && request.clientRenderedBoundaries.push(boundary);
        }
        boundary.pendingTasks--;
        errorInfo = boundary.row;
        null !== errorInfo && 0 === --errorInfo.pendingTasks && finishSuspenseListRow(request, errorInfo);
        boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
          return abortTask(fallbackTask, request, error);
        });
        boundary.fallbackAbortableTasks.clear();
      }
      task = task.row;
      null !== task && 0 === --task.pendingTasks && finishSuspenseListRow(request, task);
      request.allPendingTasks--;
      0 === request.allPendingTasks && completeAll(request);
    }
    function safelyEmitEarlyPreloads(request, shellComplete) {
      try {
        var renderState = request.renderState, onHeaders = renderState.onHeaders;
        if (onHeaders) {
          var headers = renderState.headers;
          if (headers) {
            renderState.headers = null;
            var linkHeader = headers.preconnects;
            headers.fontPreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.fontPreloads);
            headers.highImagePreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.highImagePreloads);
            if (!shellComplete) {
              var queueIter = renderState.styles.values(), queueStep = queueIter.next();
              b: for (; 0 < headers.remainingCapacity && !queueStep.done; queueStep = queueIter.next())
                for (var sheetIter = queueStep.value.sheets.values(), sheetStep = sheetIter.next(); 0 < headers.remainingCapacity && !sheetStep.done; sheetStep = sheetIter.next()) {
                  var sheet = sheetStep.value, props = sheet.props, key = props.href, props$jscomp$0 = sheet.props;
                  var header = getPreloadAsHeader(
                    props$jscomp$0.href,
                    "style",
                    {
                      crossOrigin: props$jscomp$0.crossOrigin,
                      integrity: props$jscomp$0.integrity,
                      nonce: props$jscomp$0.nonce,
                      type: props$jscomp$0.type,
                      fetchPriority: props$jscomp$0.fetchPriority,
                      referrerPolicy: props$jscomp$0.referrerPolicy,
                      media: props$jscomp$0.media
                    }
                  );
                  if (0 <= (headers.remainingCapacity -= header.length + 2))
                    renderState.resets.style[key] = PRELOAD_NO_CREDS, linkHeader && (linkHeader += ", "), linkHeader += header, renderState.resets.style[key] = "string" === typeof props.crossOrigin || "string" === typeof props.integrity ? [props.crossOrigin, props.integrity] : PRELOAD_NO_CREDS;
                  else break b;
                }
            }
            linkHeader ? onHeaders({ Link: linkHeader }) : onHeaders({});
          }
        }
      } catch (error) {
        logRecoverableError(request, error, {}, null);
      }
    }
    function completeShell(request) {
      null === request.trackedPostpones && safelyEmitEarlyPreloads(request, true);
      null === request.trackedPostpones && preparePreamble(request);
      request.onShellError = noop2;
      request = request.onShellReady;
      request();
    }
    function completeAll(request) {
      safelyEmitEarlyPreloads(
        request,
        null === request.trackedPostpones ? true : null === request.completedRootSegment || request.completedRootSegment.status !== POSTPONED
      );
      preparePreamble(request);
      request = request.onAllReady;
      request();
    }
    function queueCompletedSegment(boundary, segment) {
      if (0 === segment.chunks.length && 1 === segment.children.length && null === segment.children[0].boundary && -1 === segment.children[0].id) {
        var childSegment = segment.children[0];
        childSegment.id = segment.id;
        childSegment.parentFlushed = true;
        childSegment.status !== COMPLETED && childSegment.status !== ABORTED && childSegment.status !== ERRORED || queueCompletedSegment(boundary, childSegment);
      } else boundary.completedSegments.push(segment);
    }
    function finishedTask(request, boundary, row, segment) {
      null !== row && (0 === --row.pendingTasks ? finishSuspenseListRow(request, row) : row.together && tryToResolveTogetherRow(request, row));
      request.allPendingTasks--;
      if (null === boundary) {
        if (null !== segment && segment.parentFlushed) {
          if (null !== request.completedRootSegment)
            throw Error(
              "There can only be one root segment. This is a bug in React."
            );
          request.completedRootSegment = segment;
        }
        request.pendingRootTasks--;
        0 === request.pendingRootTasks && completeShell(request);
      } else if (boundary.pendingTasks--, boundary.status !== CLIENT_RENDERED)
        if (0 === boundary.pendingTasks)
          if (boundary.status === PENDING && (boundary.status = COMPLETED), null !== segment && segment.parentFlushed && (segment.status === COMPLETED || segment.status === ABORTED) && queueCompletedSegment(boundary, segment), boundary.parentFlushed && request.completedBoundaries.push(boundary), boundary.status === COMPLETED)
            row = boundary.row, null !== row && hoistHoistables(row.hoistables, boundary.contentState), isEligibleForOutlining(request, boundary) || (boundary.fallbackAbortableTasks.forEach(
              abortTaskSoft,
              request
            ), boundary.fallbackAbortableTasks.clear(), null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row)), 0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary.contentPreamble && preparePreamble(request);
          else {
            if (boundary.status === POSTPONED && (boundary = boundary.row, null !== boundary)) {
              if (null !== request.trackedPostpones) {
                row = request.trackedPostpones;
                var postponedRow = boundary.next;
                if (null !== postponedRow && (segment = postponedRow.boundaries, null !== segment))
                  for (postponedRow.boundaries = null, postponedRow = 0; postponedRow < segment.length; postponedRow++) {
                    var postponedBoundary = segment[postponedRow];
                    trackPostponedBoundary(request, row, postponedBoundary);
                    finishedTask(request, postponedBoundary, null, null);
                  }
              }
              0 === --boundary.pendingTasks && finishSuspenseListRow(request, boundary);
            }
          }
        else
          null === segment || !segment.parentFlushed || segment.status !== COMPLETED && segment.status !== ABORTED || (queueCompletedSegment(boundary, segment), 1 === boundary.completedSegments.length && boundary.parentFlushed && request.partialBoundaries.push(boundary)), boundary = boundary.row, null !== boundary && boundary.together && tryToResolveTogetherRow(request, boundary);
      0 === request.allPendingTasks && completeAll(request);
    }
    function performWork(request$jscomp$2) {
      if (request$jscomp$2.status !== CLOSED && 13 !== request$jscomp$2.status) {
        var prevContext = currentActiveSnapshot, prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = HooksDispatcher;
        var prevAsyncDispatcher = ReactSharedInternals.A;
        ReactSharedInternals.A = DefaultAsyncDispatcher;
        var prevRequest = currentRequest;
        currentRequest = request$jscomp$2;
        var prevGetCurrentStackImpl = ReactSharedInternals.getCurrentStack;
        ReactSharedInternals.getCurrentStack = getCurrentStackInDEV;
        var prevResumableState = currentResumableState;
        currentResumableState = request$jscomp$2.resumableState;
        try {
          var pingedTasks = request$jscomp$2.pingedTasks, i;
          for (i = 0; i < pingedTasks.length; i++) {
            var request = request$jscomp$2, task = pingedTasks[i], segment = task.blockedSegment;
            if (null === segment) {
              var prevTaskInDEV = void 0, request$jscomp$0 = request;
              request = task;
              if (0 !== request.replay.pendingTasks) {
                switchContext(request.context);
                prevTaskInDEV = currentTaskInDEV;
                currentTaskInDEV = request;
                try {
                  "number" === typeof request.replay.slots ? resumeNode(
                    request$jscomp$0,
                    request,
                    request.replay.slots,
                    request.node,
                    request.childIndex
                  ) : retryNode(request$jscomp$0, request);
                  if (1 === request.replay.pendingTasks && 0 < request.replay.nodes.length)
                    throw Error(
                      "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                    );
                  request.replay.pendingTasks--;
                  request.abortSet.delete(request);
                  finishedTask(
                    request$jscomp$0,
                    request.blockedBoundary,
                    request.row,
                    null
                  );
                } catch (thrownValue) {
                  resetHooksState();
                  var x2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue;
                  if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then) {
                    var ping = request.ping;
                    x2.then(ping, ping);
                    request.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                  } else {
                    request.replay.pendingTasks--;
                    request.abortSet.delete(request);
                    var errorInfo = getThrownInfo(request.componentStack), errorDigest = void 0, request$jscomp$1 = request$jscomp$0, boundary = request.blockedBoundary, error$jscomp$0 = 12 === request$jscomp$0.status ? request$jscomp$0.fatalError : x2, errorInfo$jscomp$0 = errorInfo, replayNodes = request.replay.nodes, resumeSlots = request.replay.slots;
                    errorDigest = logRecoverableError(
                      request$jscomp$1,
                      error$jscomp$0,
                      errorInfo$jscomp$0,
                      request.debugTask
                    );
                    abortRemainingReplayNodes(
                      request$jscomp$1,
                      boundary,
                      replayNodes,
                      resumeSlots,
                      error$jscomp$0,
                      errorDigest,
                      errorInfo$jscomp$0,
                      false
                    );
                    request$jscomp$0.pendingRootTasks--;
                    0 === request$jscomp$0.pendingRootTasks && completeShell(request$jscomp$0);
                    request$jscomp$0.allPendingTasks--;
                    0 === request$jscomp$0.allPendingTasks && completeAll(request$jscomp$0);
                  }
                } finally {
                  currentTaskInDEV = prevTaskInDEV;
                }
              }
            } else if (request$jscomp$0 = prevTaskInDEV = void 0, errorDigest = task, request$jscomp$1 = segment, request$jscomp$1.status === PENDING) {
              request$jscomp$1.status = 6;
              switchContext(errorDigest.context);
              request$jscomp$0 = currentTaskInDEV;
              currentTaskInDEV = errorDigest;
              var childrenLength = request$jscomp$1.children.length, chunkLength = request$jscomp$1.chunks.length;
              try {
                retryNode(request, errorDigest), pushSegmentFinale(
                  request$jscomp$1.chunks,
                  request.renderState,
                  request$jscomp$1.lastPushedText,
                  request$jscomp$1.textEmbedded
                ), errorDigest.abortSet.delete(errorDigest), request$jscomp$1.status = COMPLETED, finishedTask(
                  request,
                  errorDigest.blockedBoundary,
                  errorDigest.row,
                  request$jscomp$1
                );
              } catch (thrownValue) {
                resetHooksState();
                request$jscomp$1.children.length = childrenLength;
                request$jscomp$1.chunks.length = chunkLength;
                var x$jscomp$0 = thrownValue === SuspenseException ? getSuspendedThenable() : 12 === request.status ? request.fatalError : thrownValue;
                if (12 === request.status && null !== request.trackedPostpones) {
                  var trackedPostpones = request.trackedPostpones, thrownInfo = getThrownInfo(errorDigest.componentStack);
                  errorDigest.abortSet.delete(errorDigest);
                  logRecoverableError(
                    request,
                    x$jscomp$0,
                    thrownInfo,
                    errorDigest.debugTask
                  );
                  trackPostpone(
                    request,
                    trackedPostpones,
                    errorDigest,
                    request$jscomp$1
                  );
                  finishedTask(
                    request,
                    errorDigest.blockedBoundary,
                    errorDigest.row,
                    request$jscomp$1
                  );
                } else if ("object" === typeof x$jscomp$0 && null !== x$jscomp$0 && "function" === typeof x$jscomp$0.then) {
                  request$jscomp$1.status = PENDING;
                  errorDigest.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                  var ping$jscomp$0 = errorDigest.ping;
                  x$jscomp$0.then(ping$jscomp$0, ping$jscomp$0);
                } else {
                  var errorInfo$jscomp$1 = getThrownInfo(
                    errorDigest.componentStack
                  );
                  errorDigest.abortSet.delete(errorDigest);
                  request$jscomp$1.status = ERRORED;
                  var boundary$jscomp$0 = errorDigest.blockedBoundary, row = errorDigest.row, debugTask = errorDigest.debugTask;
                  null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
                  request.allPendingTasks--;
                  prevTaskInDEV = logRecoverableError(
                    request,
                    x$jscomp$0,
                    errorInfo$jscomp$1,
                    debugTask
                  );
                  if (null === boundary$jscomp$0)
                    fatalError(
                      request,
                      x$jscomp$0,
                      errorInfo$jscomp$1,
                      debugTask
                    );
                  else if (boundary$jscomp$0.pendingTasks--, boundary$jscomp$0.status !== CLIENT_RENDERED) {
                    boundary$jscomp$0.status = CLIENT_RENDERED;
                    encodeErrorForBoundary(
                      boundary$jscomp$0,
                      prevTaskInDEV,
                      x$jscomp$0,
                      errorInfo$jscomp$1,
                      false
                    );
                    untrackBoundary(request, boundary$jscomp$0);
                    var boundaryRow = boundary$jscomp$0.row;
                    null !== boundaryRow && 0 === --boundaryRow.pendingTasks && finishSuspenseListRow(request, boundaryRow);
                    boundary$jscomp$0.parentFlushed && request.clientRenderedBoundaries.push(boundary$jscomp$0);
                    0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary$jscomp$0.contentPreamble && preparePreamble(request);
                  }
                  0 === request.allPendingTasks && completeAll(request);
                }
              } finally {
                currentTaskInDEV = request$jscomp$0;
              }
            }
          }
          pingedTasks.splice(0, i);
          null !== request$jscomp$2.destination && flushCompletedQueues(
            request$jscomp$2,
            request$jscomp$2.destination
          );
        } catch (error) {
          pingedTasks = {}, logRecoverableError(request$jscomp$2, error, pingedTasks, null), fatalError(request$jscomp$2, error, pingedTasks, null);
        } finally {
          currentResumableState = prevResumableState, ReactSharedInternals.H = prevDispatcher, ReactSharedInternals.A = prevAsyncDispatcher, ReactSharedInternals.getCurrentStack = prevGetCurrentStackImpl, prevDispatcher === HooksDispatcher && switchContext(prevContext), currentRequest = prevRequest;
        }
      }
    }
    function preparePreambleFromSubtree(request, segment, collectedPreambleSegments) {
      segment.preambleChildren.length && collectedPreambleSegments.push(segment.preambleChildren);
      for (var pendingPreambles = false, i = 0; i < segment.children.length; i++)
        pendingPreambles = preparePreambleFromSegment(
          request,
          segment.children[i],
          collectedPreambleSegments
        ) || pendingPreambles;
      return pendingPreambles;
    }
    function preparePreambleFromSegment(request, segment, collectedPreambleSegments) {
      var boundary = segment.boundary;
      if (null === boundary)
        return preparePreambleFromSubtree(
          request,
          segment,
          collectedPreambleSegments
        );
      var preamble = boundary.contentPreamble, fallbackPreamble = boundary.fallbackPreamble;
      if (null === preamble || null === fallbackPreamble) return false;
      switch (boundary.status) {
        case COMPLETED:
          hoistPreambleState(request.renderState, preamble);
          request.byteSize += boundary.byteSize;
          segment = boundary.completedSegments[0];
          if (!segment)
            throw Error(
              "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
            );
          return preparePreambleFromSubtree(
            request,
            segment,
            collectedPreambleSegments
          );
        case POSTPONED:
          if (null !== request.trackedPostpones) return true;
        case CLIENT_RENDERED:
          if (segment.status === COMPLETED)
            return hoistPreambleState(request.renderState, fallbackPreamble), preparePreambleFromSubtree(
              request,
              segment,
              collectedPreambleSegments
            );
        default:
          return true;
      }
    }
    function preparePreamble(request) {
      if (request.completedRootSegment && null === request.completedPreambleSegments) {
        var collectedPreambleSegments = [], originalRequestByteSize = request.byteSize, hasPendingPreambles = preparePreambleFromSegment(
          request,
          request.completedRootSegment,
          collectedPreambleSegments
        ), preamble = request.renderState.preamble;
        false === hasPendingPreambles || preamble.headChunks && preamble.bodyChunks ? request.completedPreambleSegments = collectedPreambleSegments : request.byteSize = originalRequestByteSize;
      }
    }
    function flushSubtree(request, destination, segment, hoistableState) {
      segment.parentFlushed = true;
      switch (segment.status) {
        case PENDING:
          segment.id = request.nextSegmentId++;
        case POSTPONED:
          return hoistableState = segment.id, segment.lastPushedText = false, segment.textEmbedded = false, request = request.renderState, destination.push(placeholder1), destination.push(request.placeholderPrefix), request = hoistableState.toString(16), destination.push(request), destination.push(placeholder2);
        case COMPLETED:
          segment.status = FLUSHED;
          var r = true, chunks = segment.chunks, chunkIdx = 0;
          segment = segment.children;
          for (var childIdx = 0; childIdx < segment.length; childIdx++) {
            for (r = segment[childIdx]; chunkIdx < r.index; chunkIdx++)
              destination.push(chunks[chunkIdx]);
            r = flushSegment(request, destination, r, hoistableState);
          }
          for (; chunkIdx < chunks.length - 1; chunkIdx++)
            destination.push(chunks[chunkIdx]);
          chunkIdx < chunks.length && (r = destination.push(chunks[chunkIdx]));
          return r;
        case ABORTED:
          return true;
        default:
          throw Error(
            "Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React."
          );
      }
    }
    function flushSegment(request, destination, segment, hoistableState) {
      var boundary = segment.boundary;
      if (null === boundary)
        return flushSubtree(request, destination, segment, hoistableState);
      boundary.parentFlushed = true;
      if (boundary.status === CLIENT_RENDERED) {
        var row = boundary.row;
        null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
        if (!request.renderState.generateStaticMarkup) {
          var errorDigest = boundary.errorDigest, errorMessage = boundary.errorMessage;
          row = boundary.errorStack;
          boundary = boundary.errorComponentStack;
          destination.push(startClientRenderedSuspenseBoundary);
          destination.push(clientRenderedSuspenseBoundaryError1);
          errorDigest && (destination.push(clientRenderedSuspenseBoundaryError1A), errorDigest = escapeTextForBrowser(errorDigest), destination.push(errorDigest), destination.push(
            clientRenderedSuspenseBoundaryErrorAttrInterstitial
          ));
          errorMessage && (destination.push(clientRenderedSuspenseBoundaryError1B), errorMessage = escapeTextForBrowser(errorMessage), destination.push(errorMessage), destination.push(
            clientRenderedSuspenseBoundaryErrorAttrInterstitial
          ));
          row && (destination.push(clientRenderedSuspenseBoundaryError1C), row = escapeTextForBrowser(row), destination.push(row), destination.push(
            clientRenderedSuspenseBoundaryErrorAttrInterstitial
          ));
          boundary && (destination.push(clientRenderedSuspenseBoundaryError1D), row = escapeTextForBrowser(boundary), destination.push(row), destination.push(
            clientRenderedSuspenseBoundaryErrorAttrInterstitial
          ));
          destination.push(clientRenderedSuspenseBoundaryError2);
        }
        flushSubtree(request, destination, segment, hoistableState);
        request = request.renderState.generateStaticMarkup ? true : destination.push(endSuspenseBoundary);
        return request;
      }
      if (boundary.status !== COMPLETED)
        return boundary.status === PENDING && (boundary.rootSegmentID = request.nextSegmentId++), 0 < boundary.completedSegments.length && request.partialBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
          destination,
          request.renderState,
          boundary.rootSegmentID
        ), hoistableState && hoistHoistables(hoistableState, boundary.fallbackState), flushSubtree(request, destination, segment, hoistableState), destination.push(endSuspenseBoundary);
      if (!flushingPartialBoundaries && isEligibleForOutlining(request, boundary) && flushedByteSize + boundary.byteSize > request.progressiveChunkSize)
        return boundary.rootSegmentID = request.nextSegmentId++, request.completedBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
          destination,
          request.renderState,
          boundary.rootSegmentID
        ), flushSubtree(request, destination, segment, hoistableState), destination.push(endSuspenseBoundary);
      flushedByteSize += boundary.byteSize;
      hoistableState && hoistHoistables(hoistableState, boundary.contentState);
      segment = boundary.row;
      null !== segment && isEligibleForOutlining(request, boundary) && 0 === --segment.pendingTasks && finishSuspenseListRow(request, segment);
      request.renderState.generateStaticMarkup || destination.push(startCompletedSuspenseBoundary);
      segment = boundary.completedSegments;
      if (1 !== segment.length)
        throw Error(
          "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
        );
      flushSegment(request, destination, segment[0], hoistableState);
      request = request.renderState.generateStaticMarkup ? true : destination.push(endSuspenseBoundary);
      return request;
    }
    function flushSegmentContainer(request, destination, segment, hoistableState) {
      writeStartSegment(
        destination,
        request.renderState,
        segment.parentFormatContext,
        segment.id
      );
      flushSegment(request, destination, segment, hoistableState);
      return writeEndSegment(destination, segment.parentFormatContext);
    }
    function flushCompletedBoundary(request, destination, boundary) {
      flushedByteSize = boundary.byteSize;
      for (var completedSegments = boundary.completedSegments, i = 0; i < completedSegments.length; i++)
        flushPartiallyCompletedSegment(
          request,
          destination,
          boundary,
          completedSegments[i]
        );
      completedSegments.length = 0;
      completedSegments = boundary.row;
      null !== completedSegments && isEligibleForOutlining(request, boundary) && 0 === --completedSegments.pendingTasks && finishSuspenseListRow(request, completedSegments);
      writeHoistablesForBoundary(
        destination,
        boundary.contentState,
        request.renderState
      );
      completedSegments = request.resumableState;
      request = request.renderState;
      i = boundary.rootSegmentID;
      boundary = boundary.contentState;
      var requiresStyleInsertion = request.stylesToHoist;
      request.stylesToHoist = false;
      destination.push(request.startInlineScript);
      destination.push(endOfStartTag);
      requiresStyleInsertion ? ((completedSegments.instructions & SentClientRenderFunction) === NothingSent && (completedSegments.instructions |= SentClientRenderFunction, destination.push(clientRenderScriptFunctionOnly)), (completedSegments.instructions & SentCompleteBoundaryFunction) === NothingSent && (completedSegments.instructions |= SentCompleteBoundaryFunction, destination.push(completeBoundaryScriptFunctionOnly)), (completedSegments.instructions & SentStyleInsertionFunction) === NothingSent ? (completedSegments.instructions |= SentStyleInsertionFunction, destination.push(completeBoundaryWithStylesScript1FullPartial)) : destination.push(completeBoundaryWithStylesScript1Partial)) : ((completedSegments.instructions & SentCompleteBoundaryFunction) === NothingSent && (completedSegments.instructions |= SentCompleteBoundaryFunction, destination.push(completeBoundaryScriptFunctionOnly)), destination.push(completeBoundaryScript1Partial));
      completedSegments = i.toString(16);
      destination.push(request.boundaryPrefix);
      destination.push(completedSegments);
      destination.push(completeBoundaryScript2);
      destination.push(request.segmentPrefix);
      destination.push(completedSegments);
      requiresStyleInsertion ? (destination.push(completeBoundaryScript3a), writeStyleResourceDependenciesInJS(destination, boundary)) : destination.push(completeBoundaryScript3b);
      boundary = destination.push(completeBoundaryScriptEnd);
      return writeBootstrap(destination, request) && boundary;
    }
    function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
      if (segment.status === FLUSHED) return true;
      var hoistableState = boundary.contentState, segmentID = segment.id;
      if (-1 === segmentID) {
        if (-1 === (segment.id = boundary.rootSegmentID))
          throw Error(
            "A root segment ID must have been assigned by now. This is a bug in React."
          );
        return flushSegmentContainer(
          request,
          destination,
          segment,
          hoistableState
        );
      }
      if (segmentID === boundary.rootSegmentID)
        return flushSegmentContainer(
          request,
          destination,
          segment,
          hoistableState
        );
      flushSegmentContainer(request, destination, segment, hoistableState);
      boundary = request.resumableState;
      request = request.renderState;
      destination.push(request.startInlineScript);
      destination.push(endOfStartTag);
      (boundary.instructions & SentCompleteSegmentFunction) === NothingSent ? (boundary.instructions |= SentCompleteSegmentFunction, destination.push(completeSegmentScript1Full)) : destination.push(completeSegmentScript1Partial);
      destination.push(request.segmentPrefix);
      segmentID = segmentID.toString(16);
      destination.push(segmentID);
      destination.push(completeSegmentScript2);
      destination.push(request.placeholderPrefix);
      destination.push(segmentID);
      destination = destination.push(completeSegmentScriptEnd);
      return destination;
    }
    function flushCompletedQueues(request, destination) {
      try {
        if (!(0 < request.pendingRootTasks)) {
          var i, completedRootSegment = request.completedRootSegment;
          if (null !== completedRootSegment) {
            if (completedRootSegment.status === POSTPONED) return;
            var completedPreambleSegments = request.completedPreambleSegments;
            if (null === completedPreambleSegments) return;
            flushedByteSize = request.byteSize;
            var resumableState = request.resumableState, renderState = request.renderState, preamble = renderState.preamble, htmlChunks = preamble.htmlChunks, headChunks = preamble.headChunks, i$jscomp$0;
            if (htmlChunks) {
              for (i$jscomp$0 = 0; i$jscomp$0 < htmlChunks.length; i$jscomp$0++)
                destination.push(htmlChunks[i$jscomp$0]);
              if (headChunks)
                for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
                  destination.push(headChunks[i$jscomp$0]);
              else {
                var chunk2 = startChunkForTag("head");
                destination.push(chunk2);
                destination.push(endOfStartTag);
              }
            } else if (headChunks)
              for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
                destination.push(headChunks[i$jscomp$0]);
            var charsetChunks = renderState.charsetChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < charsetChunks.length; i$jscomp$0++)
              destination.push(charsetChunks[i$jscomp$0]);
            charsetChunks.length = 0;
            renderState.preconnects.forEach(flushResource, destination);
            renderState.preconnects.clear();
            var viewportChunks = renderState.viewportChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < viewportChunks.length; i$jscomp$0++)
              destination.push(viewportChunks[i$jscomp$0]);
            viewportChunks.length = 0;
            renderState.fontPreloads.forEach(flushResource, destination);
            renderState.fontPreloads.clear();
            renderState.highImagePreloads.forEach(flushResource, destination);
            renderState.highImagePreloads.clear();
            currentlyFlushingRenderState = renderState;
            renderState.styles.forEach(flushStylesInPreamble, destination);
            currentlyFlushingRenderState = null;
            var importMapChunks = renderState.importMapChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < importMapChunks.length; i$jscomp$0++)
              destination.push(importMapChunks[i$jscomp$0]);
            importMapChunks.length = 0;
            renderState.bootstrapScripts.forEach(flushResource, destination);
            renderState.scripts.forEach(flushResource, destination);
            renderState.scripts.clear();
            renderState.bulkPreloads.forEach(flushResource, destination);
            renderState.bulkPreloads.clear();
            resumableState.instructions |= SentCompletedShellId;
            var hoistableChunks = renderState.hoistableChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < hoistableChunks.length; i$jscomp$0++)
              destination.push(hoistableChunks[i$jscomp$0]);
            for (resumableState = hoistableChunks.length = 0; resumableState < completedPreambleSegments.length; resumableState++) {
              var segments = completedPreambleSegments[resumableState];
              for (renderState = 0; renderState < segments.length; renderState++)
                flushSegment(request, destination, segments[renderState], null);
            }
            var preamble$jscomp$0 = request.renderState.preamble, headChunks$jscomp$0 = preamble$jscomp$0.headChunks;
            if (preamble$jscomp$0.htmlChunks || headChunks$jscomp$0) {
              var chunk$jscomp$0 = endChunkForTag("head");
              destination.push(chunk$jscomp$0);
            }
            var bodyChunks = preamble$jscomp$0.bodyChunks;
            if (bodyChunks)
              for (completedPreambleSegments = 0; completedPreambleSegments < bodyChunks.length; completedPreambleSegments++)
                destination.push(bodyChunks[completedPreambleSegments]);
            flushSegment(request, destination, completedRootSegment, null);
            request.completedRootSegment = null;
            var renderState$jscomp$0 = request.renderState;
            if (0 !== request.allPendingTasks || 0 !== request.clientRenderedBoundaries.length || 0 !== request.completedBoundaries.length || null !== request.trackedPostpones && (0 !== request.trackedPostpones.rootNodes.length || null !== request.trackedPostpones.rootSlots)) {
              var resumableState$jscomp$0 = request.resumableState;
              if ((resumableState$jscomp$0.instructions & SentMarkShellTime) === NothingSent) {
                resumableState$jscomp$0.instructions |= SentMarkShellTime;
                destination.push(renderState$jscomp$0.startInlineScript);
                if ((resumableState$jscomp$0.instructions & SentCompletedShellId) === NothingSent) {
                  resumableState$jscomp$0.instructions |= SentCompletedShellId;
                  var shellId = "_" + resumableState$jscomp$0.idPrefix + "R_";
                  destination.push(completedShellIdAttributeStart);
                  var chunk$jscomp$1 = escapeTextForBrowser(shellId);
                  destination.push(chunk$jscomp$1);
                  destination.push(attributeEnd);
                }
                destination.push(endOfStartTag);
                destination.push(shellTimeRuntimeScript);
                destination.push(endInlineScript);
              }
            }
            writeBootstrap(destination, renderState$jscomp$0);
          }
          var renderState$jscomp$1 = request.renderState;
          completedRootSegment = 0;
          var viewportChunks$jscomp$0 = renderState$jscomp$1.viewportChunks;
          for (completedRootSegment = 0; completedRootSegment < viewportChunks$jscomp$0.length; completedRootSegment++)
            destination.push(viewportChunks$jscomp$0[completedRootSegment]);
          viewportChunks$jscomp$0.length = 0;
          renderState$jscomp$1.preconnects.forEach(flushResource, destination);
          renderState$jscomp$1.preconnects.clear();
          renderState$jscomp$1.fontPreloads.forEach(flushResource, destination);
          renderState$jscomp$1.fontPreloads.clear();
          renderState$jscomp$1.highImagePreloads.forEach(
            flushResource,
            destination
          );
          renderState$jscomp$1.highImagePreloads.clear();
          renderState$jscomp$1.styles.forEach(preloadLateStyles, destination);
          renderState$jscomp$1.scripts.forEach(flushResource, destination);
          renderState$jscomp$1.scripts.clear();
          renderState$jscomp$1.bulkPreloads.forEach(flushResource, destination);
          renderState$jscomp$1.bulkPreloads.clear();
          var hoistableChunks$jscomp$0 = renderState$jscomp$1.hoistableChunks;
          for (completedRootSegment = 0; completedRootSegment < hoistableChunks$jscomp$0.length; completedRootSegment++)
            destination.push(hoistableChunks$jscomp$0[completedRootSegment]);
          hoistableChunks$jscomp$0.length = 0;
          var clientRenderedBoundaries = request.clientRenderedBoundaries;
          for (i = 0; i < clientRenderedBoundaries.length; i++) {
            var boundary = clientRenderedBoundaries[i];
            renderState$jscomp$1 = destination;
            var resumableState$jscomp$1 = request.resumableState, renderState$jscomp$2 = request.renderState, id = boundary.rootSegmentID, errorDigest = boundary.errorDigest, errorMessage = boundary.errorMessage, errorStack = boundary.errorStack, errorComponentStack = boundary.errorComponentStack;
            renderState$jscomp$1.push(renderState$jscomp$2.startInlineScript);
            renderState$jscomp$1.push(endOfStartTag);
            (resumableState$jscomp$1.instructions & SentClientRenderFunction) === NothingSent ? (resumableState$jscomp$1.instructions |= SentClientRenderFunction, renderState$jscomp$1.push(clientRenderScript1Full)) : renderState$jscomp$1.push(clientRenderScript1Partial);
            renderState$jscomp$1.push(renderState$jscomp$2.boundaryPrefix);
            var chunk$jscomp$2 = id.toString(16);
            renderState$jscomp$1.push(chunk$jscomp$2);
            renderState$jscomp$1.push(clientRenderScript1A);
            if (errorDigest || errorMessage || errorStack || errorComponentStack) {
              renderState$jscomp$1.push(clientRenderErrorScriptArgInterstitial);
              var chunk$jscomp$3 = escapeJSStringsForInstructionScripts(
                errorDigest || ""
              );
              renderState$jscomp$1.push(chunk$jscomp$3);
            }
            if (errorMessage || errorStack || errorComponentStack) {
              renderState$jscomp$1.push(clientRenderErrorScriptArgInterstitial);
              var chunk$jscomp$4 = escapeJSStringsForInstructionScripts(
                errorMessage || ""
              );
              renderState$jscomp$1.push(chunk$jscomp$4);
            }
            if (errorStack || errorComponentStack) {
              renderState$jscomp$1.push(clientRenderErrorScriptArgInterstitial);
              var chunk$jscomp$5 = escapeJSStringsForInstructionScripts(
                errorStack || ""
              );
              renderState$jscomp$1.push(chunk$jscomp$5);
            }
            if (errorComponentStack) {
              renderState$jscomp$1.push(clientRenderErrorScriptArgInterstitial);
              var chunk$jscomp$6 = escapeJSStringsForInstructionScripts(errorComponentStack);
              renderState$jscomp$1.push(chunk$jscomp$6);
            }
            var JSCompiler_inline_result = renderState$jscomp$1.push(
              clientRenderScriptEnd
            );
            if (!JSCompiler_inline_result) {
              request.destination = null;
              i++;
              clientRenderedBoundaries.splice(0, i);
              return;
            }
          }
          clientRenderedBoundaries.splice(0, i);
          var completedBoundaries = request.completedBoundaries;
          for (i = 0; i < completedBoundaries.length; i++)
            if (!flushCompletedBoundary(
              request,
              destination,
              completedBoundaries[i]
            )) {
              request.destination = null;
              i++;
              completedBoundaries.splice(0, i);
              return;
            }
          completedBoundaries.splice(0, i);
          flushingPartialBoundaries = true;
          var partialBoundaries = request.partialBoundaries;
          for (i = 0; i < partialBoundaries.length; i++) {
            a: {
              clientRenderedBoundaries = request;
              boundary = destination;
              var boundary$jscomp$0 = partialBoundaries[i];
              flushedByteSize = boundary$jscomp$0.byteSize;
              var completedSegments = boundary$jscomp$0.completedSegments;
              for (JSCompiler_inline_result = 0; JSCompiler_inline_result < completedSegments.length; JSCompiler_inline_result++)
                if (!flushPartiallyCompletedSegment(
                  clientRenderedBoundaries,
                  boundary,
                  boundary$jscomp$0,
                  completedSegments[JSCompiler_inline_result]
                )) {
                  JSCompiler_inline_result++;
                  completedSegments.splice(0, JSCompiler_inline_result);
                  var JSCompiler_inline_result$jscomp$0 = false;
                  break a;
                }
              completedSegments.splice(0, JSCompiler_inline_result);
              var row = boundary$jscomp$0.row;
              null !== row && row.together && 1 === boundary$jscomp$0.pendingTasks && (1 === row.pendingTasks ? unblockSuspenseListRow(
                clientRenderedBoundaries,
                row,
                row.hoistables
              ) : row.pendingTasks--);
              JSCompiler_inline_result$jscomp$0 = writeHoistablesForBoundary(
                boundary,
                boundary$jscomp$0.contentState,
                clientRenderedBoundaries.renderState
              );
            }
            if (!JSCompiler_inline_result$jscomp$0) {
              request.destination = null;
              i++;
              partialBoundaries.splice(0, i);
              return;
            }
          }
          partialBoundaries.splice(0, i);
          flushingPartialBoundaries = false;
          var largeBoundaries = request.completedBoundaries;
          for (i = 0; i < largeBoundaries.length; i++)
            if (!flushCompletedBoundary(request, destination, largeBoundaries[i])) {
              request.destination = null;
              i++;
              largeBoundaries.splice(0, i);
              return;
            }
          largeBoundaries.splice(0, i);
        }
      } finally {
        flushingPartialBoundaries = false, 0 === request.allPendingTasks && 0 === request.clientRenderedBoundaries.length && 0 === request.completedBoundaries.length && (request.flushScheduled = false, i = request.resumableState, i.hasBody && (partialBoundaries = endChunkForTag("body"), destination.push(partialBoundaries)), i.hasHtml && (i = endChunkForTag("html"), destination.push(i)), 0 !== request.abortableTasks.size && console.error(
          "There was still abortable task at the root when we closed. This is a bug in React."
        ), request.status = CLOSED, destination.push(null), request.destination = null);
      }
    }
    function startWork(request) {
      request.flushScheduled = null !== request.destination;
      performWork(request);
      10 === request.status && (request.status = 11);
      null === request.trackedPostpones && safelyEmitEarlyPreloads(request, 0 === request.pendingRootTasks);
    }
    function enqueueFlush(request) {
      if (false === request.flushScheduled && 0 === request.pingedTasks.length && null !== request.destination) {
        request.flushScheduled = true;
        var destination = request.destination;
        destination ? flushCompletedQueues(request, destination) : request.flushScheduled = false;
      }
    }
    function startFlowing(request, destination) {
      if (13 === request.status)
        request.status = CLOSED, destination.destroy(request.fatalError);
      else if (request.status !== CLOSED && null === request.destination) {
        request.destination = destination;
        try {
          flushCompletedQueues(request, destination);
        } catch (error) {
          destination = {}, logRecoverableError(request, error, destination, null), fatalError(request, error, destination, null);
        }
      }
    }
    function abort(request, reason) {
      if (11 === request.status || 10 === request.status) request.status = 12;
      try {
        var abortableTasks = request.abortableTasks;
        if (0 < abortableTasks.size) {
          var error = void 0 === reason ? Error("The render was aborted by the server without a reason.") : "object" === typeof reason && null !== reason && "function" === typeof reason.then ? Error("The render was aborted by the server with a promise.") : reason;
          request.fatalError = error;
          abortableTasks.forEach(function(task) {
            var prevTaskInDEV = currentTaskInDEV, prevGetCurrentStackImpl = ReactSharedInternals.getCurrentStack;
            currentTaskInDEV = task;
            ReactSharedInternals.getCurrentStack = getCurrentStackInDEV;
            try {
              abortTask(task, request, error);
            } finally {
              currentTaskInDEV = prevTaskInDEV, ReactSharedInternals.getCurrentStack = prevGetCurrentStackImpl;
            }
          });
          abortableTasks.clear();
        }
        null !== request.destination && flushCompletedQueues(request, request.destination);
      } catch (error$4) {
        reason = {}, logRecoverableError(request, error$4, reason, null), fatalError(request, error$4, reason, null);
      }
    }
    function addToReplayParent(node2, parentKeyPath, trackedPostpones) {
      if (null === parentKeyPath) trackedPostpones.rootNodes.push(node2);
      else {
        var workingMap = trackedPostpones.workingMap, parentNode = workingMap.get(parentKeyPath);
        void 0 === parentNode && (parentNode = [parentKeyPath[1], parentKeyPath[2], [], null], workingMap.set(parentKeyPath, parentNode), addToReplayParent(parentNode, parentKeyPath[0], trackedPostpones));
        parentNode[2].push(node2);
      }
    }
    function onError() {
    }
    function renderToStringImpl(children, options, generateStaticMarkup, abortReason) {
      var didFatal = false, fatalError2 = null, result = "", readyToStream = false;
      options = createResumableState(
        options ? options.identifierPrefix : void 0
      );
      children = createRequest(
        children,
        options,
        createRenderState(options, generateStaticMarkup),
        createFormatContext(ROOT_HTML_MODE, null, 0, null),
        Infinity,
        onError,
        void 0,
        function() {
          readyToStream = true;
        },
        void 0,
        void 0,
        void 0
      );
      startWork(children);
      abort(children, abortReason);
      startFlowing(children, {
        push: function(chunk2) {
          null !== chunk2 && (result += chunk2);
          return true;
        },
        destroy: function(error) {
          didFatal = true;
          fatalError2 = error;
        }
      });
      if (didFatal && fatalError2 !== abortReason) throw fatalError2;
      if (!readyToStream)
        throw Error(
          "A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition."
        );
      return result;
    }
    var React2 = requireReact(), ReactDOM = requireReactDom(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_SCOPE_TYPE = /* @__PURE__ */ Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = /* @__PURE__ */ Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, isArrayImpl = Array.isArray, jsxPropsParents = /* @__PURE__ */ new WeakMap(), jsxChildrenParents = /* @__PURE__ */ new WeakMap(), CLIENT_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.client.reference"), assign = Object.assign, hasOwnProperty2 = Object.prototype.hasOwnProperty, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
      "^[: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]*$"
    ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, unitlessNumbers = new Set(
      "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
        " "
      )
    ), aliases = /* @__PURE__ */ new Map([
      ["acceptCharset", "accept-charset"],
      ["htmlFor", "for"],
      ["httpEquiv", "http-equiv"],
      ["crossOrigin", "crossorigin"],
      ["accentHeight", "accent-height"],
      ["alignmentBaseline", "alignment-baseline"],
      ["arabicForm", "arabic-form"],
      ["baselineShift", "baseline-shift"],
      ["capHeight", "cap-height"],
      ["clipPath", "clip-path"],
      ["clipRule", "clip-rule"],
      ["colorInterpolation", "color-interpolation"],
      ["colorInterpolationFilters", "color-interpolation-filters"],
      ["colorProfile", "color-profile"],
      ["colorRendering", "color-rendering"],
      ["dominantBaseline", "dominant-baseline"],
      ["enableBackground", "enable-background"],
      ["fillOpacity", "fill-opacity"],
      ["fillRule", "fill-rule"],
      ["floodColor", "flood-color"],
      ["floodOpacity", "flood-opacity"],
      ["fontFamily", "font-family"],
      ["fontSize", "font-size"],
      ["fontSizeAdjust", "font-size-adjust"],
      ["fontStretch", "font-stretch"],
      ["fontStyle", "font-style"],
      ["fontVariant", "font-variant"],
      ["fontWeight", "font-weight"],
      ["glyphName", "glyph-name"],
      ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
      ["glyphOrientationVertical", "glyph-orientation-vertical"],
      ["horizAdvX", "horiz-adv-x"],
      ["horizOriginX", "horiz-origin-x"],
      ["imageRendering", "image-rendering"],
      ["letterSpacing", "letter-spacing"],
      ["lightingColor", "lighting-color"],
      ["markerEnd", "marker-end"],
      ["markerMid", "marker-mid"],
      ["markerStart", "marker-start"],
      ["overlinePosition", "overline-position"],
      ["overlineThickness", "overline-thickness"],
      ["paintOrder", "paint-order"],
      ["panose-1", "panose-1"],
      ["pointerEvents", "pointer-events"],
      ["renderingIntent", "rendering-intent"],
      ["shapeRendering", "shape-rendering"],
      ["stopColor", "stop-color"],
      ["stopOpacity", "stop-opacity"],
      ["strikethroughPosition", "strikethrough-position"],
      ["strikethroughThickness", "strikethrough-thickness"],
      ["strokeDasharray", "stroke-dasharray"],
      ["strokeDashoffset", "stroke-dashoffset"],
      ["strokeLinecap", "stroke-linecap"],
      ["strokeLinejoin", "stroke-linejoin"],
      ["strokeMiterlimit", "stroke-miterlimit"],
      ["strokeOpacity", "stroke-opacity"],
      ["strokeWidth", "stroke-width"],
      ["textAnchor", "text-anchor"],
      ["textDecoration", "text-decoration"],
      ["textRendering", "text-rendering"],
      ["transformOrigin", "transform-origin"],
      ["underlinePosition", "underline-position"],
      ["underlineThickness", "underline-thickness"],
      ["unicodeBidi", "unicode-bidi"],
      ["unicodeRange", "unicode-range"],
      ["unitsPerEm", "units-per-em"],
      ["vAlphabetic", "v-alphabetic"],
      ["vHanging", "v-hanging"],
      ["vIdeographic", "v-ideographic"],
      ["vMathematical", "v-mathematical"],
      ["vectorEffect", "vector-effect"],
      ["vertAdvY", "vert-adv-y"],
      ["vertOriginX", "vert-origin-x"],
      ["vertOriginY", "vert-origin-y"],
      ["wordSpacing", "word-spacing"],
      ["writingMode", "writing-mode"],
      ["xmlnsXlink", "xmlns:xlink"],
      ["xHeight", "x-height"]
    ]), hasReadOnlyValue = {
      button: true,
      checkbox: true,
      image: true,
      hidden: true,
      radio: true,
      reset: true,
      submit: true
    }, ariaProperties = {
      "aria-current": 0,
      "aria-description": 0,
      "aria-details": 0,
      "aria-disabled": 0,
      "aria-hidden": 0,
      "aria-invalid": 0,
      "aria-keyshortcuts": 0,
      "aria-label": 0,
      "aria-roledescription": 0,
      "aria-autocomplete": 0,
      "aria-checked": 0,
      "aria-expanded": 0,
      "aria-haspopup": 0,
      "aria-level": 0,
      "aria-modal": 0,
      "aria-multiline": 0,
      "aria-multiselectable": 0,
      "aria-orientation": 0,
      "aria-placeholder": 0,
      "aria-pressed": 0,
      "aria-readonly": 0,
      "aria-required": 0,
      "aria-selected": 0,
      "aria-sort": 0,
      "aria-valuemax": 0,
      "aria-valuemin": 0,
      "aria-valuenow": 0,
      "aria-valuetext": 0,
      "aria-atomic": 0,
      "aria-busy": 0,
      "aria-live": 0,
      "aria-relevant": 0,
      "aria-dropeffect": 0,
      "aria-grabbed": 0,
      "aria-activedescendant": 0,
      "aria-colcount": 0,
      "aria-colindex": 0,
      "aria-colspan": 0,
      "aria-controls": 0,
      "aria-describedby": 0,
      "aria-errormessage": 0,
      "aria-flowto": 0,
      "aria-labelledby": 0,
      "aria-owns": 0,
      "aria-posinset": 0,
      "aria-rowcount": 0,
      "aria-rowindex": 0,
      "aria-rowspan": 0,
      "aria-setsize": 0,
      "aria-braillelabel": 0,
      "aria-brailleroledescription": 0,
      "aria-colindextext": 0,
      "aria-rowindextext": 0
    }, warnedProperties$1 = {}, rARIA$1 = RegExp(
      "^(aria)-[: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]*$"
    ), rARIACamel$1 = RegExp(
      "^(aria)[A-Z][: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]*$"
    ), didWarnValueNull = false, possibleStandardNames = {
      accept: "accept",
      acceptcharset: "acceptCharset",
      "accept-charset": "acceptCharset",
      accesskey: "accessKey",
      action: "action",
      allowfullscreen: "allowFullScreen",
      alt: "alt",
      as: "as",
      async: "async",
      autocapitalize: "autoCapitalize",
      autocomplete: "autoComplete",
      autocorrect: "autoCorrect",
      autofocus: "autoFocus",
      autoplay: "autoPlay",
      autosave: "autoSave",
      capture: "capture",
      cellpadding: "cellPadding",
      cellspacing: "cellSpacing",
      challenge: "challenge",
      charset: "charSet",
      checked: "checked",
      children: "children",
      cite: "cite",
      class: "className",
      classid: "classID",
      classname: "className",
      cols: "cols",
      colspan: "colSpan",
      content: "content",
      contenteditable: "contentEditable",
      contextmenu: "contextMenu",
      controls: "controls",
      controlslist: "controlsList",
      coords: "coords",
      crossorigin: "crossOrigin",
      dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
      data: "data",
      datetime: "dateTime",
      default: "default",
      defaultchecked: "defaultChecked",
      defaultvalue: "defaultValue",
      defer: "defer",
      dir: "dir",
      disabled: "disabled",
      disablepictureinpicture: "disablePictureInPicture",
      disableremoteplayback: "disableRemotePlayback",
      download: "download",
      draggable: "draggable",
      enctype: "encType",
      enterkeyhint: "enterKeyHint",
      fetchpriority: "fetchPriority",
      for: "htmlFor",
      form: "form",
      formmethod: "formMethod",
      formaction: "formAction",
      formenctype: "formEncType",
      formnovalidate: "formNoValidate",
      formtarget: "formTarget",
      frameborder: "frameBorder",
      headers: "headers",
      height: "height",
      hidden: "hidden",
      high: "high",
      href: "href",
      hreflang: "hrefLang",
      htmlfor: "htmlFor",
      httpequiv: "httpEquiv",
      "http-equiv": "httpEquiv",
      icon: "icon",
      id: "id",
      imagesizes: "imageSizes",
      imagesrcset: "imageSrcSet",
      inert: "inert",
      innerhtml: "innerHTML",
      inputmode: "inputMode",
      integrity: "integrity",
      is: "is",
      itemid: "itemID",
      itemprop: "itemProp",
      itemref: "itemRef",
      itemscope: "itemScope",
      itemtype: "itemType",
      keyparams: "keyParams",
      keytype: "keyType",
      kind: "kind",
      label: "label",
      lang: "lang",
      list: "list",
      loop: "loop",
      low: "low",
      manifest: "manifest",
      marginwidth: "marginWidth",
      marginheight: "marginHeight",
      max: "max",
      maxlength: "maxLength",
      media: "media",
      mediagroup: "mediaGroup",
      method: "method",
      min: "min",
      minlength: "minLength",
      multiple: "multiple",
      muted: "muted",
      name: "name",
      nomodule: "noModule",
      nonce: "nonce",
      novalidate: "noValidate",
      open: "open",
      optimum: "optimum",
      pattern: "pattern",
      placeholder: "placeholder",
      playsinline: "playsInline",
      poster: "poster",
      preload: "preload",
      profile: "profile",
      radiogroup: "radioGroup",
      readonly: "readOnly",
      referrerpolicy: "referrerPolicy",
      rel: "rel",
      required: "required",
      reversed: "reversed",
      role: "role",
      rows: "rows",
      rowspan: "rowSpan",
      sandbox: "sandbox",
      scope: "scope",
      scoped: "scoped",
      scrolling: "scrolling",
      seamless: "seamless",
      selected: "selected",
      shape: "shape",
      size: "size",
      sizes: "sizes",
      span: "span",
      spellcheck: "spellCheck",
      src: "src",
      srcdoc: "srcDoc",
      srclang: "srcLang",
      srcset: "srcSet",
      start: "start",
      step: "step",
      style: "style",
      summary: "summary",
      tabindex: "tabIndex",
      target: "target",
      title: "title",
      type: "type",
      usemap: "useMap",
      value: "value",
      width: "width",
      wmode: "wmode",
      wrap: "wrap",
      about: "about",
      accentheight: "accentHeight",
      "accent-height": "accentHeight",
      accumulate: "accumulate",
      additive: "additive",
      alignmentbaseline: "alignmentBaseline",
      "alignment-baseline": "alignmentBaseline",
      allowreorder: "allowReorder",
      alphabetic: "alphabetic",
      amplitude: "amplitude",
      arabicform: "arabicForm",
      "arabic-form": "arabicForm",
      ascent: "ascent",
      attributename: "attributeName",
      attributetype: "attributeType",
      autoreverse: "autoReverse",
      azimuth: "azimuth",
      basefrequency: "baseFrequency",
      baselineshift: "baselineShift",
      "baseline-shift": "baselineShift",
      baseprofile: "baseProfile",
      bbox: "bbox",
      begin: "begin",
      bias: "bias",
      by: "by",
      calcmode: "calcMode",
      capheight: "capHeight",
      "cap-height": "capHeight",
      clip: "clip",
      clippath: "clipPath",
      "clip-path": "clipPath",
      clippathunits: "clipPathUnits",
      cliprule: "clipRule",
      "clip-rule": "clipRule",
      color: "color",
      colorinterpolation: "colorInterpolation",
      "color-interpolation": "colorInterpolation",
      colorinterpolationfilters: "colorInterpolationFilters",
      "color-interpolation-filters": "colorInterpolationFilters",
      colorprofile: "colorProfile",
      "color-profile": "colorProfile",
      colorrendering: "colorRendering",
      "color-rendering": "colorRendering",
      contentscripttype: "contentScriptType",
      contentstyletype: "contentStyleType",
      cursor: "cursor",
      cx: "cx",
      cy: "cy",
      d: "d",
      datatype: "datatype",
      decelerate: "decelerate",
      descent: "descent",
      diffuseconstant: "diffuseConstant",
      direction: "direction",
      display: "display",
      divisor: "divisor",
      dominantbaseline: "dominantBaseline",
      "dominant-baseline": "dominantBaseline",
      dur: "dur",
      dx: "dx",
      dy: "dy",
      edgemode: "edgeMode",
      elevation: "elevation",
      enablebackground: "enableBackground",
      "enable-background": "enableBackground",
      end: "end",
      exponent: "exponent",
      externalresourcesrequired: "externalResourcesRequired",
      fill: "fill",
      fillopacity: "fillOpacity",
      "fill-opacity": "fillOpacity",
      fillrule: "fillRule",
      "fill-rule": "fillRule",
      filter: "filter",
      filterres: "filterRes",
      filterunits: "filterUnits",
      floodopacity: "floodOpacity",
      "flood-opacity": "floodOpacity",
      floodcolor: "floodColor",
      "flood-color": "floodColor",
      focusable: "focusable",
      fontfamily: "fontFamily",
      "font-family": "fontFamily",
      fontsize: "fontSize",
      "font-size": "fontSize",
      fontsizeadjust: "fontSizeAdjust",
      "font-size-adjust": "fontSizeAdjust",
      fontstretch: "fontStretch",
      "font-stretch": "fontStretch",
      fontstyle: "fontStyle",
      "font-style": "fontStyle",
      fontvariant: "fontVariant",
      "font-variant": "fontVariant",
      fontweight: "fontWeight",
      "font-weight": "fontWeight",
      format: "format",
      from: "from",
      fx: "fx",
      fy: "fy",
      g1: "g1",
      g2: "g2",
      glyphname: "glyphName",
      "glyph-name": "glyphName",
      glyphorientationhorizontal: "glyphOrientationHorizontal",
      "glyph-orientation-horizontal": "glyphOrientationHorizontal",
      glyphorientationvertical: "glyphOrientationVertical",
      "glyph-orientation-vertical": "glyphOrientationVertical",
      glyphref: "glyphRef",
      gradienttransform: "gradientTransform",
      gradientunits: "gradientUnits",
      hanging: "hanging",
      horizadvx: "horizAdvX",
      "horiz-adv-x": "horizAdvX",
      horizoriginx: "horizOriginX",
      "horiz-origin-x": "horizOriginX",
      ideographic: "ideographic",
      imagerendering: "imageRendering",
      "image-rendering": "imageRendering",
      in2: "in2",
      in: "in",
      inlist: "inlist",
      intercept: "intercept",
      k1: "k1",
      k2: "k2",
      k3: "k3",
      k4: "k4",
      k: "k",
      kernelmatrix: "kernelMatrix",
      kernelunitlength: "kernelUnitLength",
      kerning: "kerning",
      keypoints: "keyPoints",
      keysplines: "keySplines",
      keytimes: "keyTimes",
      lengthadjust: "lengthAdjust",
      letterspacing: "letterSpacing",
      "letter-spacing": "letterSpacing",
      lightingcolor: "lightingColor",
      "lighting-color": "lightingColor",
      limitingconeangle: "limitingConeAngle",
      local: "local",
      markerend: "markerEnd",
      "marker-end": "markerEnd",
      markerheight: "markerHeight",
      markermid: "markerMid",
      "marker-mid": "markerMid",
      markerstart: "markerStart",
      "marker-start": "markerStart",
      markerunits: "markerUnits",
      markerwidth: "markerWidth",
      mask: "mask",
      maskcontentunits: "maskContentUnits",
      maskunits: "maskUnits",
      mathematical: "mathematical",
      mode: "mode",
      numoctaves: "numOctaves",
      offset: "offset",
      opacity: "opacity",
      operator: "operator",
      order: "order",
      orient: "orient",
      orientation: "orientation",
      origin: "origin",
      overflow: "overflow",
      overlineposition: "overlinePosition",
      "overline-position": "overlinePosition",
      overlinethickness: "overlineThickness",
      "overline-thickness": "overlineThickness",
      paintorder: "paintOrder",
      "paint-order": "paintOrder",
      panose1: "panose1",
      "panose-1": "panose1",
      pathlength: "pathLength",
      patterncontentunits: "patternContentUnits",
      patterntransform: "patternTransform",
      patternunits: "patternUnits",
      pointerevents: "pointerEvents",
      "pointer-events": "pointerEvents",
      points: "points",
      pointsatx: "pointsAtX",
      pointsaty: "pointsAtY",
      pointsatz: "pointsAtZ",
      popover: "popover",
      popovertarget: "popoverTarget",
      popovertargetaction: "popoverTargetAction",
      prefix: "prefix",
      preservealpha: "preserveAlpha",
      preserveaspectratio: "preserveAspectRatio",
      primitiveunits: "primitiveUnits",
      property: "property",
      r: "r",
      radius: "radius",
      refx: "refX",
      refy: "refY",
      renderingintent: "renderingIntent",
      "rendering-intent": "renderingIntent",
      repeatcount: "repeatCount",
      repeatdur: "repeatDur",
      requiredextensions: "requiredExtensions",
      requiredfeatures: "requiredFeatures",
      resource: "resource",
      restart: "restart",
      result: "result",
      results: "results",
      rotate: "rotate",
      rx: "rx",
      ry: "ry",
      scale: "scale",
      security: "security",
      seed: "seed",
      shaperendering: "shapeRendering",
      "shape-rendering": "shapeRendering",
      slope: "slope",
      spacing: "spacing",
      specularconstant: "specularConstant",
      specularexponent: "specularExponent",
      speed: "speed",
      spreadmethod: "spreadMethod",
      startoffset: "startOffset",
      stddeviation: "stdDeviation",
      stemh: "stemh",
      stemv: "stemv",
      stitchtiles: "stitchTiles",
      stopcolor: "stopColor",
      "stop-color": "stopColor",
      stopopacity: "stopOpacity",
      "stop-opacity": "stopOpacity",
      strikethroughposition: "strikethroughPosition",
      "strikethrough-position": "strikethroughPosition",
      strikethroughthickness: "strikethroughThickness",
      "strikethrough-thickness": "strikethroughThickness",
      string: "string",
      stroke: "stroke",
      strokedasharray: "strokeDasharray",
      "stroke-dasharray": "strokeDasharray",
      strokedashoffset: "strokeDashoffset",
      "stroke-dashoffset": "strokeDashoffset",
      strokelinecap: "strokeLinecap",
      "stroke-linecap": "strokeLinecap",
      strokelinejoin: "strokeLinejoin",
      "stroke-linejoin": "strokeLinejoin",
      strokemiterlimit: "strokeMiterlimit",
      "stroke-miterlimit": "strokeMiterlimit",
      strokewidth: "strokeWidth",
      "stroke-width": "strokeWidth",
      strokeopacity: "strokeOpacity",
      "stroke-opacity": "strokeOpacity",
      suppresscontenteditablewarning: "suppressContentEditableWarning",
      suppresshydrationwarning: "suppressHydrationWarning",
      surfacescale: "surfaceScale",
      systemlanguage: "systemLanguage",
      tablevalues: "tableValues",
      targetx: "targetX",
      targety: "targetY",
      textanchor: "textAnchor",
      "text-anchor": "textAnchor",
      textdecoration: "textDecoration",
      "text-decoration": "textDecoration",
      textlength: "textLength",
      textrendering: "textRendering",
      "text-rendering": "textRendering",
      to: "to",
      transform: "transform",
      transformorigin: "transformOrigin",
      "transform-origin": "transformOrigin",
      typeof: "typeof",
      u1: "u1",
      u2: "u2",
      underlineposition: "underlinePosition",
      "underline-position": "underlinePosition",
      underlinethickness: "underlineThickness",
      "underline-thickness": "underlineThickness",
      unicode: "unicode",
      unicodebidi: "unicodeBidi",
      "unicode-bidi": "unicodeBidi",
      unicoderange: "unicodeRange",
      "unicode-range": "unicodeRange",
      unitsperem: "unitsPerEm",
      "units-per-em": "unitsPerEm",
      unselectable: "unselectable",
      valphabetic: "vAlphabetic",
      "v-alphabetic": "vAlphabetic",
      values: "values",
      vectoreffect: "vectorEffect",
      "vector-effect": "vectorEffect",
      version: "version",
      vertadvy: "vertAdvY",
      "vert-adv-y": "vertAdvY",
      vertoriginx: "vertOriginX",
      "vert-origin-x": "vertOriginX",
      vertoriginy: "vertOriginY",
      "vert-origin-y": "vertOriginY",
      vhanging: "vHanging",
      "v-hanging": "vHanging",
      videographic: "vIdeographic",
      "v-ideographic": "vIdeographic",
      viewbox: "viewBox",
      viewtarget: "viewTarget",
      visibility: "visibility",
      vmathematical: "vMathematical",
      "v-mathematical": "vMathematical",
      vocab: "vocab",
      widths: "widths",
      wordspacing: "wordSpacing",
      "word-spacing": "wordSpacing",
      writingmode: "writingMode",
      "writing-mode": "writingMode",
      x1: "x1",
      x2: "x2",
      x: "x",
      xchannelselector: "xChannelSelector",
      xheight: "xHeight",
      "x-height": "xHeight",
      xlinkactuate: "xlinkActuate",
      "xlink:actuate": "xlinkActuate",
      xlinkarcrole: "xlinkArcrole",
      "xlink:arcrole": "xlinkArcrole",
      xlinkhref: "xlinkHref",
      "xlink:href": "xlinkHref",
      xlinkrole: "xlinkRole",
      "xlink:role": "xlinkRole",
      xlinkshow: "xlinkShow",
      "xlink:show": "xlinkShow",
      xlinktitle: "xlinkTitle",
      "xlink:title": "xlinkTitle",
      xlinktype: "xlinkType",
      "xlink:type": "xlinkType",
      xmlbase: "xmlBase",
      "xml:base": "xmlBase",
      xmllang: "xmlLang",
      "xml:lang": "xmlLang",
      xmlns: "xmlns",
      "xml:space": "xmlSpace",
      xmlnsxlink: "xmlnsXlink",
      "xmlns:xlink": "xmlnsXlink",
      xmlspace: "xmlSpace",
      y1: "y1",
      y2: "y2",
      y: "y",
      ychannelselector: "yChannelSelector",
      z: "z",
      zoomandpan: "zoomAndPan"
    }, warnedProperties = {}, EVENT_NAME_REGEX = /^on./, INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/, rARIA = RegExp(
      "^(aria)-[: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]*$"
    ), rARIACamel = RegExp(
      "^(aria)[A-Z][: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]*$"
    ), badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, msPattern$1 = /^-ms-/, hyphenPattern = /-(.)/g, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = false, warnedForInfinityValue = false, matchHtmlRegExp = /["'&<>]/, uppercasePattern = /([A-Z])/g, msPattern = /^ms-/, isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i, ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, NotPending = Object.freeze({
      pending: false,
      data: null,
      method: null,
      action: null
    }), previousDispatcher = ReactDOMSharedInternals.d;
    ReactDOMSharedInternals.d = {
      f: previousDispatcher.f,
      r: previousDispatcher.r,
      D: function(href) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if ("string" === typeof href && href) {
            if (!resumableState.dnsResources.hasOwnProperty(href)) {
              resumableState.dnsResources[href] = EXISTS;
              resumableState = renderState.headers;
              var header, JSCompiler_temp;
              if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity)
                JSCompiler_temp = (header = "<" + escapeHrefForLinkHeaderURLContext(href) + ">; rel=dns-prefetch", 0 <= (resumableState.remainingCapacity -= header.length + 2));
              JSCompiler_temp ? (renderState.resets.dns[href] = EXISTS, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (header = [], pushLinkImpl(header, { href, rel: "dns-prefetch" }), renderState.preconnects.add(header));
            }
            enqueueFlush(request);
          }
        } else previousDispatcher.D(href);
      },
      C: function(href, crossOrigin) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if ("string" === typeof href && href) {
            var bucket = "use-credentials" === crossOrigin ? "credentials" : "string" === typeof crossOrigin ? "anonymous" : "default";
            if (!resumableState.connectResources[bucket].hasOwnProperty(href)) {
              resumableState.connectResources[bucket][href] = EXISTS;
              resumableState = renderState.headers;
              var header, JSCompiler_temp;
              if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity) {
                JSCompiler_temp = "<" + escapeHrefForLinkHeaderURLContext(href) + ">; rel=preconnect";
                if ("string" === typeof crossOrigin) {
                  var escapedCrossOrigin = escapeStringForLinkHeaderQuotedParamValueContext(
                    crossOrigin,
                    "crossOrigin"
                  );
                  JSCompiler_temp += '; crossorigin="' + escapedCrossOrigin + '"';
                }
                JSCompiler_temp = (header = JSCompiler_temp, 0 <= (resumableState.remainingCapacity -= header.length + 2));
              }
              JSCompiler_temp ? (renderState.resets.connect[bucket][href] = EXISTS, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (bucket = [], pushLinkImpl(bucket, {
                rel: "preconnect",
                href,
                crossOrigin
              }), renderState.preconnects.add(bucket));
            }
            enqueueFlush(request);
          }
        } else previousDispatcher.C(href, crossOrigin);
      },
      L: function(href, as, options) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (as && href) {
            switch (as) {
              case "image":
                if (options) {
                  var imageSrcSet = options.imageSrcSet;
                  var imageSizes = options.imageSizes;
                  var fetchPriority = options.fetchPriority;
                }
                var key = imageSrcSet ? imageSrcSet + "\n" + (imageSizes || "") : href;
                if (resumableState.imageResources.hasOwnProperty(key)) return;
                resumableState.imageResources[key] = PRELOAD_NO_CREDS;
                resumableState = renderState.headers;
                var header;
                resumableState && 0 < resumableState.remainingCapacity && "string" !== typeof imageSrcSet && "high" === fetchPriority && (header = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key] = PRELOAD_NO_CREDS, resumableState.highImagePreloads && (resumableState.highImagePreloads += ", "), resumableState.highImagePreloads += header) : (resumableState = [], pushLinkImpl(
                  resumableState,
                  assign(
                    {
                      rel: "preload",
                      href: imageSrcSet ? void 0 : href,
                      as
                    },
                    options
                  )
                ), "high" === fetchPriority ? renderState.highImagePreloads.add(resumableState) : (renderState.bulkPreloads.add(resumableState), renderState.preloads.images.set(key, resumableState)));
                break;
              case "style":
                if (resumableState.styleResources.hasOwnProperty(href)) return;
                imageSrcSet = [];
                pushLinkImpl(
                  imageSrcSet,
                  assign({ rel: "preload", href, as }, options)
                );
                resumableState.styleResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
                renderState.preloads.stylesheets.set(href, imageSrcSet);
                renderState.bulkPreloads.add(imageSrcSet);
                break;
              case "script":
                if (resumableState.scriptResources.hasOwnProperty(href)) return;
                imageSrcSet = [];
                renderState.preloads.scripts.set(href, imageSrcSet);
                renderState.bulkPreloads.add(imageSrcSet);
                pushLinkImpl(
                  imageSrcSet,
                  assign({ rel: "preload", href, as }, options)
                );
                resumableState.scriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
                break;
              default:
                if (resumableState.unknownResources.hasOwnProperty(as)) {
                  if (imageSrcSet = resumableState.unknownResources[as], imageSrcSet.hasOwnProperty(href))
                    return;
                } else
                  imageSrcSet = {}, resumableState.unknownResources[as] = imageSrcSet;
                imageSrcSet[href] = PRELOAD_NO_CREDS;
                if ((resumableState = renderState.headers) && 0 < resumableState.remainingCapacity && "font" === as && (key = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= key.length + 2)))
                  renderState.resets.font[href] = PRELOAD_NO_CREDS, resumableState.fontPreloads && (resumableState.fontPreloads += ", "), resumableState.fontPreloads += key;
                else
                  switch (resumableState = [], href = assign(
                    { rel: "preload", href, as },
                    options
                  ), pushLinkImpl(resumableState, href), as) {
                    case "font":
                      renderState.fontPreloads.add(resumableState);
                      break;
                    default:
                      renderState.bulkPreloads.add(resumableState);
                  }
            }
            enqueueFlush(request);
          }
        } else previousDispatcher.L(href, as, options);
      },
      m: function(href, options) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (href) {
            var as = options && "string" === typeof options.as ? options.as : "script";
            switch (as) {
              case "script":
                if (resumableState.moduleScriptResources.hasOwnProperty(href))
                  return;
                as = [];
                resumableState.moduleScriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
                renderState.preloads.moduleScripts.set(href, as);
                break;
              default:
                if (resumableState.moduleUnknownResources.hasOwnProperty(as)) {
                  var resources = resumableState.unknownResources[as];
                  if (resources.hasOwnProperty(href)) return;
                } else
                  resources = {}, resumableState.moduleUnknownResources[as] = resources;
                as = [];
                resources[href] = PRELOAD_NO_CREDS;
            }
            pushLinkImpl(
              as,
              assign({ rel: "modulepreload", href }, options)
            );
            renderState.bulkPreloads.add(as);
            enqueueFlush(request);
          }
        } else previousDispatcher.m(href, options);
      },
      X: function(src2, options) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (src2) {
            var resourceState = resumableState.scriptResources.hasOwnProperty(
              src2
            ) ? resumableState.scriptResources[src2] : void 0;
            resourceState !== EXISTS && (resumableState.scriptResources[src2] = EXISTS, options = assign({ src: src2, async: true }, options), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.scripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
          }
        } else previousDispatcher.X(src2, options);
      },
      S: function(href, precedence, options) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (href) {
            precedence = precedence || "default";
            var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(href) ? resumableState.styleResources[href] : void 0;
            resourceState !== EXISTS && (resumableState.styleResources[href] = EXISTS, styleQueue || (styleQueue = {
              precedence: escapeTextForBrowser(precedence),
              rules: [],
              hrefs: [],
              sheets: /* @__PURE__ */ new Map()
            }, renderState.styles.set(precedence, styleQueue)), precedence = {
              state: PENDING$1,
              props: assign(
                {
                  rel: "stylesheet",
                  href,
                  "data-precedence": precedence
                },
                options
              )
            }, resourceState && (2 === resourceState.length && adoptPreloadCredentials(precedence.props, resourceState), (renderState = renderState.preloads.stylesheets.get(href)) && 0 < renderState.length ? renderState.length = 0 : precedence.state = PRELOADED), styleQueue.sheets.set(href, precedence), enqueueFlush(request));
          }
        } else previousDispatcher.S(href, precedence, options);
      },
      M: function(src2, options) {
        var request = currentRequest ? currentRequest : null;
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (src2) {
            var resourceState = resumableState.moduleScriptResources.hasOwnProperty(src2) ? resumableState.moduleScriptResources[src2] : void 0;
            resourceState !== EXISTS && (resumableState.moduleScriptResources[src2] = EXISTS, options = assign(
              { src: src2, type: "module", async: true },
              options
            ), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.moduleScripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
          }
        } else previousDispatcher.M(src2, options);
      }
    };
    var NothingSent = 0, SentCompleteSegmentFunction = 1, SentCompleteBoundaryFunction = 2, SentClientRenderFunction = 4, SentStyleInsertionFunction = 8, SentCompletedShellId = 32, SentMarkShellTime = 64, EXISTS = null, PRELOAD_NO_CREDS = [];
    Object.freeze(PRELOAD_NO_CREDS);
    var currentlyFlushingRenderState = null, endInlineScript = "<\/script>", scriptRegex = /(<\/|<)(s)(cript)/gi;
    var didWarnForNewBooleanPropsWithEmptyValue = {};
    var ROOT_HTML_MODE = 0, HTML_HTML_MODE = 1, HTML_MODE = 2, HTML_HEAD_MODE = 3, SVG_MODE = 4, MATHML_MODE = 5, HTML_TABLE_MODE = 6, HTML_TABLE_BODY_MODE = 7, HTML_TABLE_ROW_MODE = 8, HTML_COLGROUP_MODE = 9, styleNameCache = /* @__PURE__ */ new Map(), styleAttributeStart = ' style="', styleAssign = ":", styleSeparator = ";", attributeSeparator = " ", attributeAssign = '="', attributeEnd = '"', attributeEmptyString = '=""', actionJavaScriptURL = escapeTextForBrowser(
      "javascript:throw new Error('React form unexpectedly submitted.')"
    ), endOfStartTag = ">", endOfStartTagSelfClosing = "/>", didWarnDefaultInputValue = false, didWarnDefaultChecked = false, didWarnDefaultSelectValue = false, didWarnDefaultTextareaValue = false, didWarnInvalidOptionChildren = false, didWarnInvalidOptionInnerHTML = false, didWarnSelectedSetOnOption = false, didWarnFormActionType = false, didWarnFormActionName = false, didWarnFormActionTarget = false, didWarnFormActionMethod = false, formReplayingRuntimeScript = `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`, styleRegex = /(<\/|<)(s)(tyle)/gi, leadingNewline = "\n", VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = /* @__PURE__ */ new Map(), endTagCache = /* @__PURE__ */ new Map(), shellTimeRuntimeScript = "requestAnimationFrame(function(){$RT=performance.now()});", placeholder1 = '<template id="', placeholder2 = '"></template>', startCompletedSuspenseBoundary = "<!--$-->", startPendingSuspenseBoundary1 = '<!--$?--><template id="', startPendingSuspenseBoundary2 = '"></template>', startClientRenderedSuspenseBoundary = "<!--$!-->", endSuspenseBoundary = "<!--/$-->", clientRenderedSuspenseBoundaryError1 = "<template", clientRenderedSuspenseBoundaryErrorAttrInterstitial = '"', clientRenderedSuspenseBoundaryError1A = ' data-dgst="', clientRenderedSuspenseBoundaryError1B = ' data-msg="', clientRenderedSuspenseBoundaryError1C = ' data-stck="', clientRenderedSuspenseBoundaryError1D = ' data-cstck="', clientRenderedSuspenseBoundaryError2 = "></template>", startSegmentHTML = '<div hidden id="', startSegmentHTML2 = '">', endSegmentHTML = "</div>", startSegmentSVG = '<svg aria-hidden="true" style="display:none" id="', startSegmentSVG2 = '">', endSegmentSVG = "</svg>", startSegmentMathML = '<math aria-hidden="true" style="display:none" id="', startSegmentMathML2 = '">', endSegmentMathML = "</math>", startSegmentTable = '<table hidden id="', startSegmentTable2 = '">', endSegmentTable = "</table>", startSegmentTableBody = '<table hidden><tbody id="', startSegmentTableBody2 = '">', endSegmentTableBody = "</tbody></table>", startSegmentTableRow = '<table hidden><tr id="', startSegmentTableRow2 = '">', endSegmentTableRow = "</tr></table>", startSegmentColGroup = '<table hidden><colgroup id="', startSegmentColGroup2 = '">', endSegmentColGroup = "</colgroup></table>", completeSegmentScript1Full = '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("', completeSegmentScript1Partial = '$RS("', completeSegmentScript2 = '","', completeSegmentScriptEnd = '")<\/script>', completeBoundaryScriptFunctionOnly = '$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};\n$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};', completeBoundaryScript1Partial = '$RC("', completeBoundaryWithStylesScript1FullPartial = '$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=\n"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=\n"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("', completeBoundaryWithStylesScript1Partial = '$RR("', completeBoundaryScript2 = '","', completeBoundaryScript3a = '",', completeBoundaryScript3b = '"', completeBoundaryScriptEnd = ")<\/script>", clientRenderScriptFunctionOnly = '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};', clientRenderScript1Full = '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("', clientRenderScript1Partial = '$RX("', clientRenderScript1A = '"', clientRenderErrorScriptArgInterstitial = ",", clientRenderScriptEnd = ")<\/script>", regexForJSStringsInInstructionScripts = /[<\u2028\u2029]/g, regexForJSStringsInScripts = /[&><\u2028\u2029]/g, lateStyleTagResourceOpen1 = ' media="not all" data-precedence="', lateStyleTagResourceOpen2 = '" data-href="', lateStyleTagResourceOpen3 = '">', lateStyleTagTemplateClose = "</style>", currentlyRenderingBoundaryHasStylesToHoist = false, destinationHasCapacity = true, stylesheetFlushingQueue = [], styleTagResourceOpen1 = ' data-precedence="', styleTagResourceOpen2 = '" data-href="', spaceSeparator = " ", styleTagResourceOpen3 = '">', styleTagResourceClose = "</style>", completedShellIdAttributeStart = ' id="', arrayFirstOpenBracket = "[", arraySubsequentOpenBracket = ",[", arrayInterstitial = ",", arrayCloseBracket = "]", PENDING$1 = 0, PRELOADED = 1, PREAMBLE = 2, LATE = 3, regexForHrefInLinkHeaderURLContext = /[<>\r\n]/g, regexForLinkHeaderQuotedParamValueContext = /["';,\r\n]/g, doctypeChunk = "", bind2 = Function.prototype.bind, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), emptyContextObject = {};
    Object.freeze(emptyContextObject);
    var rendererSigil = {};
    var currentActiveSnapshot = null, didWarnAboutNoopUpdateForComponent = {}, didWarnAboutDeprecatedWillMount = {};
    var didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
    var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
    var didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
    var didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutContextTypes$1 = /* @__PURE__ */ new Set();
    var didWarnAboutChildContextTypes = /* @__PURE__ */ new Set();
    var didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
    var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
    var classComponentUpdater = {
      enqueueSetState: function(inst, payload, callback) {
        var internals = inst._reactInternals;
        null === internals.queue ? warnNoop(inst, "setState") : (internals.queue.push(payload), void 0 !== callback && null !== callback && warnOnInvalidCallback(callback));
      },
      enqueueReplaceState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        inst.replace = true;
        inst.queue = [payload];
        void 0 !== callback && null !== callback && warnOnInvalidCallback(callback);
      },
      enqueueForceUpdate: function(inst, callback) {
        null === inst._reactInternals.queue ? warnNoop(inst, "forceUpdate") : void 0 !== callback && null !== callback && warnOnInvalidCallback(callback);
      }
    }, emptyTreeContext = { id: 1, overflow: "" }, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2, SuspenseException = Error(
      "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
    ), suspendedThenable = null, objectIs = "function" === typeof Object.is ? Object.is : is, currentlyRenderingComponent = null, currentlyRenderingTask = null, currentlyRenderingRequest = null, currentlyRenderingKeyPath = null, firstWorkInProgressHook = null, workInProgressHook = null, isReRender = false, didScheduleRenderPhaseUpdate = false, localIdCounter = 0, actionStateCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, thenableState = null, renderPhaseUpdates = null, numberOfReRenders = 0, isInHookUserCodeInDev = false, currentHookNameInDev, HooksDispatcher = {
      readContext,
      use: function(usable) {
        if (null !== usable && "object" === typeof usable) {
          if ("function" === typeof usable.then)
            return unwrapThenable(usable);
          if (usable.$$typeof === REACT_CONTEXT_TYPE)
            return readContext(usable);
        }
        throw Error(
          "An unsupported type was passed to use(): " + String(usable)
        );
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        resolveCurrentlyRenderingComponent();
        return context._currentValue2;
      },
      useMemo,
      useReducer,
      useRef: function(initialValue) {
        currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
        workInProgressHook = createWorkInProgressHook();
        var previousRef = workInProgressHook.memoizedState;
        return null === previousRef ? (initialValue = { current: initialValue }, Object.seal(initialValue), workInProgressHook.memoizedState = initialValue) : previousRef;
      },
      useState: function(initialState2) {
        currentHookNameInDev = "useState";
        return useReducer(basicStateReducer, initialState2);
      },
      useInsertionEffect: noop2,
      useLayoutEffect: noop2,
      useCallback: function(callback, deps) {
        return useMemo(function() {
          return callback;
        }, deps);
      },
      useImperativeHandle: noop2,
      useEffect: noop2,
      useDebugValue: noop2,
      useDeferredValue: function(value, initialValue) {
        resolveCurrentlyRenderingComponent();
        return void 0 !== initialValue ? initialValue : value;
      },
      useTransition: function() {
        resolveCurrentlyRenderingComponent();
        return [false, unsupportedStartTransition];
      },
      useId: function() {
        var treeId = currentlyRenderingTask.treeContext;
        var overflow = treeId.overflow;
        treeId = treeId.id;
        treeId = (treeId & ~(1 << 32 - clz32(treeId) - 1)).toString(32) + overflow;
        var resumableState = currentResumableState;
        if (null === resumableState)
          throw Error(
            "Invalid hook call. Hooks can only be called inside of the body of a function component."
          );
        overflow = localIdCounter++;
        treeId = "_" + resumableState.idPrefix + "R_" + treeId;
        0 < overflow && (treeId += "H" + overflow.toString(32));
        return treeId + "_";
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        if (void 0 === getServerSnapshot)
          throw Error(
            "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
          );
        return getServerSnapshot();
      },
      useOptimistic: function(passthrough) {
        resolveCurrentlyRenderingComponent();
        return [passthrough, unsupportedSetOptimisticState];
      },
      useActionState,
      useFormState: useActionState,
      useHostTransitionStatus: function() {
        resolveCurrentlyRenderingComponent();
        return NotPending;
      },
      useMemoCache: function(size) {
        for (var data = Array(size), i = 0; i < size; i++)
          data[i] = REACT_MEMO_CACHE_SENTINEL;
        return data;
      },
      useCacheRefresh: function() {
        return unsupportedRefresh;
      },
      useEffectEvent: function() {
        return throwOnUseEffectEventCall;
      }
    }, currentResumableState = null, currentTaskInDEV = null, DefaultAsyncDispatcher = {
      getCacheForType: function() {
        throw Error("Not implemented.");
      },
      cacheSignal: function() {
        throw Error("Not implemented.");
      },
      getOwner: function() {
        return null === currentTaskInDEV ? null : currentTaskInDEV.componentStack;
      }
    }, disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
    disabledLog.__reactDisabledLog = true;
    var prefix, suffix, reentry = false;
    var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)();
    var callComponent = {
      react_stack_bottom_frame: function(Component, props, secondArg) {
        return Component(props, secondArg);
      }
    }, callComponentInDEV = callComponent.react_stack_bottom_frame.bind(callComponent), callRender = {
      react_stack_bottom_frame: function(instance) {
        return instance.render();
      }
    }, callRenderInDEV = callRender.react_stack_bottom_frame.bind(callRender), callLazyInit = {
      react_stack_bottom_frame: function(lazy) {
        var init2 = lazy._init;
        return init2(lazy._payload);
      }
    }, callLazyInitInDEV = callLazyInit.react_stack_bottom_frame.bind(callLazyInit), lastResetTime = 0;
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var localPerformance = performance;
      var getCurrentTime = function() {
        return localPerformance.now();
      };
    } else {
      var localDate = Date;
      getCurrentTime = function() {
        return localDate.now();
      };
    }
    var CLIENT_RENDERED = 4, PENDING = 0, COMPLETED = 1, FLUSHED = 2, ABORTED = 3, ERRORED = 4, POSTPONED = 5, CLOSED = 14, currentRequest = null, didWarnAboutBadClass = {}, didWarnAboutContextTypes = {}, didWarnAboutContextTypeOnFunctionComponent = {}, didWarnAboutGetDerivedStateOnFunctionComponent = {}, didWarnAboutReassigningProps = false, didWarnAboutGenerators = false, didWarnAboutMaps = false, flushedByteSize = 0, flushingPartialBoundaries = false;
    reactDomServerLegacy_node_development.renderToStaticMarkup = function(children, options) {
      return renderToStringImpl(
        children,
        options,
        true,
        'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server'
      );
    };
    reactDomServerLegacy_node_development.renderToString = function(children, options) {
      return renderToStringImpl(
        children,
        options,
        false,
        'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server'
      );
    };
    reactDomServerLegacy_node_development.version = "19.2.4";
  })();
  return reactDomServerLegacy_node_development;
}
var reactDomServer_node_development = {};
var hasRequiredReactDomServer_node_development;
function requireReactDomServer_node_development() {
  if (hasRequiredReactDomServer_node_development) return reactDomServer_node_development;
  hasRequiredReactDomServer_node_development = 1;
  "production" !== process.env.NODE_ENV && (function() {
    function styleReplacer(match, prefix2, s2, suffix2) {
      return "" + prefix2 + ("s" === s2 ? "\\73 " : "\\53 ") + suffix2;
    }
    function scriptReplacer(match, prefix2, s2, suffix2) {
      return "" + prefix2 + ("s" === s2 ? "\\u0073" : "\\u0053") + suffix2;
    }
    function getIteratorFn(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable)
        return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    function objectName(object) {
      object = Object.prototype.toString.call(object);
      return object.slice(8, object.length - 1);
    }
    function describeKeyForErrorMessage(key) {
      var encodedKey = JSON.stringify(key);
      return '"' + key + '"' === encodedKey ? key : encodedKey;
    }
    function describeValueForErrorMessage(value) {
      switch (typeof value) {
        case "string":
          return JSON.stringify(
            10 >= value.length ? value : value.slice(0, 10) + "..."
          );
        case "object":
          if (isArrayImpl(value)) return "[...]";
          if (null !== value && value.$$typeof === CLIENT_REFERENCE_TAG)
            return "client";
          value = objectName(value);
          return "Object" === value ? "{...}" : value;
        case "function":
          return value.$$typeof === CLIENT_REFERENCE_TAG ? "client" : (value = value.displayName || value.name) ? "function " + value : "function";
        default:
          return String(value);
      }
    }
    function describeElementType(type2) {
      if ("string" === typeof type2) return type2;
      switch (type2) {
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
      }
      if ("object" === typeof type2)
        switch (type2.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            return describeElementType(type2.render);
          case REACT_MEMO_TYPE:
            return describeElementType(type2.type);
          case REACT_LAZY_TYPE:
            var payload = type2._payload;
            type2 = type2._init;
            try {
              return describeElementType(type2(payload));
            } catch (x2) {
            }
        }
      return "";
    }
    function describeObjectForErrorMessage(objectOrArray, expandedName) {
      var objKind = objectName(objectOrArray);
      if ("Object" !== objKind && "Array" !== objKind) return objKind;
      var start = -1, length = 0;
      if (isArrayImpl(objectOrArray))
        if (jsxChildrenParents.has(objectOrArray)) {
          var type2 = jsxChildrenParents.get(objectOrArray);
          objKind = "<" + describeElementType(type2) + ">";
          for (var i = 0; i < objectOrArray.length; i++) {
            var value = objectOrArray[i];
            value = "string" === typeof value ? value : "object" === typeof value && null !== value ? "{" + describeObjectForErrorMessage(value) + "}" : "{" + describeValueForErrorMessage(value) + "}";
            "" + i === expandedName ? (start = objKind.length, length = value.length, objKind += value) : objKind = 15 > value.length && 40 > objKind.length + value.length ? objKind + value : objKind + "{...}";
          }
          objKind += "</" + describeElementType(type2) + ">";
        } else {
          objKind = "[";
          for (type2 = 0; type2 < objectOrArray.length; type2++)
            0 < type2 && (objKind += ", "), i = objectOrArray[type2], i = "object" === typeof i && null !== i ? describeObjectForErrorMessage(i) : describeValueForErrorMessage(i), "" + type2 === expandedName ? (start = objKind.length, length = i.length, objKind += i) : objKind = 10 > i.length && 40 > objKind.length + i.length ? objKind + i : objKind + "...";
          objKind += "]";
        }
      else if (objectOrArray.$$typeof === REACT_ELEMENT_TYPE)
        objKind = "<" + describeElementType(objectOrArray.type) + "/>";
      else {
        if (objectOrArray.$$typeof === CLIENT_REFERENCE_TAG) return "client";
        if (jsxPropsParents.has(objectOrArray)) {
          objKind = jsxPropsParents.get(objectOrArray);
          objKind = "<" + (describeElementType(objKind) || "...");
          type2 = Object.keys(objectOrArray);
          for (i = 0; i < type2.length; i++) {
            objKind += " ";
            value = type2[i];
            objKind += describeKeyForErrorMessage(value) + "=";
            var _value2 = objectOrArray[value];
            var _substr2 = value === expandedName && "object" === typeof _value2 && null !== _value2 ? describeObjectForErrorMessage(_value2) : describeValueForErrorMessage(_value2);
            "string" !== typeof _value2 && (_substr2 = "{" + _substr2 + "}");
            value === expandedName ? (start = objKind.length, length = _substr2.length, objKind += _substr2) : objKind = 10 > _substr2.length && 40 > objKind.length + _substr2.length ? objKind + _substr2 : objKind + "...";
          }
          objKind += ">";
        } else {
          objKind = "{";
          type2 = Object.keys(objectOrArray);
          for (i = 0; i < type2.length; i++)
            0 < i && (objKind += ", "), value = type2[i], objKind += describeKeyForErrorMessage(value) + ": ", _value2 = objectOrArray[value], _value2 = "object" === typeof _value2 && null !== _value2 ? describeObjectForErrorMessage(_value2) : describeValueForErrorMessage(_value2), value === expandedName ? (start = objKind.length, length = _value2.length, objKind += _value2) : objKind = 10 > _value2.length && 40 > objKind.length + _value2.length ? objKind + _value2 : objKind + "...";
          objKind += "}";
        }
      }
      return void 0 === expandedName ? objKind : -1 < start && 0 < length ? (objectOrArray = " ".repeat(start) + "^".repeat(length), "\n  " + objKind + "\n  " + objectOrArray) : "\n  " + objKind;
    }
    function flushBuffered(destination) {
      "function" === typeof destination.flush && destination.flush();
    }
    function writeChunk(destination, chunk2) {
      if ("string" === typeof chunk2) {
        if (0 !== chunk2.length)
          if (2048 < 3 * chunk2.length)
            0 < writtenBytes && (writeToDestination(
              destination,
              currentView.subarray(0, writtenBytes)
            ), currentView = new Uint8Array(2048), writtenBytes = 0), writeToDestination(destination, chunk2);
          else {
            var target = currentView;
            0 < writtenBytes && (target = currentView.subarray(writtenBytes));
            target = textEncoder2.encodeInto(chunk2, target);
            var read = target.read;
            writtenBytes += target.written;
            read < chunk2.length && (writeToDestination(
              destination,
              currentView.subarray(0, writtenBytes)
            ), currentView = new Uint8Array(2048), writtenBytes = textEncoder2.encodeInto(
              chunk2.slice(read),
              currentView
            ).written);
            2048 === writtenBytes && (writeToDestination(destination, currentView), currentView = new Uint8Array(2048), writtenBytes = 0);
          }
      } else
        0 !== chunk2.byteLength && (2048 < chunk2.byteLength ? (0 < writtenBytes && (writeToDestination(
          destination,
          currentView.subarray(0, writtenBytes)
        ), currentView = new Uint8Array(2048), writtenBytes = 0), writeToDestination(destination, chunk2)) : (target = currentView.length - writtenBytes, target < chunk2.byteLength && (0 === target ? writeToDestination(destination, currentView) : (currentView.set(chunk2.subarray(0, target), writtenBytes), writtenBytes += target, writeToDestination(destination, currentView), chunk2 = chunk2.subarray(target)), currentView = new Uint8Array(2048), writtenBytes = 0), currentView.set(chunk2, writtenBytes), writtenBytes += chunk2.byteLength, 2048 === writtenBytes && (writeToDestination(destination, currentView), currentView = new Uint8Array(2048), writtenBytes = 0)));
    }
    function writeToDestination(destination, view) {
      destination = destination.write(view);
      destinationHasCapacity$1 = destinationHasCapacity$1 && destination;
    }
    function writeChunkAndReturn(destination, chunk2) {
      writeChunk(destination, chunk2);
      return destinationHasCapacity$1;
    }
    function completeWriting(destination) {
      currentView && 0 < writtenBytes && destination.write(currentView.subarray(0, writtenBytes));
      currentView = null;
      writtenBytes = 0;
      destinationHasCapacity$1 = true;
    }
    function stringToPrecomputedChunk(content2) {
      content2 = textEncoder2.encode(content2);
      2048 < content2.byteLength && console.error(
        "precomputed chunks must be smaller than the view size configured for this host. This is a bug in React."
      );
      return content2;
    }
    function byteLengthOfChunk(chunk2) {
      return "string" === typeof chunk2 ? Buffer.byteLength(chunk2, "utf8") : chunk2.byteLength;
    }
    function typeName(value) {
      return "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
    }
    function willCoercionThrow(value) {
      try {
        return testStringCoercion(value), false;
      } catch (e) {
        return true;
      }
    }
    function testStringCoercion(value) {
      return "" + value;
    }
    function checkAttributeStringCoercion(value, attributeName) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before using it here.",
          attributeName,
          typeName(value)
        ), testStringCoercion(value);
    }
    function checkCSSPropertyStringCoercion(value, propName) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before using it here.",
          propName,
          typeName(value)
        ), testStringCoercion(value);
    }
    function checkHtmlStringCoercion(value) {
      if (willCoercionThrow(value))
        return console.error(
          "The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before using it here.",
          typeName(value)
        ), testStringCoercion(value);
    }
    function isAttributeNameSafe(attributeName) {
      if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
        return true;
      if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName))
        return false;
      if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
        return validatedAttributeNameCache[attributeName] = true;
      illegalAttributeNameCache[attributeName] = true;
      console.error("Invalid attribute name: `%s`", attributeName);
      return false;
    }
    function checkControlledValueProps(tagName, props) {
      hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || null == props.value || ("select" === tagName ? console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set `onChange`."
      ) : console.error(
        "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."
      ));
      props.onChange || props.readOnly || props.disabled || null == props.checked || console.error(
        "You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."
      );
    }
    function validateProperty$1(tagName, name2) {
      if (hasOwnProperty2.call(warnedProperties$1, name2) && warnedProperties$1[name2])
        return true;
      if (rARIACamel$1.test(name2)) {
        tagName = "aria-" + name2.slice(4).toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.",
            name2
          ), warnedProperties$1[name2] = true;
        if (name2 !== tagName)
          return console.error(
            "Invalid ARIA attribute `%s`. Did you mean `%s`?",
            name2,
            tagName
          ), warnedProperties$1[name2] = true;
      }
      if (rARIA$1.test(name2)) {
        tagName = name2.toLowerCase();
        tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
        if (null == tagName) return warnedProperties$1[name2] = true, false;
        name2 !== tagName && (console.error(
          "Unknown ARIA attribute `%s`. Did you mean `%s`?",
          name2,
          tagName
        ), warnedProperties$1[name2] = true);
      }
      return true;
    }
    function validateProperties$2(type2, props) {
      var invalidProps = [], key;
      for (key in props)
        validateProperty$1(type2, key) || invalidProps.push(key);
      props = invalidProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === invalidProps.length ? console.error(
        "Invalid aria prop %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type2
      ) : 1 < invalidProps.length && console.error(
        "Invalid aria props %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
        props,
        type2
      );
    }
    function validateProperty(tagName, name2, value, eventRegistry) {
      if (hasOwnProperty2.call(warnedProperties, name2) && warnedProperties[name2])
        return true;
      var lowerCasedName = name2.toLowerCase();
      if ("onfocusin" === lowerCasedName || "onfocusout" === lowerCasedName)
        return console.error(
          "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."
        ), warnedProperties[name2] = true;
      if ("function" === typeof value && ("form" === tagName && "action" === name2 || "input" === tagName && "formAction" === name2 || "button" === tagName && "formAction" === name2))
        return true;
      if (EVENT_NAME_REGEX.test(name2))
        return INVALID_EVENT_NAME_REGEX.test(name2) && console.error(
          "Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.",
          name2
        ), warnedProperties[name2] = true;
      if (rARIA.test(name2) || rARIACamel.test(name2)) return true;
      if ("innerhtml" === lowerCasedName)
        return console.error(
          "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."
        ), warnedProperties[name2] = true;
      if ("aria" === lowerCasedName)
        return console.error(
          "The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."
        ), warnedProperties[name2] = true;
      if ("is" === lowerCasedName && null !== value && void 0 !== value && "string" !== typeof value)
        return console.error(
          "Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.",
          typeof value
        ), warnedProperties[name2] = true;
      if ("number" === typeof value && isNaN(value))
        return console.error(
          "Received NaN for the `%s` attribute. If this is expected, cast the value to a string.",
          name2
        ), warnedProperties[name2] = true;
      if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
        if (lowerCasedName = possibleStandardNames[lowerCasedName], lowerCasedName !== name2)
          return console.error(
            "Invalid DOM property `%s`. Did you mean `%s`?",
            name2,
            lowerCasedName
          ), warnedProperties[name2] = true;
      } else if (name2 !== lowerCasedName)
        return console.error(
          "React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.",
          name2,
          lowerCasedName
        ), warnedProperties[name2] = true;
      switch (name2) {
        case "dangerouslySetInnerHTML":
        case "children":
        case "style":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "ref":
          return true;
        case "innerText":
        case "textContent":
          return true;
      }
      switch (typeof value) {
        case "boolean":
          switch (name2) {
            case "autoFocus":
            case "checked":
            case "multiple":
            case "muted":
            case "selected":
            case "contentEditable":
            case "spellCheck":
            case "draggable":
            case "value":
            case "autoReverse":
            case "externalResourcesRequired":
            case "focusable":
            case "preserveAlpha":
            case "allowFullScreen":
            case "async":
            case "autoPlay":
            case "controls":
            case "default":
            case "defer":
            case "disabled":
            case "disablePictureInPicture":
            case "disableRemotePlayback":
            case "formNoValidate":
            case "hidden":
            case "loop":
            case "noModule":
            case "noValidate":
            case "open":
            case "playsInline":
            case "readOnly":
            case "required":
            case "reversed":
            case "scoped":
            case "seamless":
            case "itemScope":
            case "capture":
            case "download":
            case "inert":
              return true;
            default:
              lowerCasedName = name2.toLowerCase().slice(0, 5);
              if ("data-" === lowerCasedName || "aria-" === lowerCasedName)
                return true;
              value ? console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.',
                value,
                name2,
                name2,
                value,
                name2
              ) : console.error(
                'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.',
                value,
                name2,
                name2,
                value,
                name2,
                name2,
                name2
              );
              return warnedProperties[name2] = true;
          }
        case "function":
        case "symbol":
          return warnedProperties[name2] = true, false;
        case "string":
          if ("false" === value || "true" === value) {
            switch (name2) {
              case "checked":
              case "selected":
              case "multiple":
              case "muted":
              case "allowFullScreen":
              case "async":
              case "autoPlay":
              case "controls":
              case "default":
              case "defer":
              case "disabled":
              case "disablePictureInPicture":
              case "disableRemotePlayback":
              case "formNoValidate":
              case "hidden":
              case "loop":
              case "noModule":
              case "noValidate":
              case "open":
              case "playsInline":
              case "readOnly":
              case "required":
              case "reversed":
              case "scoped":
              case "seamless":
              case "itemScope":
              case "inert":
                break;
              default:
                return true;
            }
            console.error(
              "Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?",
              value,
              name2,
              "false" === value ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".',
              name2,
              value
            );
            warnedProperties[name2] = true;
          }
      }
      return true;
    }
    function warnUnknownProperties(type2, props, eventRegistry) {
      var unknownProps = [], key;
      for (key in props)
        validateProperty(type2, key, props[key]) || unknownProps.push(key);
      props = unknownProps.map(function(prop) {
        return "`" + prop + "`";
      }).join(", ");
      1 === unknownProps.length ? console.error(
        "Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type2
      ) : 1 < unknownProps.length && console.error(
        "Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://react.dev/link/attribute-behavior ",
        props,
        type2
      );
    }
    function camelize(string2) {
      return string2.replace(hyphenPattern, function(_2, character) {
        return character.toUpperCase();
      });
    }
    function escapeTextForBrowser(text2) {
      if ("boolean" === typeof text2 || "number" === typeof text2 || "bigint" === typeof text2)
        return "" + text2;
      checkHtmlStringCoercion(text2);
      text2 = "" + text2;
      var match = matchHtmlRegExp.exec(text2);
      if (match) {
        var html2 = "", index2, lastIndex = 0;
        for (index2 = match.index; index2 < text2.length; index2++) {
          switch (text2.charCodeAt(index2)) {
            case 34:
              match = "&quot;";
              break;
            case 38:
              match = "&amp;";
              break;
            case 39:
              match = "&#x27;";
              break;
            case 60:
              match = "&lt;";
              break;
            case 62:
              match = "&gt;";
              break;
            default:
              continue;
          }
          lastIndex !== index2 && (html2 += text2.slice(lastIndex, index2));
          lastIndex = index2 + 1;
          html2 += match;
        }
        text2 = lastIndex !== index2 ? html2 + text2.slice(lastIndex, index2) : html2;
      }
      return text2;
    }
    function sanitizeURL(url) {
      return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
    }
    function escapeEntireInlineScriptContent(scriptText) {
      checkHtmlStringCoercion(scriptText);
      return ("" + scriptText).replace(scriptRegex, scriptReplacer);
    }
    function createRenderState(resumableState, nonce, externalRuntimeConfig, importMap, onHeaders, maxHeadersLength) {
      externalRuntimeConfig = "string" === typeof nonce ? nonce : nonce && nonce.script;
      var inlineScriptWithNonce = void 0 === externalRuntimeConfig ? startInlineScript : stringToPrecomputedChunk(
        '<script nonce="' + escapeTextForBrowser(externalRuntimeConfig) + '"'
      ), nonceStyle = "string" === typeof nonce ? void 0 : nonce && nonce.style, inlineStyleWithNonce = void 0 === nonceStyle ? startInlineStyle : stringToPrecomputedChunk(
        '<style nonce="' + escapeTextForBrowser(nonceStyle) + '"'
      ), idPrefix = resumableState.idPrefix, bootstrapChunks = [], bootstrapScriptContent = resumableState.bootstrapScriptContent, bootstrapScripts = resumableState.bootstrapScripts, bootstrapModules = resumableState.bootstrapModules;
      void 0 !== bootstrapScriptContent && (bootstrapChunks.push(inlineScriptWithNonce), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
        endOfStartTag,
        escapeEntireInlineScriptContent(bootstrapScriptContent),
        endInlineScript
      ));
      bootstrapScriptContent = [];
      void 0 !== importMap && (bootstrapScriptContent.push(importMapScriptStart), bootstrapScriptContent.push(
        escapeEntireInlineScriptContent(JSON.stringify(importMap))
      ), bootstrapScriptContent.push(importMapScriptEnd));
      onHeaders && "number" === typeof maxHeadersLength && 0 >= maxHeadersLength && console.error(
        "React expected a positive non-zero `maxHeadersLength` option but found %s instead. When using the `onHeaders` option you may supply an optional `maxHeadersLength` option as well however, when setting this value to zero or less no headers will be captured.",
        0 === maxHeadersLength ? "zero" : maxHeadersLength
      );
      importMap = onHeaders ? {
        preconnects: "",
        fontPreloads: "",
        highImagePreloads: "",
        remainingCapacity: 2 + ("number" === typeof maxHeadersLength ? maxHeadersLength : 2e3)
      } : null;
      onHeaders = {
        placeholderPrefix: stringToPrecomputedChunk(idPrefix + "P:"),
        segmentPrefix: stringToPrecomputedChunk(idPrefix + "S:"),
        boundaryPrefix: stringToPrecomputedChunk(idPrefix + "B:"),
        startInlineScript: inlineScriptWithNonce,
        startInlineStyle: inlineStyleWithNonce,
        preamble: createPreambleState(),
        externalRuntimeScript: null,
        bootstrapChunks,
        importMapChunks: bootstrapScriptContent,
        onHeaders,
        headers: importMap,
        resets: {
          font: {},
          dns: {},
          connect: { default: {}, anonymous: {}, credentials: {} },
          image: {},
          style: {}
        },
        charsetChunks: [],
        viewportChunks: [],
        hoistableChunks: [],
        preconnects: /* @__PURE__ */ new Set(),
        fontPreloads: /* @__PURE__ */ new Set(),
        highImagePreloads: /* @__PURE__ */ new Set(),
        styles: /* @__PURE__ */ new Map(),
        bootstrapScripts: /* @__PURE__ */ new Set(),
        scripts: /* @__PURE__ */ new Set(),
        bulkPreloads: /* @__PURE__ */ new Set(),
        preloads: {
          images: /* @__PURE__ */ new Map(),
          stylesheets: /* @__PURE__ */ new Map(),
          scripts: /* @__PURE__ */ new Map(),
          moduleScripts: /* @__PURE__ */ new Map()
        },
        nonce: { script: externalRuntimeConfig, style: nonceStyle },
        hoistableState: null,
        stylesToHoist: false
      };
      if (void 0 !== bootstrapScripts)
        for (importMap = 0; importMap < bootstrapScripts.length; importMap++)
          maxHeadersLength = bootstrapScripts[importMap], inlineStyleWithNonce = nonceStyle = void 0, idPrefix = {
            rel: "preload",
            as: "script",
            fetchPriority: "low",
            nonce
          }, "string" === typeof maxHeadersLength ? idPrefix.href = inlineScriptWithNonce = maxHeadersLength : (idPrefix.href = inlineScriptWithNonce = maxHeadersLength.src, idPrefix.integrity = inlineStyleWithNonce = "string" === typeof maxHeadersLength.integrity ? maxHeadersLength.integrity : void 0, idPrefix.crossOrigin = nonceStyle = "string" === typeof maxHeadersLength || null == maxHeadersLength.crossOrigin ? void 0 : "use-credentials" === maxHeadersLength.crossOrigin ? "use-credentials" : ""), preloadBootstrapScriptOrModule(
            resumableState,
            onHeaders,
            inlineScriptWithNonce,
            idPrefix
          ), bootstrapChunks.push(
            startScriptSrc,
            escapeTextForBrowser(inlineScriptWithNonce),
            attributeEnd
          ), externalRuntimeConfig && bootstrapChunks.push(
            scriptNonce,
            escapeTextForBrowser(externalRuntimeConfig),
            attributeEnd
          ), "string" === typeof inlineStyleWithNonce && bootstrapChunks.push(
            scriptIntegirty,
            escapeTextForBrowser(inlineStyleWithNonce),
            attributeEnd
          ), "string" === typeof nonceStyle && bootstrapChunks.push(
            scriptCrossOrigin,
            escapeTextForBrowser(nonceStyle),
            attributeEnd
          ), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(endAsyncScript);
      if (void 0 !== bootstrapModules)
        for (nonce = 0; nonce < bootstrapModules.length; nonce++)
          bootstrapScripts = bootstrapModules[nonce], inlineScriptWithNonce = maxHeadersLength = void 0, nonceStyle = {
            rel: "modulepreload",
            fetchPriority: "low",
            nonce: externalRuntimeConfig
          }, "string" === typeof bootstrapScripts ? nonceStyle.href = importMap = bootstrapScripts : (nonceStyle.href = importMap = bootstrapScripts.src, nonceStyle.integrity = inlineScriptWithNonce = "string" === typeof bootstrapScripts.integrity ? bootstrapScripts.integrity : void 0, nonceStyle.crossOrigin = maxHeadersLength = "string" === typeof bootstrapScripts || null == bootstrapScripts.crossOrigin ? void 0 : "use-credentials" === bootstrapScripts.crossOrigin ? "use-credentials" : ""), preloadBootstrapScriptOrModule(
            resumableState,
            onHeaders,
            importMap,
            nonceStyle
          ), bootstrapChunks.push(
            startModuleSrc,
            escapeTextForBrowser(importMap),
            attributeEnd
          ), externalRuntimeConfig && bootstrapChunks.push(
            scriptNonce,
            escapeTextForBrowser(externalRuntimeConfig),
            attributeEnd
          ), "string" === typeof inlineScriptWithNonce && bootstrapChunks.push(
            scriptIntegirty,
            escapeTextForBrowser(inlineScriptWithNonce),
            attributeEnd
          ), "string" === typeof maxHeadersLength && bootstrapChunks.push(
            scriptCrossOrigin,
            escapeTextForBrowser(maxHeadersLength),
            attributeEnd
          ), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(endAsyncScript);
      return onHeaders;
    }
    function createResumableState(identifierPrefix, externalRuntimeConfig, bootstrapScriptContent, bootstrapScripts, bootstrapModules) {
      return {
        idPrefix: void 0 === identifierPrefix ? "" : identifierPrefix,
        nextFormID: 0,
        streamingFormat: 0,
        bootstrapScriptContent,
        bootstrapScripts,
        bootstrapModules,
        instructions: NothingSent,
        hasBody: false,
        hasHtml: false,
        unknownResources: {},
        dnsResources: {},
        connectResources: { default: {}, anonymous: {}, credentials: {} },
        imageResources: {},
        styleResources: {},
        scriptResources: {},
        moduleUnknownResources: {},
        moduleScriptResources: {}
      };
    }
    function createPreambleState() {
      return { htmlChunks: null, headChunks: null, bodyChunks: null };
    }
    function createFormatContext(insertionMode, selectedValue, tagScope, viewTransition) {
      return {
        insertionMode,
        selectedValue,
        tagScope,
        viewTransition
      };
    }
    function createRootFormatContext(namespaceURI) {
      return createFormatContext(
        "http://www.w3.org/2000/svg" === namespaceURI ? SVG_MODE : "http://www.w3.org/1998/Math/MathML" === namespaceURI ? MATHML_MODE : ROOT_HTML_MODE,
        null,
        0,
        null
      );
    }
    function getChildFormatContext(parentContext, type2, props) {
      var subtreeScope = parentContext.tagScope & -25;
      switch (type2) {
        case "noscript":
          return createFormatContext(HTML_MODE, null, subtreeScope | 1, null);
        case "select":
          return createFormatContext(
            HTML_MODE,
            null != props.value ? props.value : props.defaultValue,
            subtreeScope,
            null
          );
        case "svg":
          return createFormatContext(SVG_MODE, null, subtreeScope, null);
        case "picture":
          return createFormatContext(HTML_MODE, null, subtreeScope | 2, null);
        case "math":
          return createFormatContext(MATHML_MODE, null, subtreeScope, null);
        case "foreignObject":
          return createFormatContext(HTML_MODE, null, subtreeScope, null);
        case "table":
          return createFormatContext(HTML_TABLE_MODE, null, subtreeScope, null);
        case "thead":
        case "tbody":
        case "tfoot":
          return createFormatContext(
            HTML_TABLE_BODY_MODE,
            null,
            subtreeScope,
            null
          );
        case "colgroup":
          return createFormatContext(
            HTML_COLGROUP_MODE,
            null,
            subtreeScope,
            null
          );
        case "tr":
          return createFormatContext(
            HTML_TABLE_ROW_MODE,
            null,
            subtreeScope,
            null
          );
        case "head":
          if (parentContext.insertionMode < HTML_MODE)
            return createFormatContext(
              HTML_HEAD_MODE,
              null,
              subtreeScope,
              null
            );
          break;
        case "html":
          if (parentContext.insertionMode === ROOT_HTML_MODE)
            return createFormatContext(
              HTML_HTML_MODE,
              null,
              subtreeScope,
              null
            );
      }
      return parentContext.insertionMode >= HTML_TABLE_MODE || parentContext.insertionMode < HTML_MODE ? createFormatContext(HTML_MODE, null, subtreeScope, null) : parentContext.tagScope !== subtreeScope ? createFormatContext(
        parentContext.insertionMode,
        parentContext.selectedValue,
        subtreeScope,
        null
      ) : parentContext;
    }
    function getSuspenseViewTransition(parentViewTransition) {
      return null === parentViewTransition ? null : {
        update: parentViewTransition.update,
        enter: "none",
        exit: "none",
        share: parentViewTransition.update,
        name: parentViewTransition.autoName,
        autoName: parentViewTransition.autoName,
        nameIdx: 0
      };
    }
    function getSuspenseFallbackFormatContext(resumableState, parentContext) {
      parentContext.tagScope & 32 && (resumableState.instructions |= 128);
      return createFormatContext(
        parentContext.insertionMode,
        parentContext.selectedValue,
        parentContext.tagScope | 12,
        getSuspenseViewTransition(parentContext.viewTransition)
      );
    }
    function getSuspenseContentFormatContext(resumableState, parentContext) {
      resumableState = getSuspenseViewTransition(parentContext.viewTransition);
      var subtreeScope = parentContext.tagScope | 16;
      null !== resumableState && "none" !== resumableState.share && (subtreeScope |= 64);
      return createFormatContext(
        parentContext.insertionMode,
        parentContext.selectedValue,
        subtreeScope,
        resumableState
      );
    }
    function pushTextInstance(target, text2, renderState, textEmbedded) {
      if ("" === text2) return textEmbedded;
      textEmbedded && target.push(textSeparator);
      target.push(escapeTextForBrowser(text2));
      return true;
    }
    function pushStyleAttribute(target, style) {
      if ("object" !== typeof style)
        throw Error(
          "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
        );
      var isFirst = true, styleName;
      for (styleName in style)
        if (hasOwnProperty2.call(style, styleName)) {
          var styleValue = style[styleName];
          if (null != styleValue && "boolean" !== typeof styleValue && "" !== styleValue) {
            if (0 === styleName.indexOf("--")) {
              var nameChunk = escapeTextForBrowser(styleName);
              checkCSSPropertyStringCoercion(styleValue, styleName);
              styleValue = escapeTextForBrowser(("" + styleValue).trim());
            } else {
              nameChunk = styleName;
              var value = styleValue;
              if (-1 < nameChunk.indexOf("-")) {
                var name2 = nameChunk;
                warnedStyleNames.hasOwnProperty(name2) && warnedStyleNames[name2] || (warnedStyleNames[name2] = true, console.error(
                  "Unsupported style property %s. Did you mean %s?",
                  name2,
                  camelize(name2.replace(msPattern$1, "ms-"))
                ));
              } else if (badVendoredStyleNamePattern.test(nameChunk))
                name2 = nameChunk, warnedStyleNames.hasOwnProperty(name2) && warnedStyleNames[name2] || (warnedStyleNames[name2] = true, console.error(
                  "Unsupported vendor-prefixed style property %s. Did you mean %s?",
                  name2,
                  name2.charAt(0).toUpperCase() + name2.slice(1)
                ));
              else if (badStyleValueWithSemicolonPattern.test(value)) {
                name2 = nameChunk;
                var value$jscomp$0 = value;
                warnedStyleValues.hasOwnProperty(value$jscomp$0) && warnedStyleValues[value$jscomp$0] || (warnedStyleValues[value$jscomp$0] = true, console.error(
                  `Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`,
                  name2,
                  value$jscomp$0.replace(
                    badStyleValueWithSemicolonPattern,
                    ""
                  )
                ));
              }
              "number" === typeof value && (isNaN(value) ? warnedForNaNValue || (warnedForNaNValue = true, console.error(
                "`NaN` is an invalid value for the `%s` css style property.",
                nameChunk
              )) : isFinite(value) || warnedForInfinityValue || (warnedForInfinityValue = true, console.error(
                "`Infinity` is an invalid value for the `%s` css style property.",
                nameChunk
              )));
              nameChunk = styleName;
              value = styleNameCache.get(nameChunk);
              void 0 !== value ? nameChunk = value : (value = stringToPrecomputedChunk(
                escapeTextForBrowser(
                  nameChunk.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern, "-ms-")
                )
              ), styleNameCache.set(nameChunk, value), nameChunk = value);
              "number" === typeof styleValue ? styleValue = 0 === styleValue || unitlessNumbers.has(styleName) ? "" + styleValue : styleValue + "px" : (checkCSSPropertyStringCoercion(styleValue, styleName), styleValue = escapeTextForBrowser(
                ("" + styleValue).trim()
              ));
            }
            isFirst ? (isFirst = false, target.push(
              styleAttributeStart,
              nameChunk,
              styleAssign,
              styleValue
            )) : target.push(styleSeparator, nameChunk, styleAssign, styleValue);
          }
        }
      isFirst || target.push(attributeEnd);
    }
    function pushBooleanAttribute(target, name2, value) {
      value && "function" !== typeof value && "symbol" !== typeof value && target.push(attributeSeparator, name2, attributeEmptyString);
    }
    function pushStringAttribute(target, name2, value) {
      "function" !== typeof value && "symbol" !== typeof value && "boolean" !== typeof value && target.push(
        attributeSeparator,
        name2,
        attributeAssign,
        escapeTextForBrowser(value),
        attributeEnd
      );
    }
    function pushAdditionalFormField(value, key) {
      this.push(startHiddenInputChunk);
      validateAdditionalFormField(value);
      pushStringAttribute(this, "name", key);
      pushStringAttribute(this, "value", value);
      this.push(endOfStartTagSelfClosing);
    }
    function validateAdditionalFormField(value) {
      if ("string" !== typeof value)
        throw Error(
          "File/Blob fields are not yet supported in progressive forms. Will fallback to client hydration."
        );
    }
    function getCustomFormFields(resumableState, formAction) {
      if ("function" === typeof formAction.$$FORM_ACTION) {
        var id = resumableState.nextFormID++;
        resumableState = resumableState.idPrefix + id;
        try {
          var customFields = formAction.$$FORM_ACTION(resumableState);
          if (customFields) {
            var formData = customFields.data;
            null != formData && formData.forEach(validateAdditionalFormField);
          }
          return customFields;
        } catch (x2) {
          if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then)
            throw x2;
          console.error(
            "Failed to serialize an action for progressive enhancement:\n%s",
            x2
          );
        }
      }
      return null;
    }
    function pushFormActionAttribute(target, resumableState, renderState, formAction, formEncType, formMethod, formTarget, name2) {
      var formData = null;
      if ("function" === typeof formAction) {
        null === name2 || didWarnFormActionName || (didWarnFormActionName = true, console.error(
          'Cannot specify a "name" prop for a button that specifies a function as a formAction. React needs it to encode which action should be invoked. It will get overridden.'
        ));
        null === formEncType && null === formMethod || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
          "Cannot specify a formEncType or formMethod for a button that specifies a function as a formAction. React provides those automatically. They will get overridden."
        ));
        null === formTarget || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
          "Cannot specify a formTarget for a button that specifies a function as a formAction. The function will always be executed in the same window."
        ));
        var customFields = getCustomFormFields(resumableState, formAction);
        null !== customFields ? (name2 = customFields.name, formAction = customFields.action || "", formEncType = customFields.encType, formMethod = customFields.method, formTarget = customFields.target, formData = customFields.data) : (target.push(
          attributeSeparator,
          "formAction",
          attributeAssign,
          actionJavaScriptURL,
          attributeEnd
        ), formTarget = formMethod = formEncType = formAction = name2 = null, injectFormReplayingRuntime(resumableState, renderState));
      }
      null != name2 && pushAttribute(target, "name", name2);
      null != formAction && pushAttribute(target, "formAction", formAction);
      null != formEncType && pushAttribute(target, "formEncType", formEncType);
      null != formMethod && pushAttribute(target, "formMethod", formMethod);
      null != formTarget && pushAttribute(target, "formTarget", formTarget);
      return formData;
    }
    function pushAttribute(target, name2, value) {
      switch (name2) {
        case "className":
          pushStringAttribute(target, "class", value);
          break;
        case "tabIndex":
          pushStringAttribute(target, "tabindex", value);
          break;
        case "dir":
        case "role":
        case "viewBox":
        case "width":
        case "height":
          pushStringAttribute(target, name2, value);
          break;
        case "style":
          pushStyleAttribute(target, value);
          break;
        case "src":
        case "href":
          if ("" === value) {
            "src" === name2 ? console.error(
              'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              name2,
              name2
            ) : console.error(
              'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
              name2,
              name2
            );
            break;
          }
        case "action":
        case "formAction":
          if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
            break;
          checkAttributeStringCoercion(value, name2);
          value = sanitizeURL("" + value);
          target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "defaultValue":
        case "defaultChecked":
        case "innerHTML":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "ref":
          break;
        case "autoFocus":
        case "multiple":
        case "muted":
          pushBooleanAttribute(target, name2.toLowerCase(), value);
          break;
        case "xlinkHref":
          if ("function" === typeof value || "symbol" === typeof value || "boolean" === typeof value)
            break;
          checkAttributeStringCoercion(value, name2);
          value = sanitizeURL("" + value);
          target.push(
            attributeSeparator,
            "xlink:href",
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "contentEditable":
        case "spellCheck":
        case "draggable":
        case "value":
        case "autoReverse":
        case "externalResourcesRequired":
        case "focusable":
        case "preserveAlpha":
          "function" !== typeof value && "symbol" !== typeof value && target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "inert":
          "" !== value || didWarnForNewBooleanPropsWithEmptyValue[name2] || (didWarnForNewBooleanPropsWithEmptyValue[name2] = true, console.error(
            "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
            name2
          ));
        case "allowFullScreen":
        case "async":
        case "autoPlay":
        case "controls":
        case "default":
        case "defer":
        case "disabled":
        case "disablePictureInPicture":
        case "disableRemotePlayback":
        case "formNoValidate":
        case "hidden":
        case "loop":
        case "noModule":
        case "noValidate":
        case "open":
        case "playsInline":
        case "readOnly":
        case "required":
        case "reversed":
        case "scoped":
        case "seamless":
        case "itemScope":
          value && "function" !== typeof value && "symbol" !== typeof value && target.push(attributeSeparator, name2, attributeEmptyString);
          break;
        case "capture":
        case "download":
          true === value ? target.push(attributeSeparator, name2, attributeEmptyString) : false !== value && "function" !== typeof value && "symbol" !== typeof value && target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "cols":
        case "rows":
        case "size":
        case "span":
          "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value && target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "rowSpan":
        case "start":
          "function" === typeof value || "symbol" === typeof value || isNaN(value) || target.push(
            attributeSeparator,
            name2,
            attributeAssign,
            escapeTextForBrowser(value),
            attributeEnd
          );
          break;
        case "xlinkActuate":
          pushStringAttribute(target, "xlink:actuate", value);
          break;
        case "xlinkArcrole":
          pushStringAttribute(target, "xlink:arcrole", value);
          break;
        case "xlinkRole":
          pushStringAttribute(target, "xlink:role", value);
          break;
        case "xlinkShow":
          pushStringAttribute(target, "xlink:show", value);
          break;
        case "xlinkTitle":
          pushStringAttribute(target, "xlink:title", value);
          break;
        case "xlinkType":
          pushStringAttribute(target, "xlink:type", value);
          break;
        case "xmlBase":
          pushStringAttribute(target, "xml:base", value);
          break;
        case "xmlLang":
          pushStringAttribute(target, "xml:lang", value);
          break;
        case "xmlSpace":
          pushStringAttribute(target, "xml:space", value);
          break;
        default:
          if (!(2 < name2.length) || "o" !== name2[0] && "O" !== name2[0] || "n" !== name2[1] && "N" !== name2[1]) {
            if (name2 = aliases.get(name2) || name2, isAttributeNameSafe(name2)) {
              switch (typeof value) {
                case "function":
                case "symbol":
                  return;
                case "boolean":
                  var prefix2 = name2.toLowerCase().slice(0, 5);
                  if ("data-" !== prefix2 && "aria-" !== prefix2) return;
              }
              target.push(
                attributeSeparator,
                name2,
                attributeAssign,
                escapeTextForBrowser(value),
                attributeEnd
              );
            }
          }
      }
    }
    function pushInnerHTML(target, innerHTML, children) {
      if (null != innerHTML) {
        if (null != children)
          throw Error(
            "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
          );
        if ("object" !== typeof innerHTML || !("__html" in innerHTML))
          throw Error(
            "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
          );
        innerHTML = innerHTML.__html;
        null !== innerHTML && void 0 !== innerHTML && (checkHtmlStringCoercion(innerHTML), target.push("" + innerHTML));
      }
    }
    function checkSelectProp(props, propName) {
      var value = props[propName];
      null != value && (value = isArrayImpl(value), props.multiple && !value ? console.error(
        "The `%s` prop supplied to <select> must be an array if `multiple` is true.",
        propName
      ) : !props.multiple && value && console.error(
        "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.",
        propName
      ));
    }
    function flattenOptionChildren(children) {
      var content2 = "";
      React2.Children.forEach(children, function(child) {
        null != child && (content2 += child, didWarnInvalidOptionChildren || "string" === typeof child || "number" === typeof child || "bigint" === typeof child || (didWarnInvalidOptionChildren = true, console.error(
          "Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>."
        )));
      });
      return content2;
    }
    function injectFormReplayingRuntime(resumableState, renderState) {
      if ((resumableState.instructions & 16) === NothingSent) {
        resumableState.instructions |= 16;
        var preamble = renderState.preamble, bootstrapChunks = renderState.bootstrapChunks;
        (preamble.htmlChunks || preamble.headChunks) && 0 === bootstrapChunks.length ? (bootstrapChunks.push(renderState.startInlineScript), pushCompletedShellIdAttribute(bootstrapChunks, resumableState), bootstrapChunks.push(
          endOfStartTag,
          formReplayingRuntimeScript,
          endInlineScript
        )) : bootstrapChunks.unshift(
          renderState.startInlineScript,
          endOfStartTag,
          formReplayingRuntimeScript,
          endInlineScript
        );
      }
    }
    function pushLinkImpl(target, props) {
      target.push(startChunkForTag("link"));
      for (var propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(
                  "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                );
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTagSelfClosing);
      return null;
    }
    function escapeStyleTextContent(styleText) {
      checkHtmlStringCoercion(styleText);
      return ("" + styleText).replace(styleRegex, styleReplacer);
    }
    function pushSelfClosing(target, props, tag) {
      target.push(startChunkForTag(tag));
      for (var propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
              case "dangerouslySetInnerHTML":
                throw Error(
                  tag + " is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                );
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTagSelfClosing);
      return null;
    }
    function pushTitleImpl(target, props) {
      target.push(startChunkForTag("title"));
      var children = null, innerHTML = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                children = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      props = Array.isArray(children) ? 2 > children.length ? children[0] : null : children;
      "function" !== typeof props && "symbol" !== typeof props && null !== props && void 0 !== props && target.push(escapeTextForBrowser("" + props));
      pushInnerHTML(target, innerHTML, children);
      target.push(endChunkForTag("title"));
      return null;
    }
    function pushScriptImpl(target, props) {
      target.push(startChunkForTag("script"));
      var children = null, innerHTML = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                children = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      null != children && "string" !== typeof children && (props = "number" === typeof children ? "a number for children" : Array.isArray(children) ? "an array for children" : "something unexpected for children", console.error(
        "A script element was rendered with %s. If script element has children it must be a single string. Consider using dangerouslySetInnerHTML or passing a plain string as children.",
        props
      ));
      pushInnerHTML(target, innerHTML, children);
      "string" === typeof children && target.push(escapeEntireInlineScriptContent(children));
      target.push(endChunkForTag("script"));
      return null;
    }
    function pushStartSingletonElement(target, props, tag) {
      target.push(startChunkForTag(tag));
      var innerHTML = tag = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                tag = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      pushInnerHTML(target, innerHTML, tag);
      return tag;
    }
    function pushStartGenericElement(target, props, tag) {
      target.push(startChunkForTag(tag));
      var innerHTML = tag = null, propKey;
      for (propKey in props)
        if (hasOwnProperty2.call(props, propKey)) {
          var propValue = props[propKey];
          if (null != propValue)
            switch (propKey) {
              case "children":
                tag = propValue;
                break;
              case "dangerouslySetInnerHTML":
                innerHTML = propValue;
                break;
              default:
                pushAttribute(target, propKey, propValue);
            }
        }
      target.push(endOfStartTag);
      pushInnerHTML(target, innerHTML, tag);
      return "string" === typeof tag ? (target.push(escapeTextForBrowser(tag)), null) : tag;
    }
    function startChunkForTag(tag) {
      var tagStartChunk = validatedTagCache.get(tag);
      if (void 0 === tagStartChunk) {
        if (!VALID_TAG_REGEX.test(tag)) throw Error("Invalid tag: " + tag);
        tagStartChunk = stringToPrecomputedChunk("<" + tag);
        validatedTagCache.set(tag, tagStartChunk);
      }
      return tagStartChunk;
    }
    function pushStartInstance(target$jscomp$0, type2, props, resumableState, renderState, preambleState, hoistableState, formatContext, textEmbedded) {
      validateProperties$2(type2, props);
      "input" !== type2 && "textarea" !== type2 && "select" !== type2 || null == props || null !== props.value || didWarnValueNull || (didWarnValueNull = true, "select" === type2 && props.multiple ? console.error(
        "`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.",
        type2
      ) : console.error(
        "`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.",
        type2
      ));
      b: if (-1 === type2.indexOf("-")) var JSCompiler_inline_result = false;
      else
        switch (type2) {
          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":
            JSCompiler_inline_result = false;
            break b;
          default:
            JSCompiler_inline_result = true;
        }
      JSCompiler_inline_result || "string" === typeof props.is || warnUnknownProperties(type2, props);
      !props.suppressContentEditableWarning && props.contentEditable && null != props.children && console.error(
        "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."
      );
      formatContext.insertionMode !== SVG_MODE && formatContext.insertionMode !== MATHML_MODE && -1 === type2.indexOf("-") && type2.toLowerCase() !== type2 && console.error(
        "<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",
        type2
      );
      switch (type2) {
        case "div":
        case "span":
        case "svg":
        case "path":
          break;
        case "a":
          target$jscomp$0.push(startChunkForTag("a"));
          var children = null, innerHTML = null, propKey;
          for (propKey in props)
            if (hasOwnProperty2.call(props, propKey)) {
              var propValue = props[propKey];
              if (null != propValue)
                switch (propKey) {
                  case "children":
                    children = propValue;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML = propValue;
                    break;
                  case "href":
                    "" === propValue ? pushStringAttribute(target$jscomp$0, "href", "") : pushAttribute(target$jscomp$0, propKey, propValue);
                    break;
                  default:
                    pushAttribute(target$jscomp$0, propKey, propValue);
                }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML, children);
          if ("string" === typeof children) {
            target$jscomp$0.push(escapeTextForBrowser(children));
            var JSCompiler_inline_result$jscomp$0 = null;
          } else JSCompiler_inline_result$jscomp$0 = children;
          return JSCompiler_inline_result$jscomp$0;
        case "g":
        case "p":
        case "li":
          break;
        case "select":
          checkControlledValueProps("select", props);
          checkSelectProp(props, "value");
          checkSelectProp(props, "defaultValue");
          void 0 === props.value || void 0 === props.defaultValue || didWarnDefaultSelectValue || (console.error(
            "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://react.dev/link/controlled-components"
          ), didWarnDefaultSelectValue = true);
          target$jscomp$0.push(startChunkForTag("select"));
          var children$jscomp$0 = null, innerHTML$jscomp$0 = null, propKey$jscomp$0;
          for (propKey$jscomp$0 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$0)) {
              var propValue$jscomp$0 = props[propKey$jscomp$0];
              if (null != propValue$jscomp$0)
                switch (propKey$jscomp$0) {
                  case "children":
                    children$jscomp$0 = propValue$jscomp$0;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$0 = propValue$jscomp$0;
                    break;
                  case "defaultValue":
                  case "value":
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$0,
                      propValue$jscomp$0
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$0, children$jscomp$0);
          return children$jscomp$0;
        case "option":
          var selectedValue = formatContext.selectedValue;
          target$jscomp$0.push(startChunkForTag("option"));
          var children$jscomp$1 = null, value = null, selected = null, innerHTML$jscomp$1 = null, propKey$jscomp$1;
          for (propKey$jscomp$1 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$1)) {
              var propValue$jscomp$1 = props[propKey$jscomp$1];
              if (null != propValue$jscomp$1)
                switch (propKey$jscomp$1) {
                  case "children":
                    children$jscomp$1 = propValue$jscomp$1;
                    break;
                  case "selected":
                    selected = propValue$jscomp$1;
                    didWarnSelectedSetOnOption || (console.error(
                      "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."
                    ), didWarnSelectedSetOnOption = true);
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$1 = propValue$jscomp$1;
                    break;
                  case "value":
                    value = propValue$jscomp$1;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$1,
                      propValue$jscomp$1
                    );
                }
            }
          if (null != selectedValue) {
            if (null !== value) {
              checkAttributeStringCoercion(value, "value");
              var stringValue = "" + value;
            } else
              null === innerHTML$jscomp$1 || didWarnInvalidOptionInnerHTML || (didWarnInvalidOptionInnerHTML = true, console.error(
                "Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."
              )), stringValue = flattenOptionChildren(children$jscomp$1);
            if (isArrayImpl(selectedValue))
              for (var i = 0; i < selectedValue.length; i++) {
                if (checkAttributeStringCoercion(selectedValue[i], "value"), "" + selectedValue[i] === stringValue) {
                  target$jscomp$0.push(selectedMarkerAttribute);
                  break;
                }
              }
            else
              checkAttributeStringCoercion(selectedValue, "select.value"), "" + selectedValue === stringValue && target$jscomp$0.push(selectedMarkerAttribute);
          } else selected && target$jscomp$0.push(selectedMarkerAttribute);
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$1, children$jscomp$1);
          return children$jscomp$1;
        case "textarea":
          checkControlledValueProps("textarea", props);
          void 0 === props.value || void 0 === props.defaultValue || didWarnDefaultTextareaValue || (console.error(
            "Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://react.dev/link/controlled-components"
          ), didWarnDefaultTextareaValue = true);
          target$jscomp$0.push(startChunkForTag("textarea"));
          var value$jscomp$0 = null, defaultValue = null, children$jscomp$2 = null, propKey$jscomp$2;
          for (propKey$jscomp$2 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$2)) {
              var propValue$jscomp$2 = props[propKey$jscomp$2];
              if (null != propValue$jscomp$2)
                switch (propKey$jscomp$2) {
                  case "children":
                    children$jscomp$2 = propValue$jscomp$2;
                    break;
                  case "value":
                    value$jscomp$0 = propValue$jscomp$2;
                    break;
                  case "defaultValue":
                    defaultValue = propValue$jscomp$2;
                    break;
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                    );
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$2,
                      propValue$jscomp$2
                    );
                }
            }
          null === value$jscomp$0 && null !== defaultValue && (value$jscomp$0 = defaultValue);
          target$jscomp$0.push(endOfStartTag);
          if (null != children$jscomp$2) {
            console.error(
              "Use the `defaultValue` or `value` props instead of setting children on <textarea>."
            );
            if (null != value$jscomp$0)
              throw Error(
                "If you supply `defaultValue` on a <textarea>, do not pass children."
              );
            if (isArrayImpl(children$jscomp$2)) {
              if (1 < children$jscomp$2.length)
                throw Error("<textarea> can only have at most one child.");
              checkHtmlStringCoercion(children$jscomp$2[0]);
              value$jscomp$0 = "" + children$jscomp$2[0];
            }
            checkHtmlStringCoercion(children$jscomp$2);
            value$jscomp$0 = "" + children$jscomp$2;
          }
          "string" === typeof value$jscomp$0 && "\n" === value$jscomp$0[0] && target$jscomp$0.push(leadingNewline);
          null !== value$jscomp$0 && (checkAttributeStringCoercion(value$jscomp$0, "value"), target$jscomp$0.push(escapeTextForBrowser("" + value$jscomp$0)));
          return null;
        case "input":
          checkControlledValueProps("input", props);
          target$jscomp$0.push(startChunkForTag("input"));
          var name2 = null, formAction = null, formEncType = null, formMethod = null, formTarget = null, value$jscomp$1 = null, defaultValue$jscomp$0 = null, checked = null, defaultChecked = null, propKey$jscomp$3;
          for (propKey$jscomp$3 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$3)) {
              var propValue$jscomp$3 = props[propKey$jscomp$3];
              if (null != propValue$jscomp$3)
                switch (propKey$jscomp$3) {
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "input is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  case "name":
                    name2 = propValue$jscomp$3;
                    break;
                  case "formAction":
                    formAction = propValue$jscomp$3;
                    break;
                  case "formEncType":
                    formEncType = propValue$jscomp$3;
                    break;
                  case "formMethod":
                    formMethod = propValue$jscomp$3;
                    break;
                  case "formTarget":
                    formTarget = propValue$jscomp$3;
                    break;
                  case "defaultChecked":
                    defaultChecked = propValue$jscomp$3;
                    break;
                  case "defaultValue":
                    defaultValue$jscomp$0 = propValue$jscomp$3;
                    break;
                  case "checked":
                    checked = propValue$jscomp$3;
                    break;
                  case "value":
                    value$jscomp$1 = propValue$jscomp$3;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$3,
                      propValue$jscomp$3
                    );
                }
            }
          null === formAction || "image" === props.type || "submit" === props.type || didWarnFormActionType || (didWarnFormActionType = true, console.error(
            'An input can only specify a formAction along with type="submit" or type="image".'
          ));
          var formData = pushFormActionAttribute(
            target$jscomp$0,
            resumableState,
            renderState,
            formAction,
            formEncType,
            formMethod,
            formTarget,
            name2
          );
          null === checked || null === defaultChecked || didWarnDefaultChecked || (console.error(
            "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
            "A component",
            props.type
          ), didWarnDefaultChecked = true);
          null === value$jscomp$1 || null === defaultValue$jscomp$0 || didWarnDefaultInputValue || (console.error(
            "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
            "A component",
            props.type
          ), didWarnDefaultInputValue = true);
          null !== checked ? pushBooleanAttribute(target$jscomp$0, "checked", checked) : null !== defaultChecked && pushBooleanAttribute(target$jscomp$0, "checked", defaultChecked);
          null !== value$jscomp$1 ? pushAttribute(target$jscomp$0, "value", value$jscomp$1) : null !== defaultValue$jscomp$0 && pushAttribute(target$jscomp$0, "value", defaultValue$jscomp$0);
          target$jscomp$0.push(endOfStartTagSelfClosing);
          null != formData && formData.forEach(pushAdditionalFormField, target$jscomp$0);
          return null;
        case "button":
          target$jscomp$0.push(startChunkForTag("button"));
          var children$jscomp$3 = null, innerHTML$jscomp$2 = null, name$jscomp$0 = null, formAction$jscomp$0 = null, formEncType$jscomp$0 = null, formMethod$jscomp$0 = null, formTarget$jscomp$0 = null, propKey$jscomp$4;
          for (propKey$jscomp$4 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$4)) {
              var propValue$jscomp$4 = props[propKey$jscomp$4];
              if (null != propValue$jscomp$4)
                switch (propKey$jscomp$4) {
                  case "children":
                    children$jscomp$3 = propValue$jscomp$4;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$2 = propValue$jscomp$4;
                    break;
                  case "name":
                    name$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formAction":
                    formAction$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formEncType":
                    formEncType$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formMethod":
                    formMethod$jscomp$0 = propValue$jscomp$4;
                    break;
                  case "formTarget":
                    formTarget$jscomp$0 = propValue$jscomp$4;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$4,
                      propValue$jscomp$4
                    );
                }
            }
          null === formAction$jscomp$0 || null == props.type || "submit" === props.type || didWarnFormActionType || (didWarnFormActionType = true, console.error(
            'A button can only specify a formAction along with type="submit" or no type.'
          ));
          var formData$jscomp$0 = pushFormActionAttribute(
            target$jscomp$0,
            resumableState,
            renderState,
            formAction$jscomp$0,
            formEncType$jscomp$0,
            formMethod$jscomp$0,
            formTarget$jscomp$0,
            name$jscomp$0
          );
          target$jscomp$0.push(endOfStartTag);
          null != formData$jscomp$0 && formData$jscomp$0.forEach(pushAdditionalFormField, target$jscomp$0);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$2, children$jscomp$3);
          if ("string" === typeof children$jscomp$3) {
            target$jscomp$0.push(escapeTextForBrowser(children$jscomp$3));
            var JSCompiler_inline_result$jscomp$1 = null;
          } else JSCompiler_inline_result$jscomp$1 = children$jscomp$3;
          return JSCompiler_inline_result$jscomp$1;
        case "form":
          target$jscomp$0.push(startChunkForTag("form"));
          var children$jscomp$4 = null, innerHTML$jscomp$3 = null, formAction$jscomp$1 = null, formEncType$jscomp$1 = null, formMethod$jscomp$1 = null, formTarget$jscomp$1 = null, propKey$jscomp$5;
          for (propKey$jscomp$5 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$5)) {
              var propValue$jscomp$5 = props[propKey$jscomp$5];
              if (null != propValue$jscomp$5)
                switch (propKey$jscomp$5) {
                  case "children":
                    children$jscomp$4 = propValue$jscomp$5;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$3 = propValue$jscomp$5;
                    break;
                  case "action":
                    formAction$jscomp$1 = propValue$jscomp$5;
                    break;
                  case "encType":
                    formEncType$jscomp$1 = propValue$jscomp$5;
                    break;
                  case "method":
                    formMethod$jscomp$1 = propValue$jscomp$5;
                    break;
                  case "target":
                    formTarget$jscomp$1 = propValue$jscomp$5;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$5,
                      propValue$jscomp$5
                    );
                }
            }
          var formData$jscomp$1 = null, formActionName = null;
          if ("function" === typeof formAction$jscomp$1) {
            null === formEncType$jscomp$1 && null === formMethod$jscomp$1 || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
              "Cannot specify a encType or method for a form that specifies a function as the action. React provides those automatically. They will get overridden."
            ));
            null === formTarget$jscomp$1 || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
              "Cannot specify a target for a form that specifies a function as the action. The function will always be executed in the same window."
            ));
            var customFields = getCustomFormFields(
              resumableState,
              formAction$jscomp$1
            );
            null !== customFields ? (formAction$jscomp$1 = customFields.action || "", formEncType$jscomp$1 = customFields.encType, formMethod$jscomp$1 = customFields.method, formTarget$jscomp$1 = customFields.target, formData$jscomp$1 = customFields.data, formActionName = customFields.name) : (target$jscomp$0.push(
              attributeSeparator,
              "action",
              attributeAssign,
              actionJavaScriptURL,
              attributeEnd
            ), formTarget$jscomp$1 = formMethod$jscomp$1 = formEncType$jscomp$1 = formAction$jscomp$1 = null, injectFormReplayingRuntime(resumableState, renderState));
          }
          null != formAction$jscomp$1 && pushAttribute(target$jscomp$0, "action", formAction$jscomp$1);
          null != formEncType$jscomp$1 && pushAttribute(target$jscomp$0, "encType", formEncType$jscomp$1);
          null != formMethod$jscomp$1 && pushAttribute(target$jscomp$0, "method", formMethod$jscomp$1);
          null != formTarget$jscomp$1 && pushAttribute(target$jscomp$0, "target", formTarget$jscomp$1);
          target$jscomp$0.push(endOfStartTag);
          null !== formActionName && (target$jscomp$0.push(startHiddenInputChunk), pushStringAttribute(target$jscomp$0, "name", formActionName), target$jscomp$0.push(endOfStartTagSelfClosing), null != formData$jscomp$1 && formData$jscomp$1.forEach(
            pushAdditionalFormField,
            target$jscomp$0
          ));
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$3, children$jscomp$4);
          if ("string" === typeof children$jscomp$4) {
            target$jscomp$0.push(escapeTextForBrowser(children$jscomp$4));
            var JSCompiler_inline_result$jscomp$2 = null;
          } else JSCompiler_inline_result$jscomp$2 = children$jscomp$4;
          return JSCompiler_inline_result$jscomp$2;
        case "menuitem":
          target$jscomp$0.push(startChunkForTag("menuitem"));
          for (var propKey$jscomp$6 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$6)) {
              var propValue$jscomp$6 = props[propKey$jscomp$6];
              if (null != propValue$jscomp$6)
                switch (propKey$jscomp$6) {
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "menuitems cannot have `children` nor `dangerouslySetInnerHTML`."
                    );
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$6,
                      propValue$jscomp$6
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          return null;
        case "object":
          target$jscomp$0.push(startChunkForTag("object"));
          var children$jscomp$5 = null, innerHTML$jscomp$4 = null, propKey$jscomp$7;
          for (propKey$jscomp$7 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$7)) {
              var propValue$jscomp$7 = props[propKey$jscomp$7];
              if (null != propValue$jscomp$7)
                switch (propKey$jscomp$7) {
                  case "children":
                    children$jscomp$5 = propValue$jscomp$7;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$4 = propValue$jscomp$7;
                    break;
                  case "data":
                    checkAttributeStringCoercion(propValue$jscomp$7, "data");
                    var sanitizedValue = sanitizeURL("" + propValue$jscomp$7);
                    if ("" === sanitizedValue) {
                      console.error(
                        'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                        propKey$jscomp$7,
                        propKey$jscomp$7
                      );
                      break;
                    }
                    target$jscomp$0.push(
                      attributeSeparator,
                      "data",
                      attributeAssign,
                      escapeTextForBrowser(sanitizedValue),
                      attributeEnd
                    );
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$7,
                      propValue$jscomp$7
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          pushInnerHTML(target$jscomp$0, innerHTML$jscomp$4, children$jscomp$5);
          if ("string" === typeof children$jscomp$5) {
            target$jscomp$0.push(escapeTextForBrowser(children$jscomp$5));
            var JSCompiler_inline_result$jscomp$3 = null;
          } else JSCompiler_inline_result$jscomp$3 = children$jscomp$5;
          return JSCompiler_inline_result$jscomp$3;
        case "title":
          var noscriptTagInScope = formatContext.tagScope & 1, isFallback = formatContext.tagScope & 4;
          if (hasOwnProperty2.call(props, "children")) {
            var children$jscomp$6 = props.children, child = Array.isArray(children$jscomp$6) ? 2 > children$jscomp$6.length ? children$jscomp$6[0] : null : children$jscomp$6;
            Array.isArray(children$jscomp$6) && 1 < children$jscomp$6.length ? console.error(
              "React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an Array with length %s instead. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert `children` of <title> tags to a single string value which is why Arrays of length greater than 1 are not supported. When using JSX it can be common to combine text nodes and value nodes. For example: <title>hello {nameOfUser}</title>. While not immediately apparent, `children` in this case is an Array with length 2. If your `children` prop is using this form try rewriting it using a template string: <title>{`hello ${nameOfUser}`}</title>.",
              children$jscomp$6.length
            ) : "function" === typeof child || "symbol" === typeof child ? console.error(
              "React expect children of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found %s instead. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value.",
              "function" === typeof child ? "a Function" : "a Sybmol"
            ) : child && child.toString === {}.toString && (null != child.$$typeof ? console.error(
              "React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an object that appears to be a React element which never implements a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value which is why rendering React elements is not supported. If the `children` of <title> is a React Component try moving the <title> tag into that component. If the `children` of <title> is some HTML markup change it to be Text only to be valid HTML."
            ) : console.error(
              "React expects the `children` prop of <title> tags to be a string, number, bigint, or object with a novel `toString` method but found an object that does not implement a suitable `toString` method. Browsers treat all child Nodes of <title> tags as Text content and React expects to be able to convert children of <title> tags to a single string value. Using the default `toString` method available on every object is almost certainly an error. Consider whether the `children` of this <title> is an object in error and change it to a string or number value if so. Otherwise implement a `toString` method that React can use to produce a valid <title>."
            ));
          }
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope || null != props.itemProp)
            var JSCompiler_inline_result$jscomp$4 = pushTitleImpl(
              target$jscomp$0,
              props
            );
          else
            isFallback ? JSCompiler_inline_result$jscomp$4 = null : (pushTitleImpl(renderState.hoistableChunks, props), JSCompiler_inline_result$jscomp$4 = void 0);
          return JSCompiler_inline_result$jscomp$4;
        case "link":
          var noscriptTagInScope$jscomp$0 = formatContext.tagScope & 1, isFallback$jscomp$0 = formatContext.tagScope & 4, rel = props.rel, href = props.href, precedence = props.precedence;
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$0 || null != props.itemProp || "string" !== typeof rel || "string" !== typeof href || "" === href) {
            "stylesheet" === rel && "string" === typeof props.precedence && ("string" === typeof href && href || console.error(
              'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and expected the `href` prop to be a non-empty string but ecountered %s instead. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop ensure there is a non-empty string `href` prop as well, otherwise remove the `precedence` prop.',
              null === href ? "`null`" : void 0 === href ? "`undefined`" : "" === href ? "an empty string" : 'something with type "' + typeof href + '"'
            ));
            pushLinkImpl(target$jscomp$0, props);
            var JSCompiler_inline_result$jscomp$5 = null;
          } else if ("stylesheet" === props.rel)
            if ("string" !== typeof precedence || null != props.disabled || props.onLoad || props.onError) {
              if ("string" === typeof precedence) {
                if (null != props.disabled)
                  console.error(
                    'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and a `disabled` prop. The presence of the `disabled` prop indicates an intent to manage the stylesheet active state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the `disabled` prop, otherwise remove the `precedence` prop.'
                  );
                else if (props.onLoad || props.onError) {
                  var propDescription = props.onLoad && props.onError ? "`onLoad` and `onError` props" : props.onLoad ? "`onLoad` prop" : "`onError` prop";
                  console.error(
                    'React encountered a `<link rel="stylesheet" .../>` with a `precedence` prop and %s. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.',
                    propDescription,
                    propDescription
                  );
                }
              }
              JSCompiler_inline_result$jscomp$5 = pushLinkImpl(
                target$jscomp$0,
                props
              );
            } else {
              var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(
                href
              ) ? resumableState.styleResources[href] : void 0;
              if (resourceState !== EXISTS) {
                resumableState.styleResources[href] = EXISTS;
                styleQueue || (styleQueue = {
                  precedence: escapeTextForBrowser(precedence),
                  rules: [],
                  hrefs: [],
                  sheets: /* @__PURE__ */ new Map()
                }, renderState.styles.set(precedence, styleQueue));
                var resource = {
                  state: PENDING$1,
                  props: assign({}, props, {
                    "data-precedence": props.precedence,
                    precedence: null
                  })
                };
                if (resourceState) {
                  2 === resourceState.length && adoptPreloadCredentials(resource.props, resourceState);
                  var preloadResource = renderState.preloads.stylesheets.get(href);
                  preloadResource && 0 < preloadResource.length ? preloadResource.length = 0 : resource.state = PRELOADED;
                }
                styleQueue.sheets.set(href, resource);
                hoistableState && hoistableState.stylesheets.add(resource);
              } else if (styleQueue) {
                var _resource = styleQueue.sheets.get(href);
                _resource && hoistableState && hoistableState.stylesheets.add(_resource);
              }
              textEmbedded && target$jscomp$0.push(textSeparator);
              JSCompiler_inline_result$jscomp$5 = null;
            }
          else
            props.onLoad || props.onError ? JSCompiler_inline_result$jscomp$5 = pushLinkImpl(
              target$jscomp$0,
              props
            ) : (textEmbedded && target$jscomp$0.push(textSeparator), JSCompiler_inline_result$jscomp$5 = isFallback$jscomp$0 ? null : pushLinkImpl(renderState.hoistableChunks, props));
          return JSCompiler_inline_result$jscomp$5;
        case "script":
          var noscriptTagInScope$jscomp$1 = formatContext.tagScope & 1, asyncProp = props.async;
          if ("string" !== typeof props.src || !props.src || !asyncProp || "function" === typeof asyncProp || "symbol" === typeof asyncProp || props.onLoad || props.onError || formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$1 || null != props.itemProp)
            var JSCompiler_inline_result$jscomp$6 = pushScriptImpl(
              target$jscomp$0,
              props
            );
          else {
            var key = props.src;
            if ("module" === props.type) {
              var resources = resumableState.moduleScriptResources;
              var preloads = renderState.preloads.moduleScripts;
            } else
              resources = resumableState.scriptResources, preloads = renderState.preloads.scripts;
            var resourceState$jscomp$0 = resources.hasOwnProperty(key) ? resources[key] : void 0;
            if (resourceState$jscomp$0 !== EXISTS) {
              resources[key] = EXISTS;
              var scriptProps = props;
              if (resourceState$jscomp$0) {
                2 === resourceState$jscomp$0.length && (scriptProps = assign({}, props), adoptPreloadCredentials(scriptProps, resourceState$jscomp$0));
                var preloadResource$jscomp$0 = preloads.get(key);
                preloadResource$jscomp$0 && (preloadResource$jscomp$0.length = 0);
              }
              var resource$jscomp$0 = [];
              renderState.scripts.add(resource$jscomp$0);
              pushScriptImpl(resource$jscomp$0, scriptProps);
            }
            textEmbedded && target$jscomp$0.push(textSeparator);
            JSCompiler_inline_result$jscomp$6 = null;
          }
          return JSCompiler_inline_result$jscomp$6;
        case "style":
          var noscriptTagInScope$jscomp$2 = formatContext.tagScope & 1;
          if (hasOwnProperty2.call(props, "children")) {
            var children$jscomp$7 = props.children, child$jscomp$0 = Array.isArray(children$jscomp$7) ? 2 > children$jscomp$7.length ? children$jscomp$7[0] : null : children$jscomp$7;
            ("function" === typeof child$jscomp$0 || "symbol" === typeof child$jscomp$0 || Array.isArray(child$jscomp$0)) && console.error(
              "React expect children of <style> tags to be a string, number, or object with a `toString` method but found %s instead. In browsers style Elements can only have `Text` Nodes as children.",
              "function" === typeof child$jscomp$0 ? "a Function" : "symbol" === typeof child$jscomp$0 ? "a Sybmol" : "an Array"
            );
          }
          var precedence$jscomp$0 = props.precedence, href$jscomp$0 = props.href, nonce = props.nonce;
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$2 || null != props.itemProp || "string" !== typeof precedence$jscomp$0 || "string" !== typeof href$jscomp$0 || "" === href$jscomp$0) {
            target$jscomp$0.push(startChunkForTag("style"));
            var children$jscomp$8 = null, innerHTML$jscomp$5 = null, propKey$jscomp$8;
            for (propKey$jscomp$8 in props)
              if (hasOwnProperty2.call(props, propKey$jscomp$8)) {
                var propValue$jscomp$8 = props[propKey$jscomp$8];
                if (null != propValue$jscomp$8)
                  switch (propKey$jscomp$8) {
                    case "children":
                      children$jscomp$8 = propValue$jscomp$8;
                      break;
                    case "dangerouslySetInnerHTML":
                      innerHTML$jscomp$5 = propValue$jscomp$8;
                      break;
                    default:
                      pushAttribute(
                        target$jscomp$0,
                        propKey$jscomp$8,
                        propValue$jscomp$8
                      );
                  }
              }
            target$jscomp$0.push(endOfStartTag);
            var child$jscomp$1 = Array.isArray(children$jscomp$8) ? 2 > children$jscomp$8.length ? children$jscomp$8[0] : null : children$jscomp$8;
            "function" !== typeof child$jscomp$1 && "symbol" !== typeof child$jscomp$1 && null !== child$jscomp$1 && void 0 !== child$jscomp$1 && target$jscomp$0.push(escapeStyleTextContent(child$jscomp$1));
            pushInnerHTML(
              target$jscomp$0,
              innerHTML$jscomp$5,
              children$jscomp$8
            );
            target$jscomp$0.push(endChunkForTag("style"));
            var JSCompiler_inline_result$jscomp$7 = null;
          } else {
            href$jscomp$0.includes(" ") && console.error(
              'React expected the `href` prop for a <style> tag opting into hoisting semantics using the `precedence` prop to not have any spaces but ecountered spaces instead. using spaces in this prop will cause hydration of this style to fail on the client. The href for the <style> where this ocurred is "%s".',
              href$jscomp$0
            );
            var styleQueue$jscomp$0 = renderState.styles.get(precedence$jscomp$0), resourceState$jscomp$1 = resumableState.styleResources.hasOwnProperty(href$jscomp$0) ? resumableState.styleResources[href$jscomp$0] : void 0;
            if (resourceState$jscomp$1 !== EXISTS) {
              resumableState.styleResources[href$jscomp$0] = EXISTS;
              resourceState$jscomp$1 && console.error(
                'React encountered a hoistable style tag for the same href as a preload: "%s". When using a style tag to inline styles you should not also preload it as a stylsheet.',
                href$jscomp$0
              );
              styleQueue$jscomp$0 || (styleQueue$jscomp$0 = {
                precedence: escapeTextForBrowser(precedence$jscomp$0),
                rules: [],
                hrefs: [],
                sheets: /* @__PURE__ */ new Map()
              }, renderState.styles.set(
                precedence$jscomp$0,
                styleQueue$jscomp$0
              ));
              var nonceStyle = renderState.nonce.style;
              if (nonceStyle && nonceStyle !== nonce)
                console.error(
                  'React encountered a style tag with `precedence` "%s" and `nonce` "%s". When React manages style rules using `precedence` it will only include rules if the nonce matches the style nonce "%s" that was included with this render.',
                  precedence$jscomp$0,
                  nonce,
                  nonceStyle
                );
              else {
                !nonceStyle && nonce && console.error(
                  'React encountered a style tag with `precedence` "%s" and `nonce` "%s". When React manages style rules using `precedence` it will only include a nonce attributes if you also provide the same style nonce value as a render option.',
                  precedence$jscomp$0,
                  nonce
                );
                styleQueue$jscomp$0.hrefs.push(
                  escapeTextForBrowser(href$jscomp$0)
                );
                var target = styleQueue$jscomp$0.rules, children$jscomp$9 = null, innerHTML$jscomp$6 = null, propKey$jscomp$9;
                for (propKey$jscomp$9 in props)
                  if (hasOwnProperty2.call(props, propKey$jscomp$9)) {
                    var propValue$jscomp$9 = props[propKey$jscomp$9];
                    if (null != propValue$jscomp$9)
                      switch (propKey$jscomp$9) {
                        case "children":
                          children$jscomp$9 = propValue$jscomp$9;
                          break;
                        case "dangerouslySetInnerHTML":
                          innerHTML$jscomp$6 = propValue$jscomp$9;
                      }
                  }
                var child$jscomp$2 = Array.isArray(children$jscomp$9) ? 2 > children$jscomp$9.length ? children$jscomp$9[0] : null : children$jscomp$9;
                "function" !== typeof child$jscomp$2 && "symbol" !== typeof child$jscomp$2 && null !== child$jscomp$2 && void 0 !== child$jscomp$2 && target.push(escapeStyleTextContent(child$jscomp$2));
                pushInnerHTML(target, innerHTML$jscomp$6, children$jscomp$9);
              }
            }
            styleQueue$jscomp$0 && hoistableState && hoistableState.styles.add(styleQueue$jscomp$0);
            textEmbedded && target$jscomp$0.push(textSeparator);
            JSCompiler_inline_result$jscomp$7 = void 0;
          }
          return JSCompiler_inline_result$jscomp$7;
        case "meta":
          var noscriptTagInScope$jscomp$3 = formatContext.tagScope & 1, isFallback$jscomp$1 = formatContext.tagScope & 4;
          if (formatContext.insertionMode === SVG_MODE || noscriptTagInScope$jscomp$3 || null != props.itemProp)
            var JSCompiler_inline_result$jscomp$8 = pushSelfClosing(
              target$jscomp$0,
              props,
              "meta"
            );
          else
            textEmbedded && target$jscomp$0.push(textSeparator), JSCompiler_inline_result$jscomp$8 = isFallback$jscomp$1 ? null : "string" === typeof props.charSet ? pushSelfClosing(renderState.charsetChunks, props, "meta") : "viewport" === props.name ? pushSelfClosing(renderState.viewportChunks, props, "meta") : pushSelfClosing(
              renderState.hoistableChunks,
              props,
              "meta"
            );
          return JSCompiler_inline_result$jscomp$8;
        case "listing":
        case "pre":
          target$jscomp$0.push(startChunkForTag(type2));
          var children$jscomp$10 = null, innerHTML$jscomp$7 = null, propKey$jscomp$10;
          for (propKey$jscomp$10 in props)
            if (hasOwnProperty2.call(props, propKey$jscomp$10)) {
              var propValue$jscomp$10 = props[propKey$jscomp$10];
              if (null != propValue$jscomp$10)
                switch (propKey$jscomp$10) {
                  case "children":
                    children$jscomp$10 = propValue$jscomp$10;
                    break;
                  case "dangerouslySetInnerHTML":
                    innerHTML$jscomp$7 = propValue$jscomp$10;
                    break;
                  default:
                    pushAttribute(
                      target$jscomp$0,
                      propKey$jscomp$10,
                      propValue$jscomp$10
                    );
                }
            }
          target$jscomp$0.push(endOfStartTag);
          if (null != innerHTML$jscomp$7) {
            if (null != children$jscomp$10)
              throw Error(
                "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
              );
            if ("object" !== typeof innerHTML$jscomp$7 || !("__html" in innerHTML$jscomp$7))
              throw Error(
                "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
              );
            var html2 = innerHTML$jscomp$7.__html;
            null !== html2 && void 0 !== html2 && ("string" === typeof html2 && 0 < html2.length && "\n" === html2[0] ? target$jscomp$0.push(leadingNewline, html2) : (checkHtmlStringCoercion(html2), target$jscomp$0.push("" + html2)));
          }
          "string" === typeof children$jscomp$10 && "\n" === children$jscomp$10[0] && target$jscomp$0.push(leadingNewline);
          return children$jscomp$10;
        case "img":
          var pictureOrNoScriptTagInScope = formatContext.tagScope & 3, src2 = props.src, srcSet = props.srcSet;
          if (!("lazy" === props.loading || !src2 && !srcSet || "string" !== typeof src2 && null != src2 || "string" !== typeof srcSet && null != srcSet || "low" === props.fetchPriority || pictureOrNoScriptTagInScope) && ("string" !== typeof src2 || ":" !== src2[4] || "d" !== src2[0] && "D" !== src2[0] || "a" !== src2[1] && "A" !== src2[1] || "t" !== src2[2] && "T" !== src2[2] || "a" !== src2[3] && "A" !== src2[3]) && ("string" !== typeof srcSet || ":" !== srcSet[4] || "d" !== srcSet[0] && "D" !== srcSet[0] || "a" !== srcSet[1] && "A" !== srcSet[1] || "t" !== srcSet[2] && "T" !== srcSet[2] || "a" !== srcSet[3] && "A" !== srcSet[3])) {
            null !== hoistableState && formatContext.tagScope & 64 && (hoistableState.suspenseyImages = true);
            var sizes = "string" === typeof props.sizes ? props.sizes : void 0, key$jscomp$0 = srcSet ? srcSet + "\n" + (sizes || "") : src2, promotablePreloads = renderState.preloads.images, resource$jscomp$1 = promotablePreloads.get(key$jscomp$0);
            if (resource$jscomp$1) {
              if ("high" === props.fetchPriority || 10 > renderState.highImagePreloads.size)
                promotablePreloads.delete(key$jscomp$0), renderState.highImagePreloads.add(resource$jscomp$1);
            } else if (!resumableState.imageResources.hasOwnProperty(key$jscomp$0)) {
              resumableState.imageResources[key$jscomp$0] = PRELOAD_NO_CREDS;
              var input = props.crossOrigin;
              var crossOrigin = "string" === typeof input ? "use-credentials" === input ? input : "" : void 0;
              var headers = renderState.headers, header;
              headers && 0 < headers.remainingCapacity && "string" !== typeof props.srcSet && ("high" === props.fetchPriority || 500 > headers.highImagePreloads.length) && (header = getPreloadAsHeader(src2, "image", {
                imageSrcSet: props.srcSet,
                imageSizes: props.sizes,
                crossOrigin,
                integrity: props.integrity,
                nonce: props.nonce,
                type: props.type,
                fetchPriority: props.fetchPriority,
                referrerPolicy: props.refererPolicy
              }), 0 <= (headers.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key$jscomp$0] = PRELOAD_NO_CREDS, headers.highImagePreloads && (headers.highImagePreloads += ", "), headers.highImagePreloads += header) : (resource$jscomp$1 = [], pushLinkImpl(resource$jscomp$1, {
                rel: "preload",
                as: "image",
                href: srcSet ? void 0 : src2,
                imageSrcSet: srcSet,
                imageSizes: sizes,
                crossOrigin,
                integrity: props.integrity,
                type: props.type,
                fetchPriority: props.fetchPriority,
                referrerPolicy: props.referrerPolicy
              }), "high" === props.fetchPriority || 10 > renderState.highImagePreloads.size ? renderState.highImagePreloads.add(resource$jscomp$1) : (renderState.bulkPreloads.add(resource$jscomp$1), promotablePreloads.set(key$jscomp$0, resource$jscomp$1)));
            }
          }
          return pushSelfClosing(target$jscomp$0, props, "img");
        case "base":
        case "area":
        case "br":
        case "col":
        case "embed":
        case "hr":
        case "keygen":
        case "param":
        case "source":
        case "track":
        case "wbr":
          return pushSelfClosing(target$jscomp$0, props, type2);
        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":
          break;
        case "head":
          if (formatContext.insertionMode < HTML_MODE) {
            var preamble = preambleState || renderState.preamble;
            if (preamble.headChunks)
              throw Error("The `<head>` tag may only be rendered once.");
            null !== preambleState && target$jscomp$0.push(headPreambleContributionChunk);
            preamble.headChunks = [];
            var JSCompiler_inline_result$jscomp$9 = pushStartSingletonElement(
              preamble.headChunks,
              props,
              "head"
            );
          } else
            JSCompiler_inline_result$jscomp$9 = pushStartGenericElement(
              target$jscomp$0,
              props,
              "head"
            );
          return JSCompiler_inline_result$jscomp$9;
        case "body":
          if (formatContext.insertionMode < HTML_MODE) {
            var preamble$jscomp$0 = preambleState || renderState.preamble;
            if (preamble$jscomp$0.bodyChunks)
              throw Error("The `<body>` tag may only be rendered once.");
            null !== preambleState && target$jscomp$0.push(bodyPreambleContributionChunk);
            preamble$jscomp$0.bodyChunks = [];
            var JSCompiler_inline_result$jscomp$10 = pushStartSingletonElement(
              preamble$jscomp$0.bodyChunks,
              props,
              "body"
            );
          } else
            JSCompiler_inline_result$jscomp$10 = pushStartGenericElement(
              target$jscomp$0,
              props,
              "body"
            );
          return JSCompiler_inline_result$jscomp$10;
        case "html":
          if (formatContext.insertionMode === ROOT_HTML_MODE) {
            var preamble$jscomp$1 = preambleState || renderState.preamble;
            if (preamble$jscomp$1.htmlChunks)
              throw Error("The `<html>` tag may only be rendered once.");
            null !== preambleState && target$jscomp$0.push(htmlPreambleContributionChunk);
            preamble$jscomp$1.htmlChunks = [doctypeChunk];
            var JSCompiler_inline_result$jscomp$11 = pushStartSingletonElement(
              preamble$jscomp$1.htmlChunks,
              props,
              "html"
            );
          } else
            JSCompiler_inline_result$jscomp$11 = pushStartGenericElement(
              target$jscomp$0,
              props,
              "html"
            );
          return JSCompiler_inline_result$jscomp$11;
        default:
          if (-1 !== type2.indexOf("-")) {
            target$jscomp$0.push(startChunkForTag(type2));
            var children$jscomp$11 = null, innerHTML$jscomp$8 = null, propKey$jscomp$11;
            for (propKey$jscomp$11 in props)
              if (hasOwnProperty2.call(props, propKey$jscomp$11)) {
                var propValue$jscomp$11 = props[propKey$jscomp$11];
                if (null != propValue$jscomp$11) {
                  var attributeName = propKey$jscomp$11;
                  switch (propKey$jscomp$11) {
                    case "children":
                      children$jscomp$11 = propValue$jscomp$11;
                      break;
                    case "dangerouslySetInnerHTML":
                      innerHTML$jscomp$8 = propValue$jscomp$11;
                      break;
                    case "style":
                      pushStyleAttribute(target$jscomp$0, propValue$jscomp$11);
                      break;
                    case "suppressContentEditableWarning":
                    case "suppressHydrationWarning":
                    case "ref":
                      break;
                    case "className":
                      attributeName = "class";
                    default:
                      if (isAttributeNameSafe(propKey$jscomp$11) && "function" !== typeof propValue$jscomp$11 && "symbol" !== typeof propValue$jscomp$11 && false !== propValue$jscomp$11) {
                        if (true === propValue$jscomp$11)
                          propValue$jscomp$11 = "";
                        else if ("object" === typeof propValue$jscomp$11)
                          continue;
                        target$jscomp$0.push(
                          attributeSeparator,
                          attributeName,
                          attributeAssign,
                          escapeTextForBrowser(propValue$jscomp$11),
                          attributeEnd
                        );
                      }
                  }
                }
              }
            target$jscomp$0.push(endOfStartTag);
            pushInnerHTML(
              target$jscomp$0,
              innerHTML$jscomp$8,
              children$jscomp$11
            );
            return children$jscomp$11;
          }
      }
      return pushStartGenericElement(target$jscomp$0, props, type2);
    }
    function endChunkForTag(tag) {
      var chunk2 = endTagCache.get(tag);
      void 0 === chunk2 && (chunk2 = stringToPrecomputedChunk("</" + tag + ">"), endTagCache.set(tag, chunk2));
      return chunk2;
    }
    function hoistPreambleState(renderState, preambleState) {
      renderState = renderState.preamble;
      null === renderState.htmlChunks && preambleState.htmlChunks && (renderState.htmlChunks = preambleState.htmlChunks);
      null === renderState.headChunks && preambleState.headChunks && (renderState.headChunks = preambleState.headChunks);
      null === renderState.bodyChunks && preambleState.bodyChunks && (renderState.bodyChunks = preambleState.bodyChunks);
    }
    function writeBootstrap(destination, renderState) {
      renderState = renderState.bootstrapChunks;
      for (var i = 0; i < renderState.length - 1; i++)
        writeChunk(destination, renderState[i]);
      return i < renderState.length ? (i = renderState[i], renderState.length = 0, writeChunkAndReturn(destination, i)) : true;
    }
    function writeStartPendingSuspenseBoundary(destination, renderState, id) {
      writeChunk(destination, startPendingSuspenseBoundary1);
      if (null === id)
        throw Error(
          "An ID must have been assigned before we can complete the boundary."
        );
      writeChunk(destination, renderState.boundaryPrefix);
      writeChunk(destination, id.toString(16));
      return writeChunkAndReturn(destination, startPendingSuspenseBoundary2);
    }
    function writeStartSegment(destination, renderState, formatContext, id) {
      switch (formatContext.insertionMode) {
        case ROOT_HTML_MODE:
        case HTML_HTML_MODE:
        case HTML_HEAD_MODE:
        case HTML_MODE:
          return writeChunk(destination, startSegmentHTML), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentHTML2);
        case SVG_MODE:
          return writeChunk(destination, startSegmentSVG), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentSVG2);
        case MATHML_MODE:
          return writeChunk(destination, startSegmentMathML), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentMathML2);
        case HTML_TABLE_MODE:
          return writeChunk(destination, startSegmentTable), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentTable2);
        case HTML_TABLE_BODY_MODE:
          return writeChunk(destination, startSegmentTableBody), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentTableBody2);
        case HTML_TABLE_ROW_MODE:
          return writeChunk(destination, startSegmentTableRow), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentTableRow2);
        case HTML_COLGROUP_MODE:
          return writeChunk(destination, startSegmentColGroup), writeChunk(destination, renderState.segmentPrefix), writeChunk(destination, id.toString(16)), writeChunkAndReturn(destination, startSegmentColGroup2);
        default:
          throw Error("Unknown insertion mode. This is a bug in React.");
      }
    }
    function writeEndSegment(destination, formatContext) {
      switch (formatContext.insertionMode) {
        case ROOT_HTML_MODE:
        case HTML_HTML_MODE:
        case HTML_HEAD_MODE:
        case HTML_MODE:
          return writeChunkAndReturn(destination, endSegmentHTML);
        case SVG_MODE:
          return writeChunkAndReturn(destination, endSegmentSVG);
        case MATHML_MODE:
          return writeChunkAndReturn(destination, endSegmentMathML);
        case HTML_TABLE_MODE:
          return writeChunkAndReturn(destination, endSegmentTable);
        case HTML_TABLE_BODY_MODE:
          return writeChunkAndReturn(destination, endSegmentTableBody);
        case HTML_TABLE_ROW_MODE:
          return writeChunkAndReturn(destination, endSegmentTableRow);
        case HTML_COLGROUP_MODE:
          return writeChunkAndReturn(destination, endSegmentColGroup);
        default:
          throw Error("Unknown insertion mode. This is a bug in React.");
      }
    }
    function escapeJSStringsForInstructionScripts(input) {
      return JSON.stringify(input).replace(
        regexForJSStringsInInstructionScripts,
        function(match) {
          switch (match) {
            case "<":
              return "\\u003c";
            case "\u2028":
              return "\\u2028";
            case "\u2029":
              return "\\u2029";
            default:
              throw Error(
                "escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
              );
          }
        }
      );
    }
    function escapeJSObjectForInstructionScripts(input) {
      return JSON.stringify(input).replace(
        regexForJSStringsInScripts,
        function(match) {
          switch (match) {
            case "&":
              return "\\u0026";
            case ">":
              return "\\u003e";
            case "<":
              return "\\u003c";
            case "\u2028":
              return "\\u2028";
            case "\u2029":
              return "\\u2029";
            default:
              throw Error(
                "escapeJSObjectForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
              );
          }
        }
      );
    }
    function flushStyleTagsLateForBoundary(styleQueue) {
      var rules = styleQueue.rules, hrefs = styleQueue.hrefs;
      0 < rules.length && 0 === hrefs.length && console.error(
        "React expected to have at least one href for an a hoistable style but found none. This is a bug in React."
      );
      var i = 0;
      if (hrefs.length) {
        writeChunk(this, currentlyFlushingRenderState.startInlineStyle);
        writeChunk(this, lateStyleTagResourceOpen1);
        writeChunk(this, styleQueue.precedence);
        for (writeChunk(this, lateStyleTagResourceOpen2); i < hrefs.length - 1; i++)
          writeChunk(this, hrefs[i]), writeChunk(this, spaceSeparator);
        writeChunk(this, hrefs[i]);
        writeChunk(this, lateStyleTagResourceOpen3);
        for (i = 0; i < rules.length; i++) writeChunk(this, rules[i]);
        destinationHasCapacity = writeChunkAndReturn(
          this,
          lateStyleTagTemplateClose
        );
        currentlyRenderingBoundaryHasStylesToHoist = true;
        rules.length = 0;
        hrefs.length = 0;
      }
    }
    function hasStylesToHoist(stylesheet) {
      return stylesheet.state !== PREAMBLE ? currentlyRenderingBoundaryHasStylesToHoist = true : false;
    }
    function writeHoistablesForBoundary(destination, hoistableState, renderState) {
      currentlyRenderingBoundaryHasStylesToHoist = false;
      destinationHasCapacity = true;
      currentlyFlushingRenderState = renderState;
      hoistableState.styles.forEach(flushStyleTagsLateForBoundary, destination);
      currentlyFlushingRenderState = null;
      hoistableState.stylesheets.forEach(hasStylesToHoist);
      currentlyRenderingBoundaryHasStylesToHoist && (renderState.stylesToHoist = true);
      return destinationHasCapacity;
    }
    function flushResource(resource) {
      for (var i = 0; i < resource.length; i++) writeChunk(this, resource[i]);
      resource.length = 0;
    }
    function flushStyleInPreamble(stylesheet) {
      pushLinkImpl(stylesheetFlushingQueue, stylesheet.props);
      for (var i = 0; i < stylesheetFlushingQueue.length; i++)
        writeChunk(this, stylesheetFlushingQueue[i]);
      stylesheetFlushingQueue.length = 0;
      stylesheet.state = PREAMBLE;
    }
    function flushStylesInPreamble(styleQueue) {
      var hasStylesheets = 0 < styleQueue.sheets.size;
      styleQueue.sheets.forEach(flushStyleInPreamble, this);
      styleQueue.sheets.clear();
      var rules = styleQueue.rules, hrefs = styleQueue.hrefs;
      if (!hasStylesheets || hrefs.length) {
        writeChunk(this, currentlyFlushingRenderState.startInlineStyle);
        writeChunk(this, styleTagResourceOpen1);
        writeChunk(this, styleQueue.precedence);
        styleQueue = 0;
        if (hrefs.length) {
          for (writeChunk(this, styleTagResourceOpen2); styleQueue < hrefs.length - 1; styleQueue++)
            writeChunk(this, hrefs[styleQueue]), writeChunk(this, spaceSeparator);
          writeChunk(this, hrefs[styleQueue]);
        }
        writeChunk(this, styleTagResourceOpen3);
        for (styleQueue = 0; styleQueue < rules.length; styleQueue++)
          writeChunk(this, rules[styleQueue]);
        writeChunk(this, styleTagResourceClose);
        rules.length = 0;
        hrefs.length = 0;
      }
    }
    function preloadLateStyle(stylesheet) {
      if (stylesheet.state === PENDING$1) {
        stylesheet.state = PRELOADED;
        var props = stylesheet.props;
        pushLinkImpl(stylesheetFlushingQueue, {
          rel: "preload",
          as: "style",
          href: stylesheet.props.href,
          crossOrigin: props.crossOrigin,
          fetchPriority: props.fetchPriority,
          integrity: props.integrity,
          media: props.media,
          hrefLang: props.hrefLang,
          referrerPolicy: props.referrerPolicy
        });
        for (stylesheet = 0; stylesheet < stylesheetFlushingQueue.length; stylesheet++)
          writeChunk(this, stylesheetFlushingQueue[stylesheet]);
        stylesheetFlushingQueue.length = 0;
      }
    }
    function preloadLateStyles(styleQueue) {
      styleQueue.sheets.forEach(preloadLateStyle, this);
      styleQueue.sheets.clear();
    }
    function pushCompletedShellIdAttribute(target, resumableState) {
      (resumableState.instructions & SentCompletedShellId) === NothingSent && (resumableState.instructions |= SentCompletedShellId, target.push(
        completedShellIdAttributeStart,
        escapeTextForBrowser("_" + resumableState.idPrefix + "R_"),
        attributeEnd
      ));
    }
    function writeStyleResourceDependenciesInJS(destination, hoistableState) {
      writeChunk(destination, arrayFirstOpenBracket);
      var nextArrayOpenBrackChunk = arrayFirstOpenBracket;
      hoistableState.stylesheets.forEach(function(resource) {
        if (resource.state !== PREAMBLE)
          if (resource.state === LATE)
            writeChunk(destination, nextArrayOpenBrackChunk), resource = resource.props.href, checkAttributeStringCoercion(resource, "href"), writeChunk(
              destination,
              escapeJSObjectForInstructionScripts("" + resource)
            ), writeChunk(destination, arrayCloseBracket), nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
          else {
            writeChunk(destination, nextArrayOpenBrackChunk);
            var precedence = resource.props["data-precedence"], props = resource.props, coercedHref = sanitizeURL("" + resource.props.href);
            writeChunk(
              destination,
              escapeJSObjectForInstructionScripts(coercedHref)
            );
            checkAttributeStringCoercion(precedence, "precedence");
            precedence = "" + precedence;
            writeChunk(destination, arrayInterstitial);
            writeChunk(
              destination,
              escapeJSObjectForInstructionScripts(precedence)
            );
            for (var propKey in props)
              if (hasOwnProperty2.call(props, propKey) && (precedence = props[propKey], null != precedence))
                switch (propKey) {
                  case "href":
                  case "rel":
                  case "precedence":
                  case "data-precedence":
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      "link is a self-closing tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  default:
                    writeStyleResourceAttributeInJS(
                      destination,
                      propKey,
                      precedence
                    );
                }
            writeChunk(destination, arrayCloseBracket);
            nextArrayOpenBrackChunk = arraySubsequentOpenBracket;
            resource.state = LATE;
          }
      });
      writeChunk(destination, arrayCloseBracket);
    }
    function writeStyleResourceAttributeInJS(destination, name2, value) {
      var attributeName = name2.toLowerCase();
      switch (typeof value) {
        case "function":
        case "symbol":
          return;
      }
      switch (name2) {
        case "innerHTML":
        case "dangerouslySetInnerHTML":
        case "suppressContentEditableWarning":
        case "suppressHydrationWarning":
        case "style":
        case "ref":
          return;
        case "className":
          attributeName = "class";
          checkAttributeStringCoercion(value, attributeName);
          name2 = "" + value;
          break;
        case "hidden":
          if (false === value) return;
          name2 = "";
          break;
        case "src":
        case "href":
          value = sanitizeURL(value);
          checkAttributeStringCoercion(value, attributeName);
          name2 = "" + value;
          break;
        default:
          if (2 < name2.length && ("o" === name2[0] || "O" === name2[0]) && ("n" === name2[1] || "N" === name2[1]) || !isAttributeNameSafe(name2))
            return;
          checkAttributeStringCoercion(value, attributeName);
          name2 = "" + value;
      }
      writeChunk(destination, arrayInterstitial);
      writeChunk(
        destination,
        escapeJSObjectForInstructionScripts(attributeName)
      );
      writeChunk(destination, arrayInterstitial);
      writeChunk(destination, escapeJSObjectForInstructionScripts(name2));
    }
    function createHoistableState() {
      return { styles: /* @__PURE__ */ new Set(), stylesheets: /* @__PURE__ */ new Set(), suspenseyImages: false };
    }
    function preloadBootstrapScriptOrModule(resumableState, renderState, href, props) {
      (resumableState.scriptResources.hasOwnProperty(href) || resumableState.moduleScriptResources.hasOwnProperty(href)) && console.error(
        'Internal React Error: React expected bootstrap script or module with src "%s" to not have been preloaded already. please file an issue',
        href
      );
      resumableState.scriptResources[href] = EXISTS;
      resumableState.moduleScriptResources[href] = EXISTS;
      resumableState = [];
      pushLinkImpl(resumableState, props);
      renderState.bootstrapScripts.add(resumableState);
    }
    function adoptPreloadCredentials(target, preloadState) {
      null == target.crossOrigin && (target.crossOrigin = preloadState[0]);
      null == target.integrity && (target.integrity = preloadState[1]);
    }
    function getPreloadAsHeader(href, as, params) {
      href = escapeHrefForLinkHeaderURLContext(href);
      as = escapeStringForLinkHeaderQuotedParamValueContext(as, "as");
      as = "<" + href + '>; rel=preload; as="' + as + '"';
      for (var paramName in params)
        hasOwnProperty2.call(params, paramName) && (href = params[paramName], "string" === typeof href && (as += "; " + paramName.toLowerCase() + '="' + escapeStringForLinkHeaderQuotedParamValueContext(
          href,
          paramName
        ) + '"'));
      return as;
    }
    function escapeHrefForLinkHeaderURLContext(hrefInput) {
      checkAttributeStringCoercion(hrefInput, "href");
      return ("" + hrefInput).replace(
        regexForHrefInLinkHeaderURLContext,
        escapeHrefForLinkHeaderURLContextReplacer
      );
    }
    function escapeHrefForLinkHeaderURLContextReplacer(match) {
      switch (match) {
        case "<":
          return "%3C";
        case ">":
          return "%3E";
        case "\n":
          return "%0A";
        case "\r":
          return "%0D";
        default:
          throw Error(
            "escapeLinkHrefForHeaderContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
          );
      }
    }
    function escapeStringForLinkHeaderQuotedParamValueContext(value, name2) {
      willCoercionThrow(value) && (console.error(
        "The provided `%s` option is an unsupported type %s. This value must be coerced to a string before using it here.",
        name2,
        typeName(value)
      ), testStringCoercion(value));
      return ("" + value).replace(
        regexForLinkHeaderQuotedParamValueContext,
        escapeStringForLinkHeaderQuotedParamValueContextReplacer
      );
    }
    function escapeStringForLinkHeaderQuotedParamValueContextReplacer(match) {
      switch (match) {
        case '"':
          return "%22";
        case "'":
          return "%27";
        case ";":
          return "%3B";
        case ",":
          return "%2C";
        case "\n":
          return "%0A";
        case "\r":
          return "%0D";
        default:
          throw Error(
            "escapeStringForLinkHeaderQuotedParamValueContextReplacer encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React"
          );
      }
    }
    function hoistStyleQueueDependency(styleQueue) {
      this.styles.add(styleQueue);
    }
    function hoistStylesheetDependency(stylesheet) {
      this.stylesheets.add(stylesheet);
    }
    function hoistHoistables(parentState, childState) {
      childState.styles.forEach(hoistStyleQueueDependency, parentState);
      childState.stylesheets.forEach(hoistStylesheetDependency, parentState);
      childState.suspenseyImages && (parentState.suspenseyImages = true);
    }
    function hasSuspenseyContent(hoistableState) {
      return 0 < hoistableState.stylesheets.size || hoistableState.suspenseyImages;
    }
    function getComponentNameFromType(type2) {
      if (null == type2) return null;
      if ("function" === typeof type2)
        return type2.$$typeof === REACT_CLIENT_REFERENCE ? null : type2.displayName || type2.name || null;
      if ("string" === typeof type2) return type2;
      switch (type2) {
        case REACT_FRAGMENT_TYPE:
          return "Fragment";
        case REACT_PROFILER_TYPE:
          return "Profiler";
        case REACT_STRICT_MODE_TYPE:
          return "StrictMode";
        case REACT_SUSPENSE_TYPE:
          return "Suspense";
        case REACT_SUSPENSE_LIST_TYPE:
          return "SuspenseList";
        case REACT_ACTIVITY_TYPE:
          return "Activity";
      }
      if ("object" === typeof type2)
        switch ("number" === typeof type2.tag && console.error(
          "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
        ), type2.$$typeof) {
          case REACT_PORTAL_TYPE:
            return "Portal";
          case REACT_CONTEXT_TYPE:
            return type2.displayName || "Context";
          case REACT_CONSUMER_TYPE:
            return (type2._context.displayName || "Context") + ".Consumer";
          case REACT_FORWARD_REF_TYPE:
            var innerType = type2.render;
            type2 = type2.displayName;
            type2 || (type2 = innerType.displayName || innerType.name || "", type2 = "" !== type2 ? "ForwardRef(" + type2 + ")" : "ForwardRef");
            return type2;
          case REACT_MEMO_TYPE:
            return innerType = type2.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type2.type) || "Memo";
          case REACT_LAZY_TYPE:
            innerType = type2._payload;
            type2 = type2._init;
            try {
              return getComponentNameFromType(type2(innerType));
            } catch (x2) {
            }
        }
      return null;
    }
    function popToNearestCommonAncestor(prev, next) {
      if (prev !== next) {
        prev.context._currentValue = prev.parentValue;
        prev = prev.parent;
        var parentNext = next.parent;
        if (null === prev) {
          if (null !== parentNext)
            throw Error(
              "The stacks must reach the root at the same time. This is a bug in React."
            );
        } else {
          if (null === parentNext)
            throw Error(
              "The stacks must reach the root at the same time. This is a bug in React."
            );
          popToNearestCommonAncestor(prev, parentNext);
        }
        next.context._currentValue = next.value;
      }
    }
    function popAllPrevious(prev) {
      prev.context._currentValue = prev.parentValue;
      prev = prev.parent;
      null !== prev && popAllPrevious(prev);
    }
    function pushAllNext(next) {
      var parentNext = next.parent;
      null !== parentNext && pushAllNext(parentNext);
      next.context._currentValue = next.value;
    }
    function popPreviousToCommonLevel(prev, next) {
      prev.context._currentValue = prev.parentValue;
      prev = prev.parent;
      if (null === prev)
        throw Error(
          "The depth must equal at least at zero before reaching the root. This is a bug in React."
        );
      prev.depth === next.depth ? popToNearestCommonAncestor(prev, next) : popPreviousToCommonLevel(prev, next);
    }
    function popNextToCommonLevel(prev, next) {
      var parentNext = next.parent;
      if (null === parentNext)
        throw Error(
          "The depth must equal at least at zero before reaching the root. This is a bug in React."
        );
      prev.depth === parentNext.depth ? popToNearestCommonAncestor(prev, parentNext) : popNextToCommonLevel(prev, parentNext);
      next.context._currentValue = next.value;
    }
    function switchContext(newSnapshot) {
      var prev = currentActiveSnapshot;
      prev !== newSnapshot && (null === prev ? pushAllNext(newSnapshot) : null === newSnapshot ? popAllPrevious(prev) : prev.depth === newSnapshot.depth ? popToNearestCommonAncestor(prev, newSnapshot) : prev.depth > newSnapshot.depth ? popPreviousToCommonLevel(prev, newSnapshot) : popNextToCommonLevel(prev, newSnapshot), currentActiveSnapshot = newSnapshot);
    }
    function warnOnInvalidCallback(callback) {
      if (null !== callback && "function" !== typeof callback) {
        var key = String(callback);
        didWarnOnInvalidCallback.has(key) || (didWarnOnInvalidCallback.add(key), console.error(
          "Expected the last optional `callback` argument to be a function. Instead received: %s.",
          callback
        ));
      }
    }
    function warnNoop(publicInstance, callerName) {
      publicInstance = (publicInstance = publicInstance.constructor) && getComponentNameFromType(publicInstance) || "ReactClass";
      var warningKey = publicInstance + "." + callerName;
      didWarnAboutNoopUpdateForComponent[warningKey] || (console.error(
        "Can only update a mounting component. This usually means you called %s() outside componentWillMount() on the server. This is a no-op.\n\nPlease check the code for the %s component.",
        callerName,
        publicInstance
      ), didWarnAboutNoopUpdateForComponent[warningKey] = true);
    }
    function pushTreeContext(baseContext, totalChildren, index2) {
      var baseIdWithLeadingBit = baseContext.id;
      baseContext = baseContext.overflow;
      var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
      baseIdWithLeadingBit &= ~(1 << baseLength);
      index2 += 1;
      var length = 32 - clz32(totalChildren) + baseLength;
      if (30 < length) {
        var numberOfOverflowBits = baseLength - baseLength % 5;
        length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
        baseIdWithLeadingBit >>= numberOfOverflowBits;
        baseLength -= numberOfOverflowBits;
        return {
          id: 1 << 32 - clz32(totalChildren) + baseLength | index2 << baseLength | baseIdWithLeadingBit,
          overflow: length + baseContext
        };
      }
      return {
        id: 1 << length | index2 << baseLength | baseIdWithLeadingBit,
        overflow: baseContext
      };
    }
    function clz32Fallback(x2) {
      x2 >>>= 0;
      return 0 === x2 ? 32 : 31 - (log(x2) / LN2 | 0) | 0;
    }
    function noop2() {
    }
    function trackUsedThenable(thenableState2, thenable, index2) {
      index2 = thenableState2[index2];
      void 0 === index2 ? thenableState2.push(thenable) : index2 !== thenable && (thenable.then(noop2, noop2), thenable = index2);
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenable.reason;
        default:
          "string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenableState2 = thenable, thenableState2.status = "pending", thenableState2.then(
            function(fulfilledValue) {
              if ("pending" === thenable.status) {
                var fulfilledThenable = thenable;
                fulfilledThenable.status = "fulfilled";
                fulfilledThenable.value = fulfilledValue;
              }
            },
            function(error) {
              if ("pending" === thenable.status) {
                var rejectedThenable = thenable;
                rejectedThenable.status = "rejected";
                rejectedThenable.reason = error;
              }
            }
          ));
          switch (thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenable.reason;
          }
          suspendedThenable = thenable;
          throw SuspenseException;
      }
    }
    function getSuspendedThenable() {
      if (null === suspendedThenable)
        throw Error(
          "Expected a suspended thenable. This is a bug in React. Please file an issue."
        );
      var thenable = suspendedThenable;
      suspendedThenable = null;
      return thenable;
    }
    function is(x2, y2) {
      return x2 === y2 && (0 !== x2 || 1 / x2 === 1 / y2) || x2 !== x2 && y2 !== y2;
    }
    function resolveCurrentlyRenderingComponent() {
      if (null === currentlyRenderingComponent)
        throw Error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
      isInHookUserCodeInDev && console.error(
        "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks"
      );
      return currentlyRenderingComponent;
    }
    function createHook() {
      if (0 < numberOfReRenders)
        throw Error("Rendered more hooks than during the previous render");
      return { memoizedState: null, queue: null, next: null };
    }
    function createWorkInProgressHook() {
      null === workInProgressHook ? null === firstWorkInProgressHook ? (isReRender = false, firstWorkInProgressHook = workInProgressHook = createHook()) : (isReRender = true, workInProgressHook = firstWorkInProgressHook) : null === workInProgressHook.next ? (isReRender = false, workInProgressHook = workInProgressHook.next = createHook()) : (isReRender = true, workInProgressHook = workInProgressHook.next);
      return workInProgressHook;
    }
    function getThenableStateAfterSuspending() {
      var state = thenableState;
      thenableState = null;
      return state;
    }
    function resetHooksState() {
      isInHookUserCodeInDev = false;
      currentlyRenderingKeyPath = currentlyRenderingRequest = currentlyRenderingTask = currentlyRenderingComponent = null;
      didScheduleRenderPhaseUpdate = false;
      firstWorkInProgressHook = null;
      numberOfReRenders = 0;
      workInProgressHook = renderPhaseUpdates = null;
    }
    function readContext(context) {
      isInHookUserCodeInDev && console.error(
        "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
      );
      return context._currentValue;
    }
    function basicStateReducer(state, action) {
      return "function" === typeof action ? action(state) : action;
    }
    function useReducer(reducer2, initialArg, init2) {
      reducer2 !== basicStateReducer && (currentHookNameInDev = "useReducer");
      currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
      workInProgressHook = createWorkInProgressHook();
      if (isReRender) {
        init2 = workInProgressHook.queue;
        initialArg = init2.dispatch;
        if (null !== renderPhaseUpdates) {
          var firstRenderPhaseUpdate = renderPhaseUpdates.get(init2);
          if (void 0 !== firstRenderPhaseUpdate) {
            renderPhaseUpdates.delete(init2);
            init2 = workInProgressHook.memoizedState;
            do {
              var action = firstRenderPhaseUpdate.action;
              isInHookUserCodeInDev = true;
              init2 = reducer2(init2, action);
              isInHookUserCodeInDev = false;
              firstRenderPhaseUpdate = firstRenderPhaseUpdate.next;
            } while (null !== firstRenderPhaseUpdate);
            workInProgressHook.memoizedState = init2;
            return [init2, initialArg];
          }
        }
        return [workInProgressHook.memoizedState, initialArg];
      }
      isInHookUserCodeInDev = true;
      reducer2 = reducer2 === basicStateReducer ? "function" === typeof initialArg ? initialArg() : initialArg : void 0 !== init2 ? init2(initialArg) : initialArg;
      isInHookUserCodeInDev = false;
      workInProgressHook.memoizedState = reducer2;
      reducer2 = workInProgressHook.queue = { last: null, dispatch: null };
      reducer2 = reducer2.dispatch = dispatchAction.bind(
        null,
        currentlyRenderingComponent,
        reducer2
      );
      return [workInProgressHook.memoizedState, reducer2];
    }
    function useMemo(nextCreate, deps) {
      currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
      workInProgressHook = createWorkInProgressHook();
      deps = void 0 === deps ? null : deps;
      if (null !== workInProgressHook) {
        var prevState = workInProgressHook.memoizedState;
        if (null !== prevState && null !== deps) {
          a: {
            var JSCompiler_inline_result = prevState[1];
            if (null === JSCompiler_inline_result)
              console.error(
                "%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",
                currentHookNameInDev
              ), JSCompiler_inline_result = false;
            else {
              deps.length !== JSCompiler_inline_result.length && console.error(
                "The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",
                currentHookNameInDev,
                "[" + deps.join(", ") + "]",
                "[" + JSCompiler_inline_result.join(", ") + "]"
              );
              for (var i = 0; i < JSCompiler_inline_result.length && i < deps.length; i++)
                if (!objectIs(deps[i], JSCompiler_inline_result[i])) {
                  JSCompiler_inline_result = false;
                  break a;
                }
              JSCompiler_inline_result = true;
            }
          }
          if (JSCompiler_inline_result) return prevState[0];
        }
      }
      isInHookUserCodeInDev = true;
      nextCreate = nextCreate();
      isInHookUserCodeInDev = false;
      workInProgressHook.memoizedState = [nextCreate, deps];
      return nextCreate;
    }
    function dispatchAction(componentIdentity, queue, action) {
      if (25 <= numberOfReRenders)
        throw Error(
          "Too many re-renders. React limits the number of renders to prevent an infinite loop."
        );
      if (componentIdentity === currentlyRenderingComponent)
        if (didScheduleRenderPhaseUpdate = true, componentIdentity = { action, next: null }, null === renderPhaseUpdates && (renderPhaseUpdates = /* @__PURE__ */ new Map()), action = renderPhaseUpdates.get(queue), void 0 === action)
          renderPhaseUpdates.set(queue, componentIdentity);
        else {
          for (queue = action; null !== queue.next; ) queue = queue.next;
          queue.next = componentIdentity;
        }
    }
    function throwOnUseEffectEventCall() {
      throw Error(
        "A function wrapped in useEffectEvent can't be called during rendering."
      );
    }
    function unsupportedStartTransition() {
      throw Error("startTransition cannot be called during server rendering.");
    }
    function unsupportedSetOptimisticState() {
      throw Error("Cannot update optimistic state while rendering.");
    }
    function createPostbackActionStateKey(permalink, componentKeyPath, hookIndex) {
      if (void 0 !== permalink) return "p" + permalink;
      permalink = JSON.stringify([componentKeyPath, null, hookIndex]);
      componentKeyPath = crypto2.createHash("md5");
      componentKeyPath.update(permalink);
      return "k" + componentKeyPath.digest("hex");
    }
    function useActionState(action, initialState2, permalink) {
      resolveCurrentlyRenderingComponent();
      var actionStateHookIndex = actionStateCounter++, request = currentlyRenderingRequest;
      if ("function" === typeof action.$$FORM_ACTION) {
        var nextPostbackStateKey = null, componentKeyPath = currentlyRenderingKeyPath;
        request = request.formState;
        var isSignatureEqual = action.$$IS_SIGNATURE_EQUAL;
        if (null !== request && "function" === typeof isSignatureEqual) {
          var postbackKey = request[1];
          isSignatureEqual.call(action, request[2], request[3]) && (nextPostbackStateKey = createPostbackActionStateKey(
            permalink,
            componentKeyPath,
            actionStateHookIndex
          ), postbackKey === nextPostbackStateKey && (actionStateMatchingIndex = actionStateHookIndex, initialState2 = request[0]));
        }
        var boundAction = action.bind(null, initialState2);
        action = function(payload) {
          boundAction(payload);
        };
        "function" === typeof boundAction.$$FORM_ACTION && (action.$$FORM_ACTION = function(prefix2) {
          prefix2 = boundAction.$$FORM_ACTION(prefix2);
          void 0 !== permalink && (checkAttributeStringCoercion(permalink, "target"), permalink += "", prefix2.action = permalink);
          var formData = prefix2.data;
          formData && (null === nextPostbackStateKey && (nextPostbackStateKey = createPostbackActionStateKey(
            permalink,
            componentKeyPath,
            actionStateHookIndex
          )), formData.append("$ACTION_KEY", nextPostbackStateKey));
          return prefix2;
        });
        return [initialState2, action, false];
      }
      var _boundAction = action.bind(null, initialState2);
      return [
        initialState2,
        function(payload) {
          _boundAction(payload);
        },
        false
      ];
    }
    function unwrapThenable(thenable) {
      var index2 = thenableIndexCounter;
      thenableIndexCounter += 1;
      null === thenableState && (thenableState = []);
      return trackUsedThenable(thenableState, thenable, index2);
    }
    function unsupportedRefresh() {
      throw Error("Cache cannot be refreshed during server rendering.");
    }
    function disabledLog() {
    }
    function disableLogs() {
      if (0 === disabledDepth) {
        prevLog = console.log;
        prevInfo = console.info;
        prevWarn = console.warn;
        prevError = console.error;
        prevGroup = console.group;
        prevGroupCollapsed = console.groupCollapsed;
        prevGroupEnd = console.groupEnd;
        var props = {
          configurable: true,
          enumerable: true,
          value: disabledLog,
          writable: true
        };
        Object.defineProperties(console, {
          info: props,
          log: props,
          warn: props,
          error: props,
          group: props,
          groupCollapsed: props,
          groupEnd: props
        });
      }
      disabledDepth++;
    }
    function reenableLogs() {
      disabledDepth--;
      if (0 === disabledDepth) {
        var props = { configurable: true, enumerable: true, writable: true };
        Object.defineProperties(console, {
          log: assign({}, props, { value: prevLog }),
          info: assign({}, props, { value: prevInfo }),
          warn: assign({}, props, { value: prevWarn }),
          error: assign({}, props, { value: prevError }),
          group: assign({}, props, { value: prevGroup }),
          groupCollapsed: assign({}, props, { value: prevGroupCollapsed }),
          groupEnd: assign({}, props, { value: prevGroupEnd })
        });
      }
      0 > disabledDepth && console.error(
        "disabledDepth fell below zero. This is a bug in React. Please file an issue."
      );
    }
    function prepareStackTrace(error, structuredStackTrace) {
      error = (error.name || "Error") + ": " + (error.message || "");
      for (var i = 0; i < structuredStackTrace.length; i++)
        error += "\n    at " + structuredStackTrace[i].toString();
      return error;
    }
    function formatOwnerStack(error) {
      var prevPrepareStackTrace = Error.prepareStackTrace;
      Error.prepareStackTrace = prepareStackTrace;
      error = error.stack;
      Error.prepareStackTrace = prevPrepareStackTrace;
      error.startsWith("Error: react-stack-top-frame\n") && (error = error.slice(29));
      prevPrepareStackTrace = error.indexOf("\n");
      -1 !== prevPrepareStackTrace && (error = error.slice(prevPrepareStackTrace + 1));
      prevPrepareStackTrace = error.indexOf("react_stack_bottom_frame");
      -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error.lastIndexOf(
        "\n",
        prevPrepareStackTrace
      ));
      if (-1 !== prevPrepareStackTrace)
        error = error.slice(0, prevPrepareStackTrace);
      else return "";
      return error;
    }
    function describeBuiltInComponentFrame(name2) {
      if (void 0 === prefix)
        try {
          throw Error();
        } catch (x2) {
          var match = x2.stack.trim().match(/\n( *(at )?)/);
          prefix = match && match[1] || "";
          suffix = -1 < x2.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x2.stack.indexOf("@") ? "@unknown:0:0" : "";
        }
      return "\n" + prefix + name2 + suffix;
    }
    function describeNativeComponentFrame(fn, construct) {
      if (!fn || reentry) return "";
      var frame = componentFrameCache.get(fn);
      if (void 0 !== frame) return frame;
      reentry = true;
      frame = Error.prepareStackTrace;
      Error.prepareStackTrace = prepareStackTrace;
      var previousDispatcher2 = null;
      previousDispatcher2 = ReactSharedInternals.H;
      ReactSharedInternals.H = null;
      disableLogs();
      try {
        var RunInRootFrame = {
          DetermineComponentFrameRoot: function() {
            try {
              if (construct) {
                var Fake = function() {
                  throw Error();
                };
                Object.defineProperty(Fake.prototype, "props", {
                  set: function() {
                    throw Error();
                  }
                });
                if ("object" === typeof Reflect && Reflect.construct) {
                  try {
                    Reflect.construct(Fake, []);
                  } catch (x2) {
                    var control = x2;
                  }
                  Reflect.construct(fn, [], Fake);
                } else {
                  try {
                    Fake.call();
                  } catch (x$0) {
                    control = x$0;
                  }
                  fn.call(Fake.prototype);
                }
              } else {
                try {
                  throw Error();
                } catch (x$1) {
                  control = x$1;
                }
                (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
                });
              }
            } catch (sample) {
              if (sample && control && "string" === typeof sample.stack)
                return [sample.stack, control.stack];
            }
            return [null, null];
          }
        };
        RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
        var namePropDescriptor = Object.getOwnPropertyDescriptor(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name"
        );
        namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
          RunInRootFrame.DetermineComponentFrameRoot,
          "name",
          { value: "DetermineComponentFrameRoot" }
        );
        var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
        if (sampleStack && controlStack) {
          var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
          for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes(
            "DetermineComponentFrameRoot"
          ); )
            namePropDescriptor++;
          for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes(
            "DetermineComponentFrameRoot"
          ); )
            _RunInRootFrame$Deter++;
          if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
            for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
              _RunInRootFrame$Deter--;
          for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
            if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
              if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) {
                do
                  if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                    var _frame = "\n" + sampleLines[namePropDescriptor].replace(
                      " at new ",
                      " at "
                    );
                    fn.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn.displayName));
                    "function" === typeof fn && componentFrameCache.set(fn, _frame);
                    return _frame;
                  }
                while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
              }
              break;
            }
        }
      } finally {
        reentry = false, ReactSharedInternals.H = previousDispatcher2, reenableLogs(), Error.prepareStackTrace = frame;
      }
      sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
      "function" === typeof fn && componentFrameCache.set(fn, sampleLines);
      return sampleLines;
    }
    function describeComponentStackByType(type2) {
      if ("string" === typeof type2) return describeBuiltInComponentFrame(type2);
      if ("function" === typeof type2)
        return type2.prototype && type2.prototype.isReactComponent ? describeNativeComponentFrame(type2, true) : describeNativeComponentFrame(type2, false);
      if ("object" === typeof type2 && null !== type2) {
        switch (type2.$$typeof) {
          case REACT_FORWARD_REF_TYPE:
            return describeNativeComponentFrame(type2.render, false);
          case REACT_MEMO_TYPE:
            return describeNativeComponentFrame(type2.type, false);
          case REACT_LAZY_TYPE:
            var lazyComponent = type2, payload = lazyComponent._payload;
            lazyComponent = lazyComponent._init;
            try {
              type2 = lazyComponent(payload);
            } catch (x2) {
              return describeBuiltInComponentFrame("Lazy");
            }
            return describeComponentStackByType(type2);
        }
        if ("string" === typeof type2.name) {
          a: {
            payload = type2.name;
            lazyComponent = type2.env;
            type2 = type2.debugLocation;
            if (null != type2) {
              type2 = formatOwnerStack(type2);
              var idx = type2.lastIndexOf("\n");
              type2 = -1 === idx ? type2 : type2.slice(idx + 1);
              if (-1 !== type2.indexOf(payload)) {
                payload = "\n" + type2;
                break a;
              }
            }
            payload = describeBuiltInComponentFrame(
              payload + (lazyComponent ? " [" + lazyComponent + "]" : "")
            );
          }
          return payload;
        }
      }
      switch (type2) {
        case REACT_SUSPENSE_LIST_TYPE:
          return describeBuiltInComponentFrame("SuspenseList");
        case REACT_SUSPENSE_TYPE:
          return describeBuiltInComponentFrame("Suspense");
      }
      return "";
    }
    function resetOwnerStackLimit() {
      var now = getCurrentTime();
      1e3 < now - lastResetTime && (ReactSharedInternals.recentlyCreatedOwnerStacks = 0, lastResetTime = now);
    }
    function isEligibleForOutlining(request, boundary) {
      return (500 < boundary.byteSize || hasSuspenseyContent(boundary.contentState)) && null === boundary.contentPreamble;
    }
    function defaultErrorHandler(error) {
      if ("object" === typeof error && null !== error && "string" === typeof error.environmentName) {
        var JSCompiler_inline_result = error.environmentName;
        error = [error].slice(0);
        "string" === typeof error[0] ? error.splice(
          0,
          1,
          "\x1B[0m\x1B[7m%c%s\x1B[0m%c " + error[0],
          "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px",
          " " + JSCompiler_inline_result + " ",
          ""
        ) : error.splice(
          0,
          0,
          "\x1B[0m\x1B[7m%c%s\x1B[0m%c",
          "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px",
          " " + JSCompiler_inline_result + " ",
          ""
        );
        error.unshift(console);
        JSCompiler_inline_result = bind2.apply(console.error, error);
        JSCompiler_inline_result();
      } else console.error(error);
      return null;
    }
    function RequestInstance(resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
      var abortSet = /* @__PURE__ */ new Set();
      this.destination = null;
      this.flushScheduled = false;
      this.resumableState = resumableState;
      this.renderState = renderState;
      this.rootFormatContext = rootFormatContext;
      this.progressiveChunkSize = void 0 === progressiveChunkSize ? 12800 : progressiveChunkSize;
      this.status = 10;
      this.fatalError = null;
      this.pendingRootTasks = this.allPendingTasks = this.nextSegmentId = 0;
      this.completedPreambleSegments = this.completedRootSegment = null;
      this.byteSize = 0;
      this.abortableTasks = abortSet;
      this.pingedTasks = [];
      this.clientRenderedBoundaries = [];
      this.completedBoundaries = [];
      this.partialBoundaries = [];
      this.trackedPostpones = null;
      this.onError = void 0 === onError ? defaultErrorHandler : onError;
      this.onPostpone = void 0 === onPostpone ? noop2 : onPostpone;
      this.onAllReady = void 0 === onAllReady ? noop2 : onAllReady;
      this.onShellReady = void 0 === onShellReady ? noop2 : onShellReady;
      this.onShellError = void 0 === onShellError ? noop2 : onShellError;
      this.onFatalError = void 0 === onFatalError ? noop2 : onFatalError;
      this.formState = void 0 === formState ? null : formState;
      this.didWarnForKey = null;
    }
    function createRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone, formState) {
      resetOwnerStackLimit();
      resumableState = new RequestInstance(
        resumableState,
        renderState,
        rootFormatContext,
        progressiveChunkSize,
        onError,
        onAllReady,
        onShellReady,
        onShellError,
        onFatalError,
        onPostpone,
        formState
      );
      renderState = createPendingSegment(
        resumableState,
        0,
        null,
        rootFormatContext,
        false,
        false
      );
      renderState.parentFlushed = true;
      children = createRenderTask(
        resumableState,
        null,
        children,
        -1,
        null,
        renderState,
        null,
        null,
        resumableState.abortableTasks,
        null,
        rootFormatContext,
        null,
        emptyTreeContext,
        null,
        null,
        emptyContextObject,
        null
      );
      pushComponentStack(children);
      resumableState.pingedTasks.push(children);
      return resumableState;
    }
    function createPrerenderRequest(children, resumableState, renderState, rootFormatContext, progressiveChunkSize, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone) {
      children = createRequest(
        children,
        resumableState,
        renderState,
        rootFormatContext,
        progressiveChunkSize,
        onError,
        onAllReady,
        onShellReady,
        onShellError,
        onFatalError,
        onPostpone,
        void 0
      );
      children.trackedPostpones = {
        workingMap: /* @__PURE__ */ new Map(),
        rootNodes: [],
        rootSlots: null
      };
      return children;
    }
    function resumeRequest(children, postponedState, renderState, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone) {
      resetOwnerStackLimit();
      renderState = new RequestInstance(
        postponedState.resumableState,
        renderState,
        postponedState.rootFormatContext,
        postponedState.progressiveChunkSize,
        onError,
        onAllReady,
        onShellReady,
        onShellError,
        onFatalError,
        onPostpone,
        null
      );
      renderState.nextSegmentId = postponedState.nextSegmentId;
      if ("number" === typeof postponedState.replaySlots)
        return onError = createPendingSegment(
          renderState,
          0,
          null,
          postponedState.rootFormatContext,
          false,
          false
        ), onError.parentFlushed = true, children = createRenderTask(
          renderState,
          null,
          children,
          -1,
          null,
          onError,
          null,
          null,
          renderState.abortableTasks,
          null,
          postponedState.rootFormatContext,
          null,
          emptyTreeContext,
          null,
          null,
          emptyContextObject,
          null
        ), pushComponentStack(children), renderState.pingedTasks.push(children), renderState;
      children = createReplayTask(
        renderState,
        null,
        {
          nodes: postponedState.replayNodes,
          slots: postponedState.replaySlots,
          pendingTasks: 0
        },
        children,
        -1,
        null,
        null,
        renderState.abortableTasks,
        null,
        postponedState.rootFormatContext,
        null,
        emptyTreeContext,
        null,
        null,
        emptyContextObject,
        null
      );
      pushComponentStack(children);
      renderState.pingedTasks.push(children);
      return renderState;
    }
    function resumeAndPrerenderRequest(children, postponedState, renderState, onError, onAllReady, onShellReady, onShellError, onFatalError, onPostpone) {
      children = resumeRequest(
        children,
        postponedState,
        renderState,
        onError,
        onAllReady,
        onShellReady,
        onShellError,
        onFatalError,
        onPostpone
      );
      children.trackedPostpones = {
        workingMap: /* @__PURE__ */ new Map(),
        rootNodes: [],
        rootSlots: null
      };
      return children;
    }
    function resolveRequest() {
      if (currentRequest) return currentRequest;
      var store = requestStorage.getStore();
      return store ? store : null;
    }
    function pingTask(request, task) {
      request.pingedTasks.push(task);
      1 === request.pingedTasks.length && (request.flushScheduled = null !== request.destination, null !== request.trackedPostpones || 10 === request.status ? scheduleMicrotask(function() {
        return performWork(request);
      }) : setImmediate(function() {
        return performWork(request);
      }));
    }
    function createSuspenseBoundary(request, row, fallbackAbortableTasks, contentPreamble, fallbackPreamble) {
      fallbackAbortableTasks = {
        status: PENDING,
        rootSegmentID: -1,
        parentFlushed: false,
        pendingTasks: 0,
        row,
        completedSegments: [],
        byteSize: 0,
        fallbackAbortableTasks,
        errorDigest: null,
        contentState: createHoistableState(),
        fallbackState: createHoistableState(),
        contentPreamble,
        fallbackPreamble,
        trackedContentKeyPath: null,
        trackedFallbackNode: null,
        errorMessage: null,
        errorStack: null,
        errorComponentStack: null
      };
      null !== row && (row.pendingTasks++, contentPreamble = row.boundaries, null !== contentPreamble && (request.allPendingTasks++, fallbackAbortableTasks.pendingTasks++, contentPreamble.push(fallbackAbortableTasks)), request = row.inheritedHoistables, null !== request && hoistHoistables(fallbackAbortableTasks.contentState, request));
      return fallbackAbortableTasks;
    }
    function createRenderTask(request, thenableState2, node2, childIndex, blockedBoundary, blockedSegment, blockedPreamble, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack, legacyContext, debugTask) {
      request.allPendingTasks++;
      null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
      null !== row && row.pendingTasks++;
      var task = {
        replay: null,
        node: node2,
        childIndex,
        ping: function() {
          return pingTask(request, task);
        },
        blockedBoundary,
        blockedSegment,
        blockedPreamble,
        hoistableState,
        abortSet,
        keyPath,
        formatContext,
        context,
        treeContext,
        row,
        componentStack,
        thenableState: thenableState2
      };
      task.debugTask = debugTask;
      abortSet.add(task);
      return task;
    }
    function createReplayTask(request, thenableState2, replay, node2, childIndex, blockedBoundary, hoistableState, abortSet, keyPath, formatContext, context, treeContext, row, componentStack, legacyContext, debugTask) {
      request.allPendingTasks++;
      null === blockedBoundary ? request.pendingRootTasks++ : blockedBoundary.pendingTasks++;
      null !== row && row.pendingTasks++;
      replay.pendingTasks++;
      var task = {
        replay,
        node: node2,
        childIndex,
        ping: function() {
          return pingTask(request, task);
        },
        blockedBoundary,
        blockedSegment: null,
        blockedPreamble: null,
        hoistableState,
        abortSet,
        keyPath,
        formatContext,
        context,
        treeContext,
        row,
        componentStack,
        thenableState: thenableState2
      };
      task.debugTask = debugTask;
      abortSet.add(task);
      return task;
    }
    function createPendingSegment(request, index2, boundary, parentFormatContext, lastPushedText, textEmbedded) {
      return {
        status: PENDING,
        parentFlushed: false,
        id: -1,
        index: index2,
        chunks: [],
        children: [],
        preambleChildren: [],
        parentFormatContext,
        boundary,
        lastPushedText,
        textEmbedded
      };
    }
    function getCurrentStackInDEV() {
      if (null === currentTaskInDEV || null === currentTaskInDEV.componentStack)
        return "";
      var componentStack = currentTaskInDEV.componentStack;
      try {
        var info = "";
        if ("string" === typeof componentStack.type)
          info += describeBuiltInComponentFrame(componentStack.type);
        else if ("function" === typeof componentStack.type) {
          if (!componentStack.owner) {
            var JSCompiler_temp_const = info, fn = componentStack.type, name2 = fn ? fn.displayName || fn.name : "";
            var JSCompiler_inline_result = name2 ? describeBuiltInComponentFrame(name2) : "";
            info = JSCompiler_temp_const + JSCompiler_inline_result;
          }
        } else
          componentStack.owner || (info += describeComponentStackByType(componentStack.type));
        for (; componentStack; )
          JSCompiler_temp_const = null, null != componentStack.debugStack ? JSCompiler_temp_const = formatOwnerStack(
            componentStack.debugStack
          ) : (JSCompiler_inline_result = componentStack, null != JSCompiler_inline_result.stack && (JSCompiler_temp_const = "string" !== typeof JSCompiler_inline_result.stack ? JSCompiler_inline_result.stack = formatOwnerStack(
            JSCompiler_inline_result.stack
          ) : JSCompiler_inline_result.stack)), (componentStack = componentStack.owner) && JSCompiler_temp_const && (info += "\n" + JSCompiler_temp_const);
        var JSCompiler_inline_result$jscomp$0 = info;
      } catch (x2) {
        JSCompiler_inline_result$jscomp$0 = "\nError generating stack: " + x2.message + "\n" + x2.stack;
      }
      return JSCompiler_inline_result$jscomp$0;
    }
    function pushHaltedAwaitOnComponentStack(task, debugInfo) {
      if (null != debugInfo)
        for (var i = debugInfo.length - 1; 0 <= i; i--) {
          var info = debugInfo[i];
          if ("string" === typeof info.name) break;
          if ("number" === typeof info.time) break;
          if (null != info.awaited) {
            var bestStack = null == info.debugStack ? info.awaited : info;
            if (void 0 !== bestStack.debugStack) {
              task.componentStack = {
                parent: task.componentStack,
                type: info,
                owner: bestStack.owner,
                stack: bestStack.debugStack
              };
              task.debugTask = bestStack.debugTask;
              break;
            }
          }
        }
    }
    function pushServerComponentStack(task, debugInfo) {
      if (null != debugInfo)
        for (var i = 0; i < debugInfo.length; i++) {
          var componentInfo = debugInfo[i];
          "string" === typeof componentInfo.name && void 0 !== componentInfo.debugStack && (task.componentStack = {
            parent: task.componentStack,
            type: componentInfo,
            owner: componentInfo.owner,
            stack: componentInfo.debugStack
          }, task.debugTask = componentInfo.debugTask);
        }
    }
    function pushComponentStack(task) {
      var node2 = task.node;
      if ("object" === typeof node2 && null !== node2)
        switch (node2.$$typeof) {
          case REACT_ELEMENT_TYPE:
            var type2 = node2.type, owner = node2._owner, stack = node2._debugStack;
            pushServerComponentStack(task, node2._debugInfo);
            task.debugTask = node2._debugTask;
            task.componentStack = {
              parent: task.componentStack,
              type: type2,
              owner,
              stack
            };
            break;
          case REACT_LAZY_TYPE:
            pushServerComponentStack(task, node2._debugInfo);
            break;
          default:
            "function" === typeof node2.then && pushServerComponentStack(task, node2._debugInfo);
        }
    }
    function replaceSuspenseComponentStackWithSuspenseFallbackStack(componentStack) {
      return null === componentStack ? null : {
        parent: componentStack.parent,
        type: "Suspense Fallback",
        owner: componentStack.owner,
        stack: componentStack.stack
      };
    }
    function getThrownInfo(node$jscomp$0) {
      var errorInfo = {};
      node$jscomp$0 && Object.defineProperty(errorInfo, "componentStack", {
        configurable: true,
        enumerable: true,
        get: function() {
          try {
            var info = "", node2 = node$jscomp$0;
            do
              info += describeComponentStackByType(node2.type), node2 = node2.parent;
            while (node2);
            var stack = info;
          } catch (x2) {
            stack = "\nError generating stack: " + x2.message + "\n" + x2.stack;
          }
          Object.defineProperty(errorInfo, "componentStack", {
            value: stack
          });
          return stack;
        }
      });
      return errorInfo;
    }
    function encodeErrorForBoundary(boundary, digest, error, thrownInfo, wasAborted) {
      boundary.errorDigest = digest;
      error instanceof Error ? (digest = String(error.message), error = String(error.stack)) : (digest = "object" === typeof error && null !== error ? describeObjectForErrorMessage(error) : String(error), error = null);
      wasAborted = wasAborted ? "Switched to client rendering because the server rendering aborted due to:\n\n" : "Switched to client rendering because the server rendering errored:\n\n";
      boundary.errorMessage = wasAborted + digest;
      boundary.errorStack = null !== error ? wasAborted + error : null;
      boundary.errorComponentStack = thrownInfo.componentStack;
    }
    function logRecoverableError(request, error, errorInfo, debugTask) {
      request = request.onError;
      error = debugTask ? debugTask.run(request.bind(null, error, errorInfo)) : request(error, errorInfo);
      if (null != error && "string" !== typeof error)
        console.error(
          'onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "%s" instead',
          typeof error
        );
      else return error;
    }
    function fatalError(request, error, errorInfo, debugTask) {
      errorInfo = request.onShellError;
      var onFatalError = request.onFatalError;
      debugTask ? (debugTask.run(errorInfo.bind(null, error)), debugTask.run(onFatalError.bind(null, error))) : (errorInfo(error), onFatalError(error));
      null !== request.destination ? (request.status = CLOSED, request.destination.destroy(error)) : (request.status = 13, request.fatalError = error);
    }
    function finishSuspenseListRow(request, row) {
      unblockSuspenseListRow(request, row.next, row.hoistables);
    }
    function unblockSuspenseListRow(request, unblockedRow, inheritedHoistables) {
      for (; null !== unblockedRow; ) {
        null !== inheritedHoistables && (hoistHoistables(unblockedRow.hoistables, inheritedHoistables), unblockedRow.inheritedHoistables = inheritedHoistables);
        var unblockedBoundaries = unblockedRow.boundaries;
        if (null !== unblockedBoundaries) {
          unblockedRow.boundaries = null;
          for (var i = 0; i < unblockedBoundaries.length; i++) {
            var unblockedBoundary = unblockedBoundaries[i];
            null !== inheritedHoistables && hoistHoistables(
              unblockedBoundary.contentState,
              inheritedHoistables
            );
            finishedTask(request, unblockedBoundary, null, null);
          }
        }
        unblockedRow.pendingTasks--;
        if (0 < unblockedRow.pendingTasks) break;
        inheritedHoistables = unblockedRow.hoistables;
        unblockedRow = unblockedRow.next;
      }
    }
    function tryToResolveTogetherRow(request, togetherRow) {
      var boundaries = togetherRow.boundaries;
      if (null !== boundaries && togetherRow.pendingTasks === boundaries.length) {
        for (var allCompleteAndInlinable = true, i = 0; i < boundaries.length; i++) {
          var rowBoundary = boundaries[i];
          if (1 !== rowBoundary.pendingTasks || rowBoundary.parentFlushed || isEligibleForOutlining(request, rowBoundary)) {
            allCompleteAndInlinable = false;
            break;
          }
        }
        allCompleteAndInlinable && unblockSuspenseListRow(request, togetherRow, togetherRow.hoistables);
      }
    }
    function createSuspenseListRow(previousRow) {
      var newRow = {
        pendingTasks: 1,
        boundaries: null,
        hoistables: createHoistableState(),
        inheritedHoistables: null,
        together: false,
        next: null
      };
      null !== previousRow && 0 < previousRow.pendingTasks && (newRow.pendingTasks++, newRow.boundaries = [], previousRow.next = newRow);
      return newRow;
    }
    function renderSuspenseListRows(request, task, keyPath, rows, revealOrder) {
      var prevKeyPath = task.keyPath, prevTreeContext = task.treeContext, prevRow = task.row, previousComponentStack = task.componentStack;
      var previousDebugTask = task.debugTask;
      pushServerComponentStack(task, task.node.props.children._debugInfo);
      task.keyPath = keyPath;
      keyPath = rows.length;
      var previousSuspenseListRow = null;
      if (null !== task.replay) {
        var resumeSlots = task.replay.slots;
        if (null !== resumeSlots && "object" === typeof resumeSlots)
          for (var n = 0; n < keyPath; n++) {
            var i = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? n : keyPath - 1 - n, node2 = rows[i];
            task.row = previousSuspenseListRow = createSuspenseListRow(
              previousSuspenseListRow
            );
            task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
            var resumeSegmentID = resumeSlots[i];
            "number" === typeof resumeSegmentID ? (resumeNode(request, task, resumeSegmentID, node2, i), delete resumeSlots[i]) : renderNode(request, task, node2, i);
            0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
          }
        else
          for (resumeSlots = 0; resumeSlots < keyPath; resumeSlots++)
            n = "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder ? resumeSlots : keyPath - 1 - resumeSlots, i = rows[n], warnForMissingKey(request, task, i), task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(prevTreeContext, keyPath, n), renderNode(request, task, i, n), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
      } else if ("backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder)
        for (revealOrder = 0; revealOrder < keyPath; revealOrder++)
          resumeSlots = rows[revealOrder], warnForMissingKey(request, task, resumeSlots), task.row = previousSuspenseListRow = createSuspenseListRow(previousSuspenseListRow), task.treeContext = pushTreeContext(
            prevTreeContext,
            keyPath,
            revealOrder
          ), renderNode(request, task, resumeSlots, revealOrder), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
      else {
        revealOrder = task.blockedSegment;
        resumeSlots = revealOrder.children.length;
        n = revealOrder.chunks.length;
        for (i = keyPath - 1; 0 <= i; i--) {
          node2 = rows[i];
          task.row = previousSuspenseListRow = createSuspenseListRow(
            previousSuspenseListRow
          );
          task.treeContext = pushTreeContext(prevTreeContext, keyPath, i);
          resumeSegmentID = createPendingSegment(
            request,
            n,
            null,
            task.formatContext,
            0 === i ? revealOrder.lastPushedText : true,
            true
          );
          revealOrder.children.splice(resumeSlots, 0, resumeSegmentID);
          task.blockedSegment = resumeSegmentID;
          warnForMissingKey(request, task, node2);
          try {
            renderNode(request, task, node2, i), resumeSegmentID.lastPushedText && resumeSegmentID.textEmbedded && resumeSegmentID.chunks.push(textSeparator), resumeSegmentID.status = COMPLETED, finishedSegment(request, task.blockedBoundary, resumeSegmentID), 0 === --previousSuspenseListRow.pendingTasks && finishSuspenseListRow(request, previousSuspenseListRow);
          } catch (thrownValue) {
            throw resumeSegmentID.status = 12 === request.status ? ABORTED : ERRORED, thrownValue;
          }
        }
        task.blockedSegment = revealOrder;
        revealOrder.lastPushedText = false;
      }
      null !== prevRow && null !== previousSuspenseListRow && 0 < previousSuspenseListRow.pendingTasks && (prevRow.pendingTasks++, previousSuspenseListRow.next = prevRow);
      task.treeContext = prevTreeContext;
      task.row = prevRow;
      task.keyPath = prevKeyPath;
      task.componentStack = previousComponentStack;
      task.debugTask = previousDebugTask;
    }
    function renderWithHooks(request, task, keyPath, Component, props, secondArg) {
      var prevThenableState = task.thenableState;
      task.thenableState = null;
      currentlyRenderingComponent = {};
      currentlyRenderingTask = task;
      currentlyRenderingRequest = request;
      currentlyRenderingKeyPath = keyPath;
      isInHookUserCodeInDev = false;
      actionStateCounter = localIdCounter = 0;
      actionStateMatchingIndex = -1;
      thenableIndexCounter = 0;
      thenableState = prevThenableState;
      for (request = callComponentInDEV(Component, props, secondArg); didScheduleRenderPhaseUpdate; )
        didScheduleRenderPhaseUpdate = false, actionStateCounter = localIdCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, numberOfReRenders += 1, workInProgressHook = null, request = Component(props, secondArg);
      resetHooksState();
      return request;
    }
    function finishFunctionComponent(request, task, keyPath, children, hasId, actionStateCount, actionStateMatchingIndex2) {
      var didEmitActionStateMarkers = false;
      if (0 !== actionStateCount && null !== request.formState) {
        var segment = task.blockedSegment;
        if (null !== segment) {
          didEmitActionStateMarkers = true;
          segment = segment.chunks;
          for (var i = 0; i < actionStateCount; i++)
            i === actionStateMatchingIndex2 ? segment.push(formStateMarkerIsMatching) : segment.push(formStateMarkerIsNotMatching);
        }
      }
      actionStateCount = task.keyPath;
      task.keyPath = keyPath;
      hasId ? (keyPath = task.treeContext, task.treeContext = pushTreeContext(keyPath, 1, 0), renderNode(request, task, children, -1), task.treeContext = keyPath) : didEmitActionStateMarkers ? renderNode(request, task, children, -1) : renderNodeDestructive(request, task, children, -1);
      task.keyPath = actionStateCount;
    }
    function renderElement(request, task, keyPath, type2, props, ref2) {
      if ("function" === typeof type2)
        if (type2.prototype && type2.prototype.isReactComponent) {
          var newProps = props;
          if ("ref" in props) {
            newProps = {};
            for (var propName in props)
              "ref" !== propName && (newProps[propName] = props[propName]);
          }
          var defaultProps = type2.defaultProps;
          if (defaultProps) {
            newProps === props && (newProps = assign({}, newProps, props));
            for (var _propName in defaultProps)
              void 0 === newProps[_propName] && (newProps[_propName] = defaultProps[_propName]);
          }
          var resolvedProps = newProps;
          var context = emptyContextObject, contextType = type2.contextType;
          if ("contextType" in type2 && null !== contextType && (void 0 === contextType || contextType.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(type2)) {
            didWarnAboutInvalidateContextType.add(type2);
            var addendum = void 0 === contextType ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : "object" !== typeof contextType ? " However, it is set to a " + typeof contextType + "." : contextType.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(contextType).join(", ") + "}.";
            console.error(
              "%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",
              getComponentNameFromType(type2) || "Component",
              addendum
            );
          }
          "object" === typeof contextType && null !== contextType && (context = contextType._currentValue);
          var instance = new type2(resolvedProps, context);
          if ("function" === typeof type2.getDerivedStateFromProps && (null === instance.state || void 0 === instance.state)) {
            var componentName = getComponentNameFromType(type2) || "Component";
            didWarnAboutUninitializedState.has(componentName) || (didWarnAboutUninitializedState.add(componentName), console.error(
              "`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",
              componentName,
              null === instance.state ? "null" : "undefined",
              componentName
            ));
          }
          if ("function" === typeof type2.getDerivedStateFromProps || "function" === typeof instance.getSnapshotBeforeUpdate) {
            var foundWillMountName = null, foundWillReceivePropsName = null, foundWillUpdateName = null;
            "function" === typeof instance.componentWillMount && true !== instance.componentWillMount.__suppressDeprecationWarning ? foundWillMountName = "componentWillMount" : "function" === typeof instance.UNSAFE_componentWillMount && (foundWillMountName = "UNSAFE_componentWillMount");
            "function" === typeof instance.componentWillReceiveProps && true !== instance.componentWillReceiveProps.__suppressDeprecationWarning ? foundWillReceivePropsName = "componentWillReceiveProps" : "function" === typeof instance.UNSAFE_componentWillReceiveProps && (foundWillReceivePropsName = "UNSAFE_componentWillReceiveProps");
            "function" === typeof instance.componentWillUpdate && true !== instance.componentWillUpdate.__suppressDeprecationWarning ? foundWillUpdateName = "componentWillUpdate" : "function" === typeof instance.UNSAFE_componentWillUpdate && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
            if (null !== foundWillMountName || null !== foundWillReceivePropsName || null !== foundWillUpdateName) {
              var _componentName = getComponentNameFromType(type2) || "Component", newApiName = "function" === typeof type2.getDerivedStateFromProps ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
              didWarnAboutLegacyLifecyclesAndDerivedState.has(_componentName) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(
                _componentName
              ), console.error(
                "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://react.dev/link/unsafe-component-lifecycles",
                _componentName,
                newApiName,
                null !== foundWillMountName ? "\n  " + foundWillMountName : "",
                null !== foundWillReceivePropsName ? "\n  " + foundWillReceivePropsName : "",
                null !== foundWillUpdateName ? "\n  " + foundWillUpdateName : ""
              ));
            }
          }
          var name2 = getComponentNameFromType(type2) || "Component";
          instance.render || (type2.prototype && "function" === typeof type2.prototype.render ? console.error(
            "No `render` method found on the %s instance: did you accidentally return an object from the constructor?",
            name2
          ) : console.error(
            "No `render` method found on the %s instance: you may have forgotten to define `render`.",
            name2
          ));
          !instance.getInitialState || instance.getInitialState.isReactClassApproved || instance.state || console.error(
            "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",
            name2
          );
          instance.getDefaultProps && !instance.getDefaultProps.isReactClassApproved && console.error(
            "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",
            name2
          );
          instance.contextType && console.error(
            "contextType was defined as an instance property on %s. Use a static property to define contextType instead.",
            name2
          );
          type2.childContextTypes && !didWarnAboutChildContextTypes.has(type2) && (didWarnAboutChildContextTypes.add(type2), console.error(
            "%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)",
            name2
          ));
          type2.contextTypes && !didWarnAboutContextTypes$1.has(type2) && (didWarnAboutContextTypes$1.add(type2), console.error(
            "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)",
            name2
          ));
          "function" === typeof instance.componentShouldUpdate && console.error(
            "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",
            name2
          );
          type2.prototype && type2.prototype.isPureReactComponent && "undefined" !== typeof instance.shouldComponentUpdate && console.error(
            "%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",
            getComponentNameFromType(type2) || "A pure component"
          );
          "function" === typeof instance.componentDidUnmount && console.error(
            "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",
            name2
          );
          "function" === typeof instance.componentDidReceiveProps && console.error(
            "%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",
            name2
          );
          "function" === typeof instance.componentWillRecieveProps && console.error(
            "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",
            name2
          );
          "function" === typeof instance.UNSAFE_componentWillRecieveProps && console.error(
            "%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",
            name2
          );
          var hasMutatedProps = instance.props !== resolvedProps;
          void 0 !== instance.props && hasMutatedProps && console.error(
            "When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",
            name2
          );
          instance.defaultProps && console.error(
            "Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",
            name2,
            name2
          );
          "function" !== typeof instance.getSnapshotBeforeUpdate || "function" === typeof instance.componentDidUpdate || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(type2) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(type2), console.error(
            "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",
            getComponentNameFromType(type2)
          ));
          "function" === typeof instance.getDerivedStateFromProps && console.error(
            "%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            name2
          );
          "function" === typeof instance.getDerivedStateFromError && console.error(
            "%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            name2
          );
          "function" === typeof type2.getSnapshotBeforeUpdate && console.error(
            "%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",
            name2
          );
          var state = instance.state;
          state && ("object" !== typeof state || isArrayImpl(state)) && console.error("%s.state: must be set to an object or null", name2);
          "function" === typeof instance.getChildContext && "object" !== typeof type2.childContextTypes && console.error(
            "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",
            name2
          );
          var initialState2 = void 0 !== instance.state ? instance.state : null;
          instance.updater = classComponentUpdater;
          instance.props = resolvedProps;
          instance.state = initialState2;
          var internalInstance = { queue: [], replace: false };
          instance._reactInternals = internalInstance;
          var contextType$jscomp$0 = type2.contextType;
          instance.context = "object" === typeof contextType$jscomp$0 && null !== contextType$jscomp$0 ? contextType$jscomp$0._currentValue : emptyContextObject;
          if (instance.state === resolvedProps) {
            var componentName$jscomp$0 = getComponentNameFromType(type2) || "Component";
            didWarnAboutDirectlyAssigningPropsToState.has(
              componentName$jscomp$0
            ) || (didWarnAboutDirectlyAssigningPropsToState.add(
              componentName$jscomp$0
            ), console.error(
              "%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",
              componentName$jscomp$0
            ));
          }
          var getDerivedStateFromProps = type2.getDerivedStateFromProps;
          if ("function" === typeof getDerivedStateFromProps) {
            var partialState = getDerivedStateFromProps(
              resolvedProps,
              initialState2
            );
            if (void 0 === partialState) {
              var componentName$jscomp$1 = getComponentNameFromType(type2) || "Component";
              didWarnAboutUndefinedDerivedState.has(componentName$jscomp$1) || (didWarnAboutUndefinedDerivedState.add(componentName$jscomp$1), console.error(
                "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",
                componentName$jscomp$1
              ));
            }
            var JSCompiler_inline_result = null === partialState || void 0 === partialState ? initialState2 : assign({}, initialState2, partialState);
            instance.state = JSCompiler_inline_result;
          }
          if ("function" !== typeof type2.getDerivedStateFromProps && "function" !== typeof instance.getSnapshotBeforeUpdate && ("function" === typeof instance.UNSAFE_componentWillMount || "function" === typeof instance.componentWillMount)) {
            var oldState = instance.state;
            if ("function" === typeof instance.componentWillMount) {
              if (true !== instance.componentWillMount.__suppressDeprecationWarning) {
                var componentName$jscomp$2 = getComponentNameFromType(type2) || "Unknown";
                didWarnAboutDeprecatedWillMount[componentName$jscomp$2] || (console.warn(
                  "componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code from componentWillMount to componentDidMount (preferred in most cases) or the constructor.\n\nPlease update the following components: %s",
                  componentName$jscomp$2
                ), didWarnAboutDeprecatedWillMount[componentName$jscomp$2] = true);
              }
              instance.componentWillMount();
            }
            "function" === typeof instance.UNSAFE_componentWillMount && instance.UNSAFE_componentWillMount();
            oldState !== instance.state && (console.error(
              "%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
              getComponentNameFromType(type2) || "Component"
            ), classComponentUpdater.enqueueReplaceState(
              instance,
              instance.state,
              null
            ));
            if (null !== internalInstance.queue && 0 < internalInstance.queue.length) {
              var oldQueue = internalInstance.queue, oldReplace = internalInstance.replace;
              internalInstance.queue = null;
              internalInstance.replace = false;
              if (oldReplace && 1 === oldQueue.length)
                instance.state = oldQueue[0];
              else {
                for (var nextState = oldReplace ? oldQueue[0] : instance.state, dontMutate = true, i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
                  var partial = oldQueue[i], partialState$jscomp$0 = "function" === typeof partial ? partial.call(
                    instance,
                    nextState,
                    resolvedProps,
                    void 0
                  ) : partial;
                  null != partialState$jscomp$0 && (dontMutate ? (dontMutate = false, nextState = assign(
                    {},
                    nextState,
                    partialState$jscomp$0
                  )) : assign(nextState, partialState$jscomp$0));
                }
                instance.state = nextState;
              }
            } else internalInstance.queue = null;
          }
          var nextChildren = callRenderInDEV(instance);
          if (12 === request.status) throw null;
          instance.props !== resolvedProps && (didWarnAboutReassigningProps || console.error(
            "It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",
            getComponentNameFromType(type2) || "a component"
          ), didWarnAboutReassigningProps = true);
          var prevKeyPath = task.keyPath;
          task.keyPath = keyPath;
          renderNodeDestructive(request, task, nextChildren, -1);
          task.keyPath = prevKeyPath;
        } else {
          if (type2.prototype && "function" === typeof type2.prototype.render) {
            var componentName$jscomp$3 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutBadClass[componentName$jscomp$3] || (console.error(
              "The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",
              componentName$jscomp$3,
              componentName$jscomp$3
            ), didWarnAboutBadClass[componentName$jscomp$3] = true);
          }
          var value = renderWithHooks(
            request,
            task,
            keyPath,
            type2,
            props,
            void 0
          );
          if (12 === request.status) throw null;
          var hasId = 0 !== localIdCounter, actionStateCount = actionStateCounter, actionStateMatchingIndex$jscomp$0 = actionStateMatchingIndex;
          if (type2.contextTypes) {
            var _componentName$jscomp$0 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutContextTypes[_componentName$jscomp$0] || (didWarnAboutContextTypes[_componentName$jscomp$0] = true, console.error(
              "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)",
              _componentName$jscomp$0
            ));
          }
          type2 && type2.childContextTypes && console.error(
            "childContextTypes cannot be defined on a function component.\n  %s.childContextTypes = ...",
            type2.displayName || type2.name || "Component"
          );
          if ("function" === typeof type2.getDerivedStateFromProps) {
            var componentName$jscomp$4 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutGetDerivedStateOnFunctionComponent[componentName$jscomp$4] || (console.error(
              "%s: Function components do not support getDerivedStateFromProps.",
              componentName$jscomp$4
            ), didWarnAboutGetDerivedStateOnFunctionComponent[componentName$jscomp$4] = true);
          }
          if ("object" === typeof type2.contextType && null !== type2.contextType) {
            var _componentName2 = getComponentNameFromType(type2) || "Unknown";
            didWarnAboutContextTypeOnFunctionComponent[_componentName2] || (console.error(
              "%s: Function components do not support contextType.",
              _componentName2
            ), didWarnAboutContextTypeOnFunctionComponent[_componentName2] = true);
          }
          finishFunctionComponent(
            request,
            task,
            keyPath,
            value,
            hasId,
            actionStateCount,
            actionStateMatchingIndex$jscomp$0
          );
        }
      else if ("string" === typeof type2) {
        var segment = task.blockedSegment;
        if (null === segment) {
          var children = props.children, prevContext = task.formatContext, prevKeyPath$jscomp$0 = task.keyPath;
          task.formatContext = getChildFormatContext(prevContext, type2, props);
          task.keyPath = keyPath;
          renderNode(request, task, children, -1);
          task.formatContext = prevContext;
          task.keyPath = prevKeyPath$jscomp$0;
        } else {
          var _children = pushStartInstance(
            segment.chunks,
            type2,
            props,
            request.resumableState,
            request.renderState,
            task.blockedPreamble,
            task.hoistableState,
            task.formatContext,
            segment.lastPushedText
          );
          segment.lastPushedText = false;
          var _prevContext2 = task.formatContext, _prevKeyPath3 = task.keyPath;
          task.keyPath = keyPath;
          if ((task.formatContext = getChildFormatContext(
            _prevContext2,
            type2,
            props
          )).insertionMode === HTML_HEAD_MODE) {
            var preambleSegment = createPendingSegment(
              request,
              0,
              null,
              task.formatContext,
              false,
              false
            );
            segment.preambleChildren.push(preambleSegment);
            task.blockedSegment = preambleSegment;
            try {
              preambleSegment.status = 6, renderNode(request, task, _children, -1), preambleSegment.lastPushedText && preambleSegment.textEmbedded && preambleSegment.chunks.push(textSeparator), preambleSegment.status = COMPLETED, finishedSegment(request, task.blockedBoundary, preambleSegment);
            } finally {
              task.blockedSegment = segment;
            }
          } else renderNode(request, task, _children, -1);
          task.formatContext = _prevContext2;
          task.keyPath = _prevKeyPath3;
          a: {
            var target = segment.chunks, resumableState = request.resumableState;
            switch (type2) {
              case "title":
              case "style":
              case "script":
              case "area":
              case "base":
              case "br":
              case "col":
              case "embed":
              case "hr":
              case "img":
              case "input":
              case "keygen":
              case "link":
              case "meta":
              case "param":
              case "source":
              case "track":
              case "wbr":
                break a;
              case "body":
                if (_prevContext2.insertionMode <= HTML_HTML_MODE) {
                  resumableState.hasBody = true;
                  break a;
                }
                break;
              case "html":
                if (_prevContext2.insertionMode === ROOT_HTML_MODE) {
                  resumableState.hasHtml = true;
                  break a;
                }
                break;
              case "head":
                if (_prevContext2.insertionMode <= HTML_HTML_MODE) break a;
            }
            target.push(endChunkForTag(type2));
          }
          segment.lastPushedText = false;
        }
      } else {
        switch (type2) {
          case REACT_LEGACY_HIDDEN_TYPE:
          case REACT_STRICT_MODE_TYPE:
          case REACT_PROFILER_TYPE:
          case REACT_FRAGMENT_TYPE:
            var prevKeyPath$jscomp$1 = task.keyPath;
            task.keyPath = keyPath;
            renderNodeDestructive(request, task, props.children, -1);
            task.keyPath = prevKeyPath$jscomp$1;
            return;
          case REACT_ACTIVITY_TYPE:
            var segment$jscomp$0 = task.blockedSegment;
            if (null === segment$jscomp$0) {
              if ("hidden" !== props.mode) {
                var prevKeyPath$jscomp$2 = task.keyPath;
                task.keyPath = keyPath;
                renderNode(request, task, props.children, -1);
                task.keyPath = prevKeyPath$jscomp$2;
              }
            } else if ("hidden" !== props.mode) {
              segment$jscomp$0.chunks.push(startActivityBoundary);
              segment$jscomp$0.lastPushedText = false;
              var _prevKeyPath4 = task.keyPath;
              task.keyPath = keyPath;
              renderNode(request, task, props.children, -1);
              task.keyPath = _prevKeyPath4;
              segment$jscomp$0.chunks.push(endActivityBoundary);
              segment$jscomp$0.lastPushedText = false;
            }
            return;
          case REACT_SUSPENSE_LIST_TYPE:
            a: {
              var children$jscomp$0 = props.children, revealOrder = props.revealOrder;
              if ("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder) {
                if (isArrayImpl(children$jscomp$0)) {
                  renderSuspenseListRows(
                    request,
                    task,
                    keyPath,
                    children$jscomp$0,
                    revealOrder
                  );
                  break a;
                }
                var iteratorFn = getIteratorFn(children$jscomp$0);
                if (iteratorFn) {
                  var iterator2 = iteratorFn.call(children$jscomp$0);
                  if (iterator2) {
                    validateIterable(
                      task,
                      children$jscomp$0,
                      -1,
                      iterator2,
                      iteratorFn
                    );
                    var step = iterator2.next();
                    if (!step.done) {
                      var rows = [];
                      do
                        rows.push(step.value), step = iterator2.next();
                      while (!step.done);
                      renderSuspenseListRows(
                        request,
                        task,
                        keyPath,
                        children$jscomp$0,
                        revealOrder
                      );
                    }
                    break a;
                  }
                }
              }
              if ("together" === revealOrder) {
                var _prevKeyPath2 = task.keyPath, prevRow = task.row, newRow = task.row = createSuspenseListRow(null);
                newRow.boundaries = [];
                newRow.together = true;
                task.keyPath = keyPath;
                renderNodeDestructive(request, task, children$jscomp$0, -1);
                0 === --newRow.pendingTasks && finishSuspenseListRow(request, newRow);
                task.keyPath = _prevKeyPath2;
                task.row = prevRow;
                null !== prevRow && 0 < newRow.pendingTasks && (prevRow.pendingTasks++, newRow.next = prevRow);
              } else {
                var prevKeyPath$jscomp$3 = task.keyPath;
                task.keyPath = keyPath;
                renderNodeDestructive(request, task, children$jscomp$0, -1);
                task.keyPath = prevKeyPath$jscomp$3;
              }
            }
            return;
          case REACT_VIEW_TRANSITION_TYPE:
          case REACT_SCOPE_TYPE:
            throw Error(
              "ReactDOMServer does not yet support scope components."
            );
          case REACT_SUSPENSE_TYPE:
            a: if (null !== task.replay) {
              var _prevKeyPath = task.keyPath, _prevContext = task.formatContext, _prevRow = task.row;
              task.keyPath = keyPath;
              task.formatContext = getSuspenseContentFormatContext(
                request.resumableState,
                _prevContext
              );
              task.row = null;
              var _content = props.children;
              try {
                renderNode(request, task, _content, -1);
              } finally {
                task.keyPath = _prevKeyPath, task.formatContext = _prevContext, task.row = _prevRow;
              }
            } else {
              var prevKeyPath$jscomp$4 = task.keyPath, prevContext$jscomp$0 = task.formatContext, prevRow$jscomp$0 = task.row, parentBoundary = task.blockedBoundary, parentPreamble = task.blockedPreamble, parentHoistableState = task.hoistableState, parentSegment = task.blockedSegment, fallback = props.fallback, content2 = props.children, fallbackAbortSet = /* @__PURE__ */ new Set();
              var newBoundary = task.formatContext.insertionMode < HTML_MODE ? createSuspenseBoundary(
                request,
                task.row,
                fallbackAbortSet,
                createPreambleState(),
                createPreambleState()
              ) : createSuspenseBoundary(
                request,
                task.row,
                fallbackAbortSet,
                null,
                null
              );
              null !== request.trackedPostpones && (newBoundary.trackedContentKeyPath = keyPath);
              var boundarySegment = createPendingSegment(
                request,
                parentSegment.chunks.length,
                newBoundary,
                task.formatContext,
                false,
                false
              );
              parentSegment.children.push(boundarySegment);
              parentSegment.lastPushedText = false;
              var contentRootSegment = createPendingSegment(
                request,
                0,
                null,
                task.formatContext,
                false,
                false
              );
              contentRootSegment.parentFlushed = true;
              if (null !== request.trackedPostpones) {
                var suspenseComponentStack = task.componentStack, fallbackKeyPath = [
                  keyPath[0],
                  "Suspense Fallback",
                  keyPath[2]
                ], fallbackReplayNode = [
                  fallbackKeyPath[1],
                  fallbackKeyPath[2],
                  [],
                  null
                ];
                request.trackedPostpones.workingMap.set(
                  fallbackKeyPath,
                  fallbackReplayNode
                );
                newBoundary.trackedFallbackNode = fallbackReplayNode;
                task.blockedSegment = boundarySegment;
                task.blockedPreamble = newBoundary.fallbackPreamble;
                task.keyPath = fallbackKeyPath;
                task.formatContext = getSuspenseFallbackFormatContext(
                  request.resumableState,
                  prevContext$jscomp$0
                );
                task.componentStack = replaceSuspenseComponentStackWithSuspenseFallbackStack(
                  suspenseComponentStack
                );
                boundarySegment.status = 6;
                try {
                  renderNode(request, task, fallback, -1), boundarySegment.lastPushedText && boundarySegment.textEmbedded && boundarySegment.chunks.push(textSeparator), boundarySegment.status = COMPLETED, finishedSegment(request, parentBoundary, boundarySegment);
                } catch (thrownValue) {
                  throw boundarySegment.status = 12 === request.status ? ABORTED : ERRORED, thrownValue;
                } finally {
                  task.blockedSegment = parentSegment, task.blockedPreamble = parentPreamble, task.keyPath = prevKeyPath$jscomp$4, task.formatContext = prevContext$jscomp$0;
                }
                var suspendedPrimaryTask = createRenderTask(
                  request,
                  null,
                  content2,
                  -1,
                  newBoundary,
                  contentRootSegment,
                  newBoundary.contentPreamble,
                  newBoundary.contentState,
                  task.abortSet,
                  keyPath,
                  getSuspenseContentFormatContext(
                    request.resumableState,
                    task.formatContext
                  ),
                  task.context,
                  task.treeContext,
                  null,
                  suspenseComponentStack,
                  emptyContextObject,
                  task.debugTask
                );
                pushComponentStack(suspendedPrimaryTask);
                request.pingedTasks.push(suspendedPrimaryTask);
              } else {
                task.blockedBoundary = newBoundary;
                task.blockedPreamble = newBoundary.contentPreamble;
                task.hoistableState = newBoundary.contentState;
                task.blockedSegment = contentRootSegment;
                task.keyPath = keyPath;
                task.formatContext = getSuspenseContentFormatContext(
                  request.resumableState,
                  prevContext$jscomp$0
                );
                task.row = null;
                contentRootSegment.status = 6;
                try {
                  if (renderNode(request, task, content2, -1), contentRootSegment.lastPushedText && contentRootSegment.textEmbedded && contentRootSegment.chunks.push(textSeparator), contentRootSegment.status = COMPLETED, finishedSegment(request, newBoundary, contentRootSegment), queueCompletedSegment(newBoundary, contentRootSegment), 0 === newBoundary.pendingTasks && newBoundary.status === PENDING) {
                    if (newBoundary.status = COMPLETED, !isEligibleForOutlining(request, newBoundary)) {
                      null !== prevRow$jscomp$0 && 0 === --prevRow$jscomp$0.pendingTasks && finishSuspenseListRow(request, prevRow$jscomp$0);
                      0 === request.pendingRootTasks && task.blockedPreamble && preparePreamble(request);
                      break a;
                    }
                  } else
                    null !== prevRow$jscomp$0 && prevRow$jscomp$0.together && tryToResolveTogetherRow(request, prevRow$jscomp$0);
                } catch (thrownValue$2) {
                  newBoundary.status = CLIENT_RENDERED;
                  if (12 === request.status) {
                    contentRootSegment.status = ABORTED;
                    var error = request.fatalError;
                  } else
                    contentRootSegment.status = ERRORED, error = thrownValue$2;
                  var thrownInfo = getThrownInfo(task.componentStack);
                  var errorDigest = logRecoverableError(
                    request,
                    error,
                    thrownInfo,
                    task.debugTask
                  );
                  encodeErrorForBoundary(
                    newBoundary,
                    errorDigest,
                    error,
                    thrownInfo,
                    false
                  );
                  untrackBoundary(request, newBoundary);
                } finally {
                  task.blockedBoundary = parentBoundary, task.blockedPreamble = parentPreamble, task.hoistableState = parentHoistableState, task.blockedSegment = parentSegment, task.keyPath = prevKeyPath$jscomp$4, task.formatContext = prevContext$jscomp$0, task.row = prevRow$jscomp$0;
                }
                var suspendedFallbackTask = createRenderTask(
                  request,
                  null,
                  fallback,
                  -1,
                  parentBoundary,
                  boundarySegment,
                  newBoundary.fallbackPreamble,
                  newBoundary.fallbackState,
                  fallbackAbortSet,
                  [keyPath[0], "Suspense Fallback", keyPath[2]],
                  getSuspenseFallbackFormatContext(
                    request.resumableState,
                    task.formatContext
                  ),
                  task.context,
                  task.treeContext,
                  task.row,
                  replaceSuspenseComponentStackWithSuspenseFallbackStack(
                    task.componentStack
                  ),
                  emptyContextObject,
                  task.debugTask
                );
                pushComponentStack(suspendedFallbackTask);
                request.pingedTasks.push(suspendedFallbackTask);
              }
            }
            return;
        }
        if ("object" === typeof type2 && null !== type2)
          switch (type2.$$typeof) {
            case REACT_FORWARD_REF_TYPE:
              if ("ref" in props) {
                var propsWithoutRef = {};
                for (var key in props)
                  "ref" !== key && (propsWithoutRef[key] = props[key]);
              } else propsWithoutRef = props;
              var children$jscomp$1 = renderWithHooks(
                request,
                task,
                keyPath,
                type2.render,
                propsWithoutRef,
                ref2
              );
              finishFunctionComponent(
                request,
                task,
                keyPath,
                children$jscomp$1,
                0 !== localIdCounter,
                actionStateCounter,
                actionStateMatchingIndex
              );
              return;
            case REACT_MEMO_TYPE:
              renderElement(request, task, keyPath, type2.type, props, ref2);
              return;
            case REACT_CONTEXT_TYPE:
              var value$jscomp$0 = props.value, children$jscomp$2 = props.children;
              var prevSnapshot = task.context;
              var prevKeyPath$jscomp$5 = task.keyPath;
              var prevValue = type2._currentValue;
              type2._currentValue = value$jscomp$0;
              void 0 !== type2._currentRenderer && null !== type2._currentRenderer && type2._currentRenderer !== rendererSigil && console.error(
                "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
              );
              type2._currentRenderer = rendererSigil;
              var prevNode = currentActiveSnapshot, newNode = {
                parent: prevNode,
                depth: null === prevNode ? 0 : prevNode.depth + 1,
                context: type2,
                parentValue: prevValue,
                value: value$jscomp$0
              };
              currentActiveSnapshot = newNode;
              task.context = newNode;
              task.keyPath = keyPath;
              renderNodeDestructive(request, task, children$jscomp$2, -1);
              var prevSnapshot$jscomp$0 = currentActiveSnapshot;
              if (null === prevSnapshot$jscomp$0)
                throw Error(
                  "Tried to pop a Context at the root of the app. This is a bug in React."
                );
              prevSnapshot$jscomp$0.context !== type2 && console.error(
                "The parent context is not the expected context. This is probably a bug in React."
              );
              prevSnapshot$jscomp$0.context._currentValue = prevSnapshot$jscomp$0.parentValue;
              void 0 !== type2._currentRenderer && null !== type2._currentRenderer && type2._currentRenderer !== rendererSigil && console.error(
                "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
              );
              type2._currentRenderer = rendererSigil;
              var JSCompiler_inline_result$jscomp$0 = currentActiveSnapshot = prevSnapshot$jscomp$0.parent;
              task.context = JSCompiler_inline_result$jscomp$0;
              task.keyPath = prevKeyPath$jscomp$5;
              prevSnapshot !== task.context && console.error(
                "Popping the context provider did not return back to the original snapshot. This is a bug in React."
              );
              return;
            case REACT_CONSUMER_TYPE:
              var context$jscomp$0 = type2._context, render = props.children;
              "function" !== typeof render && console.error(
                "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."
              );
              var newChildren = render(context$jscomp$0._currentValue), prevKeyPath$jscomp$6 = task.keyPath;
              task.keyPath = keyPath;
              renderNodeDestructive(request, task, newChildren, -1);
              task.keyPath = prevKeyPath$jscomp$6;
              return;
            case REACT_LAZY_TYPE:
              var Component = callLazyInitInDEV(type2);
              if (12 === request.status) throw null;
              renderElement(request, task, keyPath, Component, props, ref2);
              return;
          }
        var info = "";
        if (void 0 === type2 || "object" === typeof type2 && null !== type2 && 0 === Object.keys(type2).length)
          info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
        throw Error(
          "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + ((null == type2 ? type2 : typeof type2) + "." + info)
        );
      }
    }
    function resumeNode(request, task, segmentId, node2, childIndex) {
      var prevReplay = task.replay, blockedBoundary = task.blockedBoundary, resumedSegment = createPendingSegment(
        request,
        0,
        null,
        task.formatContext,
        false,
        false
      );
      resumedSegment.id = segmentId;
      resumedSegment.parentFlushed = true;
      try {
        task.replay = null, task.blockedSegment = resumedSegment, renderNode(request, task, node2, childIndex), resumedSegment.status = COMPLETED, finishedSegment(request, blockedBoundary, resumedSegment), null === blockedBoundary ? request.completedRootSegment = resumedSegment : (queueCompletedSegment(blockedBoundary, resumedSegment), blockedBoundary.parentFlushed && request.partialBoundaries.push(blockedBoundary));
      } finally {
        task.replay = prevReplay, task.blockedSegment = null;
      }
    }
    function replayElement(request, task, keyPath, name2, keyOrIndex, childIndex, type2, props, ref2, replay) {
      childIndex = replay.nodes;
      for (var i = 0; i < childIndex.length; i++) {
        var node2 = childIndex[i];
        if (keyOrIndex === node2[1]) {
          if (4 === node2.length) {
            if (null !== name2 && name2 !== node2[0])
              throw Error(
                "Expected the resume to render <" + node2[0] + "> in this slot but instead it rendered <" + name2 + ">. The tree doesn't match so React will fallback to client rendering."
              );
            var childNodes = node2[2];
            name2 = node2[3];
            keyOrIndex = task.node;
            task.replay = { nodes: childNodes, slots: name2, pendingTasks: 1 };
            try {
              renderElement(request, task, keyPath, type2, props, ref2);
              if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                throw Error(
                  "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                );
              task.replay.pendingTasks--;
            } catch (x2) {
              if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
                throw task.node === keyOrIndex ? task.replay = replay : childIndex.splice(i, 1), x2;
              task.replay.pendingTasks--;
              type2 = getThrownInfo(task.componentStack);
              props = request;
              request = task.blockedBoundary;
              keyPath = x2;
              ref2 = name2;
              name2 = logRecoverableError(props, keyPath, type2, task.debugTask);
              abortRemainingReplayNodes(
                props,
                request,
                childNodes,
                ref2,
                keyPath,
                name2,
                type2,
                false
              );
            }
            task.replay = replay;
          } else {
            if (type2 !== REACT_SUSPENSE_TYPE)
              throw Error(
                "Expected the resume to render <Suspense> in this slot but instead it rendered <" + (getComponentNameFromType(type2) || "Unknown") + ">. The tree doesn't match so React will fallback to client rendering."
              );
            a: {
              replay = void 0;
              name2 = node2[5];
              type2 = node2[2];
              ref2 = node2[3];
              keyOrIndex = null === node2[4] ? [] : node2[4][2];
              node2 = null === node2[4] ? null : node2[4][3];
              var prevKeyPath = task.keyPath, prevContext = task.formatContext, prevRow = task.row, previousReplaySet = task.replay, parentBoundary = task.blockedBoundary, parentHoistableState = task.hoistableState, content2 = props.children, fallback = props.fallback, fallbackAbortSet = /* @__PURE__ */ new Set();
              props = task.formatContext.insertionMode < HTML_MODE ? createSuspenseBoundary(
                request,
                task.row,
                fallbackAbortSet,
                createPreambleState(),
                createPreambleState()
              ) : createSuspenseBoundary(
                request,
                task.row,
                fallbackAbortSet,
                null,
                null
              );
              props.parentFlushed = true;
              props.rootSegmentID = name2;
              task.blockedBoundary = props;
              task.hoistableState = props.contentState;
              task.keyPath = keyPath;
              task.formatContext = getSuspenseContentFormatContext(
                request.resumableState,
                prevContext
              );
              task.row = null;
              task.replay = { nodes: type2, slots: ref2, pendingTasks: 1 };
              try {
                renderNode(request, task, content2, -1);
                if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                  throw Error(
                    "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                  );
                task.replay.pendingTasks--;
                if (0 === props.pendingTasks && props.status === PENDING) {
                  props.status = COMPLETED;
                  request.completedBoundaries.push(props);
                  break a;
                }
              } catch (error) {
                props.status = CLIENT_RENDERED, childNodes = getThrownInfo(task.componentStack), replay = logRecoverableError(
                  request,
                  error,
                  childNodes,
                  task.debugTask
                ), encodeErrorForBoundary(props, replay, error, childNodes, false), task.replay.pendingTasks--, request.clientRenderedBoundaries.push(props);
              } finally {
                task.blockedBoundary = parentBoundary, task.hoistableState = parentHoistableState, task.replay = previousReplaySet, task.keyPath = prevKeyPath, task.formatContext = prevContext, task.row = prevRow;
              }
              props = createReplayTask(
                request,
                null,
                { nodes: keyOrIndex, slots: node2, pendingTasks: 0 },
                fallback,
                -1,
                parentBoundary,
                props.fallbackState,
                fallbackAbortSet,
                [keyPath[0], "Suspense Fallback", keyPath[2]],
                getSuspenseFallbackFormatContext(
                  request.resumableState,
                  task.formatContext
                ),
                task.context,
                task.treeContext,
                task.row,
                replaceSuspenseComponentStackWithSuspenseFallbackStack(
                  task.componentStack
                ),
                emptyContextObject,
                task.debugTask
              );
              pushComponentStack(props);
              request.pingedTasks.push(props);
            }
          }
          childIndex.splice(i, 1);
          break;
        }
      }
    }
    function validateIterable(task, iterable, childIndex, iterator2, iteratorFn) {
      if (iterator2 === iterable) {
        if (-1 !== childIndex || null === task.componentStack || "function" !== typeof task.componentStack.type || "[object GeneratorFunction]" !== Object.prototype.toString.call(task.componentStack.type) || "[object Generator]" !== Object.prototype.toString.call(iterator2))
          didWarnAboutGenerators || console.error(
            "Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."
          ), didWarnAboutGenerators = true;
      } else
        iterable.entries !== iteratorFn || didWarnAboutMaps || (console.error(
          "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
        ), didWarnAboutMaps = true);
    }
    function renderNodeDestructive(request, task, node2, childIndex) {
      null !== task.replay && "number" === typeof task.replay.slots ? resumeNode(request, task, task.replay.slots, node2, childIndex) : (task.node = node2, task.childIndex = childIndex, node2 = task.componentStack, childIndex = task.debugTask, pushComponentStack(task), retryNode(request, task), task.componentStack = node2, task.debugTask = childIndex);
    }
    function retryNode(request, task) {
      var node2 = task.node, childIndex = task.childIndex;
      if (null !== node2) {
        if ("object" === typeof node2) {
          switch (node2.$$typeof) {
            case REACT_ELEMENT_TYPE:
              var type2 = node2.type, key = node2.key;
              node2 = node2.props;
              var refProp = node2.ref;
              refProp = void 0 !== refProp ? refProp : null;
              var debugTask = task.debugTask, name2 = getComponentNameFromType(type2);
              key = null == key ? -1 === childIndex ? 0 : childIndex : key;
              var keyPath = [task.keyPath, name2, key];
              null !== task.replay ? debugTask ? debugTask.run(
                replayElement.bind(
                  null,
                  request,
                  task,
                  keyPath,
                  name2,
                  key,
                  childIndex,
                  type2,
                  node2,
                  refProp,
                  task.replay
                )
              ) : replayElement(
                request,
                task,
                keyPath,
                name2,
                key,
                childIndex,
                type2,
                node2,
                refProp,
                task.replay
              ) : debugTask ? debugTask.run(
                renderElement.bind(
                  null,
                  request,
                  task,
                  keyPath,
                  type2,
                  node2,
                  refProp
                )
              ) : renderElement(request, task, keyPath, type2, node2, refProp);
              return;
            case REACT_PORTAL_TYPE:
              throw Error(
                "Portals are not currently supported by the server renderer. Render them conditionally so that they only appear on the client render."
              );
            case REACT_LAZY_TYPE:
              type2 = callLazyInitInDEV(node2);
              if (12 === request.status) throw null;
              renderNodeDestructive(request, task, type2, childIndex);
              return;
          }
          if (isArrayImpl(node2)) {
            renderChildrenArray(request, task, node2, childIndex);
            return;
          }
          if (key = getIteratorFn(node2)) {
            if (type2 = key.call(node2)) {
              validateIterable(task, node2, childIndex, type2, key);
              node2 = type2.next();
              if (!node2.done) {
                key = [];
                do
                  key.push(node2.value), node2 = type2.next();
                while (!node2.done);
                renderChildrenArray(request, task, key, childIndex);
              }
              return;
            }
          }
          if ("function" === typeof node2.then)
            return task.thenableState = null, renderNodeDestructive(
              request,
              task,
              unwrapThenable(node2),
              childIndex
            );
          if (node2.$$typeof === REACT_CONTEXT_TYPE)
            return renderNodeDestructive(
              request,
              task,
              node2._currentValue,
              childIndex
            );
          request = Object.prototype.toString.call(node2);
          throw Error(
            "Objects are not valid as a React child (found: " + ("[object Object]" === request ? "object with keys {" + Object.keys(node2).join(", ") + "}" : request) + "). If you meant to render a collection of children, use an array instead."
          );
        }
        "string" === typeof node2 ? (task = task.blockedSegment, null !== task && (task.lastPushedText = pushTextInstance(
          task.chunks,
          node2,
          request.renderState,
          task.lastPushedText
        ))) : "number" === typeof node2 || "bigint" === typeof node2 ? (task = task.blockedSegment, null !== task && (task.lastPushedText = pushTextInstance(
          task.chunks,
          "" + node2,
          request.renderState,
          task.lastPushedText
        ))) : ("function" === typeof node2 && (request = node2.displayName || node2.name || "Component", console.error(
          "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.",
          request,
          request
        )), "symbol" === typeof node2 && console.error(
          "Symbols are not valid as a React child.\n  %s",
          String(node2)
        ));
      }
    }
    function warnForMissingKey(request, task, child) {
      if (null !== child && "object" === typeof child && (child.$$typeof === REACT_ELEMENT_TYPE || child.$$typeof === REACT_PORTAL_TYPE) && child._store && (!child._store.validated && null == child.key || 2 === child._store.validated)) {
        if ("object" !== typeof child._store)
          throw Error(
            "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."
          );
        child._store.validated = 1;
        var didWarnForKey = request.didWarnForKey;
        null == didWarnForKey && (didWarnForKey = request.didWarnForKey = /* @__PURE__ */ new WeakSet());
        request = task.componentStack;
        if (null !== request && !didWarnForKey.has(request)) {
          didWarnForKey.add(request);
          var componentName = getComponentNameFromType(child.type);
          didWarnForKey = child._owner;
          var parentOwner = request.owner;
          request = "";
          if (parentOwner && "undefined" !== typeof parentOwner.type) {
            var name2 = getComponentNameFromType(parentOwner.type);
            name2 && (request = "\n\nCheck the render method of `" + name2 + "`.");
          }
          request || componentName && (request = "\n\nCheck the top-level render call using <" + componentName + ">.");
          componentName = "";
          null != didWarnForKey && parentOwner !== didWarnForKey && (parentOwner = null, "undefined" !== typeof didWarnForKey.type ? parentOwner = getComponentNameFromType(didWarnForKey.type) : "string" === typeof didWarnForKey.name && (parentOwner = didWarnForKey.name), parentOwner && (componentName = " It was passed a child from " + parentOwner + "."));
          didWarnForKey = task.componentStack;
          task.componentStack = {
            parent: task.componentStack,
            type: child.type,
            owner: child._owner,
            stack: child._debugStack
          };
          console.error(
            'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
            request,
            componentName
          );
          task.componentStack = didWarnForKey;
        }
      }
    }
    function renderChildrenArray(request, task, children, childIndex) {
      var prevKeyPath = task.keyPath, previousComponentStack = task.componentStack;
      var previousDebugTask = task.debugTask;
      pushServerComponentStack(task, task.node._debugInfo);
      if (-1 !== childIndex && (task.keyPath = [task.keyPath, "Fragment", childIndex], null !== task.replay)) {
        for (var replay = task.replay, replayNodes = replay.nodes, j2 = 0; j2 < replayNodes.length; j2++) {
          var node2 = replayNodes[j2];
          if (node2[1] === childIndex) {
            childIndex = node2[2];
            node2 = node2[3];
            task.replay = { nodes: childIndex, slots: node2, pendingTasks: 1 };
            try {
              renderChildrenArray(request, task, children, -1);
              if (1 === task.replay.pendingTasks && 0 < task.replay.nodes.length)
                throw Error(
                  "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                );
              task.replay.pendingTasks--;
            } catch (x2) {
              if ("object" === typeof x2 && null !== x2 && (x2 === SuspenseException || "function" === typeof x2.then))
                throw x2;
              task.replay.pendingTasks--;
              var thrownInfo = getThrownInfo(task.componentStack);
              children = task.blockedBoundary;
              var error = x2, resumeSlots = node2;
              node2 = logRecoverableError(
                request,
                error,
                thrownInfo,
                task.debugTask
              );
              abortRemainingReplayNodes(
                request,
                children,
                childIndex,
                resumeSlots,
                error,
                node2,
                thrownInfo,
                false
              );
            }
            task.replay = replay;
            replayNodes.splice(j2, 1);
            break;
          }
        }
        task.keyPath = prevKeyPath;
        task.componentStack = previousComponentStack;
        task.debugTask = previousDebugTask;
        return;
      }
      replay = task.treeContext;
      replayNodes = children.length;
      if (null !== task.replay && (j2 = task.replay.slots, null !== j2 && "object" === typeof j2)) {
        for (childIndex = 0; childIndex < replayNodes; childIndex++)
          node2 = children[childIndex], task.treeContext = pushTreeContext(
            replay,
            replayNodes,
            childIndex
          ), error = j2[childIndex], "number" === typeof error ? (resumeNode(request, task, error, node2, childIndex), delete j2[childIndex]) : renderNode(request, task, node2, childIndex);
        task.treeContext = replay;
        task.keyPath = prevKeyPath;
        task.componentStack = previousComponentStack;
        task.debugTask = previousDebugTask;
        return;
      }
      for (j2 = 0; j2 < replayNodes; j2++)
        childIndex = children[j2], warnForMissingKey(request, task, childIndex), task.treeContext = pushTreeContext(replay, replayNodes, j2), renderNode(request, task, childIndex, j2);
      task.treeContext = replay;
      task.keyPath = prevKeyPath;
      task.componentStack = previousComponentStack;
      task.debugTask = previousDebugTask;
    }
    function trackPostponedBoundary(request, trackedPostpones, boundary) {
      boundary.status = POSTPONED;
      boundary.rootSegmentID = request.nextSegmentId++;
      request = boundary.trackedContentKeyPath;
      if (null === request)
        throw Error(
          "It should not be possible to postpone at the root. This is a bug in React."
        );
      var fallbackReplayNode = boundary.trackedFallbackNode, children = [], boundaryNode = trackedPostpones.workingMap.get(request);
      if (void 0 === boundaryNode)
        return boundary = [
          request[1],
          request[2],
          children,
          null,
          fallbackReplayNode,
          boundary.rootSegmentID
        ], trackedPostpones.workingMap.set(request, boundary), addToReplayParent(boundary, request[0], trackedPostpones), boundary;
      boundaryNode[4] = fallbackReplayNode;
      boundaryNode[5] = boundary.rootSegmentID;
      return boundaryNode;
    }
    function trackPostpone(request, trackedPostpones, task, segment) {
      segment.status = POSTPONED;
      var keyPath = task.keyPath, boundary = task.blockedBoundary;
      if (null === boundary)
        segment.id = request.nextSegmentId++, trackedPostpones.rootSlots = segment.id, null !== request.completedRootSegment && (request.completedRootSegment.status = POSTPONED);
      else {
        if (null !== boundary && boundary.status === PENDING) {
          var boundaryNode = trackPostponedBoundary(
            request,
            trackedPostpones,
            boundary
          );
          if (boundary.trackedContentKeyPath === keyPath && -1 === task.childIndex) {
            -1 === segment.id && (segment.id = segment.parentFlushed ? boundary.rootSegmentID : request.nextSegmentId++);
            boundaryNode[3] = segment.id;
            return;
          }
        }
        -1 === segment.id && (segment.id = segment.parentFlushed && null !== boundary ? boundary.rootSegmentID : request.nextSegmentId++);
        if (-1 === task.childIndex)
          null === keyPath ? trackedPostpones.rootSlots = segment.id : (task = trackedPostpones.workingMap.get(keyPath), void 0 === task ? (task = [keyPath[1], keyPath[2], [], segment.id], addToReplayParent(task, keyPath[0], trackedPostpones)) : task[3] = segment.id);
        else {
          if (null === keyPath)
            if (request = trackedPostpones.rootSlots, null === request)
              request = trackedPostpones.rootSlots = {};
            else {
              if ("number" === typeof request)
                throw Error(
                  "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
                );
            }
          else if (boundary = trackedPostpones.workingMap, boundaryNode = boundary.get(keyPath), void 0 === boundaryNode)
            request = {}, boundaryNode = [keyPath[1], keyPath[2], [], request], boundary.set(keyPath, boundaryNode), addToReplayParent(boundaryNode, keyPath[0], trackedPostpones);
          else if (request = boundaryNode[3], null === request)
            request = boundaryNode[3] = {};
          else if ("number" === typeof request)
            throw Error(
              "It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React."
            );
          request[task.childIndex] = segment.id;
        }
      }
    }
    function untrackBoundary(request, boundary) {
      request = request.trackedPostpones;
      null !== request && (boundary = boundary.trackedContentKeyPath, null !== boundary && (boundary = request.workingMap.get(boundary), void 0 !== boundary && (boundary.length = 4, boundary[2] = [], boundary[3] = null)));
    }
    function spawnNewSuspendedReplayTask(request, task, thenableState2) {
      return createReplayTask(
        request,
        thenableState2,
        task.replay,
        task.node,
        task.childIndex,
        task.blockedBoundary,
        task.hoistableState,
        task.abortSet,
        task.keyPath,
        task.formatContext,
        task.context,
        task.treeContext,
        task.row,
        task.componentStack,
        emptyContextObject,
        task.debugTask
      );
    }
    function spawnNewSuspendedRenderTask(request, task, thenableState2) {
      var segment = task.blockedSegment, newSegment = createPendingSegment(
        request,
        segment.chunks.length,
        null,
        task.formatContext,
        segment.lastPushedText,
        true
      );
      segment.children.push(newSegment);
      segment.lastPushedText = false;
      return createRenderTask(
        request,
        thenableState2,
        task.node,
        task.childIndex,
        task.blockedBoundary,
        newSegment,
        task.blockedPreamble,
        task.hoistableState,
        task.abortSet,
        task.keyPath,
        task.formatContext,
        task.context,
        task.treeContext,
        task.row,
        task.componentStack,
        emptyContextObject,
        task.debugTask
      );
    }
    function renderNode(request, task, node2, childIndex) {
      var previousFormatContext = task.formatContext, previousContext = task.context, previousKeyPath = task.keyPath, previousTreeContext = task.treeContext, previousComponentStack = task.componentStack, previousDebugTask = task.debugTask, segment = task.blockedSegment;
      if (null === segment) {
        segment = task.replay;
        try {
          return renderNodeDestructive(request, task, node2, childIndex);
        } catch (thrownValue) {
          if (resetHooksState(), node2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue, 12 !== request.status && "object" === typeof node2 && null !== node2) {
            if ("function" === typeof node2.then) {
              childIndex = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
              request = spawnNewSuspendedReplayTask(
                request,
                task,
                childIndex
              ).ping;
              node2.then(request, request);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.replay = segment;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
            if ("Maximum call stack size exceeded" === node2.message) {
              node2 = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
              node2 = spawnNewSuspendedReplayTask(request, task, node2);
              request.pingedTasks.push(node2);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.replay = segment;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
          }
        }
      } else {
        var childrenLength = segment.children.length, chunkLength = segment.chunks.length;
        try {
          return renderNodeDestructive(request, task, node2, childIndex);
        } catch (thrownValue$3) {
          if (resetHooksState(), segment.children.length = childrenLength, segment.chunks.length = chunkLength, node2 = thrownValue$3 === SuspenseException ? getSuspendedThenable() : thrownValue$3, 12 !== request.status && "object" === typeof node2 && null !== node2) {
            if ("function" === typeof node2.then) {
              segment = node2;
              node2 = thrownValue$3 === SuspenseException ? getThenableStateAfterSuspending() : null;
              request = spawnNewSuspendedRenderTask(request, task, node2).ping;
              segment.then(request, request);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
            if ("Maximum call stack size exceeded" === node2.message) {
              segment = thrownValue$3 === SuspenseException ? getThenableStateAfterSuspending() : null;
              segment = spawnNewSuspendedRenderTask(request, task, segment);
              request.pingedTasks.push(segment);
              task.formatContext = previousFormatContext;
              task.context = previousContext;
              task.keyPath = previousKeyPath;
              task.treeContext = previousTreeContext;
              task.componentStack = previousComponentStack;
              task.debugTask = previousDebugTask;
              switchContext(previousContext);
              return;
            }
          }
        }
      }
      task.formatContext = previousFormatContext;
      task.context = previousContext;
      task.keyPath = previousKeyPath;
      task.treeContext = previousTreeContext;
      switchContext(previousContext);
      throw node2;
    }
    function abortTaskSoft(task) {
      var boundary = task.blockedBoundary, segment = task.blockedSegment;
      null !== segment && (segment.status = ABORTED, finishedTask(this, boundary, task.row, segment));
    }
    function abortRemainingReplayNodes(request$jscomp$0, boundary, nodes, slots, error$jscomp$0, errorDigest$jscomp$0, errorInfo$jscomp$0, aborted) {
      for (var i = 0; i < nodes.length; i++) {
        var node2 = nodes[i];
        if (4 === node2.length)
          abortRemainingReplayNodes(
            request$jscomp$0,
            boundary,
            node2[2],
            node2[3],
            error$jscomp$0,
            errorDigest$jscomp$0,
            errorInfo$jscomp$0,
            aborted
          );
        else {
          var request = request$jscomp$0;
          node2 = node2[5];
          var error = error$jscomp$0, errorDigest = errorDigest$jscomp$0, errorInfo = errorInfo$jscomp$0, wasAborted = aborted, resumedBoundary = createSuspenseBoundary(
            request,
            null,
            /* @__PURE__ */ new Set(),
            null,
            null
          );
          resumedBoundary.parentFlushed = true;
          resumedBoundary.rootSegmentID = node2;
          resumedBoundary.status = CLIENT_RENDERED;
          encodeErrorForBoundary(
            resumedBoundary,
            errorDigest,
            error,
            errorInfo,
            wasAborted
          );
          resumedBoundary.parentFlushed && request.clientRenderedBoundaries.push(resumedBoundary);
        }
      }
      nodes.length = 0;
      if (null !== slots) {
        if (null === boundary)
          throw Error(
            "We should not have any resumable nodes in the shell. This is a bug in React."
          );
        boundary.status !== CLIENT_RENDERED && (boundary.status = CLIENT_RENDERED, encodeErrorForBoundary(
          boundary,
          errorDigest$jscomp$0,
          error$jscomp$0,
          errorInfo$jscomp$0,
          aborted
        ), boundary.parentFlushed && request$jscomp$0.clientRenderedBoundaries.push(boundary));
        if ("object" === typeof slots)
          for (var index2 in slots) delete slots[index2];
      }
    }
    function abortTask(task, request, error) {
      var boundary = task.blockedBoundary, segment = task.blockedSegment;
      if (null !== segment) {
        if (6 === segment.status) return;
        segment.status = ABORTED;
      }
      var errorInfo = getThrownInfo(task.componentStack), node2 = task.node;
      null !== node2 && "object" === typeof node2 && pushHaltedAwaitOnComponentStack(task, node2._debugInfo);
      if (null === boundary) {
        if (13 !== request.status && request.status !== CLOSED) {
          boundary = task.replay;
          if (null === boundary) {
            null !== request.trackedPostpones && null !== segment ? (boundary = request.trackedPostpones, logRecoverableError(request, error, errorInfo, task.debugTask), trackPostpone(request, boundary, task, segment), finishedTask(request, null, task.row, segment)) : (logRecoverableError(request, error, errorInfo, task.debugTask), fatalError(request, error, errorInfo, task.debugTask));
            return;
          }
          boundary.pendingTasks--;
          0 === boundary.pendingTasks && 0 < boundary.nodes.length && (segment = logRecoverableError(request, error, errorInfo, null), abortRemainingReplayNodes(
            request,
            null,
            boundary.nodes,
            boundary.slots,
            error,
            segment,
            errorInfo,
            true
          ));
          request.pendingRootTasks--;
          0 === request.pendingRootTasks && completeShell(request);
        }
      } else {
        node2 = request.trackedPostpones;
        if (boundary.status !== CLIENT_RENDERED) {
          if (null !== node2 && null !== segment)
            return logRecoverableError(request, error, errorInfo, task.debugTask), trackPostpone(request, node2, task, segment), boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
              return abortTask(fallbackTask, request, error);
            }), boundary.fallbackAbortableTasks.clear(), finishedTask(request, boundary, task.row, segment);
          boundary.status = CLIENT_RENDERED;
          segment = logRecoverableError(
            request,
            error,
            errorInfo,
            task.debugTask
          );
          boundary.status = CLIENT_RENDERED;
          encodeErrorForBoundary(boundary, segment, error, errorInfo, true);
          untrackBoundary(request, boundary);
          boundary.parentFlushed && request.clientRenderedBoundaries.push(boundary);
        }
        boundary.pendingTasks--;
        errorInfo = boundary.row;
        null !== errorInfo && 0 === --errorInfo.pendingTasks && finishSuspenseListRow(request, errorInfo);
        boundary.fallbackAbortableTasks.forEach(function(fallbackTask) {
          return abortTask(fallbackTask, request, error);
        });
        boundary.fallbackAbortableTasks.clear();
      }
      task = task.row;
      null !== task && 0 === --task.pendingTasks && finishSuspenseListRow(request, task);
      request.allPendingTasks--;
      0 === request.allPendingTasks && completeAll(request);
    }
    function safelyEmitEarlyPreloads(request, shellComplete) {
      try {
        var renderState = request.renderState, onHeaders = renderState.onHeaders;
        if (onHeaders) {
          var headers = renderState.headers;
          if (headers) {
            renderState.headers = null;
            var linkHeader = headers.preconnects;
            headers.fontPreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.fontPreloads);
            headers.highImagePreloads && (linkHeader && (linkHeader += ", "), linkHeader += headers.highImagePreloads);
            if (!shellComplete) {
              var queueIter = renderState.styles.values(), queueStep = queueIter.next();
              b: for (; 0 < headers.remainingCapacity && !queueStep.done; queueStep = queueIter.next())
                for (var sheetIter = queueStep.value.sheets.values(), sheetStep = sheetIter.next(); 0 < headers.remainingCapacity && !sheetStep.done; sheetStep = sheetIter.next()) {
                  var sheet = sheetStep.value, props = sheet.props, key = props.href, props$jscomp$0 = sheet.props;
                  var header = getPreloadAsHeader(
                    props$jscomp$0.href,
                    "style",
                    {
                      crossOrigin: props$jscomp$0.crossOrigin,
                      integrity: props$jscomp$0.integrity,
                      nonce: props$jscomp$0.nonce,
                      type: props$jscomp$0.type,
                      fetchPriority: props$jscomp$0.fetchPriority,
                      referrerPolicy: props$jscomp$0.referrerPolicy,
                      media: props$jscomp$0.media
                    }
                  );
                  if (0 <= (headers.remainingCapacity -= header.length + 2))
                    renderState.resets.style[key] = PRELOAD_NO_CREDS, linkHeader && (linkHeader += ", "), linkHeader += header, renderState.resets.style[key] = "string" === typeof props.crossOrigin || "string" === typeof props.integrity ? [props.crossOrigin, props.integrity] : PRELOAD_NO_CREDS;
                  else break b;
                }
            }
            linkHeader ? onHeaders({ Link: linkHeader }) : onHeaders({});
          }
        }
      } catch (error) {
        logRecoverableError(request, error, {}, null);
      }
    }
    function completeShell(request) {
      null === request.trackedPostpones && safelyEmitEarlyPreloads(request, true);
      null === request.trackedPostpones && preparePreamble(request);
      request.onShellError = noop2;
      request = request.onShellReady;
      request();
    }
    function completeAll(request) {
      safelyEmitEarlyPreloads(
        request,
        null === request.trackedPostpones ? true : null === request.completedRootSegment || request.completedRootSegment.status !== POSTPONED
      );
      preparePreamble(request);
      request = request.onAllReady;
      request();
    }
    function queueCompletedSegment(boundary, segment) {
      if (0 === segment.chunks.length && 1 === segment.children.length && null === segment.children[0].boundary && -1 === segment.children[0].id) {
        var childSegment = segment.children[0];
        childSegment.id = segment.id;
        childSegment.parentFlushed = true;
        childSegment.status !== COMPLETED && childSegment.status !== ABORTED && childSegment.status !== ERRORED || queueCompletedSegment(boundary, childSegment);
      } else boundary.completedSegments.push(segment);
    }
    function finishedSegment(request, boundary, segment) {
      if (null !== byteLengthOfChunk) {
        segment = segment.chunks;
        for (var segmentByteSize = 0, i = 0; i < segment.length; i++)
          segmentByteSize += byteLengthOfChunk(segment[i]);
        null === boundary ? request.byteSize += segmentByteSize : boundary.byteSize += segmentByteSize;
      }
    }
    function finishedTask(request, boundary, row, segment) {
      null !== row && (0 === --row.pendingTasks ? finishSuspenseListRow(request, row) : row.together && tryToResolveTogetherRow(request, row));
      request.allPendingTasks--;
      if (null === boundary) {
        if (null !== segment && segment.parentFlushed) {
          if (null !== request.completedRootSegment)
            throw Error(
              "There can only be one root segment. This is a bug in React."
            );
          request.completedRootSegment = segment;
        }
        request.pendingRootTasks--;
        0 === request.pendingRootTasks && completeShell(request);
      } else if (boundary.pendingTasks--, boundary.status !== CLIENT_RENDERED)
        if (0 === boundary.pendingTasks)
          if (boundary.status === PENDING && (boundary.status = COMPLETED), null !== segment && segment.parentFlushed && (segment.status === COMPLETED || segment.status === ABORTED) && queueCompletedSegment(boundary, segment), boundary.parentFlushed && request.completedBoundaries.push(boundary), boundary.status === COMPLETED)
            row = boundary.row, null !== row && hoistHoistables(row.hoistables, boundary.contentState), isEligibleForOutlining(request, boundary) || (boundary.fallbackAbortableTasks.forEach(
              abortTaskSoft,
              request
            ), boundary.fallbackAbortableTasks.clear(), null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row)), 0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary.contentPreamble && preparePreamble(request);
          else {
            if (boundary.status === POSTPONED && (boundary = boundary.row, null !== boundary)) {
              if (null !== request.trackedPostpones) {
                row = request.trackedPostpones;
                var postponedRow = boundary.next;
                if (null !== postponedRow && (segment = postponedRow.boundaries, null !== segment))
                  for (postponedRow.boundaries = null, postponedRow = 0; postponedRow < segment.length; postponedRow++) {
                    var postponedBoundary = segment[postponedRow];
                    trackPostponedBoundary(request, row, postponedBoundary);
                    finishedTask(request, postponedBoundary, null, null);
                  }
              }
              0 === --boundary.pendingTasks && finishSuspenseListRow(request, boundary);
            }
          }
        else
          null === segment || !segment.parentFlushed || segment.status !== COMPLETED && segment.status !== ABORTED || (queueCompletedSegment(boundary, segment), 1 === boundary.completedSegments.length && boundary.parentFlushed && request.partialBoundaries.push(boundary)), boundary = boundary.row, null !== boundary && boundary.together && tryToResolveTogetherRow(request, boundary);
      0 === request.allPendingTasks && completeAll(request);
    }
    function performWork(request$jscomp$2) {
      if (request$jscomp$2.status !== CLOSED && 13 !== request$jscomp$2.status) {
        var prevContext = currentActiveSnapshot, prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = HooksDispatcher;
        var prevAsyncDispatcher = ReactSharedInternals.A;
        ReactSharedInternals.A = DefaultAsyncDispatcher;
        var prevRequest = currentRequest;
        currentRequest = request$jscomp$2;
        var prevGetCurrentStackImpl = ReactSharedInternals.getCurrentStack;
        ReactSharedInternals.getCurrentStack = getCurrentStackInDEV;
        var prevResumableState = currentResumableState;
        currentResumableState = request$jscomp$2.resumableState;
        try {
          var pingedTasks = request$jscomp$2.pingedTasks, i;
          for (i = 0; i < pingedTasks.length; i++) {
            var request = request$jscomp$2, task = pingedTasks[i], segment = task.blockedSegment;
            if (null === segment) {
              var prevTaskInDEV = void 0, request$jscomp$0 = request;
              request = task;
              if (0 !== request.replay.pendingTasks) {
                switchContext(request.context);
                prevTaskInDEV = currentTaskInDEV;
                currentTaskInDEV = request;
                try {
                  "number" === typeof request.replay.slots ? resumeNode(
                    request$jscomp$0,
                    request,
                    request.replay.slots,
                    request.node,
                    request.childIndex
                  ) : retryNode(request$jscomp$0, request);
                  if (1 === request.replay.pendingTasks && 0 < request.replay.nodes.length)
                    throw Error(
                      "Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering."
                    );
                  request.replay.pendingTasks--;
                  request.abortSet.delete(request);
                  finishedTask(
                    request$jscomp$0,
                    request.blockedBoundary,
                    request.row,
                    null
                  );
                } catch (thrownValue) {
                  resetHooksState();
                  var x2 = thrownValue === SuspenseException ? getSuspendedThenable() : thrownValue;
                  if ("object" === typeof x2 && null !== x2 && "function" === typeof x2.then) {
                    var ping = request.ping;
                    x2.then(ping, ping);
                    request.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                  } else {
                    request.replay.pendingTasks--;
                    request.abortSet.delete(request);
                    var errorInfo = getThrownInfo(request.componentStack), errorDigest = void 0, request$jscomp$1 = request$jscomp$0, boundary = request.blockedBoundary, error$jscomp$0 = 12 === request$jscomp$0.status ? request$jscomp$0.fatalError : x2, errorInfo$jscomp$0 = errorInfo, replayNodes = request.replay.nodes, resumeSlots = request.replay.slots;
                    errorDigest = logRecoverableError(
                      request$jscomp$1,
                      error$jscomp$0,
                      errorInfo$jscomp$0,
                      request.debugTask
                    );
                    abortRemainingReplayNodes(
                      request$jscomp$1,
                      boundary,
                      replayNodes,
                      resumeSlots,
                      error$jscomp$0,
                      errorDigest,
                      errorInfo$jscomp$0,
                      false
                    );
                    request$jscomp$0.pendingRootTasks--;
                    0 === request$jscomp$0.pendingRootTasks && completeShell(request$jscomp$0);
                    request$jscomp$0.allPendingTasks--;
                    0 === request$jscomp$0.allPendingTasks && completeAll(request$jscomp$0);
                  }
                } finally {
                  currentTaskInDEV = prevTaskInDEV;
                }
              }
            } else if (request$jscomp$0 = prevTaskInDEV = void 0, errorDigest = task, request$jscomp$1 = segment, request$jscomp$1.status === PENDING) {
              request$jscomp$1.status = 6;
              switchContext(errorDigest.context);
              request$jscomp$0 = currentTaskInDEV;
              currentTaskInDEV = errorDigest;
              var childrenLength = request$jscomp$1.children.length, chunkLength = request$jscomp$1.chunks.length;
              try {
                retryNode(request, errorDigest), request$jscomp$1.lastPushedText && request$jscomp$1.textEmbedded && request$jscomp$1.chunks.push(textSeparator), errorDigest.abortSet.delete(errorDigest), request$jscomp$1.status = COMPLETED, finishedSegment(
                  request,
                  errorDigest.blockedBoundary,
                  request$jscomp$1
                ), finishedTask(
                  request,
                  errorDigest.blockedBoundary,
                  errorDigest.row,
                  request$jscomp$1
                );
              } catch (thrownValue) {
                resetHooksState();
                request$jscomp$1.children.length = childrenLength;
                request$jscomp$1.chunks.length = chunkLength;
                var x$jscomp$0 = thrownValue === SuspenseException ? getSuspendedThenable() : 12 === request.status ? request.fatalError : thrownValue;
                if (12 === request.status && null !== request.trackedPostpones) {
                  var trackedPostpones = request.trackedPostpones, thrownInfo = getThrownInfo(errorDigest.componentStack);
                  errorDigest.abortSet.delete(errorDigest);
                  logRecoverableError(
                    request,
                    x$jscomp$0,
                    thrownInfo,
                    errorDigest.debugTask
                  );
                  trackPostpone(
                    request,
                    trackedPostpones,
                    errorDigest,
                    request$jscomp$1
                  );
                  finishedTask(
                    request,
                    errorDigest.blockedBoundary,
                    errorDigest.row,
                    request$jscomp$1
                  );
                } else if ("object" === typeof x$jscomp$0 && null !== x$jscomp$0 && "function" === typeof x$jscomp$0.then) {
                  request$jscomp$1.status = PENDING;
                  errorDigest.thenableState = thrownValue === SuspenseException ? getThenableStateAfterSuspending() : null;
                  var ping$jscomp$0 = errorDigest.ping;
                  x$jscomp$0.then(ping$jscomp$0, ping$jscomp$0);
                } else {
                  var errorInfo$jscomp$1 = getThrownInfo(
                    errorDigest.componentStack
                  );
                  errorDigest.abortSet.delete(errorDigest);
                  request$jscomp$1.status = ERRORED;
                  var boundary$jscomp$0 = errorDigest.blockedBoundary, row = errorDigest.row, debugTask = errorDigest.debugTask;
                  null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
                  request.allPendingTasks--;
                  prevTaskInDEV = logRecoverableError(
                    request,
                    x$jscomp$0,
                    errorInfo$jscomp$1,
                    debugTask
                  );
                  if (null === boundary$jscomp$0)
                    fatalError(
                      request,
                      x$jscomp$0,
                      errorInfo$jscomp$1,
                      debugTask
                    );
                  else if (boundary$jscomp$0.pendingTasks--, boundary$jscomp$0.status !== CLIENT_RENDERED) {
                    boundary$jscomp$0.status = CLIENT_RENDERED;
                    encodeErrorForBoundary(
                      boundary$jscomp$0,
                      prevTaskInDEV,
                      x$jscomp$0,
                      errorInfo$jscomp$1,
                      false
                    );
                    untrackBoundary(request, boundary$jscomp$0);
                    var boundaryRow = boundary$jscomp$0.row;
                    null !== boundaryRow && 0 === --boundaryRow.pendingTasks && finishSuspenseListRow(request, boundaryRow);
                    boundary$jscomp$0.parentFlushed && request.clientRenderedBoundaries.push(boundary$jscomp$0);
                    0 === request.pendingRootTasks && null === request.trackedPostpones && null !== boundary$jscomp$0.contentPreamble && preparePreamble(request);
                  }
                  0 === request.allPendingTasks && completeAll(request);
                }
              } finally {
                currentTaskInDEV = request$jscomp$0;
              }
            }
          }
          pingedTasks.splice(0, i);
          null !== request$jscomp$2.destination && flushCompletedQueues(
            request$jscomp$2,
            request$jscomp$2.destination
          );
        } catch (error) {
          pingedTasks = {}, logRecoverableError(request$jscomp$2, error, pingedTasks, null), fatalError(request$jscomp$2, error, pingedTasks, null);
        } finally {
          currentResumableState = prevResumableState, ReactSharedInternals.H = prevDispatcher, ReactSharedInternals.A = prevAsyncDispatcher, ReactSharedInternals.getCurrentStack = prevGetCurrentStackImpl, prevDispatcher === HooksDispatcher && switchContext(prevContext), currentRequest = prevRequest;
        }
      }
    }
    function preparePreambleFromSubtree(request, segment, collectedPreambleSegments) {
      segment.preambleChildren.length && collectedPreambleSegments.push(segment.preambleChildren);
      for (var pendingPreambles = false, i = 0; i < segment.children.length; i++)
        pendingPreambles = preparePreambleFromSegment(
          request,
          segment.children[i],
          collectedPreambleSegments
        ) || pendingPreambles;
      return pendingPreambles;
    }
    function preparePreambleFromSegment(request, segment, collectedPreambleSegments) {
      var boundary = segment.boundary;
      if (null === boundary)
        return preparePreambleFromSubtree(
          request,
          segment,
          collectedPreambleSegments
        );
      var preamble = boundary.contentPreamble, fallbackPreamble = boundary.fallbackPreamble;
      if (null === preamble || null === fallbackPreamble) return false;
      switch (boundary.status) {
        case COMPLETED:
          hoistPreambleState(request.renderState, preamble);
          request.byteSize += boundary.byteSize;
          segment = boundary.completedSegments[0];
          if (!segment)
            throw Error(
              "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
            );
          return preparePreambleFromSubtree(
            request,
            segment,
            collectedPreambleSegments
          );
        case POSTPONED:
          if (null !== request.trackedPostpones) return true;
        case CLIENT_RENDERED:
          if (segment.status === COMPLETED)
            return hoistPreambleState(request.renderState, fallbackPreamble), preparePreambleFromSubtree(
              request,
              segment,
              collectedPreambleSegments
            );
        default:
          return true;
      }
    }
    function preparePreamble(request) {
      if (request.completedRootSegment && null === request.completedPreambleSegments) {
        var collectedPreambleSegments = [], originalRequestByteSize = request.byteSize, hasPendingPreambles = preparePreambleFromSegment(
          request,
          request.completedRootSegment,
          collectedPreambleSegments
        ), preamble = request.renderState.preamble;
        false === hasPendingPreambles || preamble.headChunks && preamble.bodyChunks ? request.completedPreambleSegments = collectedPreambleSegments : request.byteSize = originalRequestByteSize;
      }
    }
    function flushSubtree(request, destination, segment, hoistableState) {
      segment.parentFlushed = true;
      switch (segment.status) {
        case PENDING:
          segment.id = request.nextSegmentId++;
        case POSTPONED:
          return hoistableState = segment.id, segment.lastPushedText = false, segment.textEmbedded = false, request = request.renderState, writeChunk(destination, placeholder1), writeChunk(destination, request.placeholderPrefix), request = hoistableState.toString(16), writeChunk(destination, request), writeChunkAndReturn(destination, placeholder2);
        case COMPLETED:
          segment.status = FLUSHED;
          var r = true, chunks = segment.chunks, chunkIdx = 0;
          segment = segment.children;
          for (var childIdx = 0; childIdx < segment.length; childIdx++) {
            for (r = segment[childIdx]; chunkIdx < r.index; chunkIdx++)
              writeChunk(destination, chunks[chunkIdx]);
            r = flushSegment(request, destination, r, hoistableState);
          }
          for (; chunkIdx < chunks.length - 1; chunkIdx++)
            writeChunk(destination, chunks[chunkIdx]);
          chunkIdx < chunks.length && (r = writeChunkAndReturn(destination, chunks[chunkIdx]));
          return r;
        case ABORTED:
          return true;
        default:
          throw Error(
            "Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React."
          );
      }
    }
    function flushSegment(request, destination, segment, hoistableState) {
      var boundary = segment.boundary;
      if (null === boundary)
        return flushSubtree(request, destination, segment, hoistableState);
      boundary.parentFlushed = true;
      if (boundary.status === CLIENT_RENDERED) {
        var row = boundary.row;
        null !== row && 0 === --row.pendingTasks && finishSuspenseListRow(request, row);
        row = boundary.errorDigest;
        var errorMessage = boundary.errorMessage, errorStack = boundary.errorStack;
        boundary = boundary.errorComponentStack;
        writeChunkAndReturn(destination, startClientRenderedSuspenseBoundary);
        writeChunk(destination, clientRenderedSuspenseBoundaryError1);
        row && (writeChunk(destination, clientRenderedSuspenseBoundaryError1A), writeChunk(destination, escapeTextForBrowser(row)), writeChunk(
          destination,
          clientRenderedSuspenseBoundaryErrorAttrInterstitial
        ));
        errorMessage && (writeChunk(destination, clientRenderedSuspenseBoundaryError1B), writeChunk(destination, escapeTextForBrowser(errorMessage)), writeChunk(
          destination,
          clientRenderedSuspenseBoundaryErrorAttrInterstitial
        ));
        errorStack && (writeChunk(destination, clientRenderedSuspenseBoundaryError1C), writeChunk(destination, escapeTextForBrowser(errorStack)), writeChunk(
          destination,
          clientRenderedSuspenseBoundaryErrorAttrInterstitial
        ));
        boundary && (writeChunk(destination, clientRenderedSuspenseBoundaryError1D), writeChunk(destination, escapeTextForBrowser(boundary)), writeChunk(
          destination,
          clientRenderedSuspenseBoundaryErrorAttrInterstitial
        ));
        writeChunkAndReturn(destination, clientRenderedSuspenseBoundaryError2);
        flushSubtree(request, destination, segment, hoistableState);
      } else if (boundary.status !== COMPLETED)
        boundary.status === PENDING && (boundary.rootSegmentID = request.nextSegmentId++), 0 < boundary.completedSegments.length && request.partialBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
          destination,
          request.renderState,
          boundary.rootSegmentID
        ), hoistableState && hoistHoistables(hoistableState, boundary.fallbackState), flushSubtree(request, destination, segment, hoistableState);
      else if (!flushingPartialBoundaries && isEligibleForOutlining(request, boundary) && (flushedByteSize + boundary.byteSize > request.progressiveChunkSize || hasSuspenseyContent(boundary.contentState)))
        boundary.rootSegmentID = request.nextSegmentId++, request.completedBoundaries.push(boundary), writeStartPendingSuspenseBoundary(
          destination,
          request.renderState,
          boundary.rootSegmentID
        ), flushSubtree(request, destination, segment, hoistableState);
      else {
        flushedByteSize += boundary.byteSize;
        hoistableState && hoistHoistables(hoistableState, boundary.contentState);
        segment = boundary.row;
        null !== segment && isEligibleForOutlining(request, boundary) && 0 === --segment.pendingTasks && finishSuspenseListRow(request, segment);
        writeChunkAndReturn(destination, startCompletedSuspenseBoundary);
        segment = boundary.completedSegments;
        if (1 !== segment.length)
          throw Error(
            "A previously unvisited boundary must have exactly one root segment. This is a bug in React."
          );
        flushSegment(request, destination, segment[0], hoistableState);
      }
      return writeChunkAndReturn(destination, endSuspenseBoundary);
    }
    function flushSegmentContainer(request, destination, segment, hoistableState) {
      writeStartSegment(
        destination,
        request.renderState,
        segment.parentFormatContext,
        segment.id
      );
      flushSegment(request, destination, segment, hoistableState);
      return writeEndSegment(destination, segment.parentFormatContext);
    }
    function flushCompletedBoundary(request, destination, boundary) {
      flushedByteSize = boundary.byteSize;
      for (var completedSegments = boundary.completedSegments, i = 0; i < completedSegments.length; i++)
        flushPartiallyCompletedSegment(
          request,
          destination,
          boundary,
          completedSegments[i]
        );
      completedSegments.length = 0;
      completedSegments = boundary.row;
      null !== completedSegments && isEligibleForOutlining(request, boundary) && 0 === --completedSegments.pendingTasks && finishSuspenseListRow(request, completedSegments);
      writeHoistablesForBoundary(
        destination,
        boundary.contentState,
        request.renderState
      );
      completedSegments = request.resumableState;
      request = request.renderState;
      i = boundary.rootSegmentID;
      boundary = boundary.contentState;
      var requiresStyleInsertion = request.stylesToHoist;
      request.stylesToHoist = false;
      writeChunk(destination, request.startInlineScript);
      writeChunk(destination, endOfStartTag);
      requiresStyleInsertion ? ((completedSegments.instructions & SentClientRenderFunction) === NothingSent && (completedSegments.instructions |= SentClientRenderFunction, writeChunk(destination, clientRenderScriptFunctionOnly)), (completedSegments.instructions & SentCompleteBoundaryFunction) === NothingSent && (completedSegments.instructions |= SentCompleteBoundaryFunction, writeChunk(destination, completeBoundaryScriptFunctionOnly)), (completedSegments.instructions & SentStyleInsertionFunction) === NothingSent ? (completedSegments.instructions |= SentStyleInsertionFunction, writeChunk(
        destination,
        completeBoundaryWithStylesScript1FullPartial
      )) : writeChunk(destination, completeBoundaryWithStylesScript1Partial)) : ((completedSegments.instructions & SentCompleteBoundaryFunction) === NothingSent && (completedSegments.instructions |= SentCompleteBoundaryFunction, writeChunk(destination, completeBoundaryScriptFunctionOnly)), writeChunk(destination, completeBoundaryScript1Partial));
      completedSegments = i.toString(16);
      writeChunk(destination, request.boundaryPrefix);
      writeChunk(destination, completedSegments);
      writeChunk(destination, completeBoundaryScript2);
      writeChunk(destination, request.segmentPrefix);
      writeChunk(destination, completedSegments);
      requiresStyleInsertion ? (writeChunk(destination, completeBoundaryScript3a), writeStyleResourceDependenciesInJS(destination, boundary)) : writeChunk(destination, completeBoundaryScript3b);
      boundary = writeChunkAndReturn(destination, completeBoundaryScriptEnd);
      return writeBootstrap(destination, request) && boundary;
    }
    function flushPartiallyCompletedSegment(request, destination, boundary, segment) {
      if (segment.status === FLUSHED) return true;
      var hoistableState = boundary.contentState, segmentID = segment.id;
      if (-1 === segmentID) {
        if (-1 === (segment.id = boundary.rootSegmentID))
          throw Error(
            "A root segment ID must have been assigned by now. This is a bug in React."
          );
        return flushSegmentContainer(
          request,
          destination,
          segment,
          hoistableState
        );
      }
      if (segmentID === boundary.rootSegmentID)
        return flushSegmentContainer(
          request,
          destination,
          segment,
          hoistableState
        );
      flushSegmentContainer(request, destination, segment, hoistableState);
      boundary = request.resumableState;
      request = request.renderState;
      writeChunk(destination, request.startInlineScript);
      writeChunk(destination, endOfStartTag);
      (boundary.instructions & SentCompleteSegmentFunction) === NothingSent ? (boundary.instructions |= SentCompleteSegmentFunction, writeChunk(destination, completeSegmentScript1Full)) : writeChunk(destination, completeSegmentScript1Partial);
      writeChunk(destination, request.segmentPrefix);
      segmentID = segmentID.toString(16);
      writeChunk(destination, segmentID);
      writeChunk(destination, completeSegmentScript2);
      writeChunk(destination, request.placeholderPrefix);
      writeChunk(destination, segmentID);
      destination = writeChunkAndReturn(destination, completeSegmentScriptEnd);
      return destination;
    }
    function flushCompletedQueues(request, destination) {
      currentView = new Uint8Array(2048);
      writtenBytes = 0;
      destinationHasCapacity$1 = true;
      try {
        if (!(0 < request.pendingRootTasks)) {
          var i, completedRootSegment = request.completedRootSegment;
          if (null !== completedRootSegment) {
            if (completedRootSegment.status === POSTPONED) return;
            var completedPreambleSegments = request.completedPreambleSegments;
            if (null === completedPreambleSegments) return;
            flushedByteSize = request.byteSize;
            var resumableState = request.resumableState, renderState = request.renderState, preamble = renderState.preamble, htmlChunks = preamble.htmlChunks, headChunks = preamble.headChunks, i$jscomp$0;
            if (htmlChunks) {
              for (i$jscomp$0 = 0; i$jscomp$0 < htmlChunks.length; i$jscomp$0++)
                writeChunk(destination, htmlChunks[i$jscomp$0]);
              if (headChunks)
                for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
                  writeChunk(destination, headChunks[i$jscomp$0]);
              else
                writeChunk(destination, startChunkForTag("head")), writeChunk(destination, endOfStartTag);
            } else if (headChunks)
              for (i$jscomp$0 = 0; i$jscomp$0 < headChunks.length; i$jscomp$0++)
                writeChunk(destination, headChunks[i$jscomp$0]);
            var charsetChunks = renderState.charsetChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < charsetChunks.length; i$jscomp$0++)
              writeChunk(destination, charsetChunks[i$jscomp$0]);
            charsetChunks.length = 0;
            renderState.preconnects.forEach(flushResource, destination);
            renderState.preconnects.clear();
            var viewportChunks = renderState.viewportChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < viewportChunks.length; i$jscomp$0++)
              writeChunk(destination, viewportChunks[i$jscomp$0]);
            viewportChunks.length = 0;
            renderState.fontPreloads.forEach(flushResource, destination);
            renderState.fontPreloads.clear();
            renderState.highImagePreloads.forEach(flushResource, destination);
            renderState.highImagePreloads.clear();
            currentlyFlushingRenderState = renderState;
            renderState.styles.forEach(flushStylesInPreamble, destination);
            currentlyFlushingRenderState = null;
            var importMapChunks = renderState.importMapChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < importMapChunks.length; i$jscomp$0++)
              writeChunk(destination, importMapChunks[i$jscomp$0]);
            importMapChunks.length = 0;
            renderState.bootstrapScripts.forEach(flushResource, destination);
            renderState.scripts.forEach(flushResource, destination);
            renderState.scripts.clear();
            renderState.bulkPreloads.forEach(flushResource, destination);
            renderState.bulkPreloads.clear();
            htmlChunks || headChunks || (resumableState.instructions |= SentCompletedShellId);
            var hoistableChunks = renderState.hoistableChunks;
            for (i$jscomp$0 = 0; i$jscomp$0 < hoistableChunks.length; i$jscomp$0++)
              writeChunk(destination, hoistableChunks[i$jscomp$0]);
            for (resumableState = hoistableChunks.length = 0; resumableState < completedPreambleSegments.length; resumableState++) {
              var segments = completedPreambleSegments[resumableState];
              for (renderState = 0; renderState < segments.length; renderState++)
                flushSegment(request, destination, segments[renderState], null);
            }
            var preamble$jscomp$0 = request.renderState.preamble, headChunks$jscomp$0 = preamble$jscomp$0.headChunks;
            (preamble$jscomp$0.htmlChunks || headChunks$jscomp$0) && writeChunk(destination, endChunkForTag("head"));
            var bodyChunks = preamble$jscomp$0.bodyChunks;
            if (bodyChunks)
              for (completedPreambleSegments = 0; completedPreambleSegments < bodyChunks.length; completedPreambleSegments++)
                writeChunk(destination, bodyChunks[completedPreambleSegments]);
            flushSegment(request, destination, completedRootSegment, null);
            request.completedRootSegment = null;
            var renderState$jscomp$0 = request.renderState;
            if (0 !== request.allPendingTasks || 0 !== request.clientRenderedBoundaries.length || 0 !== request.completedBoundaries.length || null !== request.trackedPostpones && (0 !== request.trackedPostpones.rootNodes.length || null !== request.trackedPostpones.rootSlots)) {
              var resumableState$jscomp$0 = request.resumableState;
              if ((resumableState$jscomp$0.instructions & SentMarkShellTime) === NothingSent) {
                resumableState$jscomp$0.instructions |= SentMarkShellTime;
                writeChunk(destination, renderState$jscomp$0.startInlineScript);
                if ((resumableState$jscomp$0.instructions & SentCompletedShellId) === NothingSent) {
                  resumableState$jscomp$0.instructions |= SentCompletedShellId;
                  var shellId = "_" + resumableState$jscomp$0.idPrefix + "R_";
                  writeChunk(destination, completedShellIdAttributeStart);
                  writeChunk(destination, escapeTextForBrowser(shellId));
                  writeChunk(destination, attributeEnd);
                }
                writeChunk(destination, endOfStartTag);
                writeChunk(destination, shellTimeRuntimeScript);
                writeChunkAndReturn(destination, endInlineScript);
              }
            }
            writeBootstrap(destination, renderState$jscomp$0);
          }
          var renderState$jscomp$1 = request.renderState;
          completedRootSegment = 0;
          var viewportChunks$jscomp$0 = renderState$jscomp$1.viewportChunks;
          for (completedRootSegment = 0; completedRootSegment < viewportChunks$jscomp$0.length; completedRootSegment++)
            writeChunk(
              destination,
              viewportChunks$jscomp$0[completedRootSegment]
            );
          viewportChunks$jscomp$0.length = 0;
          renderState$jscomp$1.preconnects.forEach(flushResource, destination);
          renderState$jscomp$1.preconnects.clear();
          renderState$jscomp$1.fontPreloads.forEach(flushResource, destination);
          renderState$jscomp$1.fontPreloads.clear();
          renderState$jscomp$1.highImagePreloads.forEach(
            flushResource,
            destination
          );
          renderState$jscomp$1.highImagePreloads.clear();
          renderState$jscomp$1.styles.forEach(preloadLateStyles, destination);
          renderState$jscomp$1.scripts.forEach(flushResource, destination);
          renderState$jscomp$1.scripts.clear();
          renderState$jscomp$1.bulkPreloads.forEach(flushResource, destination);
          renderState$jscomp$1.bulkPreloads.clear();
          var hoistableChunks$jscomp$0 = renderState$jscomp$1.hoistableChunks;
          for (completedRootSegment = 0; completedRootSegment < hoistableChunks$jscomp$0.length; completedRootSegment++)
            writeChunk(
              destination,
              hoistableChunks$jscomp$0[completedRootSegment]
            );
          hoistableChunks$jscomp$0.length = 0;
          var clientRenderedBoundaries = request.clientRenderedBoundaries;
          for (i = 0; i < clientRenderedBoundaries.length; i++) {
            var boundary = clientRenderedBoundaries[i];
            renderState$jscomp$1 = destination;
            var resumableState$jscomp$1 = request.resumableState, renderState$jscomp$2 = request.renderState, id = boundary.rootSegmentID, errorDigest = boundary.errorDigest, errorMessage = boundary.errorMessage, errorStack = boundary.errorStack, errorComponentStack = boundary.errorComponentStack;
            writeChunk(
              renderState$jscomp$1,
              renderState$jscomp$2.startInlineScript
            );
            writeChunk(renderState$jscomp$1, endOfStartTag);
            (resumableState$jscomp$1.instructions & SentClientRenderFunction) === NothingSent ? (resumableState$jscomp$1.instructions |= SentClientRenderFunction, writeChunk(renderState$jscomp$1, clientRenderScript1Full)) : writeChunk(renderState$jscomp$1, clientRenderScript1Partial);
            writeChunk(
              renderState$jscomp$1,
              renderState$jscomp$2.boundaryPrefix
            );
            writeChunk(renderState$jscomp$1, id.toString(16));
            writeChunk(renderState$jscomp$1, clientRenderScript1A);
            if (errorDigest || errorMessage || errorStack || errorComponentStack)
              writeChunk(
                renderState$jscomp$1,
                clientRenderErrorScriptArgInterstitial
              ), writeChunk(
                renderState$jscomp$1,
                escapeJSStringsForInstructionScripts(errorDigest || "")
              );
            if (errorMessage || errorStack || errorComponentStack)
              writeChunk(
                renderState$jscomp$1,
                clientRenderErrorScriptArgInterstitial
              ), writeChunk(
                renderState$jscomp$1,
                escapeJSStringsForInstructionScripts(errorMessage || "")
              );
            if (errorStack || errorComponentStack)
              writeChunk(
                renderState$jscomp$1,
                clientRenderErrorScriptArgInterstitial
              ), writeChunk(
                renderState$jscomp$1,
                escapeJSStringsForInstructionScripts(errorStack || "")
              );
            errorComponentStack && (writeChunk(
              renderState$jscomp$1,
              clientRenderErrorScriptArgInterstitial
            ), writeChunk(
              renderState$jscomp$1,
              escapeJSStringsForInstructionScripts(errorComponentStack)
            ));
            var JSCompiler_inline_result = writeChunkAndReturn(
              renderState$jscomp$1,
              clientRenderScriptEnd
            );
            if (!JSCompiler_inline_result) {
              request.destination = null;
              i++;
              clientRenderedBoundaries.splice(0, i);
              return;
            }
          }
          clientRenderedBoundaries.splice(0, i);
          var completedBoundaries = request.completedBoundaries;
          for (i = 0; i < completedBoundaries.length; i++)
            if (!flushCompletedBoundary(
              request,
              destination,
              completedBoundaries[i]
            )) {
              request.destination = null;
              i++;
              completedBoundaries.splice(0, i);
              return;
            }
          completedBoundaries.splice(0, i);
          completeWriting(destination);
          currentView = new Uint8Array(2048);
          writtenBytes = 0;
          flushingPartialBoundaries = destinationHasCapacity$1 = true;
          var partialBoundaries = request.partialBoundaries;
          for (i = 0; i < partialBoundaries.length; i++) {
            a: {
              clientRenderedBoundaries = request;
              boundary = destination;
              var boundary$jscomp$0 = partialBoundaries[i];
              flushedByteSize = boundary$jscomp$0.byteSize;
              var completedSegments = boundary$jscomp$0.completedSegments;
              for (JSCompiler_inline_result = 0; JSCompiler_inline_result < completedSegments.length; JSCompiler_inline_result++)
                if (!flushPartiallyCompletedSegment(
                  clientRenderedBoundaries,
                  boundary,
                  boundary$jscomp$0,
                  completedSegments[JSCompiler_inline_result]
                )) {
                  JSCompiler_inline_result++;
                  completedSegments.splice(0, JSCompiler_inline_result);
                  var JSCompiler_inline_result$jscomp$0 = false;
                  break a;
                }
              completedSegments.splice(0, JSCompiler_inline_result);
              var row = boundary$jscomp$0.row;
              null !== row && row.together && 1 === boundary$jscomp$0.pendingTasks && (1 === row.pendingTasks ? unblockSuspenseListRow(
                clientRenderedBoundaries,
                row,
                row.hoistables
              ) : row.pendingTasks--);
              JSCompiler_inline_result$jscomp$0 = writeHoistablesForBoundary(
                boundary,
                boundary$jscomp$0.contentState,
                clientRenderedBoundaries.renderState
              );
            }
            if (!JSCompiler_inline_result$jscomp$0) {
              request.destination = null;
              i++;
              partialBoundaries.splice(0, i);
              return;
            }
          }
          partialBoundaries.splice(0, i);
          flushingPartialBoundaries = false;
          var largeBoundaries = request.completedBoundaries;
          for (i = 0; i < largeBoundaries.length; i++)
            if (!flushCompletedBoundary(request, destination, largeBoundaries[i])) {
              request.destination = null;
              i++;
              largeBoundaries.splice(0, i);
              return;
            }
          largeBoundaries.splice(0, i);
        }
      } finally {
        flushingPartialBoundaries = false, 0 === request.allPendingTasks && 0 === request.clientRenderedBoundaries.length && 0 === request.completedBoundaries.length ? (request.flushScheduled = false, i = request.resumableState, i.hasBody && writeChunk(destination, endChunkForTag("body")), i.hasHtml && writeChunk(destination, endChunkForTag("html")), completeWriting(destination), flushBuffered(destination), 0 !== request.abortableTasks.size && console.error(
          "There was still abortable task at the root when we closed. This is a bug in React."
        ), request.status = CLOSED, destination.end(), request.destination = null) : (completeWriting(destination), flushBuffered(destination));
      }
    }
    function startWork(request) {
      request.flushScheduled = null !== request.destination;
      scheduleMicrotask(function() {
        return requestStorage.run(request, performWork, request);
      });
      setImmediate(function() {
        10 === request.status && (request.status = 11);
        null === request.trackedPostpones && requestStorage.run(
          request,
          enqueueEarlyPreloadsAfterInitialWork,
          request
        );
      });
    }
    function enqueueEarlyPreloadsAfterInitialWork(request) {
      safelyEmitEarlyPreloads(request, 0 === request.pendingRootTasks);
    }
    function enqueueFlush(request) {
      false === request.flushScheduled && 0 === request.pingedTasks.length && null !== request.destination && (request.flushScheduled = true, setImmediate(function() {
        var destination = request.destination;
        destination ? flushCompletedQueues(request, destination) : request.flushScheduled = false;
      }));
    }
    function startFlowing(request, destination) {
      if (13 === request.status)
        request.status = CLOSED, destination.destroy(request.fatalError);
      else if (request.status !== CLOSED && null === request.destination) {
        request.destination = destination;
        try {
          flushCompletedQueues(request, destination);
        } catch (error) {
          destination = {}, logRecoverableError(request, error, destination, null), fatalError(request, error, destination, null);
        }
      }
    }
    function abort(request, reason) {
      if (11 === request.status || 10 === request.status) request.status = 12;
      try {
        var abortableTasks = request.abortableTasks;
        if (0 < abortableTasks.size) {
          var error = void 0 === reason ? Error("The render was aborted by the server without a reason.") : "object" === typeof reason && null !== reason && "function" === typeof reason.then ? Error("The render was aborted by the server with a promise.") : reason;
          request.fatalError = error;
          abortableTasks.forEach(function(task) {
            var prevTaskInDEV = currentTaskInDEV, prevGetCurrentStackImpl = ReactSharedInternals.getCurrentStack;
            currentTaskInDEV = task;
            ReactSharedInternals.getCurrentStack = getCurrentStackInDEV;
            try {
              abortTask(task, request, error);
            } finally {
              currentTaskInDEV = prevTaskInDEV, ReactSharedInternals.getCurrentStack = prevGetCurrentStackImpl;
            }
          });
          abortableTasks.clear();
        }
        null !== request.destination && flushCompletedQueues(request, request.destination);
      } catch (error$4) {
        reason = {}, logRecoverableError(request, error$4, reason, null), fatalError(request, error$4, reason, null);
      }
    }
    function addToReplayParent(node2, parentKeyPath, trackedPostpones) {
      if (null === parentKeyPath) trackedPostpones.rootNodes.push(node2);
      else {
        var workingMap = trackedPostpones.workingMap, parentNode = workingMap.get(parentKeyPath);
        void 0 === parentNode && (parentNode = [parentKeyPath[1], parentKeyPath[2], [], null], workingMap.set(parentKeyPath, parentNode), addToReplayParent(parentNode, parentKeyPath[0], trackedPostpones));
        parentNode[2].push(node2);
      }
    }
    function getPostponedState(request) {
      var trackedPostpones = request.trackedPostpones;
      if (null === trackedPostpones || 0 === trackedPostpones.rootNodes.length && null === trackedPostpones.rootSlots)
        return request.trackedPostpones = null;
      if (null === request.completedRootSegment || request.completedRootSegment.status !== POSTPONED && null !== request.completedPreambleSegments) {
        var nextSegmentId = request.nextSegmentId;
        var replaySlots = trackedPostpones.rootSlots;
        var resumableState = request.resumableState;
        resumableState.bootstrapScriptContent = void 0;
        resumableState.bootstrapScripts = void 0;
        resumableState.bootstrapModules = void 0;
      } else {
        nextSegmentId = 0;
        replaySlots = -1;
        resumableState = request.resumableState;
        var renderState = request.renderState;
        resumableState.nextFormID = 0;
        resumableState.hasBody = false;
        resumableState.hasHtml = false;
        resumableState.unknownResources = { font: renderState.resets.font };
        resumableState.dnsResources = renderState.resets.dns;
        resumableState.connectResources = renderState.resets.connect;
        resumableState.imageResources = renderState.resets.image;
        resumableState.styleResources = renderState.resets.style;
        resumableState.scriptResources = {};
        resumableState.moduleUnknownResources = {};
        resumableState.moduleScriptResources = {};
        resumableState.instructions = NothingSent;
      }
      return {
        nextSegmentId,
        rootFormatContext: request.rootFormatContext,
        progressiveChunkSize: request.progressiveChunkSize,
        resumableState: request.resumableState,
        replayNodes: trackedPostpones.rootNodes,
        replaySlots
      };
    }
    function ensureCorrectIsomorphicReactVersion() {
      var isomorphicReactPackageVersion = React2.version;
      if ("19.2.4" !== isomorphicReactPackageVersion)
        throw Error(
          'Incompatible React versions: The "react" and "react-dom" packages must have the exact same version. Instead got:\n  - react:      ' + (isomorphicReactPackageVersion + "\n  - react-dom:  19.2.4\nLearn more: https://react.dev/warnings/version-mismatch")
        );
    }
    function createDrainHandler(destination, request) {
      return function() {
        return startFlowing(request, destination);
      };
    }
    function createCancelHandler(request, reason) {
      return function() {
        request.destination = null;
        abort(request, Error(reason));
      };
    }
    function createRequestImpl(children, options) {
      var resumableState = createResumableState(
        options ? options.identifierPrefix : void 0,
        options ? options.unstable_externalRuntimeSrc : void 0,
        options ? options.bootstrapScriptContent : void 0,
        options ? options.bootstrapScripts : void 0,
        options ? options.bootstrapModules : void 0
      );
      return createRequest(
        children,
        resumableState,
        createRenderState(
          resumableState,
          options ? options.nonce : void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.importMap : void 0,
          options ? options.onHeaders : void 0,
          options ? options.maxHeadersLength : void 0
        ),
        createRootFormatContext(options ? options.namespaceURI : void 0),
        options ? options.progressiveChunkSize : void 0,
        options ? options.onError : void 0,
        options ? options.onAllReady : void 0,
        options ? options.onShellReady : void 0,
        options ? options.onShellError : void 0,
        void 0,
        options ? options.onPostpone : void 0,
        options ? options.formState : void 0
      );
    }
    function createFakeWritableFromReadableStreamController$1(controller) {
      return {
        write: function(chunk2) {
          "string" === typeof chunk2 && (chunk2 = textEncoder2.encode(chunk2));
          controller.enqueue(chunk2);
          return true;
        },
        end: function() {
          controller.close();
        },
        destroy: function(error) {
          "function" === typeof controller.error ? controller.error(error) : controller.close();
        }
      };
    }
    function resumeRequestImpl(children, postponedState, options) {
      return resumeRequest(
        children,
        postponedState,
        createRenderState(
          postponedState.resumableState,
          options ? options.nonce : void 0,
          void 0,
          void 0,
          void 0,
          void 0
        ),
        options ? options.onError : void 0,
        options ? options.onAllReady : void 0,
        options ? options.onShellReady : void 0,
        options ? options.onShellError : void 0,
        void 0,
        options ? options.onPostpone : void 0
      );
    }
    function createFakeWritableFromReadableStreamController(controller) {
      return {
        write: function(chunk2) {
          "string" === typeof chunk2 && (chunk2 = textEncoder2.encode(chunk2));
          controller.enqueue(chunk2);
          return true;
        },
        end: function() {
          controller.close();
        },
        destroy: function(error) {
          "function" === typeof controller.error ? controller.error(error) : controller.close();
        }
      };
    }
    function createFakeWritableFromReadable(readable) {
      return {
        write: function(chunk2) {
          return readable.push(chunk2);
        },
        end: function() {
          readable.push(null);
        },
        destroy: function(error) {
          readable.destroy(error);
        }
      };
    }
    var util = require$$0$1, crypto2 = require$$1$1, async_hooks = require$$2, React2 = requireReact(), ReactDOM = requireReactDom(), stream$1 = stream, REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_SCOPE_TYPE = /* @__PURE__ */ Symbol.for("react.scope"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_LEGACY_HIDDEN_TYPE = /* @__PURE__ */ Symbol.for("react.legacy_hidden"), REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel"), REACT_VIEW_TRANSITION_TYPE = /* @__PURE__ */ Symbol.for("react.view_transition"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, isArrayImpl = Array.isArray, jsxPropsParents = /* @__PURE__ */ new WeakMap(), jsxChildrenParents = /* @__PURE__ */ new WeakMap(), CLIENT_REFERENCE_TAG = /* @__PURE__ */ Symbol.for("react.client.reference"), scheduleMicrotask = queueMicrotask, currentView = null, writtenBytes = 0, destinationHasCapacity$1 = true, textEncoder2 = new util.TextEncoder(), assign = Object.assign, hasOwnProperty2 = Object.prototype.hasOwnProperty, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
      "^[: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]*$"
    ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, unitlessNumbers = new Set(
      "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
        " "
      )
    ), aliases = /* @__PURE__ */ new Map([
      ["acceptCharset", "accept-charset"],
      ["htmlFor", "for"],
      ["httpEquiv", "http-equiv"],
      ["crossOrigin", "crossorigin"],
      ["accentHeight", "accent-height"],
      ["alignmentBaseline", "alignment-baseline"],
      ["arabicForm", "arabic-form"],
      ["baselineShift", "baseline-shift"],
      ["capHeight", "cap-height"],
      ["clipPath", "clip-path"],
      ["clipRule", "clip-rule"],
      ["colorInterpolation", "color-interpolation"],
      ["colorInterpolationFilters", "color-interpolation-filters"],
      ["colorProfile", "color-profile"],
      ["colorRendering", "color-rendering"],
      ["dominantBaseline", "dominant-baseline"],
      ["enableBackground", "enable-background"],
      ["fillOpacity", "fill-opacity"],
      ["fillRule", "fill-rule"],
      ["floodColor", "flood-color"],
      ["floodOpacity", "flood-opacity"],
      ["fontFamily", "font-family"],
      ["fontSize", "font-size"],
      ["fontSizeAdjust", "font-size-adjust"],
      ["fontStretch", "font-stretch"],
      ["fontStyle", "font-style"],
      ["fontVariant", "font-variant"],
      ["fontWeight", "font-weight"],
      ["glyphName", "glyph-name"],
      ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
      ["glyphOrientationVertical", "glyph-orientation-vertical"],
      ["horizAdvX", "horiz-adv-x"],
      ["horizOriginX", "horiz-origin-x"],
      ["imageRendering", "image-rendering"],
      ["letterSpacing", "letter-spacing"],
      ["lightingColor", "lighting-color"],
      ["markerEnd", "marker-end"],
      ["markerMid", "marker-mid"],
      ["markerStart", "marker-start"],
      ["overlinePosition", "overline-position"],
      ["overlineThickness", "overline-thickness"],
      ["paintOrder", "paint-order"],
      ["panose-1", "panose-1"],
      ["pointerEvents", "pointer-events"],
      ["renderingIntent", "rendering-intent"],
      ["shapeRendering", "shape-rendering"],
      ["stopColor", "stop-color"],
      ["stopOpacity", "stop-opacity"],
      ["strikethroughPosition", "strikethrough-position"],
      ["strikethroughThickness", "strikethrough-thickness"],
      ["strokeDasharray", "stroke-dasharray"],
      ["strokeDashoffset", "stroke-dashoffset"],
      ["strokeLinecap", "stroke-linecap"],
      ["strokeLinejoin", "stroke-linejoin"],
      ["strokeMiterlimit", "stroke-miterlimit"],
      ["strokeOpacity", "stroke-opacity"],
      ["strokeWidth", "stroke-width"],
      ["textAnchor", "text-anchor"],
      ["textDecoration", "text-decoration"],
      ["textRendering", "text-rendering"],
      ["transformOrigin", "transform-origin"],
      ["underlinePosition", "underline-position"],
      ["underlineThickness", "underline-thickness"],
      ["unicodeBidi", "unicode-bidi"],
      ["unicodeRange", "unicode-range"],
      ["unitsPerEm", "units-per-em"],
      ["vAlphabetic", "v-alphabetic"],
      ["vHanging", "v-hanging"],
      ["vIdeographic", "v-ideographic"],
      ["vMathematical", "v-mathematical"],
      ["vectorEffect", "vector-effect"],
      ["vertAdvY", "vert-adv-y"],
      ["vertOriginX", "vert-origin-x"],
      ["vertOriginY", "vert-origin-y"],
      ["wordSpacing", "word-spacing"],
      ["writingMode", "writing-mode"],
      ["xmlnsXlink", "xmlns:xlink"],
      ["xHeight", "x-height"]
    ]), hasReadOnlyValue = {
      button: true,
      checkbox: true,
      image: true,
      hidden: true,
      radio: true,
      reset: true,
      submit: true
    }, ariaProperties = {
      "aria-current": 0,
      "aria-description": 0,
      "aria-details": 0,
      "aria-disabled": 0,
      "aria-hidden": 0,
      "aria-invalid": 0,
      "aria-keyshortcuts": 0,
      "aria-label": 0,
      "aria-roledescription": 0,
      "aria-autocomplete": 0,
      "aria-checked": 0,
      "aria-expanded": 0,
      "aria-haspopup": 0,
      "aria-level": 0,
      "aria-modal": 0,
      "aria-multiline": 0,
      "aria-multiselectable": 0,
      "aria-orientation": 0,
      "aria-placeholder": 0,
      "aria-pressed": 0,
      "aria-readonly": 0,
      "aria-required": 0,
      "aria-selected": 0,
      "aria-sort": 0,
      "aria-valuemax": 0,
      "aria-valuemin": 0,
      "aria-valuenow": 0,
      "aria-valuetext": 0,
      "aria-atomic": 0,
      "aria-busy": 0,
      "aria-live": 0,
      "aria-relevant": 0,
      "aria-dropeffect": 0,
      "aria-grabbed": 0,
      "aria-activedescendant": 0,
      "aria-colcount": 0,
      "aria-colindex": 0,
      "aria-colspan": 0,
      "aria-controls": 0,
      "aria-describedby": 0,
      "aria-errormessage": 0,
      "aria-flowto": 0,
      "aria-labelledby": 0,
      "aria-owns": 0,
      "aria-posinset": 0,
      "aria-rowcount": 0,
      "aria-rowindex": 0,
      "aria-rowspan": 0,
      "aria-setsize": 0,
      "aria-braillelabel": 0,
      "aria-brailleroledescription": 0,
      "aria-colindextext": 0,
      "aria-rowindextext": 0
    }, warnedProperties$1 = {}, rARIA$1 = RegExp(
      "^(aria)-[: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]*$"
    ), rARIACamel$1 = RegExp(
      "^(aria)[A-Z][: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]*$"
    ), didWarnValueNull = false, possibleStandardNames = {
      accept: "accept",
      acceptcharset: "acceptCharset",
      "accept-charset": "acceptCharset",
      accesskey: "accessKey",
      action: "action",
      allowfullscreen: "allowFullScreen",
      alt: "alt",
      as: "as",
      async: "async",
      autocapitalize: "autoCapitalize",
      autocomplete: "autoComplete",
      autocorrect: "autoCorrect",
      autofocus: "autoFocus",
      autoplay: "autoPlay",
      autosave: "autoSave",
      capture: "capture",
      cellpadding: "cellPadding",
      cellspacing: "cellSpacing",
      challenge: "challenge",
      charset: "charSet",
      checked: "checked",
      children: "children",
      cite: "cite",
      class: "className",
      classid: "classID",
      classname: "className",
      cols: "cols",
      colspan: "colSpan",
      content: "content",
      contenteditable: "contentEditable",
      contextmenu: "contextMenu",
      controls: "controls",
      controlslist: "controlsList",
      coords: "coords",
      crossorigin: "crossOrigin",
      dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
      data: "data",
      datetime: "dateTime",
      default: "default",
      defaultchecked: "defaultChecked",
      defaultvalue: "defaultValue",
      defer: "defer",
      dir: "dir",
      disabled: "disabled",
      disablepictureinpicture: "disablePictureInPicture",
      disableremoteplayback: "disableRemotePlayback",
      download: "download",
      draggable: "draggable",
      enctype: "encType",
      enterkeyhint: "enterKeyHint",
      fetchpriority: "fetchPriority",
      for: "htmlFor",
      form: "form",
      formmethod: "formMethod",
      formaction: "formAction",
      formenctype: "formEncType",
      formnovalidate: "formNoValidate",
      formtarget: "formTarget",
      frameborder: "frameBorder",
      headers: "headers",
      height: "height",
      hidden: "hidden",
      high: "high",
      href: "href",
      hreflang: "hrefLang",
      htmlfor: "htmlFor",
      httpequiv: "httpEquiv",
      "http-equiv": "httpEquiv",
      icon: "icon",
      id: "id",
      imagesizes: "imageSizes",
      imagesrcset: "imageSrcSet",
      inert: "inert",
      innerhtml: "innerHTML",
      inputmode: "inputMode",
      integrity: "integrity",
      is: "is",
      itemid: "itemID",
      itemprop: "itemProp",
      itemref: "itemRef",
      itemscope: "itemScope",
      itemtype: "itemType",
      keyparams: "keyParams",
      keytype: "keyType",
      kind: "kind",
      label: "label",
      lang: "lang",
      list: "list",
      loop: "loop",
      low: "low",
      manifest: "manifest",
      marginwidth: "marginWidth",
      marginheight: "marginHeight",
      max: "max",
      maxlength: "maxLength",
      media: "media",
      mediagroup: "mediaGroup",
      method: "method",
      min: "min",
      minlength: "minLength",
      multiple: "multiple",
      muted: "muted",
      name: "name",
      nomodule: "noModule",
      nonce: "nonce",
      novalidate: "noValidate",
      open: "open",
      optimum: "optimum",
      pattern: "pattern",
      placeholder: "placeholder",
      playsinline: "playsInline",
      poster: "poster",
      preload: "preload",
      profile: "profile",
      radiogroup: "radioGroup",
      readonly: "readOnly",
      referrerpolicy: "referrerPolicy",
      rel: "rel",
      required: "required",
      reversed: "reversed",
      role: "role",
      rows: "rows",
      rowspan: "rowSpan",
      sandbox: "sandbox",
      scope: "scope",
      scoped: "scoped",
      scrolling: "scrolling",
      seamless: "seamless",
      selected: "selected",
      shape: "shape",
      size: "size",
      sizes: "sizes",
      span: "span",
      spellcheck: "spellCheck",
      src: "src",
      srcdoc: "srcDoc",
      srclang: "srcLang",
      srcset: "srcSet",
      start: "start",
      step: "step",
      style: "style",
      summary: "summary",
      tabindex: "tabIndex",
      target: "target",
      title: "title",
      type: "type",
      usemap: "useMap",
      value: "value",
      width: "width",
      wmode: "wmode",
      wrap: "wrap",
      about: "about",
      accentheight: "accentHeight",
      "accent-height": "accentHeight",
      accumulate: "accumulate",
      additive: "additive",
      alignmentbaseline: "alignmentBaseline",
      "alignment-baseline": "alignmentBaseline",
      allowreorder: "allowReorder",
      alphabetic: "alphabetic",
      amplitude: "amplitude",
      arabicform: "arabicForm",
      "arabic-form": "arabicForm",
      ascent: "ascent",
      attributename: "attributeName",
      attributetype: "attributeType",
      autoreverse: "autoReverse",
      azimuth: "azimuth",
      basefrequency: "baseFrequency",
      baselineshift: "baselineShift",
      "baseline-shift": "baselineShift",
      baseprofile: "baseProfile",
      bbox: "bbox",
      begin: "begin",
      bias: "bias",
      by: "by",
      calcmode: "calcMode",
      capheight: "capHeight",
      "cap-height": "capHeight",
      clip: "clip",
      clippath: "clipPath",
      "clip-path": "clipPath",
      clippathunits: "clipPathUnits",
      cliprule: "clipRule",
      "clip-rule": "clipRule",
      color: "color",
      colorinterpolation: "colorInterpolation",
      "color-interpolation": "colorInterpolation",
      colorinterpolationfilters: "colorInterpolationFilters",
      "color-interpolation-filters": "colorInterpolationFilters",
      colorprofile: "colorProfile",
      "color-profile": "colorProfile",
      colorrendering: "colorRendering",
      "color-rendering": "colorRendering",
      contentscripttype: "contentScriptType",
      contentstyletype: "contentStyleType",
      cursor: "cursor",
      cx: "cx",
      cy: "cy",
      d: "d",
      datatype: "datatype",
      decelerate: "decelerate",
      descent: "descent",
      diffuseconstant: "diffuseConstant",
      direction: "direction",
      display: "display",
      divisor: "divisor",
      dominantbaseline: "dominantBaseline",
      "dominant-baseline": "dominantBaseline",
      dur: "dur",
      dx: "dx",
      dy: "dy",
      edgemode: "edgeMode",
      elevation: "elevation",
      enablebackground: "enableBackground",
      "enable-background": "enableBackground",
      end: "end",
      exponent: "exponent",
      externalresourcesrequired: "externalResourcesRequired",
      fill: "fill",
      fillopacity: "fillOpacity",
      "fill-opacity": "fillOpacity",
      fillrule: "fillRule",
      "fill-rule": "fillRule",
      filter: "filter",
      filterres: "filterRes",
      filterunits: "filterUnits",
      floodopacity: "floodOpacity",
      "flood-opacity": "floodOpacity",
      floodcolor: "floodColor",
      "flood-color": "floodColor",
      focusable: "focusable",
      fontfamily: "fontFamily",
      "font-family": "fontFamily",
      fontsize: "fontSize",
      "font-size": "fontSize",
      fontsizeadjust: "fontSizeAdjust",
      "font-size-adjust": "fontSizeAdjust",
      fontstretch: "fontStretch",
      "font-stretch": "fontStretch",
      fontstyle: "fontStyle",
      "font-style": "fontStyle",
      fontvariant: "fontVariant",
      "font-variant": "fontVariant",
      fontweight: "fontWeight",
      "font-weight": "fontWeight",
      format: "format",
      from: "from",
      fx: "fx",
      fy: "fy",
      g1: "g1",
      g2: "g2",
      glyphname: "glyphName",
      "glyph-name": "glyphName",
      glyphorientationhorizontal: "glyphOrientationHorizontal",
      "glyph-orientation-horizontal": "glyphOrientationHorizontal",
      glyphorientationvertical: "glyphOrientationVertical",
      "glyph-orientation-vertical": "glyphOrientationVertical",
      glyphref: "glyphRef",
      gradienttransform: "gradientTransform",
      gradientunits: "gradientUnits",
      hanging: "hanging",
      horizadvx: "horizAdvX",
      "horiz-adv-x": "horizAdvX",
      horizoriginx: "horizOriginX",
      "horiz-origin-x": "horizOriginX",
      ideographic: "ideographic",
      imagerendering: "imageRendering",
      "image-rendering": "imageRendering",
      in2: "in2",
      in: "in",
      inlist: "inlist",
      intercept: "intercept",
      k1: "k1",
      k2: "k2",
      k3: "k3",
      k4: "k4",
      k: "k",
      kernelmatrix: "kernelMatrix",
      kernelunitlength: "kernelUnitLength",
      kerning: "kerning",
      keypoints: "keyPoints",
      keysplines: "keySplines",
      keytimes: "keyTimes",
      lengthadjust: "lengthAdjust",
      letterspacing: "letterSpacing",
      "letter-spacing": "letterSpacing",
      lightingcolor: "lightingColor",
      "lighting-color": "lightingColor",
      limitingconeangle: "limitingConeAngle",
      local: "local",
      markerend: "markerEnd",
      "marker-end": "markerEnd",
      markerheight: "markerHeight",
      markermid: "markerMid",
      "marker-mid": "markerMid",
      markerstart: "markerStart",
      "marker-start": "markerStart",
      markerunits: "markerUnits",
      markerwidth: "markerWidth",
      mask: "mask",
      maskcontentunits: "maskContentUnits",
      maskunits: "maskUnits",
      mathematical: "mathematical",
      mode: "mode",
      numoctaves: "numOctaves",
      offset: "offset",
      opacity: "opacity",
      operator: "operator",
      order: "order",
      orient: "orient",
      orientation: "orientation",
      origin: "origin",
      overflow: "overflow",
      overlineposition: "overlinePosition",
      "overline-position": "overlinePosition",
      overlinethickness: "overlineThickness",
      "overline-thickness": "overlineThickness",
      paintorder: "paintOrder",
      "paint-order": "paintOrder",
      panose1: "panose1",
      "panose-1": "panose1",
      pathlength: "pathLength",
      patterncontentunits: "patternContentUnits",
      patterntransform: "patternTransform",
      patternunits: "patternUnits",
      pointerevents: "pointerEvents",
      "pointer-events": "pointerEvents",
      points: "points",
      pointsatx: "pointsAtX",
      pointsaty: "pointsAtY",
      pointsatz: "pointsAtZ",
      popover: "popover",
      popovertarget: "popoverTarget",
      popovertargetaction: "popoverTargetAction",
      prefix: "prefix",
      preservealpha: "preserveAlpha",
      preserveaspectratio: "preserveAspectRatio",
      primitiveunits: "primitiveUnits",
      property: "property",
      r: "r",
      radius: "radius",
      refx: "refX",
      refy: "refY",
      renderingintent: "renderingIntent",
      "rendering-intent": "renderingIntent",
      repeatcount: "repeatCount",
      repeatdur: "repeatDur",
      requiredextensions: "requiredExtensions",
      requiredfeatures: "requiredFeatures",
      resource: "resource",
      restart: "restart",
      result: "result",
      results: "results",
      rotate: "rotate",
      rx: "rx",
      ry: "ry",
      scale: "scale",
      security: "security",
      seed: "seed",
      shaperendering: "shapeRendering",
      "shape-rendering": "shapeRendering",
      slope: "slope",
      spacing: "spacing",
      specularconstant: "specularConstant",
      specularexponent: "specularExponent",
      speed: "speed",
      spreadmethod: "spreadMethod",
      startoffset: "startOffset",
      stddeviation: "stdDeviation",
      stemh: "stemh",
      stemv: "stemv",
      stitchtiles: "stitchTiles",
      stopcolor: "stopColor",
      "stop-color": "stopColor",
      stopopacity: "stopOpacity",
      "stop-opacity": "stopOpacity",
      strikethroughposition: "strikethroughPosition",
      "strikethrough-position": "strikethroughPosition",
      strikethroughthickness: "strikethroughThickness",
      "strikethrough-thickness": "strikethroughThickness",
      string: "string",
      stroke: "stroke",
      strokedasharray: "strokeDasharray",
      "stroke-dasharray": "strokeDasharray",
      strokedashoffset: "strokeDashoffset",
      "stroke-dashoffset": "strokeDashoffset",
      strokelinecap: "strokeLinecap",
      "stroke-linecap": "strokeLinecap",
      strokelinejoin: "strokeLinejoin",
      "stroke-linejoin": "strokeLinejoin",
      strokemiterlimit: "strokeMiterlimit",
      "stroke-miterlimit": "strokeMiterlimit",
      strokewidth: "strokeWidth",
      "stroke-width": "strokeWidth",
      strokeopacity: "strokeOpacity",
      "stroke-opacity": "strokeOpacity",
      suppresscontenteditablewarning: "suppressContentEditableWarning",
      suppresshydrationwarning: "suppressHydrationWarning",
      surfacescale: "surfaceScale",
      systemlanguage: "systemLanguage",
      tablevalues: "tableValues",
      targetx: "targetX",
      targety: "targetY",
      textanchor: "textAnchor",
      "text-anchor": "textAnchor",
      textdecoration: "textDecoration",
      "text-decoration": "textDecoration",
      textlength: "textLength",
      textrendering: "textRendering",
      "text-rendering": "textRendering",
      to: "to",
      transform: "transform",
      transformorigin: "transformOrigin",
      "transform-origin": "transformOrigin",
      typeof: "typeof",
      u1: "u1",
      u2: "u2",
      underlineposition: "underlinePosition",
      "underline-position": "underlinePosition",
      underlinethickness: "underlineThickness",
      "underline-thickness": "underlineThickness",
      unicode: "unicode",
      unicodebidi: "unicodeBidi",
      "unicode-bidi": "unicodeBidi",
      unicoderange: "unicodeRange",
      "unicode-range": "unicodeRange",
      unitsperem: "unitsPerEm",
      "units-per-em": "unitsPerEm",
      unselectable: "unselectable",
      valphabetic: "vAlphabetic",
      "v-alphabetic": "vAlphabetic",
      values: "values",
      vectoreffect: "vectorEffect",
      "vector-effect": "vectorEffect",
      version: "version",
      vertadvy: "vertAdvY",
      "vert-adv-y": "vertAdvY",
      vertoriginx: "vertOriginX",
      "vert-origin-x": "vertOriginX",
      vertoriginy: "vertOriginY",
      "vert-origin-y": "vertOriginY",
      vhanging: "vHanging",
      "v-hanging": "vHanging",
      videographic: "vIdeographic",
      "v-ideographic": "vIdeographic",
      viewbox: "viewBox",
      viewtarget: "viewTarget",
      visibility: "visibility",
      vmathematical: "vMathematical",
      "v-mathematical": "vMathematical",
      vocab: "vocab",
      widths: "widths",
      wordspacing: "wordSpacing",
      "word-spacing": "wordSpacing",
      writingmode: "writingMode",
      "writing-mode": "writingMode",
      x1: "x1",
      x2: "x2",
      x: "x",
      xchannelselector: "xChannelSelector",
      xheight: "xHeight",
      "x-height": "xHeight",
      xlinkactuate: "xlinkActuate",
      "xlink:actuate": "xlinkActuate",
      xlinkarcrole: "xlinkArcrole",
      "xlink:arcrole": "xlinkArcrole",
      xlinkhref: "xlinkHref",
      "xlink:href": "xlinkHref",
      xlinkrole: "xlinkRole",
      "xlink:role": "xlinkRole",
      xlinkshow: "xlinkShow",
      "xlink:show": "xlinkShow",
      xlinktitle: "xlinkTitle",
      "xlink:title": "xlinkTitle",
      xlinktype: "xlinkType",
      "xlink:type": "xlinkType",
      xmlbase: "xmlBase",
      "xml:base": "xmlBase",
      xmllang: "xmlLang",
      "xml:lang": "xmlLang",
      xmlns: "xmlns",
      "xml:space": "xmlSpace",
      xmlnsxlink: "xmlnsXlink",
      "xmlns:xlink": "xmlnsXlink",
      xmlspace: "xmlSpace",
      y1: "y1",
      y2: "y2",
      y: "y",
      ychannelselector: "yChannelSelector",
      z: "z",
      zoomandpan: "zoomAndPan"
    }, warnedProperties = {}, EVENT_NAME_REGEX = /^on./, INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/, rARIA = RegExp(
      "^(aria)-[: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]*$"
    ), rARIACamel = RegExp(
      "^(aria)[A-Z][: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]*$"
    ), badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, msPattern$1 = /^-ms-/, hyphenPattern = /-(.)/g, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = false, warnedForInfinityValue = false, matchHtmlRegExp = /["'&<>]/, uppercasePattern = /([A-Z])/g, msPattern = /^ms-/, isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i, ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, NotPending = Object.freeze({
      pending: false,
      data: null,
      method: null,
      action: null
    }), previousDispatcher = ReactDOMSharedInternals.d;
    ReactDOMSharedInternals.d = {
      f: previousDispatcher.f,
      r: previousDispatcher.r,
      D: function(href) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if ("string" === typeof href && href) {
            if (!resumableState.dnsResources.hasOwnProperty(href)) {
              resumableState.dnsResources[href] = EXISTS;
              resumableState = renderState.headers;
              var header, JSCompiler_temp;
              if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity)
                JSCompiler_temp = (header = "<" + escapeHrefForLinkHeaderURLContext(href) + ">; rel=dns-prefetch", 0 <= (resumableState.remainingCapacity -= header.length + 2));
              JSCompiler_temp ? (renderState.resets.dns[href] = EXISTS, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (header = [], pushLinkImpl(header, { href, rel: "dns-prefetch" }), renderState.preconnects.add(header));
            }
            enqueueFlush(request);
          }
        } else previousDispatcher.D(href);
      },
      C: function(href, crossOrigin) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if ("string" === typeof href && href) {
            var bucket = "use-credentials" === crossOrigin ? "credentials" : "string" === typeof crossOrigin ? "anonymous" : "default";
            if (!resumableState.connectResources[bucket].hasOwnProperty(href)) {
              resumableState.connectResources[bucket][href] = EXISTS;
              resumableState = renderState.headers;
              var header, JSCompiler_temp;
              if (JSCompiler_temp = resumableState && 0 < resumableState.remainingCapacity) {
                JSCompiler_temp = "<" + escapeHrefForLinkHeaderURLContext(href) + ">; rel=preconnect";
                if ("string" === typeof crossOrigin) {
                  var escapedCrossOrigin = escapeStringForLinkHeaderQuotedParamValueContext(
                    crossOrigin,
                    "crossOrigin"
                  );
                  JSCompiler_temp += '; crossorigin="' + escapedCrossOrigin + '"';
                }
                JSCompiler_temp = (header = JSCompiler_temp, 0 <= (resumableState.remainingCapacity -= header.length + 2));
              }
              JSCompiler_temp ? (renderState.resets.connect[bucket][href] = EXISTS, resumableState.preconnects && (resumableState.preconnects += ", "), resumableState.preconnects += header) : (bucket = [], pushLinkImpl(bucket, {
                rel: "preconnect",
                href,
                crossOrigin
              }), renderState.preconnects.add(bucket));
            }
            enqueueFlush(request);
          }
        } else previousDispatcher.C(href, crossOrigin);
      },
      L: function(href, as, options) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (as && href) {
            switch (as) {
              case "image":
                if (options) {
                  var imageSrcSet = options.imageSrcSet;
                  var imageSizes = options.imageSizes;
                  var fetchPriority = options.fetchPriority;
                }
                var key = imageSrcSet ? imageSrcSet + "\n" + (imageSizes || "") : href;
                if (resumableState.imageResources.hasOwnProperty(key)) return;
                resumableState.imageResources[key] = PRELOAD_NO_CREDS;
                resumableState = renderState.headers;
                var header;
                resumableState && 0 < resumableState.remainingCapacity && "string" !== typeof imageSrcSet && "high" === fetchPriority && (header = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= header.length + 2)) ? (renderState.resets.image[key] = PRELOAD_NO_CREDS, resumableState.highImagePreloads && (resumableState.highImagePreloads += ", "), resumableState.highImagePreloads += header) : (resumableState = [], pushLinkImpl(
                  resumableState,
                  assign(
                    {
                      rel: "preload",
                      href: imageSrcSet ? void 0 : href,
                      as
                    },
                    options
                  )
                ), "high" === fetchPriority ? renderState.highImagePreloads.add(resumableState) : (renderState.bulkPreloads.add(resumableState), renderState.preloads.images.set(key, resumableState)));
                break;
              case "style":
                if (resumableState.styleResources.hasOwnProperty(href)) return;
                imageSrcSet = [];
                pushLinkImpl(
                  imageSrcSet,
                  assign({ rel: "preload", href, as }, options)
                );
                resumableState.styleResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
                renderState.preloads.stylesheets.set(href, imageSrcSet);
                renderState.bulkPreloads.add(imageSrcSet);
                break;
              case "script":
                if (resumableState.scriptResources.hasOwnProperty(href)) return;
                imageSrcSet = [];
                renderState.preloads.scripts.set(href, imageSrcSet);
                renderState.bulkPreloads.add(imageSrcSet);
                pushLinkImpl(
                  imageSrcSet,
                  assign({ rel: "preload", href, as }, options)
                );
                resumableState.scriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
                break;
              default:
                if (resumableState.unknownResources.hasOwnProperty(as)) {
                  if (imageSrcSet = resumableState.unknownResources[as], imageSrcSet.hasOwnProperty(href))
                    return;
                } else
                  imageSrcSet = {}, resumableState.unknownResources[as] = imageSrcSet;
                imageSrcSet[href] = PRELOAD_NO_CREDS;
                if ((resumableState = renderState.headers) && 0 < resumableState.remainingCapacity && "font" === as && (key = getPreloadAsHeader(href, as, options), 0 <= (resumableState.remainingCapacity -= key.length + 2)))
                  renderState.resets.font[href] = PRELOAD_NO_CREDS, resumableState.fontPreloads && (resumableState.fontPreloads += ", "), resumableState.fontPreloads += key;
                else
                  switch (resumableState = [], href = assign(
                    { rel: "preload", href, as },
                    options
                  ), pushLinkImpl(resumableState, href), as) {
                    case "font":
                      renderState.fontPreloads.add(resumableState);
                      break;
                    default:
                      renderState.bulkPreloads.add(resumableState);
                  }
            }
            enqueueFlush(request);
          }
        } else previousDispatcher.L(href, as, options);
      },
      m: function(href, options) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (href) {
            var as = options && "string" === typeof options.as ? options.as : "script";
            switch (as) {
              case "script":
                if (resumableState.moduleScriptResources.hasOwnProperty(href))
                  return;
                as = [];
                resumableState.moduleScriptResources[href] = !options || "string" !== typeof options.crossOrigin && "string" !== typeof options.integrity ? PRELOAD_NO_CREDS : [options.crossOrigin, options.integrity];
                renderState.preloads.moduleScripts.set(href, as);
                break;
              default:
                if (resumableState.moduleUnknownResources.hasOwnProperty(as)) {
                  var resources = resumableState.unknownResources[as];
                  if (resources.hasOwnProperty(href)) return;
                } else
                  resources = {}, resumableState.moduleUnknownResources[as] = resources;
                as = [];
                resources[href] = PRELOAD_NO_CREDS;
            }
            pushLinkImpl(
              as,
              assign({ rel: "modulepreload", href }, options)
            );
            renderState.bulkPreloads.add(as);
            enqueueFlush(request);
          }
        } else previousDispatcher.m(href, options);
      },
      X: function(src2, options) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (src2) {
            var resourceState = resumableState.scriptResources.hasOwnProperty(
              src2
            ) ? resumableState.scriptResources[src2] : void 0;
            resourceState !== EXISTS && (resumableState.scriptResources[src2] = EXISTS, options = assign({ src: src2, async: true }, options), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.scripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
          }
        } else previousDispatcher.X(src2, options);
      },
      S: function(href, precedence, options) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (href) {
            precedence = precedence || "default";
            var styleQueue = renderState.styles.get(precedence), resourceState = resumableState.styleResources.hasOwnProperty(href) ? resumableState.styleResources[href] : void 0;
            resourceState !== EXISTS && (resumableState.styleResources[href] = EXISTS, styleQueue || (styleQueue = {
              precedence: escapeTextForBrowser(precedence),
              rules: [],
              hrefs: [],
              sheets: /* @__PURE__ */ new Map()
            }, renderState.styles.set(precedence, styleQueue)), precedence = {
              state: PENDING$1,
              props: assign(
                {
                  rel: "stylesheet",
                  href,
                  "data-precedence": precedence
                },
                options
              )
            }, resourceState && (2 === resourceState.length && adoptPreloadCredentials(precedence.props, resourceState), (renderState = renderState.preloads.stylesheets.get(href)) && 0 < renderState.length ? renderState.length = 0 : precedence.state = PRELOADED), styleQueue.sheets.set(href, precedence), enqueueFlush(request));
          }
        } else previousDispatcher.S(href, precedence, options);
      },
      M: function(src2, options) {
        var request = resolveRequest();
        if (request) {
          var resumableState = request.resumableState, renderState = request.renderState;
          if (src2) {
            var resourceState = resumableState.moduleScriptResources.hasOwnProperty(src2) ? resumableState.moduleScriptResources[src2] : void 0;
            resourceState !== EXISTS && (resumableState.moduleScriptResources[src2] = EXISTS, options = assign(
              { src: src2, type: "module", async: true },
              options
            ), resourceState && (2 === resourceState.length && adoptPreloadCredentials(options, resourceState), src2 = renderState.preloads.moduleScripts.get(src2)) && (src2.length = 0), src2 = [], renderState.scripts.add(src2), pushScriptImpl(src2, options), enqueueFlush(request));
          }
        } else previousDispatcher.M(src2, options);
      }
    };
    var NothingSent = 0, SentCompleteSegmentFunction = 1, SentCompleteBoundaryFunction = 2, SentClientRenderFunction = 4, SentStyleInsertionFunction = 8, SentCompletedShellId = 32, SentMarkShellTime = 64, EXISTS = null, PRELOAD_NO_CREDS = [];
    Object.freeze(PRELOAD_NO_CREDS);
    var currentlyFlushingRenderState = null;
    stringToPrecomputedChunk('"></template>');
    var startInlineScript = stringToPrecomputedChunk("<script"), endInlineScript = stringToPrecomputedChunk("<\/script>"), startScriptSrc = stringToPrecomputedChunk('<script src="'), startModuleSrc = stringToPrecomputedChunk('<script type="module" src="'), scriptNonce = stringToPrecomputedChunk(' nonce="'), scriptIntegirty = stringToPrecomputedChunk(' integrity="'), scriptCrossOrigin = stringToPrecomputedChunk(' crossorigin="'), endAsyncScript = stringToPrecomputedChunk(' async=""><\/script>'), startInlineStyle = stringToPrecomputedChunk("<style"), scriptRegex = /(<\/|<)(s)(cript)/gi, importMapScriptStart = stringToPrecomputedChunk(
      '<script type="importmap">'
    ), importMapScriptEnd = stringToPrecomputedChunk("<\/script>");
    var didWarnForNewBooleanPropsWithEmptyValue = {};
    var ROOT_HTML_MODE = 0, HTML_HTML_MODE = 1, HTML_MODE = 2, HTML_HEAD_MODE = 3, SVG_MODE = 4, MATHML_MODE = 5, HTML_TABLE_MODE = 6, HTML_TABLE_BODY_MODE = 7, HTML_TABLE_ROW_MODE = 8, HTML_COLGROUP_MODE = 9, textSeparator = stringToPrecomputedChunk("<!-- -->"), styleNameCache = /* @__PURE__ */ new Map(), styleAttributeStart = stringToPrecomputedChunk(' style="'), styleAssign = stringToPrecomputedChunk(":"), styleSeparator = stringToPrecomputedChunk(";"), attributeSeparator = stringToPrecomputedChunk(" "), attributeAssign = stringToPrecomputedChunk('="'), attributeEnd = stringToPrecomputedChunk('"'), attributeEmptyString = stringToPrecomputedChunk('=""'), actionJavaScriptURL = stringToPrecomputedChunk(
      escapeTextForBrowser(
        "javascript:throw new Error('React form unexpectedly submitted.')"
      )
    ), startHiddenInputChunk = stringToPrecomputedChunk('<input type="hidden"'), endOfStartTag = stringToPrecomputedChunk(">"), endOfStartTagSelfClosing = stringToPrecomputedChunk("/>"), didWarnDefaultInputValue = false, didWarnDefaultChecked = false, didWarnDefaultSelectValue = false, didWarnDefaultTextareaValue = false, didWarnInvalidOptionChildren = false, didWarnInvalidOptionInnerHTML = false, didWarnSelectedSetOnOption = false, didWarnFormActionType = false, didWarnFormActionName = false, didWarnFormActionTarget = false, didWarnFormActionMethod = false, selectedMarkerAttribute = stringToPrecomputedChunk(' selected=""'), formReplayingRuntimeScript = stringToPrecomputedChunk(
      `addEventListener("submit",function(a){if(!a.defaultPrevented){var c=a.target,d=a.submitter,e=c.action,b=d;if(d){var f=d.getAttribute("formAction");null!=f&&(e=f,b=null)}"javascript:throw new Error('React form unexpectedly submitted.')"===e&&(a.preventDefault(),b?(a=document.createElement("input"),a.name=b.name,a.value=b.value,b.parentNode.insertBefore(a,b),b=new FormData(c),a.parentNode.removeChild(a)):b=new FormData(c),a=c.ownerDocument||c,(a.$$reactFormReplay=a.$$reactFormReplay||[]).push(c,d,b))}});`
    ), formStateMarkerIsMatching = stringToPrecomputedChunk("<!--F!-->"), formStateMarkerIsNotMatching = stringToPrecomputedChunk("<!--F-->"), styleRegex = /(<\/|<)(s)(tyle)/gi, headPreambleContributionChunk = stringToPrecomputedChunk("<!--head-->"), bodyPreambleContributionChunk = stringToPrecomputedChunk("<!--body-->"), htmlPreambleContributionChunk = stringToPrecomputedChunk("<!--html-->"), leadingNewline = stringToPrecomputedChunk("\n"), VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/, validatedTagCache = /* @__PURE__ */ new Map(), doctypeChunk = stringToPrecomputedChunk("<!DOCTYPE html>"), endTagCache = /* @__PURE__ */ new Map(), shellTimeRuntimeScript = stringToPrecomputedChunk(
      "requestAnimationFrame(function(){$RT=performance.now()});"
    ), placeholder1 = stringToPrecomputedChunk('<template id="'), placeholder2 = stringToPrecomputedChunk('"></template>'), startActivityBoundary = stringToPrecomputedChunk("<!--&-->"), endActivityBoundary = stringToPrecomputedChunk("<!--/&-->"), startCompletedSuspenseBoundary = stringToPrecomputedChunk("<!--$-->"), startPendingSuspenseBoundary1 = stringToPrecomputedChunk(
      '<!--$?--><template id="'
    ), startPendingSuspenseBoundary2 = stringToPrecomputedChunk('"></template>'), startClientRenderedSuspenseBoundary = stringToPrecomputedChunk("<!--$!-->"), endSuspenseBoundary = stringToPrecomputedChunk("<!--/$-->"), clientRenderedSuspenseBoundaryError1 = stringToPrecomputedChunk("<template"), clientRenderedSuspenseBoundaryErrorAttrInterstitial = stringToPrecomputedChunk('"'), clientRenderedSuspenseBoundaryError1A = stringToPrecomputedChunk(' data-dgst="'), clientRenderedSuspenseBoundaryError1B = stringToPrecomputedChunk(' data-msg="'), clientRenderedSuspenseBoundaryError1C = stringToPrecomputedChunk(' data-stck="'), clientRenderedSuspenseBoundaryError1D = stringToPrecomputedChunk(' data-cstck="'), clientRenderedSuspenseBoundaryError2 = stringToPrecomputedChunk("></template>"), startSegmentHTML = stringToPrecomputedChunk('<div hidden id="'), startSegmentHTML2 = stringToPrecomputedChunk('">'), endSegmentHTML = stringToPrecomputedChunk("</div>"), startSegmentSVG = stringToPrecomputedChunk(
      '<svg aria-hidden="true" style="display:none" id="'
    ), startSegmentSVG2 = stringToPrecomputedChunk('">'), endSegmentSVG = stringToPrecomputedChunk("</svg>"), startSegmentMathML = stringToPrecomputedChunk(
      '<math aria-hidden="true" style="display:none" id="'
    ), startSegmentMathML2 = stringToPrecomputedChunk('">'), endSegmentMathML = stringToPrecomputedChunk("</math>"), startSegmentTable = stringToPrecomputedChunk('<table hidden id="'), startSegmentTable2 = stringToPrecomputedChunk('">'), endSegmentTable = stringToPrecomputedChunk("</table>"), startSegmentTableBody = stringToPrecomputedChunk(
      '<table hidden><tbody id="'
    ), startSegmentTableBody2 = stringToPrecomputedChunk('">'), endSegmentTableBody = stringToPrecomputedChunk("</tbody></table>"), startSegmentTableRow = stringToPrecomputedChunk('<table hidden><tr id="'), startSegmentTableRow2 = stringToPrecomputedChunk('">'), endSegmentTableRow = stringToPrecomputedChunk("</tr></table>"), startSegmentColGroup = stringToPrecomputedChunk(
      '<table hidden><colgroup id="'
    ), startSegmentColGroup2 = stringToPrecomputedChunk('">'), endSegmentColGroup = stringToPrecomputedChunk("</colgroup></table>"), completeSegmentScript1Full = stringToPrecomputedChunk(
      '$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'
    ), completeSegmentScript1Partial = stringToPrecomputedChunk('$RS("'), completeSegmentScript2 = stringToPrecomputedChunk('","'), completeSegmentScriptEnd = stringToPrecomputedChunk('")<\/script>');
    stringToPrecomputedChunk('<template data-rsi="" data-sid="');
    stringToPrecomputedChunk('" data-pid="');
    var completeBoundaryScriptFunctionOnly = stringToPrecomputedChunk(
      '$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};\n$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};'
    ), completeBoundaryScript1Partial = stringToPrecomputedChunk('$RC("'), completeBoundaryWithStylesScript1FullPartial = stringToPrecomputedChunk(
      '$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=\n"stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=\n"$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("'
    ), completeBoundaryWithStylesScript1Partial = stringToPrecomputedChunk('$RR("'), completeBoundaryScript2 = stringToPrecomputedChunk('","'), completeBoundaryScript3a = stringToPrecomputedChunk('",'), completeBoundaryScript3b = stringToPrecomputedChunk('"'), completeBoundaryScriptEnd = stringToPrecomputedChunk(")<\/script>");
    stringToPrecomputedChunk('<template data-rci="" data-bid="');
    stringToPrecomputedChunk('<template data-rri="" data-bid="');
    stringToPrecomputedChunk('" data-sid="');
    stringToPrecomputedChunk('" data-sty="');
    var clientRenderScriptFunctionOnly = stringToPrecomputedChunk(
      '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};'
    ), clientRenderScript1Full = stringToPrecomputedChunk(
      '$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("'
    ), clientRenderScript1Partial = stringToPrecomputedChunk('$RX("'), clientRenderScript1A = stringToPrecomputedChunk('"'), clientRenderErrorScriptArgInterstitial = stringToPrecomputedChunk(","), clientRenderScriptEnd = stringToPrecomputedChunk(")<\/script>");
    stringToPrecomputedChunk('<template data-rxi="" data-bid="');
    stringToPrecomputedChunk('" data-dgst="');
    stringToPrecomputedChunk('" data-msg="');
    stringToPrecomputedChunk('" data-stck="');
    stringToPrecomputedChunk('" data-cstck="');
    var regexForJSStringsInInstructionScripts = /[<\u2028\u2029]/g, regexForJSStringsInScripts = /[&><\u2028\u2029]/g, lateStyleTagResourceOpen1 = stringToPrecomputedChunk(
      ' media="not all" data-precedence="'
    ), lateStyleTagResourceOpen2 = stringToPrecomputedChunk('" data-href="'), lateStyleTagResourceOpen3 = stringToPrecomputedChunk('">'), lateStyleTagTemplateClose = stringToPrecomputedChunk("</style>"), currentlyRenderingBoundaryHasStylesToHoist = false, destinationHasCapacity = true, stylesheetFlushingQueue = [], styleTagResourceOpen1 = stringToPrecomputedChunk(' data-precedence="'), styleTagResourceOpen2 = stringToPrecomputedChunk('" data-href="'), spaceSeparator = stringToPrecomputedChunk(" "), styleTagResourceOpen3 = stringToPrecomputedChunk('">'), styleTagResourceClose = stringToPrecomputedChunk("</style>");
    stringToPrecomputedChunk('<link rel="expect" href="#');
    stringToPrecomputedChunk('" blocking="render"/>');
    var completedShellIdAttributeStart = stringToPrecomputedChunk(' id="'), arrayFirstOpenBracket = stringToPrecomputedChunk("["), arraySubsequentOpenBracket = stringToPrecomputedChunk(",["), arrayInterstitial = stringToPrecomputedChunk(","), arrayCloseBracket = stringToPrecomputedChunk("]"), PENDING$1 = 0, PRELOADED = 1, PREAMBLE = 2, LATE = 3, regexForHrefInLinkHeaderURLContext = /[<>\r\n]/g, regexForLinkHeaderQuotedParamValueContext = /["';,\r\n]/g, bind2 = Function.prototype.bind, requestStorage = new async_hooks.AsyncLocalStorage(), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), emptyContextObject = {};
    Object.freeze(emptyContextObject);
    var rendererSigil = {};
    var currentActiveSnapshot = null, didWarnAboutNoopUpdateForComponent = {}, didWarnAboutDeprecatedWillMount = {};
    var didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
    var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
    var didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
    var didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
    var didWarnAboutContextTypes$1 = /* @__PURE__ */ new Set();
    var didWarnAboutChildContextTypes = /* @__PURE__ */ new Set();
    var didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
    var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
    var classComponentUpdater = {
      enqueueSetState: function(inst, payload, callback) {
        var internals = inst._reactInternals;
        null === internals.queue ? warnNoop(inst, "setState") : (internals.queue.push(payload), void 0 !== callback && null !== callback && warnOnInvalidCallback(callback));
      },
      enqueueReplaceState: function(inst, payload, callback) {
        inst = inst._reactInternals;
        inst.replace = true;
        inst.queue = [payload];
        void 0 !== callback && null !== callback && warnOnInvalidCallback(callback);
      },
      enqueueForceUpdate: function(inst, callback) {
        null === inst._reactInternals.queue ? warnNoop(inst, "forceUpdate") : void 0 !== callback && null !== callback && warnOnInvalidCallback(callback);
      }
    }, emptyTreeContext = { id: 1, overflow: "" }, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2, SuspenseException = Error(
      "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
    ), suspendedThenable = null, objectIs = "function" === typeof Object.is ? Object.is : is, currentlyRenderingComponent = null, currentlyRenderingTask = null, currentlyRenderingRequest = null, currentlyRenderingKeyPath = null, firstWorkInProgressHook = null, workInProgressHook = null, isReRender = false, didScheduleRenderPhaseUpdate = false, localIdCounter = 0, actionStateCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, thenableState = null, renderPhaseUpdates = null, numberOfReRenders = 0, isInHookUserCodeInDev = false, currentHookNameInDev, HooksDispatcher = {
      readContext,
      use: function(usable) {
        if (null !== usable && "object" === typeof usable) {
          if ("function" === typeof usable.then)
            return unwrapThenable(usable);
          if (usable.$$typeof === REACT_CONTEXT_TYPE)
            return readContext(usable);
        }
        throw Error(
          "An unsupported type was passed to use(): " + String(usable)
        );
      },
      useContext: function(context) {
        currentHookNameInDev = "useContext";
        resolveCurrentlyRenderingComponent();
        return context._currentValue;
      },
      useMemo,
      useReducer,
      useRef: function(initialValue) {
        currentlyRenderingComponent = resolveCurrentlyRenderingComponent();
        workInProgressHook = createWorkInProgressHook();
        var previousRef = workInProgressHook.memoizedState;
        return null === previousRef ? (initialValue = { current: initialValue }, Object.seal(initialValue), workInProgressHook.memoizedState = initialValue) : previousRef;
      },
      useState: function(initialState2) {
        currentHookNameInDev = "useState";
        return useReducer(basicStateReducer, initialState2);
      },
      useInsertionEffect: noop2,
      useLayoutEffect: noop2,
      useCallback: function(callback, deps) {
        return useMemo(function() {
          return callback;
        }, deps);
      },
      useImperativeHandle: noop2,
      useEffect: noop2,
      useDebugValue: noop2,
      useDeferredValue: function(value, initialValue) {
        resolveCurrentlyRenderingComponent();
        return void 0 !== initialValue ? initialValue : value;
      },
      useTransition: function() {
        resolveCurrentlyRenderingComponent();
        return [false, unsupportedStartTransition];
      },
      useId: function() {
        var treeId = currentlyRenderingTask.treeContext;
        var overflow = treeId.overflow;
        treeId = treeId.id;
        treeId = (treeId & ~(1 << 32 - clz32(treeId) - 1)).toString(32) + overflow;
        var resumableState = currentResumableState;
        if (null === resumableState)
          throw Error(
            "Invalid hook call. Hooks can only be called inside of the body of a function component."
          );
        overflow = localIdCounter++;
        treeId = "_" + resumableState.idPrefix + "R_" + treeId;
        0 < overflow && (treeId += "H" + overflow.toString(32));
        return treeId + "_";
      },
      useSyncExternalStore: function(subscribe, getSnapshot, getServerSnapshot) {
        if (void 0 === getServerSnapshot)
          throw Error(
            "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
          );
        return getServerSnapshot();
      },
      useOptimistic: function(passthrough) {
        resolveCurrentlyRenderingComponent();
        return [passthrough, unsupportedSetOptimisticState];
      },
      useActionState,
      useFormState: useActionState,
      useHostTransitionStatus: function() {
        resolveCurrentlyRenderingComponent();
        return NotPending;
      },
      useMemoCache: function(size) {
        for (var data = Array(size), i = 0; i < size; i++)
          data[i] = REACT_MEMO_CACHE_SENTINEL;
        return data;
      },
      useCacheRefresh: function() {
        return unsupportedRefresh;
      },
      useEffectEvent: function() {
        return throwOnUseEffectEventCall;
      }
    }, currentResumableState = null, currentTaskInDEV = null, DefaultAsyncDispatcher = {
      getCacheForType: function() {
        throw Error("Not implemented.");
      },
      cacheSignal: function() {
        throw Error("Not implemented.");
      },
      getOwner: function() {
        return null === currentTaskInDEV ? null : currentTaskInDEV.componentStack;
      }
    }, disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
    disabledLog.__reactDisabledLog = true;
    var prefix, suffix, reentry = false;
    var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)();
    var callComponent = {
      react_stack_bottom_frame: function(Component, props, secondArg) {
        return Component(props, secondArg);
      }
    }, callComponentInDEV = callComponent.react_stack_bottom_frame.bind(callComponent), callRender = {
      react_stack_bottom_frame: function(instance) {
        return instance.render();
      }
    }, callRenderInDEV = callRender.react_stack_bottom_frame.bind(callRender), callLazyInit = {
      react_stack_bottom_frame: function(lazy) {
        var init2 = lazy._init;
        return init2(lazy._payload);
      }
    }, callLazyInitInDEV = callLazyInit.react_stack_bottom_frame.bind(callLazyInit), lastResetTime = 0;
    if ("object" === typeof performance && "function" === typeof performance.now) {
      var localPerformance = performance;
      var getCurrentTime = function() {
        return localPerformance.now();
      };
    } else {
      var localDate = Date;
      getCurrentTime = function() {
        return localDate.now();
      };
    }
    var CLIENT_RENDERED = 4, PENDING = 0, COMPLETED = 1, FLUSHED = 2, ABORTED = 3, ERRORED = 4, POSTPONED = 5, CLOSED = 14, currentRequest = null, didWarnAboutBadClass = {}, didWarnAboutContextTypes = {}, didWarnAboutContextTypeOnFunctionComponent = {}, didWarnAboutGetDerivedStateOnFunctionComponent = {}, didWarnAboutReassigningProps = false, didWarnAboutGenerators = false, didWarnAboutMaps = false, flushedByteSize = 0, flushingPartialBoundaries = false;
    ensureCorrectIsomorphicReactVersion();
    ensureCorrectIsomorphicReactVersion();
    reactDomServer_node_development.prerender = function(children, options) {
      return new Promise(function(resolve, reject) {
        var onHeaders = options ? options.onHeaders : void 0, onHeadersImpl;
        onHeaders && (onHeadersImpl = function(headersDescriptor) {
          onHeaders(new Headers(headersDescriptor));
        });
        var resources = createResumableState(
          options ? options.identifierPrefix : void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.bootstrapScriptContent : void 0,
          options ? options.bootstrapScripts : void 0,
          options ? options.bootstrapModules : void 0
        ), request = createPrerenderRequest(
          children,
          resources,
          createRenderState(
            resources,
            void 0,
            options ? options.unstable_externalRuntimeSrc : void 0,
            options ? options.importMap : void 0,
            onHeadersImpl,
            options ? options.maxHeadersLength : void 0
          ),
          createRootFormatContext(options ? options.namespaceURI : void 0),
          options ? options.progressiveChunkSize : void 0,
          options ? options.onError : void 0,
          function() {
            var writable, stream2 = new ReadableStream(
              {
                type: "bytes",
                start: function(controller) {
                  writable = createFakeWritableFromReadableStreamController(
                    controller
                  );
                },
                pull: function() {
                  startFlowing(request, writable);
                },
                cancel: function(reason) {
                  request.destination = null;
                  abort(request, reason);
                }
              },
              { highWaterMark: 0 }
            );
            stream2 = {
              postponed: getPostponedState(request),
              prelude: stream2
            };
            resolve(stream2);
          },
          void 0,
          void 0,
          reject,
          options ? options.onPostpone : void 0
        );
        if (options && options.signal) {
          var signal = options.signal;
          if (signal.aborted) abort(request, signal.reason);
          else {
            var listener = function() {
              abort(request, signal.reason);
              signal.removeEventListener("abort", listener);
            };
            signal.addEventListener("abort", listener);
          }
        }
        startWork(request);
      });
    };
    reactDomServer_node_development.prerenderToNodeStream = function(children, options) {
      return new Promise(function(resolve, reject) {
        var resumableState = createResumableState(
          options ? options.identifierPrefix : void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.bootstrapScriptContent : void 0,
          options ? options.bootstrapScripts : void 0,
          options ? options.bootstrapModules : void 0
        ), request = createPrerenderRequest(
          children,
          resumableState,
          createRenderState(
            resumableState,
            void 0,
            options ? options.unstable_externalRuntimeSrc : void 0,
            options ? options.importMap : void 0,
            options ? options.onHeaders : void 0,
            options ? options.maxHeadersLength : void 0
          ),
          createRootFormatContext(options ? options.namespaceURI : void 0),
          options ? options.progressiveChunkSize : void 0,
          options ? options.onError : void 0,
          function() {
            var readable = new stream$1.Readable({
              read: function() {
                startFlowing(request, writable);
              }
            }), writable = createFakeWritableFromReadable(readable);
            readable = {
              postponed: getPostponedState(request),
              prelude: readable
            };
            resolve(readable);
          },
          void 0,
          void 0,
          reject,
          options ? options.onPostpone : void 0
        );
        if (options && options.signal) {
          var signal = options.signal;
          if (signal.aborted) abort(request, signal.reason);
          else {
            var listener = function() {
              abort(request, signal.reason);
              signal.removeEventListener("abort", listener);
            };
            signal.addEventListener("abort", listener);
          }
        }
        startWork(request);
      });
    };
    reactDomServer_node_development.renderToPipeableStream = function(children, options) {
      var request = createRequestImpl(children, options), hasStartedFlowing = false;
      startWork(request);
      return {
        pipe: function(destination) {
          if (hasStartedFlowing)
            throw Error(
              "React currently only supports piping to one writable stream."
            );
          hasStartedFlowing = true;
          safelyEmitEarlyPreloads(
            request,
            null === request.trackedPostpones ? 0 === request.pendingRootTasks : null === request.completedRootSegment ? 0 === request.pendingRootTasks : request.completedRootSegment.status !== POSTPONED
          );
          startFlowing(request, destination);
          destination.on("drain", createDrainHandler(destination, request));
          destination.on(
            "error",
            createCancelHandler(
              request,
              "The destination stream errored while writing data."
            )
          );
          destination.on(
            "close",
            createCancelHandler(request, "The destination stream closed early.")
          );
          return destination;
        },
        abort: function(reason) {
          abort(request, reason);
        }
      };
    };
    reactDomServer_node_development.renderToReadableStream = function(children, options) {
      return new Promise(function(resolve, reject) {
        var onFatalError, onAllReady, allReady = new Promise(function(res, rej) {
          onAllReady = res;
          onFatalError = rej;
        }), onHeaders = options ? options.onHeaders : void 0, onHeadersImpl;
        onHeaders && (onHeadersImpl = function(headersDescriptor) {
          onHeaders(new Headers(headersDescriptor));
        });
        var resumableState = createResumableState(
          options ? options.identifierPrefix : void 0,
          options ? options.unstable_externalRuntimeSrc : void 0,
          options ? options.bootstrapScriptContent : void 0,
          options ? options.bootstrapScripts : void 0,
          options ? options.bootstrapModules : void 0
        ), request = createRequest(
          children,
          resumableState,
          createRenderState(
            resumableState,
            options ? options.nonce : void 0,
            options ? options.unstable_externalRuntimeSrc : void 0,
            options ? options.importMap : void 0,
            onHeadersImpl,
            options ? options.maxHeadersLength : void 0
          ),
          createRootFormatContext(options ? options.namespaceURI : void 0),
          options ? options.progressiveChunkSize : void 0,
          options ? options.onError : void 0,
          onAllReady,
          function() {
            var writable, stream2 = new ReadableStream(
              {
                type: "bytes",
                start: function(controller) {
                  writable = createFakeWritableFromReadableStreamController$1(
                    controller
                  );
                },
                pull: function() {
                  startFlowing(request, writable);
                },
                cancel: function(reason) {
                  request.destination = null;
                  abort(request, reason);
                }
              },
              { highWaterMark: 0 }
            );
            stream2.allReady = allReady;
            resolve(stream2);
          },
          function(error) {
            allReady.catch(function() {
            });
            reject(error);
          },
          onFatalError,
          options ? options.onPostpone : void 0,
          options ? options.formState : void 0
        );
        if (options && options.signal) {
          var signal = options.signal;
          if (signal.aborted) abort(request, signal.reason);
          else {
            var listener = function() {
              abort(request, signal.reason);
              signal.removeEventListener("abort", listener);
            };
            signal.addEventListener("abort", listener);
          }
        }
        startWork(request);
      });
    };
    reactDomServer_node_development.resume = function(children, postponedState, options) {
      return new Promise(function(resolve, reject) {
        var onFatalError, onAllReady, allReady = new Promise(function(res, rej) {
          onAllReady = res;
          onFatalError = rej;
        }), request = resumeRequest(
          children,
          postponedState,
          createRenderState(
            postponedState.resumableState,
            options ? options.nonce : void 0,
            void 0,
            void 0,
            void 0,
            void 0
          ),
          options ? options.onError : void 0,
          onAllReady,
          function() {
            var writable, stream2 = new ReadableStream(
              {
                type: "bytes",
                start: function(controller) {
                  writable = createFakeWritableFromReadableStreamController$1(
                    controller
                  );
                },
                pull: function() {
                  startFlowing(request, writable);
                },
                cancel: function(reason) {
                  request.destination = null;
                  abort(request, reason);
                }
              },
              { highWaterMark: 0 }
            );
            stream2.allReady = allReady;
            resolve(stream2);
          },
          function(error) {
            allReady.catch(function() {
            });
            reject(error);
          },
          onFatalError,
          options ? options.onPostpone : void 0
        );
        if (options && options.signal) {
          var signal = options.signal;
          if (signal.aborted) abort(request, signal.reason);
          else {
            var listener = function() {
              abort(request, signal.reason);
              signal.removeEventListener("abort", listener);
            };
            signal.addEventListener("abort", listener);
          }
        }
        startWork(request);
      });
    };
    reactDomServer_node_development.resumeAndPrerender = function(children, postponedState, options) {
      return new Promise(function(resolve, reject) {
        var request = resumeAndPrerenderRequest(
          children,
          postponedState,
          createRenderState(
            postponedState.resumableState,
            void 0,
            void 0,
            void 0,
            void 0,
            void 0
          ),
          options ? options.onError : void 0,
          function() {
            var writable, stream2 = new ReadableStream(
              {
                type: "bytes",
                start: function(controller) {
                  writable = createFakeWritableFromReadableStreamController(
                    controller
                  );
                },
                pull: function() {
                  startFlowing(request, writable);
                },
                cancel: function(reason) {
                  request.destination = null;
                  abort(request, reason);
                }
              },
              { highWaterMark: 0 }
            );
            stream2 = { postponed: getPostponedState(request), prelude: stream2 };
            resolve(stream2);
          },
          void 0,
          void 0,
          reject,
          options ? options.onPostpone : void 0
        );
        if (options && options.signal) {
          var signal = options.signal;
          if (signal.aborted) abort(request, signal.reason);
          else {
            var listener = function() {
              abort(request, signal.reason);
              signal.removeEventListener("abort", listener);
            };
            signal.addEventListener("abort", listener);
          }
        }
        startWork(request);
      });
    };
    reactDomServer_node_development.resumeAndPrerenderToNodeStream = function(children, postponedState, options) {
      return new Promise(function(resolve, reject) {
        var request = resumeAndPrerenderRequest(
          children,
          postponedState,
          createRenderState(
            postponedState.resumableState,
            void 0,
            void 0,
            void 0,
            void 0,
            void 0
          ),
          options ? options.onError : void 0,
          function() {
            var readable = new stream$1.Readable({
              read: function() {
                startFlowing(request, writable);
              }
            }), writable = createFakeWritableFromReadable(readable);
            readable = {
              postponed: getPostponedState(request),
              prelude: readable
            };
            resolve(readable);
          },
          void 0,
          void 0,
          reject,
          options ? options.onPostpone : void 0
        );
        if (options && options.signal) {
          var signal = options.signal;
          if (signal.aborted) abort(request, signal.reason);
          else {
            var listener = function() {
              abort(request, signal.reason);
              signal.removeEventListener("abort", listener);
            };
            signal.addEventListener("abort", listener);
          }
        }
        startWork(request);
      });
    };
    reactDomServer_node_development.resumeToPipeableStream = function(children, postponedState, options) {
      var request = resumeRequestImpl(children, postponedState, options), hasStartedFlowing = false;
      startWork(request);
      return {
        pipe: function(destination) {
          if (hasStartedFlowing)
            throw Error(
              "React currently only supports piping to one writable stream."
            );
          hasStartedFlowing = true;
          startFlowing(request, destination);
          destination.on("drain", createDrainHandler(destination, request));
          destination.on(
            "error",
            createCancelHandler(
              request,
              "The destination stream errored while writing data."
            )
          );
          destination.on(
            "close",
            createCancelHandler(request, "The destination stream closed early.")
          );
          return destination;
        },
        abort: function(reason) {
          abort(request, reason);
        }
      };
    };
    reactDomServer_node_development.version = "19.2.4";
  })();
  return reactDomServer_node_development;
}
var hasRequiredServer_node;
function requireServer_node() {
  if (hasRequiredServer_node) return server_node;
  hasRequiredServer_node = 1;
  var l3, s2;
  if (process.env.NODE_ENV === "production") {
    l3 = requireReactDomServerLegacy_node_production();
    s2 = requireReactDomServer_node_production();
  } else {
    l3 = requireReactDomServerLegacy_node_development();
    s2 = requireReactDomServer_node_development();
  }
  server_node.version = l3.version;
  server_node.renderToString = l3.renderToString;
  server_node.renderToStaticMarkup = l3.renderToStaticMarkup;
  server_node.renderToPipeableStream = s2.renderToPipeableStream;
  server_node.renderToReadableStream = s2.renderToReadableStream;
  server_node.resumeToPipeableStream = s2.resumeToPipeableStream;
  server_node.resume = s2.resume;
  return server_node;
}
var server_nodeExports = requireServer_node();
const ReactDOMServer = /* @__PURE__ */ getDefaultExportFromCjs(server_nodeExports);
const pages = /* @__PURE__ */ Object.assign({
  "./Pages/Academy/Billing/Account.jsx": __vite_glob_0_0,
  "./Pages/Academy/Billing/Cancel.jsx": __vite_glob_0_1,
  "./Pages/Academy/Billing/Pricing.jsx": __vite_glob_0_2,
  "./Pages/Academy/Billing/Success.jsx": __vite_glob_0_3,
  "./Pages/Academy/ChallengeSubmit.jsx": __vite_glob_0_4,
  "./Pages/Academy/CoursesIndex.jsx": __vite_glob_0_5,
  "./Pages/Academy/CoursesShow.jsx": __vite_glob_0_6,
  "./Pages/Academy/Index.jsx": __vite_glob_0_7,
  "./Pages/Academy/List.jsx": __vite_glob_0_8,
  "./Pages/Academy/Show.jsx": __vite_glob_0_9,
  "./Pages/Admin/Academy/AnalyticsContent.jsx": __vite_glob_0_10,
  "./Pages/Admin/Academy/AnalyticsFunnel.jsx": __vite_glob_0_11,
  "./Pages/Admin/Academy/AnalyticsIntelligence.jsx": __vite_glob_0_12,
  "./Pages/Admin/Academy/AnalyticsNav.jsx": __vite_glob_0_13,
  "./Pages/Admin/Academy/AnalyticsOverview.jsx": __vite_glob_0_14,
  "./Pages/Admin/Academy/AnalyticsSearch.jsx": __vite_glob_0_15,
  "./Pages/Admin/Academy/Billing.jsx": __vite_glob_0_16,
  "./Pages/Admin/Academy/ChallengeEditor.jsx": __vite_glob_0_17,
  "./Pages/Admin/Academy/CourseBuilder.jsx": __vite_glob_0_18,
  "./Pages/Admin/Academy/CourseEditor.jsx": __vite_glob_0_19,
  "./Pages/Admin/Academy/CrudForm.jsx": __vite_glob_0_20,
  "./Pages/Admin/Academy/CrudIndex.jsx": __vite_glob_0_21,
  "./Pages/Admin/Academy/Dashboard.jsx": __vite_glob_0_22,
  "./Pages/Admin/Academy/LessonEditor.jsx": __vite_glob_0_23,
  "./Pages/Admin/Academy/Submissions.jsx": __vite_glob_0_24,
  "./Pages/Admin/AiBiography.jsx": __vite_glob_0_25,
  "./Pages/Admin/Artworks.jsx": __vite_glob_0_26,
  "./Pages/Admin/AuthAudit.jsx": __vite_glob_0_27,
  "./Pages/Admin/DailyActivity.jsx": __vite_glob_0_28,
  "./Pages/Admin/Dashboard.jsx": __vite_glob_0_29,
  "./Pages/Admin/FeaturedArtworks.jsx": __vite_glob_0_30,
  "./Pages/Admin/HomepageAnnouncements/Form.jsx": __vite_glob_0_31,
  "./Pages/Admin/HomepageAnnouncements/Index.jsx": __vite_glob_0_32,
  "./Pages/Admin/Settings.jsx": __vite_glob_0_33,
  "./Pages/Admin/Stories.jsx": __vite_glob_0_34,
  "./Pages/Admin/UploadQueue.jsx": __vite_glob_0_35,
  "./Pages/Admin/UsernameQueue.jsx": __vite_glob_0_36,
  "./Pages/Admin/Users/Index.jsx": __vite_glob_0_37,
  "./Pages/Artwork/SimilarArtworksHeader.jsx": __vite_glob_0_38,
  "./Pages/ArtworkPage.jsx": __vite_glob_0_39,
  "./Pages/CategoriesPage.jsx": __vite_glob_0_40,
  "./Pages/Collection/CollectionAnalytics.jsx": __vite_glob_0_41,
  "./Pages/Collection/CollectionDashboard.jsx": __vite_glob_0_42,
  "./Pages/Collection/CollectionFeaturedIndex.jsx": __vite_glob_0_43,
  "./Pages/Collection/CollectionHistory.jsx": __vite_glob_0_44,
  "./Pages/Collection/CollectionManage.jsx": __vite_glob_0_45,
  "./Pages/Collection/CollectionSeriesShow.jsx": __vite_glob_0_46,
  "./Pages/Collection/CollectionShow.jsx": __vite_glob_0_47,
  "./Pages/Collection/CollectionStaffProgramming.jsx": __vite_glob_0_48,
  "./Pages/Collection/CollectionStaffSurfaces.jsx": __vite_glob_0_49,
  "./Pages/Collection/FeaturedArtworksAdmin.jsx": __vite_glob_0_50,
  "./Pages/Collection/NovaCardsAdminIndex.jsx": __vite_glob_0_51,
  "./Pages/Collection/NovaCardsAssetPackAdmin.jsx": __vite_glob_0_52,
  "./Pages/Collection/NovaCardsChallengeAdmin.jsx": __vite_glob_0_53,
  "./Pages/Collection/NovaCardsCollectionAdmin.jsx": __vite_glob_0_54,
  "./Pages/Collection/NovaCardsTemplateAdmin.jsx": __vite_glob_0_55,
  "./Pages/Collection/SavedCollections.jsx": __vite_glob_0_56,
  "./Pages/Community/CommunityActivityPage.jsx": __vite_glob_0_57,
  "./Pages/Community/LatestCommentsPage.jsx": __vite_glob_0_58,
  "./Pages/Enhance/Create.jsx": __vite_glob_0_59,
  "./Pages/Enhance/Index.jsx": __vite_glob_0_60,
  "./Pages/Enhance/Show.jsx": __vite_glob_0_61,
  "./Pages/Feed/FollowingFeed.jsx": __vite_glob_0_62,
  "./Pages/Feed/HashtagFeed.jsx": __vite_glob_0_63,
  "./Pages/Feed/SavedFeed.jsx": __vite_glob_0_64,
  "./Pages/Feed/SearchFeed.jsx": __vite_glob_0_65,
  "./Pages/Feed/TrendingFeed.jsx": __vite_glob_0_66,
  "./Pages/Forum/ForumCategory.jsx": __vite_glob_0_67,
  "./Pages/Forum/ForumEditPost.jsx": __vite_glob_0_68,
  "./Pages/Forum/ForumIndex.jsx": __vite_glob_0_69,
  "./Pages/Forum/ForumNewThread.jsx": __vite_glob_0_70,
  "./Pages/Forum/ForumSection.jsx": __vite_glob_0_71,
  "./Pages/Forum/ForumThread.jsx": __vite_glob_0_72,
  "./Pages/Group/GroupChallengeShow.jsx": __vite_glob_0_73,
  "./Pages/Group/GroupEventShow.jsx": __vite_glob_0_74,
  "./Pages/Group/GroupFaqPage.jsx": __vite_glob_0_75,
  "./Pages/Group/GroupHelpPage.jsx": __vite_glob_0_76,
  "./Pages/Group/GroupIndex.jsx": __vite_glob_0_77,
  "./Pages/Group/GroupPostShow.jsx": __vite_glob_0_78,
  "./Pages/Group/GroupProjectShow.jsx": __vite_glob_0_79,
  "./Pages/Group/GroupQuickstartPage.jsx": __vite_glob_0_80,
  "./Pages/Group/GroupReleaseShow.jsx": __vite_glob_0_81,
  "./Pages/Group/GroupShow.jsx": __vite_glob_0_82,
  "./Pages/Help/AccountHelpPage.jsx": __vite_glob_0_83,
  "./Pages/Help/AuthHelpPage.jsx": __vite_glob_0_84,
  "./Pages/Help/CardsHelpPage.jsx": __vite_glob_0_85,
  "./Pages/Help/HelpCenterPage.jsx": __vite_glob_0_86,
  "./Pages/Help/ProfileHelpPage.jsx": __vite_glob_0_87,
  "./Pages/Help/StudioHelpPage.jsx": __vite_glob_0_88,
  "./Pages/Help/TroubleshootingHelpPage.jsx": __vite_glob_0_89,
  "./Pages/Help/UploadHelpPage.jsx": __vite_glob_0_90,
  "./Pages/Help/WorldsHelpPage.jsx": __vite_glob_0_91,
  "./Pages/Leaderboard/LeaderboardPage.jsx": __vite_glob_0_92,
  "./Pages/Messages/Index.jsx": __vite_glob_0_93,
  "./Pages/Moderation/AiBiographyAdmin.jsx": __vite_glob_0_94,
  "./Pages/Moderation/ArtworkMaturityQueue.jsx": __vite_glob_0_95,
  "./Pages/Moderation/Enhance/Index.jsx": __vite_glob_0_96,
  "./Pages/Moderation/Enhance/Show.jsx": __vite_glob_0_97,
  "./Pages/Moderation/WorldWebStoriesIndex.jsx": __vite_glob_0_98,
  "./Pages/Moderation/WorldWebStoryEditor.jsx": __vite_glob_0_99,
  "./Pages/News/NewsComments.jsx": __vite_glob_0_100,
  "./Pages/News/NewsImagePreview.jsx": __vite_glob_0_101,
  "./Pages/Profile/ProfileGallery.jsx": __vite_glob_0_102,
  "./Pages/Profile/ProfileShow.jsx": __vite_glob_0_103,
  "./Pages/Settings/ProfileEdit.jsx": __vite_glob_0_104,
  "./Pages/Studio/StudioActivity.jsx": __vite_glob_0_105,
  "./Pages/Studio/StudioAnalytics.jsx": __vite_glob_0_106,
  "./Pages/Studio/StudioArchived.jsx": __vite_glob_0_107,
  "./Pages/Studio/StudioArtworkAnalytics.jsx": __vite_glob_0_108,
  "./Pages/Studio/StudioArtworkEdit.jsx": __vite_glob_0_109,
  "./Pages/Studio/StudioArtworks.jsx": __vite_glob_0_110,
  "./Pages/Studio/StudioAssets.jsx": __vite_glob_0_111,
  "./Pages/Studio/StudioCalendar.jsx": __vite_glob_0_112,
  "./Pages/Studio/StudioCardAnalytics.jsx": __vite_glob_0_113,
  "./Pages/Studio/StudioCardEditor.jsx": __vite_glob_0_114,
  "./Pages/Studio/StudioCardsIndex.jsx": __vite_glob_0_115,
  "./Pages/Studio/StudioChallenges.jsx": __vite_glob_0_116,
  "./Pages/Studio/StudioCollections.jsx": __vite_glob_0_117,
  "./Pages/Studio/StudioComments.jsx": __vite_glob_0_118,
  "./Pages/Studio/StudioContentIndex.jsx": __vite_glob_0_119,
  "./Pages/Studio/StudioDashboard.jsx": __vite_glob_0_120,
  "./Pages/Studio/StudioDrafts.jsx": __vite_glob_0_121,
  "./Pages/Studio/StudioFeatured.jsx": __vite_glob_0_122,
  "./Pages/Studio/StudioFollowers.jsx": __vite_glob_0_123,
  "./Pages/Studio/StudioGroupActivity.jsx": __vite_glob_0_124,
  "./Pages/Studio/StudioGroupArtworks.jsx": __vite_glob_0_125,
  "./Pages/Studio/StudioGroupAssets.jsx": __vite_glob_0_126,
  "./Pages/Studio/StudioGroupChallengeEditor.jsx": __vite_glob_0_127,
  "./Pages/Studio/StudioGroupChallenges.jsx": __vite_glob_0_128,
  "./Pages/Studio/StudioGroupCollections.jsx": __vite_glob_0_129,
  "./Pages/Studio/StudioGroupCreate.jsx": __vite_glob_0_130,
  "./Pages/Studio/StudioGroupDashboard.jsx": __vite_glob_0_131,
  "./Pages/Studio/StudioGroupEventEditor.jsx": __vite_glob_0_132,
  "./Pages/Studio/StudioGroupEvents.jsx": __vite_glob_0_133,
  "./Pages/Studio/StudioGroupInvitations.jsx": __vite_glob_0_134,
  "./Pages/Studio/StudioGroupJoinRequests.jsx": __vite_glob_0_135,
  "./Pages/Studio/StudioGroupMembers.jsx": __vite_glob_0_136,
  "./Pages/Studio/StudioGroupPostEditor.jsx": __vite_glob_0_137,
  "./Pages/Studio/StudioGroupPosts.jsx": __vite_glob_0_138,
  "./Pages/Studio/StudioGroupProjectEditor.jsx": __vite_glob_0_139,
  "./Pages/Studio/StudioGroupProjects.jsx": __vite_glob_0_140,
  "./Pages/Studio/StudioGroupRecruitment.jsx": __vite_glob_0_141,
  "./Pages/Studio/StudioGroupReleaseEditor.jsx": __vite_glob_0_142,
  "./Pages/Studio/StudioGroupReleases.jsx": __vite_glob_0_143,
  "./Pages/Studio/StudioGroupReputation.jsx": __vite_glob_0_144,
  "./Pages/Studio/StudioGroupReviewQueue.jsx": __vite_glob_0_145,
  "./Pages/Studio/StudioGroupSettings.jsx": __vite_glob_0_146,
  "./Pages/Studio/StudioGroupsIndex.jsx": __vite_glob_0_147,
  "./Pages/Studio/StudioGrowth.jsx": __vite_glob_0_148,
  "./Pages/Studio/StudioInbox.jsx": __vite_glob_0_149,
  "./Pages/Studio/StudioNewsEditor.jsx": __vite_glob_0_150,
  "./Pages/Studio/StudioNewsIndex.jsx": __vite_glob_0_151,
  "./Pages/Studio/StudioNewsTaxonomies.jsx": __vite_glob_0_152,
  "./Pages/Studio/StudioPreferences.jsx": __vite_glob_0_153,
  "./Pages/Studio/StudioProfile.jsx": __vite_glob_0_154,
  "./Pages/Studio/StudioScheduled.jsx": __vite_glob_0_155,
  "./Pages/Studio/StudioSearch.jsx": __vite_glob_0_156,
  "./Pages/Studio/StudioSettings.jsx": __vite_glob_0_157,
  "./Pages/Studio/StudioStories.jsx": __vite_glob_0_158,
  "./Pages/Studio/StudioUploadQueue.jsx": __vite_glob_0_159,
  "./Pages/Studio/StudioWorldEditor.jsx": __vite_glob_0_160,
  "./Pages/Studio/StudioWorldsIndex.jsx": __vite_glob_0_161,
  "./Pages/Upload/Index.jsx": __vite_glob_0_162,
  "./Pages/World/WorldIndex.jsx": __vite_glob_0_163,
  "./Pages/World/WorldShow.jsx": __vite_glob_0_164
});
const ClientOnlyPlaceholder = () => null;
d(
  (page) => W$1({
    page,
    render: ReactDOMServer.renderToString,
    resolve: (name2) => {
      if (name2.startsWith("Studio/StudioNews")) {
        return ClientOnlyPlaceholder;
      }
      const module = pages[`./Pages/${name2}.jsx`];
      if (!module) {
        throw new Error(`[SSR] Unknown Inertia page: "./Pages/${name2}.jsx"`);
      }
      return module.default;
    },
    setup: ({ App, props }) => /* @__PURE__ */ React.createElement(App, { ...props })
  })
);
export {
  ShareToast as S,
  ShareArtworkModal$1 as a
};
